cb7cfa9b34f27a789d178e5aeea5c95118c40c50
[sfrench/cifs-2.6.git] / drivers / gpu / drm / amd / display / amdgpu_dm / amdgpu_dm.c
1 /*
2  * Copyright 2015 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  * Authors: AMD
23  *
24  */
25
26 /* The caprices of the preprocessor require that this be declared right here */
27 #define CREATE_TRACE_POINTS
28
29 #include "dm_services_types.h"
30 #include "dc.h"
31 #include "dc/inc/core_types.h"
32 #include "dal_asic_id.h"
33
34 #include "vid.h"
35 #include "amdgpu.h"
36 #include "amdgpu_display.h"
37 #include "amdgpu_ucode.h"
38 #include "atom.h"
39 #include "amdgpu_dm.h"
40 #include "amdgpu_pm.h"
41
42 #include "amd_shared.h"
43 #include "amdgpu_dm_irq.h"
44 #include "dm_helpers.h"
45 #include "amdgpu_dm_mst_types.h"
46 #if defined(CONFIG_DEBUG_FS)
47 #include "amdgpu_dm_debugfs.h"
48 #endif
49
50 #include "ivsrcid/ivsrcid_vislands30.h"
51
52 #include <linux/module.h>
53 #include <linux/moduleparam.h>
54 #include <linux/version.h>
55 #include <linux/types.h>
56 #include <linux/pm_runtime.h>
57 #include <linux/pci.h>
58 #include <linux/firmware.h>
59 #include <linux/component.h>
60
61 #include <drm/drm_atomic.h>
62 #include <drm/drm_atomic_uapi.h>
63 #include <drm/drm_atomic_helper.h>
64 #include <drm/drm_dp_mst_helper.h>
65 #include <drm/drm_fb_helper.h>
66 #include <drm/drm_fourcc.h>
67 #include <drm/drm_edid.h>
68 #include <drm/drm_vblank.h>
69 #include <drm/drm_audio_component.h>
70
71 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
72 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
73
74 #include "dcn/dcn_1_0_offset.h"
75 #include "dcn/dcn_1_0_sh_mask.h"
76 #include "soc15_hw_ip.h"
77 #include "vega10_ip_offset.h"
78
79 #include "soc15_common.h"
80 #endif
81
82 #include "modules/inc/mod_freesync.h"
83 #include "modules/power/power_helpers.h"
84 #include "modules/inc/mod_info_packet.h"
85
86 #define FIRMWARE_RAVEN_DMCU             "amdgpu/raven_dmcu.bin"
87 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
88
89 /**
90  * DOC: overview
91  *
92  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
93  * **dm**) sits between DRM and DC. It acts as a liason, converting DRM
94  * requests into DC requests, and DC responses into DRM responses.
95  *
96  * The root control structure is &struct amdgpu_display_manager.
97  */
98
99 /* basic init/fini API */
100 static int amdgpu_dm_init(struct amdgpu_device *adev);
101 static void amdgpu_dm_fini(struct amdgpu_device *adev);
102
103 /*
104  * initializes drm_device display related structures, based on the information
105  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
106  * drm_encoder, drm_mode_config
107  *
108  * Returns 0 on success
109  */
110 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
111 /* removes and deallocates the drm structures, created by the above function */
112 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
113
114 static void
115 amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector);
116
117 static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
118                                 struct drm_plane *plane,
119                                 unsigned long possible_crtcs,
120                                 const struct dc_plane_cap *plane_cap);
121 static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
122                                struct drm_plane *plane,
123                                uint32_t link_index);
124 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
125                                     struct amdgpu_dm_connector *amdgpu_dm_connector,
126                                     uint32_t link_index,
127                                     struct amdgpu_encoder *amdgpu_encoder);
128 static int amdgpu_dm_encoder_init(struct drm_device *dev,
129                                   struct amdgpu_encoder *aencoder,
130                                   uint32_t link_index);
131
132 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
133
134 static int amdgpu_dm_atomic_commit(struct drm_device *dev,
135                                    struct drm_atomic_state *state,
136                                    bool nonblock);
137
138 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
139
140 static int amdgpu_dm_atomic_check(struct drm_device *dev,
141                                   struct drm_atomic_state *state);
142
143 static void handle_cursor_update(struct drm_plane *plane,
144                                  struct drm_plane_state *old_plane_state);
145
146 /*
147  * dm_vblank_get_counter
148  *
149  * @brief
150  * Get counter for number of vertical blanks
151  *
152  * @param
153  * struct amdgpu_device *adev - [in] desired amdgpu device
154  * int disp_idx - [in] which CRTC to get the counter from
155  *
156  * @return
157  * Counter for vertical blanks
158  */
159 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
160 {
161         if (crtc >= adev->mode_info.num_crtc)
162                 return 0;
163         else {
164                 struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
165                 struct dm_crtc_state *acrtc_state = to_dm_crtc_state(
166                                 acrtc->base.state);
167
168
169                 if (acrtc_state->stream == NULL) {
170                         DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
171                                   crtc);
172                         return 0;
173                 }
174
175                 return dc_stream_get_vblank_counter(acrtc_state->stream);
176         }
177 }
178
179 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
180                                   u32 *vbl, u32 *position)
181 {
182         uint32_t v_blank_start, v_blank_end, h_position, v_position;
183
184         if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
185                 return -EINVAL;
186         else {
187                 struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
188                 struct dm_crtc_state *acrtc_state = to_dm_crtc_state(
189                                                 acrtc->base.state);
190
191                 if (acrtc_state->stream ==  NULL) {
192                         DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
193                                   crtc);
194                         return 0;
195                 }
196
197                 /*
198                  * TODO rework base driver to use values directly.
199                  * for now parse it back into reg-format
200                  */
201                 dc_stream_get_scanoutpos(acrtc_state->stream,
202                                          &v_blank_start,
203                                          &v_blank_end,
204                                          &h_position,
205                                          &v_position);
206
207                 *position = v_position | (h_position << 16);
208                 *vbl = v_blank_start | (v_blank_end << 16);
209         }
210
211         return 0;
212 }
213
214 static bool dm_is_idle(void *handle)
215 {
216         /* XXX todo */
217         return true;
218 }
219
220 static int dm_wait_for_idle(void *handle)
221 {
222         /* XXX todo */
223         return 0;
224 }
225
226 static bool dm_check_soft_reset(void *handle)
227 {
228         return false;
229 }
230
231 static int dm_soft_reset(void *handle)
232 {
233         /* XXX todo */
234         return 0;
235 }
236
237 static struct amdgpu_crtc *
238 get_crtc_by_otg_inst(struct amdgpu_device *adev,
239                      int otg_inst)
240 {
241         struct drm_device *dev = adev->ddev;
242         struct drm_crtc *crtc;
243         struct amdgpu_crtc *amdgpu_crtc;
244
245         if (otg_inst == -1) {
246                 WARN_ON(1);
247                 return adev->mode_info.crtcs[0];
248         }
249
250         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
251                 amdgpu_crtc = to_amdgpu_crtc(crtc);
252
253                 if (amdgpu_crtc->otg_inst == otg_inst)
254                         return amdgpu_crtc;
255         }
256
257         return NULL;
258 }
259
260 static inline bool amdgpu_dm_vrr_active(struct dm_crtc_state *dm_state)
261 {
262         return dm_state->freesync_config.state == VRR_STATE_ACTIVE_VARIABLE ||
263                dm_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
264 }
265
266 static void dm_pflip_high_irq(void *interrupt_params)
267 {
268         struct amdgpu_crtc *amdgpu_crtc;
269         struct common_irq_params *irq_params = interrupt_params;
270         struct amdgpu_device *adev = irq_params->adev;
271         unsigned long flags;
272         struct drm_pending_vblank_event *e;
273         struct dm_crtc_state *acrtc_state;
274         uint32_t vpos, hpos, v_blank_start, v_blank_end;
275         bool vrr_active;
276
277         amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
278
279         /* IRQ could occur when in initial stage */
280         /* TODO work and BO cleanup */
281         if (amdgpu_crtc == NULL) {
282                 DRM_DEBUG_DRIVER("CRTC is null, returning.\n");
283                 return;
284         }
285
286         spin_lock_irqsave(&adev->ddev->event_lock, flags);
287
288         if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED){
289                 DRM_DEBUG_DRIVER("amdgpu_crtc->pflip_status = %d !=AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p] \n",
290                                                  amdgpu_crtc->pflip_status,
291                                                  AMDGPU_FLIP_SUBMITTED,
292                                                  amdgpu_crtc->crtc_id,
293                                                  amdgpu_crtc);
294                 spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
295                 return;
296         }
297
298         /* page flip completed. */
299         e = amdgpu_crtc->event;
300         amdgpu_crtc->event = NULL;
301
302         if (!e)
303                 WARN_ON(1);
304
305         acrtc_state = to_dm_crtc_state(amdgpu_crtc->base.state);
306         vrr_active = amdgpu_dm_vrr_active(acrtc_state);
307
308         /* Fixed refresh rate, or VRR scanout position outside front-porch? */
309         if (!vrr_active ||
310             !dc_stream_get_scanoutpos(acrtc_state->stream, &v_blank_start,
311                                       &v_blank_end, &hpos, &vpos) ||
312             (vpos < v_blank_start)) {
313                 /* Update to correct count and vblank timestamp if racing with
314                  * vblank irq. This also updates to the correct vblank timestamp
315                  * even in VRR mode, as scanout is past the front-porch atm.
316                  */
317                 drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
318
319                 /* Wake up userspace by sending the pageflip event with proper
320                  * count and timestamp of vblank of flip completion.
321                  */
322                 if (e) {
323                         drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
324
325                         /* Event sent, so done with vblank for this flip */
326                         drm_crtc_vblank_put(&amdgpu_crtc->base);
327                 }
328         } else if (e) {
329                 /* VRR active and inside front-porch: vblank count and
330                  * timestamp for pageflip event will only be up to date after
331                  * drm_crtc_handle_vblank() has been executed from late vblank
332                  * irq handler after start of back-porch (vline 0). We queue the
333                  * pageflip event for send-out by drm_crtc_handle_vblank() with
334                  * updated timestamp and count, once it runs after us.
335                  *
336                  * We need to open-code this instead of using the helper
337                  * drm_crtc_arm_vblank_event(), as that helper would
338                  * call drm_crtc_accurate_vblank_count(), which we must
339                  * not call in VRR mode while we are in front-porch!
340                  */
341
342                 /* sequence will be replaced by real count during send-out. */
343                 e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
344                 e->pipe = amdgpu_crtc->crtc_id;
345
346                 list_add_tail(&e->base.link, &adev->ddev->vblank_event_list);
347                 e = NULL;
348         }
349
350         /* Keep track of vblank of this flip for flip throttling. We use the
351          * cooked hw counter, as that one incremented at start of this vblank
352          * of pageflip completion, so last_flip_vblank is the forbidden count
353          * for queueing new pageflips if vsync + VRR is enabled.
354          */
355         amdgpu_crtc->last_flip_vblank = amdgpu_get_vblank_counter_kms(adev->ddev,
356                                                         amdgpu_crtc->crtc_id);
357
358         amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
359         spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
360
361         DRM_DEBUG_DRIVER("crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
362                          amdgpu_crtc->crtc_id, amdgpu_crtc,
363                          vrr_active, (int) !e);
364 }
365
366 static void dm_vupdate_high_irq(void *interrupt_params)
367 {
368         struct common_irq_params *irq_params = interrupt_params;
369         struct amdgpu_device *adev = irq_params->adev;
370         struct amdgpu_crtc *acrtc;
371         struct dm_crtc_state *acrtc_state;
372         unsigned long flags;
373
374         acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
375
376         if (acrtc) {
377                 acrtc_state = to_dm_crtc_state(acrtc->base.state);
378
379                 DRM_DEBUG_DRIVER("crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
380                                  amdgpu_dm_vrr_active(acrtc_state));
381
382                 /* Core vblank handling is done here after end of front-porch in
383                  * vrr mode, as vblank timestamping will give valid results
384                  * while now done after front-porch. This will also deliver
385                  * page-flip completion events that have been queued to us
386                  * if a pageflip happened inside front-porch.
387                  */
388                 if (amdgpu_dm_vrr_active(acrtc_state)) {
389                         drm_crtc_handle_vblank(&acrtc->base);
390
391                         /* BTR processing for pre-DCE12 ASICs */
392                         if (acrtc_state->stream &&
393                             adev->family < AMDGPU_FAMILY_AI) {
394                                 spin_lock_irqsave(&adev->ddev->event_lock, flags);
395                                 mod_freesync_handle_v_update(
396                                     adev->dm.freesync_module,
397                                     acrtc_state->stream,
398                                     &acrtc_state->vrr_params);
399
400                                 dc_stream_adjust_vmin_vmax(
401                                     adev->dm.dc,
402                                     acrtc_state->stream,
403                                     &acrtc_state->vrr_params.adjust);
404                                 spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
405                         }
406                 }
407         }
408 }
409
410 static void dm_crtc_high_irq(void *interrupt_params)
411 {
412         struct common_irq_params *irq_params = interrupt_params;
413         struct amdgpu_device *adev = irq_params->adev;
414         struct amdgpu_crtc *acrtc;
415         struct dm_crtc_state *acrtc_state;
416         unsigned long flags;
417
418         acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
419
420         if (acrtc) {
421                 acrtc_state = to_dm_crtc_state(acrtc->base.state);
422
423                 DRM_DEBUG_DRIVER("crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
424                                  amdgpu_dm_vrr_active(acrtc_state));
425
426                 /* Core vblank handling at start of front-porch is only possible
427                  * in non-vrr mode, as only there vblank timestamping will give
428                  * valid results while done in front-porch. Otherwise defer it
429                  * to dm_vupdate_high_irq after end of front-porch.
430                  */
431                 if (!amdgpu_dm_vrr_active(acrtc_state))
432                         drm_crtc_handle_vblank(&acrtc->base);
433
434                 /* Following stuff must happen at start of vblank, for crc
435                  * computation and below-the-range btr support in vrr mode.
436                  */
437                 amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
438
439                 if (acrtc_state->stream && adev->family >= AMDGPU_FAMILY_AI &&
440                     acrtc_state->vrr_params.supported &&
441                     acrtc_state->freesync_config.state == VRR_STATE_ACTIVE_VARIABLE) {
442                         spin_lock_irqsave(&adev->ddev->event_lock, flags);
443                         mod_freesync_handle_v_update(
444                                 adev->dm.freesync_module,
445                                 acrtc_state->stream,
446                                 &acrtc_state->vrr_params);
447
448                         dc_stream_adjust_vmin_vmax(
449                                 adev->dm.dc,
450                                 acrtc_state->stream,
451                                 &acrtc_state->vrr_params.adjust);
452                         spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
453                 }
454         }
455 }
456
457 static int dm_set_clockgating_state(void *handle,
458                   enum amd_clockgating_state state)
459 {
460         return 0;
461 }
462
463 static int dm_set_powergating_state(void *handle,
464                   enum amd_powergating_state state)
465 {
466         return 0;
467 }
468
469 /* Prototypes of private functions */
470 static int dm_early_init(void* handle);
471
472 /* Allocate memory for FBC compressed data  */
473 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
474 {
475         struct drm_device *dev = connector->dev;
476         struct amdgpu_device *adev = dev->dev_private;
477         struct dm_comressor_info *compressor = &adev->dm.compressor;
478         struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
479         struct drm_display_mode *mode;
480         unsigned long max_size = 0;
481
482         if (adev->dm.dc->fbc_compressor == NULL)
483                 return;
484
485         if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
486                 return;
487
488         if (compressor->bo_ptr)
489                 return;
490
491
492         list_for_each_entry(mode, &connector->modes, head) {
493                 if (max_size < mode->htotal * mode->vtotal)
494                         max_size = mode->htotal * mode->vtotal;
495         }
496
497         if (max_size) {
498                 int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
499                             AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
500                             &compressor->gpu_addr, &compressor->cpu_addr);
501
502                 if (r)
503                         DRM_ERROR("DM: Failed to initialize FBC\n");
504                 else {
505                         adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
506                         DRM_INFO("DM: FBC alloc %lu\n", max_size*4);
507                 }
508
509         }
510
511 }
512
513 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
514                                           int pipe, bool *enabled,
515                                           unsigned char *buf, int max_bytes)
516 {
517         struct drm_device *dev = dev_get_drvdata(kdev);
518         struct amdgpu_device *adev = dev->dev_private;
519         struct drm_connector *connector;
520         struct drm_connector_list_iter conn_iter;
521         struct amdgpu_dm_connector *aconnector;
522         int ret = 0;
523
524         *enabled = false;
525
526         mutex_lock(&adev->dm.audio_lock);
527
528         drm_connector_list_iter_begin(dev, &conn_iter);
529         drm_for_each_connector_iter(connector, &conn_iter) {
530                 aconnector = to_amdgpu_dm_connector(connector);
531                 if (aconnector->audio_inst != port)
532                         continue;
533
534                 *enabled = true;
535                 ret = drm_eld_size(connector->eld);
536                 memcpy(buf, connector->eld, min(max_bytes, ret));
537
538                 break;
539         }
540         drm_connector_list_iter_end(&conn_iter);
541
542         mutex_unlock(&adev->dm.audio_lock);
543
544         DRM_DEBUG_KMS("Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
545
546         return ret;
547 }
548
549 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
550         .get_eld = amdgpu_dm_audio_component_get_eld,
551 };
552
553 static int amdgpu_dm_audio_component_bind(struct device *kdev,
554                                        struct device *hda_kdev, void *data)
555 {
556         struct drm_device *dev = dev_get_drvdata(kdev);
557         struct amdgpu_device *adev = dev->dev_private;
558         struct drm_audio_component *acomp = data;
559
560         acomp->ops = &amdgpu_dm_audio_component_ops;
561         acomp->dev = kdev;
562         adev->dm.audio_component = acomp;
563
564         return 0;
565 }
566
567 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
568                                           struct device *hda_kdev, void *data)
569 {
570         struct drm_device *dev = dev_get_drvdata(kdev);
571         struct amdgpu_device *adev = dev->dev_private;
572         struct drm_audio_component *acomp = data;
573
574         acomp->ops = NULL;
575         acomp->dev = NULL;
576         adev->dm.audio_component = NULL;
577 }
578
579 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
580         .bind   = amdgpu_dm_audio_component_bind,
581         .unbind = amdgpu_dm_audio_component_unbind,
582 };
583
584 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
585 {
586         int i, ret;
587
588         if (!amdgpu_audio)
589                 return 0;
590
591         adev->mode_info.audio.enabled = true;
592
593         adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
594
595         for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
596                 adev->mode_info.audio.pin[i].channels = -1;
597                 adev->mode_info.audio.pin[i].rate = -1;
598                 adev->mode_info.audio.pin[i].bits_per_sample = -1;
599                 adev->mode_info.audio.pin[i].status_bits = 0;
600                 adev->mode_info.audio.pin[i].category_code = 0;
601                 adev->mode_info.audio.pin[i].connected = false;
602                 adev->mode_info.audio.pin[i].id =
603                         adev->dm.dc->res_pool->audios[i]->inst;
604                 adev->mode_info.audio.pin[i].offset = 0;
605         }
606
607         ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
608         if (ret < 0)
609                 return ret;
610
611         adev->dm.audio_registered = true;
612
613         return 0;
614 }
615
616 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
617 {
618         if (!amdgpu_audio)
619                 return;
620
621         if (!adev->mode_info.audio.enabled)
622                 return;
623
624         if (adev->dm.audio_registered) {
625                 component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
626                 adev->dm.audio_registered = false;
627         }
628
629         /* TODO: Disable audio? */
630
631         adev->mode_info.audio.enabled = false;
632 }
633
634 void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
635 {
636         struct drm_audio_component *acomp = adev->dm.audio_component;
637
638         if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
639                 DRM_DEBUG_KMS("Notify ELD: %d\n", pin);
640
641                 acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
642                                                  pin, -1);
643         }
644 }
645
646 static int amdgpu_dm_init(struct amdgpu_device *adev)
647 {
648         struct dc_init_data init_data;
649         adev->dm.ddev = adev->ddev;
650         adev->dm.adev = adev;
651
652         /* Zero all the fields */
653         memset(&init_data, 0, sizeof(init_data));
654
655         mutex_init(&adev->dm.dc_lock);
656         mutex_init(&adev->dm.audio_lock);
657
658         if(amdgpu_dm_irq_init(adev)) {
659                 DRM_ERROR("amdgpu: failed to initialize DM IRQ support.\n");
660                 goto error;
661         }
662
663         init_data.asic_id.chip_family = adev->family;
664
665         init_data.asic_id.pci_revision_id = adev->rev_id;
666         init_data.asic_id.hw_internal_rev = adev->external_rev_id;
667
668         init_data.asic_id.vram_width = adev->gmc.vram_width;
669         /* TODO: initialize init_data.asic_id.vram_type here!!!! */
670         init_data.asic_id.atombios_base_address =
671                 adev->mode_info.atom_context->bios;
672
673         init_data.driver = adev;
674
675         adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
676
677         if (!adev->dm.cgs_device) {
678                 DRM_ERROR("amdgpu: failed to create cgs device.\n");
679                 goto error;
680         }
681
682         init_data.cgs_device = adev->dm.cgs_device;
683
684         init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
685
686         /*
687          * TODO debug why this doesn't work on Raven
688          */
689         if (adev->flags & AMD_IS_APU &&
690             adev->asic_type >= CHIP_CARRIZO &&
691             adev->asic_type < CHIP_RAVEN)
692                 init_data.flags.gpu_vm_support = true;
693
694         if (amdgpu_dc_feature_mask & DC_FBC_MASK)
695                 init_data.flags.fbc_support = true;
696
697         init_data.flags.power_down_display_on_boot = true;
698
699 #ifdef CONFIG_DRM_AMD_DC_DCN2_0
700         init_data.soc_bounding_box = adev->dm.soc_bounding_box;
701 #endif
702
703         /* Display Core create. */
704         adev->dm.dc = dc_create(&init_data);
705
706         if (adev->dm.dc) {
707                 DRM_INFO("Display Core initialized with v%s!\n", DC_VER);
708         } else {
709                 DRM_INFO("Display Core failed to initialize with v%s!\n", DC_VER);
710                 goto error;
711         }
712
713         adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
714         if (!adev->dm.freesync_module) {
715                 DRM_ERROR(
716                 "amdgpu: failed to initialize freesync_module.\n");
717         } else
718                 DRM_DEBUG_DRIVER("amdgpu: freesync_module init done %p.\n",
719                                 adev->dm.freesync_module);
720
721         amdgpu_dm_init_color_mod();
722
723         if (amdgpu_dm_initialize_drm_device(adev)) {
724                 DRM_ERROR(
725                 "amdgpu: failed to initialize sw for display support.\n");
726                 goto error;
727         }
728
729         /* Update the actual used number of crtc */
730         adev->mode_info.num_crtc = adev->dm.display_indexes_num;
731
732         /* TODO: Add_display_info? */
733
734         /* TODO use dynamic cursor width */
735         adev->ddev->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
736         adev->ddev->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
737
738         if (drm_vblank_init(adev->ddev, adev->dm.display_indexes_num)) {
739                 DRM_ERROR(
740                 "amdgpu: failed to initialize sw for display support.\n");
741                 goto error;
742         }
743
744 #if defined(CONFIG_DEBUG_FS)
745         if (dtn_debugfs_init(adev))
746                 DRM_ERROR("amdgpu: failed initialize dtn debugfs support.\n");
747 #endif
748
749         DRM_DEBUG_DRIVER("KMS initialized.\n");
750
751         return 0;
752 error:
753         amdgpu_dm_fini(adev);
754
755         return -EINVAL;
756 }
757
758 static void amdgpu_dm_fini(struct amdgpu_device *adev)
759 {
760         amdgpu_dm_audio_fini(adev);
761
762         amdgpu_dm_destroy_drm_device(&adev->dm);
763
764         /* DC Destroy TODO: Replace destroy DAL */
765         if (adev->dm.dc)
766                 dc_destroy(&adev->dm.dc);
767         /*
768          * TODO: pageflip, vlank interrupt
769          *
770          * amdgpu_dm_irq_fini(adev);
771          */
772
773         if (adev->dm.cgs_device) {
774                 amdgpu_cgs_destroy_device(adev->dm.cgs_device);
775                 adev->dm.cgs_device = NULL;
776         }
777         if (adev->dm.freesync_module) {
778                 mod_freesync_destroy(adev->dm.freesync_module);
779                 adev->dm.freesync_module = NULL;
780         }
781
782         mutex_destroy(&adev->dm.audio_lock);
783         mutex_destroy(&adev->dm.dc_lock);
784
785         return;
786 }
787
788 static int load_dmcu_fw(struct amdgpu_device *adev)
789 {
790         const char *fw_name_dmcu = NULL;
791         int r;
792         const struct dmcu_firmware_header_v1_0 *hdr;
793
794         switch(adev->asic_type) {
795         case CHIP_BONAIRE:
796         case CHIP_HAWAII:
797         case CHIP_KAVERI:
798         case CHIP_KABINI:
799         case CHIP_MULLINS:
800         case CHIP_TONGA:
801         case CHIP_FIJI:
802         case CHIP_CARRIZO:
803         case CHIP_STONEY:
804         case CHIP_POLARIS11:
805         case CHIP_POLARIS10:
806         case CHIP_POLARIS12:
807         case CHIP_VEGAM:
808         case CHIP_VEGA10:
809         case CHIP_VEGA12:
810         case CHIP_VEGA20:
811         case CHIP_NAVI10:
812                 return 0;
813         case CHIP_RAVEN:
814                 if (ASICREV_IS_PICASSO(adev->external_rev_id))
815                         fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
816                 else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
817                         fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
818                 else
819                         return 0;
820                 break;
821         default:
822                 DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
823                 return -EINVAL;
824         }
825
826         if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
827                 DRM_DEBUG_KMS("dm: DMCU firmware not supported on direct or SMU loading\n");
828                 return 0;
829         }
830
831         r = request_firmware_direct(&adev->dm.fw_dmcu, fw_name_dmcu, adev->dev);
832         if (r == -ENOENT) {
833                 /* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
834                 DRM_DEBUG_KMS("dm: DMCU firmware not found\n");
835                 adev->dm.fw_dmcu = NULL;
836                 return 0;
837         }
838         if (r) {
839                 dev_err(adev->dev, "amdgpu_dm: Can't load firmware \"%s\"\n",
840                         fw_name_dmcu);
841                 return r;
842         }
843
844         r = amdgpu_ucode_validate(adev->dm.fw_dmcu);
845         if (r) {
846                 dev_err(adev->dev, "amdgpu_dm: Can't validate firmware \"%s\"\n",
847                         fw_name_dmcu);
848                 release_firmware(adev->dm.fw_dmcu);
849                 adev->dm.fw_dmcu = NULL;
850                 return r;
851         }
852
853         hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
854         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
855         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
856         adev->firmware.fw_size +=
857                 ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
858
859         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
860         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
861         adev->firmware.fw_size +=
862                 ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
863
864         adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
865
866         DRM_DEBUG_KMS("PSP loading DMCU firmware\n");
867
868         return 0;
869 }
870
871 static int dm_sw_init(void *handle)
872 {
873         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
874
875         return load_dmcu_fw(adev);
876 }
877
878 static int dm_sw_fini(void *handle)
879 {
880         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
881
882         if(adev->dm.fw_dmcu) {
883                 release_firmware(adev->dm.fw_dmcu);
884                 adev->dm.fw_dmcu = NULL;
885         }
886
887         return 0;
888 }
889
890 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
891 {
892         struct amdgpu_dm_connector *aconnector;
893         struct drm_connector *connector;
894         int ret = 0;
895
896         drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
897
898         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
899                 aconnector = to_amdgpu_dm_connector(connector);
900                 if (aconnector->dc_link->type == dc_connection_mst_branch &&
901                     aconnector->mst_mgr.aux) {
902                         DRM_DEBUG_DRIVER("DM_MST: starting TM on aconnector: %p [id: %d]\n",
903                                         aconnector, aconnector->base.base.id);
904
905                         ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
906                         if (ret < 0) {
907                                 DRM_ERROR("DM_MST: Failed to start MST\n");
908                                 ((struct dc_link *)aconnector->dc_link)->type = dc_connection_single;
909                                 return ret;
910                                 }
911                         }
912         }
913
914         drm_modeset_unlock(&dev->mode_config.connection_mutex);
915         return ret;
916 }
917
918 static int dm_late_init(void *handle)
919 {
920         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
921
922         struct dmcu_iram_parameters params;
923         unsigned int linear_lut[16];
924         int i;
925         struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
926         bool ret = false;
927
928         for (i = 0; i < 16; i++)
929                 linear_lut[i] = 0xFFFF * i / 15;
930
931         params.set = 0;
932         params.backlight_ramping_start = 0xCCCC;
933         params.backlight_ramping_reduction = 0xCCCCCCCC;
934         params.backlight_lut_array_size = 16;
935         params.backlight_lut_array = linear_lut;
936
937         /* todo will enable for navi10 */
938         if (adev->asic_type <= CHIP_RAVEN) {
939                 ret = dmcu_load_iram(dmcu, params);
940
941                 if (!ret)
942                         return -EINVAL;
943         }
944
945         return detect_mst_link_for_all_connectors(adev->ddev);
946 }
947
948 static void s3_handle_mst(struct drm_device *dev, bool suspend)
949 {
950         struct amdgpu_dm_connector *aconnector;
951         struct drm_connector *connector;
952         struct drm_dp_mst_topology_mgr *mgr;
953         int ret;
954         bool need_hotplug = false;
955
956         drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
957
958         list_for_each_entry(connector, &dev->mode_config.connector_list,
959                             head) {
960                 aconnector = to_amdgpu_dm_connector(connector);
961                 if (aconnector->dc_link->type != dc_connection_mst_branch ||
962                     aconnector->mst_port)
963                         continue;
964
965                 mgr = &aconnector->mst_mgr;
966
967                 if (suspend) {
968                         drm_dp_mst_topology_mgr_suspend(mgr);
969                 } else {
970                         ret = drm_dp_mst_topology_mgr_resume(mgr);
971                         if (ret < 0) {
972                                 drm_dp_mst_topology_mgr_set_mst(mgr, false);
973                                 need_hotplug = true;
974                         }
975                 }
976         }
977
978         drm_modeset_unlock(&dev->mode_config.connection_mutex);
979
980         if (need_hotplug)
981                 drm_kms_helper_hotplug_event(dev);
982 }
983
984 /**
985  * dm_hw_init() - Initialize DC device
986  * @handle: The base driver device containing the amdpgu_dm device.
987  *
988  * Initialize the &struct amdgpu_display_manager device. This involves calling
989  * the initializers of each DM component, then populating the struct with them.
990  *
991  * Although the function implies hardware initialization, both hardware and
992  * software are initialized here. Splitting them out to their relevant init
993  * hooks is a future TODO item.
994  *
995  * Some notable things that are initialized here:
996  *
997  * - Display Core, both software and hardware
998  * - DC modules that we need (freesync and color management)
999  * - DRM software states
1000  * - Interrupt sources and handlers
1001  * - Vblank support
1002  * - Debug FS entries, if enabled
1003  */
1004 static int dm_hw_init(void *handle)
1005 {
1006         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
1007         /* Create DAL display manager */
1008         amdgpu_dm_init(adev);
1009         amdgpu_dm_hpd_init(adev);
1010
1011         return 0;
1012 }
1013
1014 /**
1015  * dm_hw_fini() - Teardown DC device
1016  * @handle: The base driver device containing the amdpgu_dm device.
1017  *
1018  * Teardown components within &struct amdgpu_display_manager that require
1019  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
1020  * were loaded. Also flush IRQ workqueues and disable them.
1021  */
1022 static int dm_hw_fini(void *handle)
1023 {
1024         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
1025
1026         amdgpu_dm_hpd_fini(adev);
1027
1028         amdgpu_dm_irq_fini(adev);
1029         amdgpu_dm_fini(adev);
1030         return 0;
1031 }
1032
1033 static int dm_suspend(void *handle)
1034 {
1035         struct amdgpu_device *adev = handle;
1036         struct amdgpu_display_manager *dm = &adev->dm;
1037         int ret = 0;
1038
1039         WARN_ON(adev->dm.cached_state);
1040         adev->dm.cached_state = drm_atomic_helper_suspend(adev->ddev);
1041
1042         s3_handle_mst(adev->ddev, true);
1043
1044         amdgpu_dm_irq_suspend(adev);
1045
1046
1047         dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
1048
1049         return ret;
1050 }
1051
1052 static struct amdgpu_dm_connector *
1053 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
1054                                              struct drm_crtc *crtc)
1055 {
1056         uint32_t i;
1057         struct drm_connector_state *new_con_state;
1058         struct drm_connector *connector;
1059         struct drm_crtc *crtc_from_state;
1060
1061         for_each_new_connector_in_state(state, connector, new_con_state, i) {
1062                 crtc_from_state = new_con_state->crtc;
1063
1064                 if (crtc_from_state == crtc)
1065                         return to_amdgpu_dm_connector(connector);
1066         }
1067
1068         return NULL;
1069 }
1070
1071 static void emulated_link_detect(struct dc_link *link)
1072 {
1073         struct dc_sink_init_data sink_init_data = { 0 };
1074         struct display_sink_capability sink_caps = { 0 };
1075         enum dc_edid_status edid_status;
1076         struct dc_context *dc_ctx = link->ctx;
1077         struct dc_sink *sink = NULL;
1078         struct dc_sink *prev_sink = NULL;
1079
1080         link->type = dc_connection_none;
1081         prev_sink = link->local_sink;
1082
1083         if (prev_sink != NULL)
1084                 dc_sink_retain(prev_sink);
1085
1086         switch (link->connector_signal) {
1087         case SIGNAL_TYPE_HDMI_TYPE_A: {
1088                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1089                 sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
1090                 break;
1091         }
1092
1093         case SIGNAL_TYPE_DVI_SINGLE_LINK: {
1094                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1095                 sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
1096                 break;
1097         }
1098
1099         case SIGNAL_TYPE_DVI_DUAL_LINK: {
1100                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1101                 sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
1102                 break;
1103         }
1104
1105         case SIGNAL_TYPE_LVDS: {
1106                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1107                 sink_caps.signal = SIGNAL_TYPE_LVDS;
1108                 break;
1109         }
1110
1111         case SIGNAL_TYPE_EDP: {
1112                 sink_caps.transaction_type =
1113                         DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
1114                 sink_caps.signal = SIGNAL_TYPE_EDP;
1115                 break;
1116         }
1117
1118         case SIGNAL_TYPE_DISPLAY_PORT: {
1119                 sink_caps.transaction_type =
1120                         DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
1121                 sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
1122                 break;
1123         }
1124
1125         default:
1126                 DC_ERROR("Invalid connector type! signal:%d\n",
1127                         link->connector_signal);
1128                 return;
1129         }
1130
1131         sink_init_data.link = link;
1132         sink_init_data.sink_signal = sink_caps.signal;
1133
1134         sink = dc_sink_create(&sink_init_data);
1135         if (!sink) {
1136                 DC_ERROR("Failed to create sink!\n");
1137                 return;
1138         }
1139
1140         /* dc_sink_create returns a new reference */
1141         link->local_sink = sink;
1142
1143         edid_status = dm_helpers_read_local_edid(
1144                         link->ctx,
1145                         link,
1146                         sink);
1147
1148         if (edid_status != EDID_OK)
1149                 DC_ERROR("Failed to read EDID");
1150
1151 }
1152
1153 static int dm_resume(void *handle)
1154 {
1155         struct amdgpu_device *adev = handle;
1156         struct drm_device *ddev = adev->ddev;
1157         struct amdgpu_display_manager *dm = &adev->dm;
1158         struct amdgpu_dm_connector *aconnector;
1159         struct drm_connector *connector;
1160         struct drm_crtc *crtc;
1161         struct drm_crtc_state *new_crtc_state;
1162         struct dm_crtc_state *dm_new_crtc_state;
1163         struct drm_plane *plane;
1164         struct drm_plane_state *new_plane_state;
1165         struct dm_plane_state *dm_new_plane_state;
1166         struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
1167         enum dc_connection_type new_connection_type = dc_connection_none;
1168         int i;
1169
1170         /* Recreate dc_state - DC invalidates it when setting power state to S3. */
1171         dc_release_state(dm_state->context);
1172         dm_state->context = dc_create_state(dm->dc);
1173         /* TODO: Remove dc_state->dccg, use dc->dccg directly. */
1174         dc_resource_state_construct(dm->dc, dm_state->context);
1175
1176         /* power on hardware */
1177         dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
1178
1179         /* program HPD filter */
1180         dc_resume(dm->dc);
1181
1182         /* On resume we need to  rewrite the MSTM control bits to enamble MST*/
1183         s3_handle_mst(ddev, false);
1184
1185         /*
1186          * early enable HPD Rx IRQ, should be done before set mode as short
1187          * pulse interrupts are used for MST
1188          */
1189         amdgpu_dm_irq_resume_early(adev);
1190
1191         /* Do detection*/
1192         list_for_each_entry(connector, &ddev->mode_config.connector_list, head) {
1193                 aconnector = to_amdgpu_dm_connector(connector);
1194
1195                 /*
1196                  * this is the case when traversing through already created
1197                  * MST connectors, should be skipped
1198                  */
1199                 if (aconnector->mst_port)
1200                         continue;
1201
1202                 mutex_lock(&aconnector->hpd_lock);
1203                 if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
1204                         DRM_ERROR("KMS: Failed to detect connector\n");
1205
1206                 if (aconnector->base.force && new_connection_type == dc_connection_none)
1207                         emulated_link_detect(aconnector->dc_link);
1208                 else
1209                         dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
1210
1211                 if (aconnector->fake_enable && aconnector->dc_link->local_sink)
1212                         aconnector->fake_enable = false;
1213
1214                 if (aconnector->dc_sink)
1215                         dc_sink_release(aconnector->dc_sink);
1216                 aconnector->dc_sink = NULL;
1217                 amdgpu_dm_update_connector_after_detect(aconnector);
1218                 mutex_unlock(&aconnector->hpd_lock);
1219         }
1220
1221         /* Force mode set in atomic commit */
1222         for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i)
1223                 new_crtc_state->active_changed = true;
1224
1225         /*
1226          * atomic_check is expected to create the dc states. We need to release
1227          * them here, since they were duplicated as part of the suspend
1228          * procedure.
1229          */
1230         for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
1231                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
1232                 if (dm_new_crtc_state->stream) {
1233                         WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
1234                         dc_stream_release(dm_new_crtc_state->stream);
1235                         dm_new_crtc_state->stream = NULL;
1236                 }
1237         }
1238
1239         for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
1240                 dm_new_plane_state = to_dm_plane_state(new_plane_state);
1241                 if (dm_new_plane_state->dc_state) {
1242                         WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
1243                         dc_plane_state_release(dm_new_plane_state->dc_state);
1244                         dm_new_plane_state->dc_state = NULL;
1245                 }
1246         }
1247
1248         drm_atomic_helper_resume(ddev, dm->cached_state);
1249
1250         dm->cached_state = NULL;
1251
1252         amdgpu_dm_irq_resume_late(adev);
1253
1254         return 0;
1255 }
1256
1257 /**
1258  * DOC: DM Lifecycle
1259  *
1260  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
1261  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
1262  * the base driver's device list to be initialized and torn down accordingly.
1263  *
1264  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
1265  */
1266
1267 static const struct amd_ip_funcs amdgpu_dm_funcs = {
1268         .name = "dm",
1269         .early_init = dm_early_init,
1270         .late_init = dm_late_init,
1271         .sw_init = dm_sw_init,
1272         .sw_fini = dm_sw_fini,
1273         .hw_init = dm_hw_init,
1274         .hw_fini = dm_hw_fini,
1275         .suspend = dm_suspend,
1276         .resume = dm_resume,
1277         .is_idle = dm_is_idle,
1278         .wait_for_idle = dm_wait_for_idle,
1279         .check_soft_reset = dm_check_soft_reset,
1280         .soft_reset = dm_soft_reset,
1281         .set_clockgating_state = dm_set_clockgating_state,
1282         .set_powergating_state = dm_set_powergating_state,
1283 };
1284
1285 const struct amdgpu_ip_block_version dm_ip_block =
1286 {
1287         .type = AMD_IP_BLOCK_TYPE_DCE,
1288         .major = 1,
1289         .minor = 0,
1290         .rev = 0,
1291         .funcs = &amdgpu_dm_funcs,
1292 };
1293
1294
1295 /**
1296  * DOC: atomic
1297  *
1298  * *WIP*
1299  */
1300
1301 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
1302         .fb_create = amdgpu_display_user_framebuffer_create,
1303         .output_poll_changed = drm_fb_helper_output_poll_changed,
1304         .atomic_check = amdgpu_dm_atomic_check,
1305         .atomic_commit = amdgpu_dm_atomic_commit,
1306 };
1307
1308 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
1309         .atomic_commit_tail = amdgpu_dm_atomic_commit_tail
1310 };
1311
1312 static void
1313 amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector)
1314 {
1315         struct drm_connector *connector = &aconnector->base;
1316         struct drm_device *dev = connector->dev;
1317         struct dc_sink *sink;
1318
1319         /* MST handled by drm_mst framework */
1320         if (aconnector->mst_mgr.mst_state == true)
1321                 return;
1322
1323
1324         sink = aconnector->dc_link->local_sink;
1325         if (sink)
1326                 dc_sink_retain(sink);
1327
1328         /*
1329          * Edid mgmt connector gets first update only in mode_valid hook and then
1330          * the connector sink is set to either fake or physical sink depends on link status.
1331          * Skip if already done during boot.
1332          */
1333         if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
1334                         && aconnector->dc_em_sink) {
1335
1336                 /*
1337                  * For S3 resume with headless use eml_sink to fake stream
1338                  * because on resume connector->sink is set to NULL
1339                  */
1340                 mutex_lock(&dev->mode_config.mutex);
1341
1342                 if (sink) {
1343                         if (aconnector->dc_sink) {
1344                                 amdgpu_dm_update_freesync_caps(connector, NULL);
1345                                 /*
1346                                  * retain and release below are used to
1347                                  * bump up refcount for sink because the link doesn't point
1348                                  * to it anymore after disconnect, so on next crtc to connector
1349                                  * reshuffle by UMD we will get into unwanted dc_sink release
1350                                  */
1351                                 dc_sink_release(aconnector->dc_sink);
1352                         }
1353                         aconnector->dc_sink = sink;
1354                         dc_sink_retain(aconnector->dc_sink);
1355                         amdgpu_dm_update_freesync_caps(connector,
1356                                         aconnector->edid);
1357                 } else {
1358                         amdgpu_dm_update_freesync_caps(connector, NULL);
1359                         if (!aconnector->dc_sink) {
1360                                 aconnector->dc_sink = aconnector->dc_em_sink;
1361                                 dc_sink_retain(aconnector->dc_sink);
1362                         }
1363                 }
1364
1365                 mutex_unlock(&dev->mode_config.mutex);
1366
1367                 if (sink)
1368                         dc_sink_release(sink);
1369                 return;
1370         }
1371
1372         /*
1373          * TODO: temporary guard to look for proper fix
1374          * if this sink is MST sink, we should not do anything
1375          */
1376         if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
1377                 dc_sink_release(sink);
1378                 return;
1379         }
1380
1381         if (aconnector->dc_sink == sink) {
1382                 /*
1383                  * We got a DP short pulse (Link Loss, DP CTS, etc...).
1384                  * Do nothing!!
1385                  */
1386                 DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: dc_sink didn't change.\n",
1387                                 aconnector->connector_id);
1388                 if (sink)
1389                         dc_sink_release(sink);
1390                 return;
1391         }
1392
1393         DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
1394                 aconnector->connector_id, aconnector->dc_sink, sink);
1395
1396         mutex_lock(&dev->mode_config.mutex);
1397
1398         /*
1399          * 1. Update status of the drm connector
1400          * 2. Send an event and let userspace tell us what to do
1401          */
1402         if (sink) {
1403                 /*
1404                  * TODO: check if we still need the S3 mode update workaround.
1405                  * If yes, put it here.
1406                  */
1407                 if (aconnector->dc_sink)
1408                         amdgpu_dm_update_freesync_caps(connector, NULL);
1409
1410                 aconnector->dc_sink = sink;
1411                 dc_sink_retain(aconnector->dc_sink);
1412                 if (sink->dc_edid.length == 0) {
1413                         aconnector->edid = NULL;
1414                         drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
1415                 } else {
1416                         aconnector->edid =
1417                                 (struct edid *) sink->dc_edid.raw_edid;
1418
1419
1420                         drm_connector_update_edid_property(connector,
1421                                         aconnector->edid);
1422                         drm_dp_cec_set_edid(&aconnector->dm_dp_aux.aux,
1423                                             aconnector->edid);
1424                 }
1425                 amdgpu_dm_update_freesync_caps(connector, aconnector->edid);
1426
1427         } else {
1428                 drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
1429                 amdgpu_dm_update_freesync_caps(connector, NULL);
1430                 drm_connector_update_edid_property(connector, NULL);
1431                 aconnector->num_modes = 0;
1432                 dc_sink_release(aconnector->dc_sink);
1433                 aconnector->dc_sink = NULL;
1434                 aconnector->edid = NULL;
1435         }
1436
1437         mutex_unlock(&dev->mode_config.mutex);
1438
1439         if (sink)
1440                 dc_sink_release(sink);
1441 }
1442
1443 static void handle_hpd_irq(void *param)
1444 {
1445         struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
1446         struct drm_connector *connector = &aconnector->base;
1447         struct drm_device *dev = connector->dev;
1448         enum dc_connection_type new_connection_type = dc_connection_none;
1449
1450         /*
1451          * In case of failure or MST no need to update connector status or notify the OS
1452          * since (for MST case) MST does this in its own context.
1453          */
1454         mutex_lock(&aconnector->hpd_lock);
1455
1456         if (aconnector->fake_enable)
1457                 aconnector->fake_enable = false;
1458
1459         if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
1460                 DRM_ERROR("KMS: Failed to detect connector\n");
1461
1462         if (aconnector->base.force && new_connection_type == dc_connection_none) {
1463                 emulated_link_detect(aconnector->dc_link);
1464
1465
1466                 drm_modeset_lock_all(dev);
1467                 dm_restore_drm_connector_state(dev, connector);
1468                 drm_modeset_unlock_all(dev);
1469
1470                 if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
1471                         drm_kms_helper_hotplug_event(dev);
1472
1473         } else if (dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD)) {
1474                 amdgpu_dm_update_connector_after_detect(aconnector);
1475
1476
1477                 drm_modeset_lock_all(dev);
1478                 dm_restore_drm_connector_state(dev, connector);
1479                 drm_modeset_unlock_all(dev);
1480
1481                 if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
1482                         drm_kms_helper_hotplug_event(dev);
1483         }
1484         mutex_unlock(&aconnector->hpd_lock);
1485
1486 }
1487
1488 static void dm_handle_hpd_rx_irq(struct amdgpu_dm_connector *aconnector)
1489 {
1490         uint8_t esi[DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI] = { 0 };
1491         uint8_t dret;
1492         bool new_irq_handled = false;
1493         int dpcd_addr;
1494         int dpcd_bytes_to_read;
1495
1496         const int max_process_count = 30;
1497         int process_count = 0;
1498
1499         const struct dc_link_status *link_status = dc_link_get_status(aconnector->dc_link);
1500
1501         if (link_status->dpcd_caps->dpcd_rev.raw < 0x12) {
1502                 dpcd_bytes_to_read = DP_LANE0_1_STATUS - DP_SINK_COUNT;
1503                 /* DPCD 0x200 - 0x201 for downstream IRQ */
1504                 dpcd_addr = DP_SINK_COUNT;
1505         } else {
1506                 dpcd_bytes_to_read = DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI;
1507                 /* DPCD 0x2002 - 0x2005 for downstream IRQ */
1508                 dpcd_addr = DP_SINK_COUNT_ESI;
1509         }
1510
1511         dret = drm_dp_dpcd_read(
1512                 &aconnector->dm_dp_aux.aux,
1513                 dpcd_addr,
1514                 esi,
1515                 dpcd_bytes_to_read);
1516
1517         while (dret == dpcd_bytes_to_read &&
1518                 process_count < max_process_count) {
1519                 uint8_t retry;
1520                 dret = 0;
1521
1522                 process_count++;
1523
1524                 DRM_DEBUG_DRIVER("ESI %02x %02x %02x\n", esi[0], esi[1], esi[2]);
1525                 /* handle HPD short pulse irq */
1526                 if (aconnector->mst_mgr.mst_state)
1527                         drm_dp_mst_hpd_irq(
1528                                 &aconnector->mst_mgr,
1529                                 esi,
1530                                 &new_irq_handled);
1531
1532                 if (new_irq_handled) {
1533                         /* ACK at DPCD to notify down stream */
1534                         const int ack_dpcd_bytes_to_write =
1535                                 dpcd_bytes_to_read - 1;
1536
1537                         for (retry = 0; retry < 3; retry++) {
1538                                 uint8_t wret;
1539
1540                                 wret = drm_dp_dpcd_write(
1541                                         &aconnector->dm_dp_aux.aux,
1542                                         dpcd_addr + 1,
1543                                         &esi[1],
1544                                         ack_dpcd_bytes_to_write);
1545                                 if (wret == ack_dpcd_bytes_to_write)
1546                                         break;
1547                         }
1548
1549                         /* check if there is new irq to be handled */
1550                         dret = drm_dp_dpcd_read(
1551                                 &aconnector->dm_dp_aux.aux,
1552                                 dpcd_addr,
1553                                 esi,
1554                                 dpcd_bytes_to_read);
1555
1556                         new_irq_handled = false;
1557                 } else {
1558                         break;
1559                 }
1560         }
1561
1562         if (process_count == max_process_count)
1563                 DRM_DEBUG_DRIVER("Loop exceeded max iterations\n");
1564 }
1565
1566 static void handle_hpd_rx_irq(void *param)
1567 {
1568         struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
1569         struct drm_connector *connector = &aconnector->base;
1570         struct drm_device *dev = connector->dev;
1571         struct dc_link *dc_link = aconnector->dc_link;
1572         bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
1573         enum dc_connection_type new_connection_type = dc_connection_none;
1574
1575         /*
1576          * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
1577          * conflict, after implement i2c helper, this mutex should be
1578          * retired.
1579          */
1580         if (dc_link->type != dc_connection_mst_branch)
1581                 mutex_lock(&aconnector->hpd_lock);
1582
1583         if (dc_link_handle_hpd_rx_irq(dc_link, NULL, NULL) &&
1584                         !is_mst_root_connector) {
1585                 /* Downstream Port status changed. */
1586                 if (!dc_link_detect_sink(dc_link, &new_connection_type))
1587                         DRM_ERROR("KMS: Failed to detect connector\n");
1588
1589                 if (aconnector->base.force && new_connection_type == dc_connection_none) {
1590                         emulated_link_detect(dc_link);
1591
1592                         if (aconnector->fake_enable)
1593                                 aconnector->fake_enable = false;
1594
1595                         amdgpu_dm_update_connector_after_detect(aconnector);
1596
1597
1598                         drm_modeset_lock_all(dev);
1599                         dm_restore_drm_connector_state(dev, connector);
1600                         drm_modeset_unlock_all(dev);
1601
1602                         drm_kms_helper_hotplug_event(dev);
1603                 } else if (dc_link_detect(dc_link, DETECT_REASON_HPDRX)) {
1604
1605                         if (aconnector->fake_enable)
1606                                 aconnector->fake_enable = false;
1607
1608                         amdgpu_dm_update_connector_after_detect(aconnector);
1609
1610
1611                         drm_modeset_lock_all(dev);
1612                         dm_restore_drm_connector_state(dev, connector);
1613                         drm_modeset_unlock_all(dev);
1614
1615                         drm_kms_helper_hotplug_event(dev);
1616                 }
1617         }
1618         if ((dc_link->cur_link_settings.lane_count != LANE_COUNT_UNKNOWN) ||
1619             (dc_link->type == dc_connection_mst_branch))
1620                 dm_handle_hpd_rx_irq(aconnector);
1621
1622         if (dc_link->type != dc_connection_mst_branch) {
1623                 drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
1624                 mutex_unlock(&aconnector->hpd_lock);
1625         }
1626 }
1627
1628 static void register_hpd_handlers(struct amdgpu_device *adev)
1629 {
1630         struct drm_device *dev = adev->ddev;
1631         struct drm_connector *connector;
1632         struct amdgpu_dm_connector *aconnector;
1633         const struct dc_link *dc_link;
1634         struct dc_interrupt_params int_params = {0};
1635
1636         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1637         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1638
1639         list_for_each_entry(connector,
1640                         &dev->mode_config.connector_list, head) {
1641
1642                 aconnector = to_amdgpu_dm_connector(connector);
1643                 dc_link = aconnector->dc_link;
1644
1645                 if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd) {
1646                         int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1647                         int_params.irq_source = dc_link->irq_source_hpd;
1648
1649                         amdgpu_dm_irq_register_interrupt(adev, &int_params,
1650                                         handle_hpd_irq,
1651                                         (void *) aconnector);
1652                 }
1653
1654                 if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd_rx) {
1655
1656                         /* Also register for DP short pulse (hpd_rx). */
1657                         int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1658                         int_params.irq_source = dc_link->irq_source_hpd_rx;
1659
1660                         amdgpu_dm_irq_register_interrupt(adev, &int_params,
1661                                         handle_hpd_rx_irq,
1662                                         (void *) aconnector);
1663                 }
1664         }
1665 }
1666
1667 /* Register IRQ sources and initialize IRQ callbacks */
1668 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
1669 {
1670         struct dc *dc = adev->dm.dc;
1671         struct common_irq_params *c_irq_params;
1672         struct dc_interrupt_params int_params = {0};
1673         int r;
1674         int i;
1675         unsigned client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
1676
1677         if (adev->asic_type >= CHIP_VEGA10)
1678                 client_id = SOC15_IH_CLIENTID_DCE;
1679
1680         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1681         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1682
1683         /*
1684          * Actions of amdgpu_irq_add_id():
1685          * 1. Register a set() function with base driver.
1686          *    Base driver will call set() function to enable/disable an
1687          *    interrupt in DC hardware.
1688          * 2. Register amdgpu_dm_irq_handler().
1689          *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1690          *    coming from DC hardware.
1691          *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1692          *    for acknowledging and handling. */
1693
1694         /* Use VBLANK interrupt */
1695         for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
1696                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
1697                 if (r) {
1698                         DRM_ERROR("Failed to add crtc irq id!\n");
1699                         return r;
1700                 }
1701
1702                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1703                 int_params.irq_source =
1704                         dc_interrupt_to_irq_source(dc, i, 0);
1705
1706                 c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1707
1708                 c_irq_params->adev = adev;
1709                 c_irq_params->irq_src = int_params.irq_source;
1710
1711                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1712                                 dm_crtc_high_irq, c_irq_params);
1713         }
1714
1715         /* Use VUPDATE interrupt */
1716         for (i = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT; i <= VISLANDS30_IV_SRCID_D6_V_UPDATE_INT; i += 2) {
1717                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->vupdate_irq);
1718                 if (r) {
1719                         DRM_ERROR("Failed to add vupdate irq id!\n");
1720                         return r;
1721                 }
1722
1723                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1724                 int_params.irq_source =
1725                         dc_interrupt_to_irq_source(dc, i, 0);
1726
1727                 c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
1728
1729                 c_irq_params->adev = adev;
1730                 c_irq_params->irq_src = int_params.irq_source;
1731
1732                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1733                                 dm_vupdate_high_irq, c_irq_params);
1734         }
1735
1736         /* Use GRPH_PFLIP interrupt */
1737         for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
1738                         i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
1739                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
1740                 if (r) {
1741                         DRM_ERROR("Failed to add page flip irq id!\n");
1742                         return r;
1743                 }
1744
1745                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1746                 int_params.irq_source =
1747                         dc_interrupt_to_irq_source(dc, i, 0);
1748
1749                 c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1750
1751                 c_irq_params->adev = adev;
1752                 c_irq_params->irq_src = int_params.irq_source;
1753
1754                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1755                                 dm_pflip_high_irq, c_irq_params);
1756
1757         }
1758
1759         /* HPD */
1760         r = amdgpu_irq_add_id(adev, client_id,
1761                         VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
1762         if (r) {
1763                 DRM_ERROR("Failed to add hpd irq id!\n");
1764                 return r;
1765         }
1766
1767         register_hpd_handlers(adev);
1768
1769         return 0;
1770 }
1771
1772 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
1773 /* Register IRQ sources and initialize IRQ callbacks */
1774 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
1775 {
1776         struct dc *dc = adev->dm.dc;
1777         struct common_irq_params *c_irq_params;
1778         struct dc_interrupt_params int_params = {0};
1779         int r;
1780         int i;
1781
1782         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1783         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1784
1785         /*
1786          * Actions of amdgpu_irq_add_id():
1787          * 1. Register a set() function with base driver.
1788          *    Base driver will call set() function to enable/disable an
1789          *    interrupt in DC hardware.
1790          * 2. Register amdgpu_dm_irq_handler().
1791          *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1792          *    coming from DC hardware.
1793          *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1794          *    for acknowledging and handling.
1795          */
1796
1797         /* Use VSTARTUP interrupt */
1798         for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
1799                         i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
1800                         i++) {
1801                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
1802
1803                 if (r) {
1804                         DRM_ERROR("Failed to add crtc irq id!\n");
1805                         return r;
1806                 }
1807
1808                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1809                 int_params.irq_source =
1810                         dc_interrupt_to_irq_source(dc, i, 0);
1811
1812                 c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1813
1814                 c_irq_params->adev = adev;
1815                 c_irq_params->irq_src = int_params.irq_source;
1816
1817                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1818                                 dm_crtc_high_irq, c_irq_params);
1819         }
1820
1821         /* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
1822          * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
1823          * to trigger at end of each vblank, regardless of state of the lock,
1824          * matching DCE behaviour.
1825          */
1826         for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
1827              i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
1828              i++) {
1829                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
1830
1831                 if (r) {
1832                         DRM_ERROR("Failed to add vupdate irq id!\n");
1833                         return r;
1834                 }
1835
1836                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1837                 int_params.irq_source =
1838                         dc_interrupt_to_irq_source(dc, i, 0);
1839
1840                 c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
1841
1842                 c_irq_params->adev = adev;
1843                 c_irq_params->irq_src = int_params.irq_source;
1844
1845                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1846                                 dm_vupdate_high_irq, c_irq_params);
1847         }
1848
1849         /* Use GRPH_PFLIP interrupt */
1850         for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
1851                         i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + adev->mode_info.num_crtc - 1;
1852                         i++) {
1853                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
1854                 if (r) {
1855                         DRM_ERROR("Failed to add page flip irq id!\n");
1856                         return r;
1857                 }
1858
1859                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1860                 int_params.irq_source =
1861                         dc_interrupt_to_irq_source(dc, i, 0);
1862
1863                 c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1864
1865                 c_irq_params->adev = adev;
1866                 c_irq_params->irq_src = int_params.irq_source;
1867
1868                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1869                                 dm_pflip_high_irq, c_irq_params);
1870
1871         }
1872
1873         /* HPD */
1874         r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
1875                         &adev->hpd_irq);
1876         if (r) {
1877                 DRM_ERROR("Failed to add hpd irq id!\n");
1878                 return r;
1879         }
1880
1881         register_hpd_handlers(adev);
1882
1883         return 0;
1884 }
1885 #endif
1886
1887 /*
1888  * Acquires the lock for the atomic state object and returns
1889  * the new atomic state.
1890  *
1891  * This should only be called during atomic check.
1892  */
1893 static int dm_atomic_get_state(struct drm_atomic_state *state,
1894                                struct dm_atomic_state **dm_state)
1895 {
1896         struct drm_device *dev = state->dev;
1897         struct amdgpu_device *adev = dev->dev_private;
1898         struct amdgpu_display_manager *dm = &adev->dm;
1899         struct drm_private_state *priv_state;
1900
1901         if (*dm_state)
1902                 return 0;
1903
1904         priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
1905         if (IS_ERR(priv_state))
1906                 return PTR_ERR(priv_state);
1907
1908         *dm_state = to_dm_atomic_state(priv_state);
1909
1910         return 0;
1911 }
1912
1913 struct dm_atomic_state *
1914 dm_atomic_get_new_state(struct drm_atomic_state *state)
1915 {
1916         struct drm_device *dev = state->dev;
1917         struct amdgpu_device *adev = dev->dev_private;
1918         struct amdgpu_display_manager *dm = &adev->dm;
1919         struct drm_private_obj *obj;
1920         struct drm_private_state *new_obj_state;
1921         int i;
1922
1923         for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
1924                 if (obj->funcs == dm->atomic_obj.funcs)
1925                         return to_dm_atomic_state(new_obj_state);
1926         }
1927
1928         return NULL;
1929 }
1930
1931 struct dm_atomic_state *
1932 dm_atomic_get_old_state(struct drm_atomic_state *state)
1933 {
1934         struct drm_device *dev = state->dev;
1935         struct amdgpu_device *adev = dev->dev_private;
1936         struct amdgpu_display_manager *dm = &adev->dm;
1937         struct drm_private_obj *obj;
1938         struct drm_private_state *old_obj_state;
1939         int i;
1940
1941         for_each_old_private_obj_in_state(state, obj, old_obj_state, i) {
1942                 if (obj->funcs == dm->atomic_obj.funcs)
1943                         return to_dm_atomic_state(old_obj_state);
1944         }
1945
1946         return NULL;
1947 }
1948
1949 static struct drm_private_state *
1950 dm_atomic_duplicate_state(struct drm_private_obj *obj)
1951 {
1952         struct dm_atomic_state *old_state, *new_state;
1953
1954         new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
1955         if (!new_state)
1956                 return NULL;
1957
1958         __drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
1959
1960         old_state = to_dm_atomic_state(obj->state);
1961
1962         if (old_state && old_state->context)
1963                 new_state->context = dc_copy_state(old_state->context);
1964
1965         if (!new_state->context) {
1966                 kfree(new_state);
1967                 return NULL;
1968         }
1969
1970         return &new_state->base;
1971 }
1972
1973 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
1974                                     struct drm_private_state *state)
1975 {
1976         struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
1977
1978         if (dm_state && dm_state->context)
1979                 dc_release_state(dm_state->context);
1980
1981         kfree(dm_state);
1982 }
1983
1984 static struct drm_private_state_funcs dm_atomic_state_funcs = {
1985         .atomic_duplicate_state = dm_atomic_duplicate_state,
1986         .atomic_destroy_state = dm_atomic_destroy_state,
1987 };
1988
1989 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
1990 {
1991         struct dm_atomic_state *state;
1992         int r;
1993
1994         adev->mode_info.mode_config_initialized = true;
1995
1996         adev->ddev->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
1997         adev->ddev->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
1998
1999         adev->ddev->mode_config.max_width = 16384;
2000         adev->ddev->mode_config.max_height = 16384;
2001
2002         adev->ddev->mode_config.preferred_depth = 24;
2003         adev->ddev->mode_config.prefer_shadow = 1;
2004         /* indicates support for immediate flip */
2005         adev->ddev->mode_config.async_page_flip = true;
2006
2007         adev->ddev->mode_config.fb_base = adev->gmc.aper_base;
2008
2009         state = kzalloc(sizeof(*state), GFP_KERNEL);
2010         if (!state)
2011                 return -ENOMEM;
2012
2013         state->context = dc_create_state(adev->dm.dc);
2014         if (!state->context) {
2015                 kfree(state);
2016                 return -ENOMEM;
2017         }
2018
2019         dc_resource_state_copy_construct_current(adev->dm.dc, state->context);
2020
2021         drm_atomic_private_obj_init(adev->ddev,
2022                                     &adev->dm.atomic_obj,
2023                                     &state->base,
2024                                     &dm_atomic_state_funcs);
2025
2026         r = amdgpu_display_modeset_create_props(adev);
2027         if (r)
2028                 return r;
2029
2030         r = amdgpu_dm_audio_init(adev);
2031         if (r)
2032                 return r;
2033
2034         return 0;
2035 }
2036
2037 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
2038 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
2039
2040 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
2041         defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
2042
2043 static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm)
2044 {
2045 #if defined(CONFIG_ACPI)
2046         struct amdgpu_dm_backlight_caps caps;
2047
2048         if (dm->backlight_caps.caps_valid)
2049                 return;
2050
2051         amdgpu_acpi_get_backlight_caps(dm->adev, &caps);
2052         if (caps.caps_valid) {
2053                 dm->backlight_caps.min_input_signal = caps.min_input_signal;
2054                 dm->backlight_caps.max_input_signal = caps.max_input_signal;
2055                 dm->backlight_caps.caps_valid = true;
2056         } else {
2057                 dm->backlight_caps.min_input_signal =
2058                                 AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
2059                 dm->backlight_caps.max_input_signal =
2060                                 AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
2061         }
2062 #else
2063         dm->backlight_caps.min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
2064         dm->backlight_caps.max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
2065 #endif
2066 }
2067
2068 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
2069 {
2070         struct amdgpu_display_manager *dm = bl_get_data(bd);
2071         struct amdgpu_dm_backlight_caps caps;
2072         uint32_t brightness = bd->props.brightness;
2073
2074         amdgpu_dm_update_backlight_caps(dm);
2075         caps = dm->backlight_caps;
2076         /*
2077          * The brightness input is in the range 0-255
2078          * It needs to be rescaled to be between the
2079          * requested min and max input signal
2080          *
2081          * It also needs to be scaled up by 0x101 to
2082          * match the DC interface which has a range of
2083          * 0 to 0xffff
2084          */
2085         brightness =
2086                 brightness
2087                 * 0x101
2088                 * (caps.max_input_signal - caps.min_input_signal)
2089                 / AMDGPU_MAX_BL_LEVEL
2090                 + caps.min_input_signal * 0x101;
2091
2092         if (dc_link_set_backlight_level(dm->backlight_link,
2093                         brightness, 0))
2094                 return 0;
2095         else
2096                 return 1;
2097 }
2098
2099 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
2100 {
2101         struct amdgpu_display_manager *dm = bl_get_data(bd);
2102         int ret = dc_link_get_backlight_level(dm->backlight_link);
2103
2104         if (ret == DC_ERROR_UNEXPECTED)
2105                 return bd->props.brightness;
2106         return ret;
2107 }
2108
2109 static const struct backlight_ops amdgpu_dm_backlight_ops = {
2110         .get_brightness = amdgpu_dm_backlight_get_brightness,
2111         .update_status  = amdgpu_dm_backlight_update_status,
2112 };
2113
2114 static void
2115 amdgpu_dm_register_backlight_device(struct amdgpu_display_manager *dm)
2116 {
2117         char bl_name[16];
2118         struct backlight_properties props = { 0 };
2119
2120         amdgpu_dm_update_backlight_caps(dm);
2121
2122         props.max_brightness = AMDGPU_MAX_BL_LEVEL;
2123         props.brightness = AMDGPU_MAX_BL_LEVEL;
2124         props.type = BACKLIGHT_RAW;
2125
2126         snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
2127                         dm->adev->ddev->primary->index);
2128
2129         dm->backlight_dev = backlight_device_register(bl_name,
2130                         dm->adev->ddev->dev,
2131                         dm,
2132                         &amdgpu_dm_backlight_ops,
2133                         &props);
2134
2135         if (IS_ERR(dm->backlight_dev))
2136                 DRM_ERROR("DM: Backlight registration failed!\n");
2137         else
2138                 DRM_DEBUG_DRIVER("DM: Registered Backlight device: %s\n", bl_name);
2139 }
2140
2141 #endif
2142
2143 static int initialize_plane(struct amdgpu_display_manager *dm,
2144                             struct amdgpu_mode_info *mode_info, int plane_id,
2145                             enum drm_plane_type plane_type,
2146                             const struct dc_plane_cap *plane_cap)
2147 {
2148         struct drm_plane *plane;
2149         unsigned long possible_crtcs;
2150         int ret = 0;
2151
2152         plane = kzalloc(sizeof(struct drm_plane), GFP_KERNEL);
2153         if (!plane) {
2154                 DRM_ERROR("KMS: Failed to allocate plane\n");
2155                 return -ENOMEM;
2156         }
2157         plane->type = plane_type;
2158
2159         /*
2160          * HACK: IGT tests expect that the primary plane for a CRTC
2161          * can only have one possible CRTC. Only expose support for
2162          * any CRTC if they're not going to be used as a primary plane
2163          * for a CRTC - like overlay or underlay planes.
2164          */
2165         possible_crtcs = 1 << plane_id;
2166         if (plane_id >= dm->dc->caps.max_streams)
2167                 possible_crtcs = 0xff;
2168
2169         ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
2170
2171         if (ret) {
2172                 DRM_ERROR("KMS: Failed to initialize plane\n");
2173                 kfree(plane);
2174                 return ret;
2175         }
2176
2177         if (mode_info)
2178                 mode_info->planes[plane_id] = plane;
2179
2180         return ret;
2181 }
2182
2183
2184 static void register_backlight_device(struct amdgpu_display_manager *dm,
2185                                       struct dc_link *link)
2186 {
2187 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
2188         defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
2189
2190         if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
2191             link->type != dc_connection_none) {
2192                 /*
2193                  * Event if registration failed, we should continue with
2194                  * DM initialization because not having a backlight control
2195                  * is better then a black screen.
2196                  */
2197                 amdgpu_dm_register_backlight_device(dm);
2198
2199                 if (dm->backlight_dev)
2200                         dm->backlight_link = link;
2201         }
2202 #endif
2203 }
2204
2205
2206 /*
2207  * In this architecture, the association
2208  * connector -> encoder -> crtc
2209  * id not really requried. The crtc and connector will hold the
2210  * display_index as an abstraction to use with DAL component
2211  *
2212  * Returns 0 on success
2213  */
2214 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
2215 {
2216         struct amdgpu_display_manager *dm = &adev->dm;
2217         int32_t i;
2218         struct amdgpu_dm_connector *aconnector = NULL;
2219         struct amdgpu_encoder *aencoder = NULL;
2220         struct amdgpu_mode_info *mode_info = &adev->mode_info;
2221         uint32_t link_cnt;
2222         int32_t primary_planes;
2223         enum dc_connection_type new_connection_type = dc_connection_none;
2224         const struct dc_plane_cap *plane;
2225
2226         link_cnt = dm->dc->caps.max_links;
2227         if (amdgpu_dm_mode_config_init(dm->adev)) {
2228                 DRM_ERROR("DM: Failed to initialize mode config\n");
2229                 return -EINVAL;
2230         }
2231
2232         /* There is one primary plane per CRTC */
2233         primary_planes = dm->dc->caps.max_streams;
2234         ASSERT(primary_planes <= AMDGPU_MAX_PLANES);
2235
2236         /*
2237          * Initialize primary planes, implicit planes for legacy IOCTLS.
2238          * Order is reversed to match iteration order in atomic check.
2239          */
2240         for (i = (primary_planes - 1); i >= 0; i--) {
2241                 plane = &dm->dc->caps.planes[i];
2242
2243                 if (initialize_plane(dm, mode_info, i,
2244                                      DRM_PLANE_TYPE_PRIMARY, plane)) {
2245                         DRM_ERROR("KMS: Failed to initialize primary plane\n");
2246                         goto fail;
2247                 }
2248         }
2249
2250         /*
2251          * Initialize overlay planes, index starting after primary planes.
2252          * These planes have a higher DRM index than the primary planes since
2253          * they should be considered as having a higher z-order.
2254          * Order is reversed to match iteration order in atomic check.
2255          *
2256          * Only support DCN for now, and only expose one so we don't encourage
2257          * userspace to use up all the pipes.
2258          */
2259         for (i = 0; i < dm->dc->caps.max_planes; ++i) {
2260                 struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
2261
2262                 if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
2263                         continue;
2264
2265                 if (!plane->blends_with_above || !plane->blends_with_below)
2266                         continue;
2267
2268                 if (!plane->pixel_format_support.argb8888)
2269                         continue;
2270
2271                 if (initialize_plane(dm, NULL, primary_planes + i,
2272                                      DRM_PLANE_TYPE_OVERLAY, plane)) {
2273                         DRM_ERROR("KMS: Failed to initialize overlay plane\n");
2274                         goto fail;
2275                 }
2276
2277                 /* Only create one overlay plane. */
2278                 break;
2279         }
2280
2281         for (i = 0; i < dm->dc->caps.max_streams; i++)
2282                 if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
2283                         DRM_ERROR("KMS: Failed to initialize crtc\n");
2284                         goto fail;
2285                 }
2286
2287         dm->display_indexes_num = dm->dc->caps.max_streams;
2288
2289         /* loops over all connectors on the board */
2290         for (i = 0; i < link_cnt; i++) {
2291                 struct dc_link *link = NULL;
2292
2293                 if (i > AMDGPU_DM_MAX_DISPLAY_INDEX) {
2294                         DRM_ERROR(
2295                                 "KMS: Cannot support more than %d display indexes\n",
2296                                         AMDGPU_DM_MAX_DISPLAY_INDEX);
2297                         continue;
2298                 }
2299
2300                 aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
2301                 if (!aconnector)
2302                         goto fail;
2303
2304                 aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
2305                 if (!aencoder)
2306                         goto fail;
2307
2308                 if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
2309                         DRM_ERROR("KMS: Failed to initialize encoder\n");
2310                         goto fail;
2311                 }
2312
2313                 if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
2314                         DRM_ERROR("KMS: Failed to initialize connector\n");
2315                         goto fail;
2316                 }
2317
2318                 link = dc_get_link_at_index(dm->dc, i);
2319
2320                 if (!dc_link_detect_sink(link, &new_connection_type))
2321                         DRM_ERROR("KMS: Failed to detect connector\n");
2322
2323                 if (aconnector->base.force && new_connection_type == dc_connection_none) {
2324                         emulated_link_detect(link);
2325                         amdgpu_dm_update_connector_after_detect(aconnector);
2326
2327                 } else if (dc_link_detect(link, DETECT_REASON_BOOT)) {
2328                         amdgpu_dm_update_connector_after_detect(aconnector);
2329                         register_backlight_device(dm, link);
2330                 }
2331
2332
2333         }
2334
2335         /* Software is initialized. Now we can register interrupt handlers. */
2336         switch (adev->asic_type) {
2337         case CHIP_BONAIRE:
2338         case CHIP_HAWAII:
2339         case CHIP_KAVERI:
2340         case CHIP_KABINI:
2341         case CHIP_MULLINS:
2342         case CHIP_TONGA:
2343         case CHIP_FIJI:
2344         case CHIP_CARRIZO:
2345         case CHIP_STONEY:
2346         case CHIP_POLARIS11:
2347         case CHIP_POLARIS10:
2348         case CHIP_POLARIS12:
2349         case CHIP_VEGAM:
2350         case CHIP_VEGA10:
2351         case CHIP_VEGA12:
2352         case CHIP_VEGA20:
2353                 if (dce110_register_irq_handlers(dm->adev)) {
2354                         DRM_ERROR("DM: Failed to initialize IRQ\n");
2355                         goto fail;
2356                 }
2357                 break;
2358 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
2359         case CHIP_RAVEN:
2360 #if defined(CONFIG_DRM_AMD_DC_DCN2_0)
2361         case CHIP_NAVI10:
2362 #endif
2363                 if (dcn10_register_irq_handlers(dm->adev)) {
2364                         DRM_ERROR("DM: Failed to initialize IRQ\n");
2365                         goto fail;
2366                 }
2367                 break;
2368 #endif
2369         default:
2370                 DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
2371                 goto fail;
2372         }
2373
2374         if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2375                 dm->dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2376
2377         return 0;
2378 fail:
2379         kfree(aencoder);
2380         kfree(aconnector);
2381
2382         return -EINVAL;
2383 }
2384
2385 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
2386 {
2387         drm_mode_config_cleanup(dm->ddev);
2388         drm_atomic_private_obj_fini(&dm->atomic_obj);
2389         return;
2390 }
2391
2392 /******************************************************************************
2393  * amdgpu_display_funcs functions
2394  *****************************************************************************/
2395
2396 /*
2397  * dm_bandwidth_update - program display watermarks
2398  *
2399  * @adev: amdgpu_device pointer
2400  *
2401  * Calculate and program the display watermarks and line buffer allocation.
2402  */
2403 static void dm_bandwidth_update(struct amdgpu_device *adev)
2404 {
2405         /* TODO: implement later */
2406 }
2407
2408 static const struct amdgpu_display_funcs dm_display_funcs = {
2409         .bandwidth_update = dm_bandwidth_update, /* called unconditionally */
2410         .vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
2411         .backlight_set_level = NULL, /* never called for DC */
2412         .backlight_get_level = NULL, /* never called for DC */
2413         .hpd_sense = NULL,/* called unconditionally */
2414         .hpd_set_polarity = NULL, /* called unconditionally */
2415         .hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
2416         .page_flip_get_scanoutpos =
2417                 dm_crtc_get_scanoutpos,/* called unconditionally */
2418         .add_encoder = NULL, /* VBIOS parsing. DAL does it. */
2419         .add_connector = NULL, /* VBIOS parsing. DAL does it. */
2420 };
2421
2422 #if defined(CONFIG_DEBUG_KERNEL_DC)
2423
2424 static ssize_t s3_debug_store(struct device *device,
2425                               struct device_attribute *attr,
2426                               const char *buf,
2427                               size_t count)
2428 {
2429         int ret;
2430         int s3_state;
2431         struct pci_dev *pdev = to_pci_dev(device);
2432         struct drm_device *drm_dev = pci_get_drvdata(pdev);
2433         struct amdgpu_device *adev = drm_dev->dev_private;
2434
2435         ret = kstrtoint(buf, 0, &s3_state);
2436
2437         if (ret == 0) {
2438                 if (s3_state) {
2439                         dm_resume(adev);
2440                         drm_kms_helper_hotplug_event(adev->ddev);
2441                 } else
2442                         dm_suspend(adev);
2443         }
2444
2445         return ret == 0 ? count : 0;
2446 }
2447
2448 DEVICE_ATTR_WO(s3_debug);
2449
2450 #endif
2451
2452 static int dm_early_init(void *handle)
2453 {
2454         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2455
2456         switch (adev->asic_type) {
2457         case CHIP_BONAIRE:
2458         case CHIP_HAWAII:
2459                 adev->mode_info.num_crtc = 6;
2460                 adev->mode_info.num_hpd = 6;
2461                 adev->mode_info.num_dig = 6;
2462                 break;
2463         case CHIP_KAVERI:
2464                 adev->mode_info.num_crtc = 4;
2465                 adev->mode_info.num_hpd = 6;
2466                 adev->mode_info.num_dig = 7;
2467                 break;
2468         case CHIP_KABINI:
2469         case CHIP_MULLINS:
2470                 adev->mode_info.num_crtc = 2;
2471                 adev->mode_info.num_hpd = 6;
2472                 adev->mode_info.num_dig = 6;
2473                 break;
2474         case CHIP_FIJI:
2475         case CHIP_TONGA:
2476                 adev->mode_info.num_crtc = 6;
2477                 adev->mode_info.num_hpd = 6;
2478                 adev->mode_info.num_dig = 7;
2479                 break;
2480         case CHIP_CARRIZO:
2481                 adev->mode_info.num_crtc = 3;
2482                 adev->mode_info.num_hpd = 6;
2483                 adev->mode_info.num_dig = 9;
2484                 break;
2485         case CHIP_STONEY:
2486                 adev->mode_info.num_crtc = 2;
2487                 adev->mode_info.num_hpd = 6;
2488                 adev->mode_info.num_dig = 9;
2489                 break;
2490         case CHIP_POLARIS11:
2491         case CHIP_POLARIS12:
2492                 adev->mode_info.num_crtc = 5;
2493                 adev->mode_info.num_hpd = 5;
2494                 adev->mode_info.num_dig = 5;
2495                 break;
2496         case CHIP_POLARIS10:
2497         case CHIP_VEGAM:
2498                 adev->mode_info.num_crtc = 6;
2499                 adev->mode_info.num_hpd = 6;
2500                 adev->mode_info.num_dig = 6;
2501                 break;
2502         case CHIP_VEGA10:
2503         case CHIP_VEGA12:
2504         case CHIP_VEGA20:
2505                 adev->mode_info.num_crtc = 6;
2506                 adev->mode_info.num_hpd = 6;
2507                 adev->mode_info.num_dig = 6;
2508                 break;
2509 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
2510         case CHIP_RAVEN:
2511                 adev->mode_info.num_crtc = 4;
2512                 adev->mode_info.num_hpd = 4;
2513                 adev->mode_info.num_dig = 4;
2514                 break;
2515 #endif
2516 #if defined(CONFIG_DRM_AMD_DC_DCN2_0)
2517         case CHIP_NAVI10:
2518                 adev->mode_info.num_crtc = 6;
2519                 adev->mode_info.num_hpd = 6;
2520                 adev->mode_info.num_dig = 6;
2521                 break;
2522 #endif
2523         default:
2524                 DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
2525                 return -EINVAL;
2526         }
2527
2528         amdgpu_dm_set_irq_funcs(adev);
2529
2530         if (adev->mode_info.funcs == NULL)
2531                 adev->mode_info.funcs = &dm_display_funcs;
2532
2533         /*
2534          * Note: Do NOT change adev->audio_endpt_rreg and
2535          * adev->audio_endpt_wreg because they are initialised in
2536          * amdgpu_device_init()
2537          */
2538 #if defined(CONFIG_DEBUG_KERNEL_DC)
2539         device_create_file(
2540                 adev->ddev->dev,
2541                 &dev_attr_s3_debug);
2542 #endif
2543
2544         return 0;
2545 }
2546
2547 static bool modeset_required(struct drm_crtc_state *crtc_state,
2548                              struct dc_stream_state *new_stream,
2549                              struct dc_stream_state *old_stream)
2550 {
2551         if (!drm_atomic_crtc_needs_modeset(crtc_state))
2552                 return false;
2553
2554         if (!crtc_state->enable)
2555                 return false;
2556
2557         return crtc_state->active;
2558 }
2559
2560 static bool modereset_required(struct drm_crtc_state *crtc_state)
2561 {
2562         if (!drm_atomic_crtc_needs_modeset(crtc_state))
2563                 return false;
2564
2565         return !crtc_state->enable || !crtc_state->active;
2566 }
2567
2568 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
2569 {
2570         drm_encoder_cleanup(encoder);
2571         kfree(encoder);
2572 }
2573
2574 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
2575         .destroy = amdgpu_dm_encoder_destroy,
2576 };
2577
2578
2579 static int fill_dc_scaling_info(const struct drm_plane_state *state,
2580                                 struct dc_scaling_info *scaling_info)
2581 {
2582         int scale_w, scale_h;
2583
2584         memset(scaling_info, 0, sizeof(*scaling_info));
2585
2586         /* Source is fixed 16.16 but we ignore mantissa for now... */
2587         scaling_info->src_rect.x = state->src_x >> 16;
2588         scaling_info->src_rect.y = state->src_y >> 16;
2589
2590         scaling_info->src_rect.width = state->src_w >> 16;
2591         if (scaling_info->src_rect.width == 0)
2592                 return -EINVAL;
2593
2594         scaling_info->src_rect.height = state->src_h >> 16;
2595         if (scaling_info->src_rect.height == 0)
2596                 return -EINVAL;
2597
2598         scaling_info->dst_rect.x = state->crtc_x;
2599         scaling_info->dst_rect.y = state->crtc_y;
2600
2601         if (state->crtc_w == 0)
2602                 return -EINVAL;
2603
2604         scaling_info->dst_rect.width = state->crtc_w;
2605
2606         if (state->crtc_h == 0)
2607                 return -EINVAL;
2608
2609         scaling_info->dst_rect.height = state->crtc_h;
2610
2611         /* DRM doesn't specify clipping on destination output. */
2612         scaling_info->clip_rect = scaling_info->dst_rect;
2613
2614         /* TODO: Validate scaling per-format with DC plane caps */
2615         scale_w = scaling_info->dst_rect.width * 1000 /
2616                   scaling_info->src_rect.width;
2617
2618         if (scale_w < 250 || scale_w > 16000)
2619                 return -EINVAL;
2620
2621         scale_h = scaling_info->dst_rect.height * 1000 /
2622                   scaling_info->src_rect.height;
2623
2624         if (scale_h < 250 || scale_h > 16000)
2625                 return -EINVAL;
2626
2627         /*
2628          * The "scaling_quality" can be ignored for now, quality = 0 has DC
2629          * assume reasonable defaults based on the format.
2630          */
2631
2632         return 0;
2633 }
2634
2635 static int get_fb_info(const struct amdgpu_framebuffer *amdgpu_fb,
2636                        uint64_t *tiling_flags)
2637 {
2638         struct amdgpu_bo *rbo = gem_to_amdgpu_bo(amdgpu_fb->base.obj[0]);
2639         int r = amdgpu_bo_reserve(rbo, false);
2640
2641         if (unlikely(r)) {
2642                 /* Don't show error message when returning -ERESTARTSYS */
2643                 if (r != -ERESTARTSYS)
2644                         DRM_ERROR("Unable to reserve buffer: %d\n", r);
2645                 return r;
2646         }
2647
2648         if (tiling_flags)
2649                 amdgpu_bo_get_tiling_flags(rbo, tiling_flags);
2650
2651         amdgpu_bo_unreserve(rbo);
2652
2653         return r;
2654 }
2655
2656 static inline uint64_t get_dcc_address(uint64_t address, uint64_t tiling_flags)
2657 {
2658         uint32_t offset = AMDGPU_TILING_GET(tiling_flags, DCC_OFFSET_256B);
2659
2660         return offset ? (address + offset * 256) : 0;
2661 }
2662
2663 static int
2664 fill_plane_dcc_attributes(struct amdgpu_device *adev,
2665                           const struct amdgpu_framebuffer *afb,
2666                           const enum surface_pixel_format format,
2667                           const enum dc_rotation_angle rotation,
2668                           const union plane_size *plane_size,
2669                           const union dc_tiling_info *tiling_info,
2670                           const uint64_t info,
2671                           struct dc_plane_dcc_param *dcc,
2672                           struct dc_plane_address *address)
2673 {
2674         struct dc *dc = adev->dm.dc;
2675         struct dc_dcc_surface_param input;
2676         struct dc_surface_dcc_cap output;
2677         uint32_t offset = AMDGPU_TILING_GET(info, DCC_OFFSET_256B);
2678         uint32_t i64b = AMDGPU_TILING_GET(info, DCC_INDEPENDENT_64B) != 0;
2679         uint64_t dcc_address;
2680
2681         memset(&input, 0, sizeof(input));
2682         memset(&output, 0, sizeof(output));
2683
2684         if (!offset)
2685                 return 0;
2686
2687         if (format >= SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
2688                 return 0;
2689
2690         if (!dc->cap_funcs.get_dcc_compression_cap)
2691                 return -EINVAL;
2692
2693         input.format = format;
2694         input.surface_size.width = plane_size->grph.surface_size.width;
2695         input.surface_size.height = plane_size->grph.surface_size.height;
2696         input.swizzle_mode = tiling_info->gfx9.swizzle;
2697
2698         if (rotation == ROTATION_ANGLE_0 || rotation == ROTATION_ANGLE_180)
2699                 input.scan = SCAN_DIRECTION_HORIZONTAL;
2700         else if (rotation == ROTATION_ANGLE_90 || rotation == ROTATION_ANGLE_270)
2701                 input.scan = SCAN_DIRECTION_VERTICAL;
2702
2703         if (!dc->cap_funcs.get_dcc_compression_cap(dc, &input, &output))
2704                 return -EINVAL;
2705
2706         if (!output.capable)
2707                 return -EINVAL;
2708
2709         if (i64b == 0 && output.grph.rgb.independent_64b_blks != 0)
2710                 return -EINVAL;
2711
2712         dcc->enable = 1;
2713         dcc->grph.meta_pitch =
2714                 AMDGPU_TILING_GET(info, DCC_PITCH_MAX) + 1;
2715         dcc->grph.independent_64b_blks = i64b;
2716
2717         dcc_address = get_dcc_address(afb->address, info);
2718         address->grph.meta_addr.low_part = lower_32_bits(dcc_address);
2719         address->grph.meta_addr.high_part = upper_32_bits(dcc_address);
2720
2721         return 0;
2722 }
2723
2724 static int
2725 fill_plane_buffer_attributes(struct amdgpu_device *adev,
2726                              const struct amdgpu_framebuffer *afb,
2727                              const enum surface_pixel_format format,
2728                              const enum dc_rotation_angle rotation,
2729                              const uint64_t tiling_flags,
2730                              union dc_tiling_info *tiling_info,
2731                              union plane_size *plane_size,
2732                              struct dc_plane_dcc_param *dcc,
2733                              struct dc_plane_address *address)
2734 {
2735         const struct drm_framebuffer *fb = &afb->base;
2736         int ret;
2737
2738         memset(tiling_info, 0, sizeof(*tiling_info));
2739         memset(plane_size, 0, sizeof(*plane_size));
2740         memset(dcc, 0, sizeof(*dcc));
2741         memset(address, 0, sizeof(*address));
2742
2743         if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN) {
2744                 plane_size->grph.surface_size.x = 0;
2745                 plane_size->grph.surface_size.y = 0;
2746                 plane_size->grph.surface_size.width = fb->width;
2747                 plane_size->grph.surface_size.height = fb->height;
2748                 plane_size->grph.surface_pitch =
2749                         fb->pitches[0] / fb->format->cpp[0];
2750
2751                 address->type = PLN_ADDR_TYPE_GRAPHICS;
2752                 address->grph.addr.low_part = lower_32_bits(afb->address);
2753                 address->grph.addr.high_part = upper_32_bits(afb->address);
2754         } else if (format < SURFACE_PIXEL_FORMAT_INVALID) {
2755                 uint64_t chroma_addr = afb->address + fb->offsets[1];
2756
2757                 plane_size->video.luma_size.x = 0;
2758                 plane_size->video.luma_size.y = 0;
2759                 plane_size->video.luma_size.width = fb->width;
2760                 plane_size->video.luma_size.height = fb->height;
2761                 plane_size->video.luma_pitch =
2762                         fb->pitches[0] / fb->format->cpp[0];
2763
2764                 plane_size->video.chroma_size.x = 0;
2765                 plane_size->video.chroma_size.y = 0;
2766                 /* TODO: set these based on surface format */
2767                 plane_size->video.chroma_size.width = fb->width / 2;
2768                 plane_size->video.chroma_size.height = fb->height / 2;
2769
2770                 plane_size->video.chroma_pitch =
2771                         fb->pitches[1] / fb->format->cpp[1];
2772
2773                 address->type = PLN_ADDR_TYPE_VIDEO_PROGRESSIVE;
2774                 address->video_progressive.luma_addr.low_part =
2775                         lower_32_bits(afb->address);
2776                 address->video_progressive.luma_addr.high_part =
2777                         upper_32_bits(afb->address);
2778                 address->video_progressive.chroma_addr.low_part =
2779                         lower_32_bits(chroma_addr);
2780                 address->video_progressive.chroma_addr.high_part =
2781                         upper_32_bits(chroma_addr);
2782         }
2783
2784         /* Fill GFX8 params */
2785         if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE) == DC_ARRAY_2D_TILED_THIN1) {
2786                 unsigned int bankw, bankh, mtaspect, tile_split, num_banks;
2787
2788                 bankw = AMDGPU_TILING_GET(tiling_flags, BANK_WIDTH);
2789                 bankh = AMDGPU_TILING_GET(tiling_flags, BANK_HEIGHT);
2790                 mtaspect = AMDGPU_TILING_GET(tiling_flags, MACRO_TILE_ASPECT);
2791                 tile_split = AMDGPU_TILING_GET(tiling_flags, TILE_SPLIT);
2792                 num_banks = AMDGPU_TILING_GET(tiling_flags, NUM_BANKS);
2793
2794                 /* XXX fix me for VI */
2795                 tiling_info->gfx8.num_banks = num_banks;
2796                 tiling_info->gfx8.array_mode =
2797                                 DC_ARRAY_2D_TILED_THIN1;
2798                 tiling_info->gfx8.tile_split = tile_split;
2799                 tiling_info->gfx8.bank_width = bankw;
2800                 tiling_info->gfx8.bank_height = bankh;
2801                 tiling_info->gfx8.tile_aspect = mtaspect;
2802                 tiling_info->gfx8.tile_mode =
2803                                 DC_ADDR_SURF_MICRO_TILING_DISPLAY;
2804         } else if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE)
2805                         == DC_ARRAY_1D_TILED_THIN1) {
2806                 tiling_info->gfx8.array_mode = DC_ARRAY_1D_TILED_THIN1;
2807         }
2808
2809         tiling_info->gfx8.pipe_config =
2810                         AMDGPU_TILING_GET(tiling_flags, PIPE_CONFIG);
2811
2812         if (adev->asic_type == CHIP_VEGA10 ||
2813             adev->asic_type == CHIP_VEGA12 ||
2814             adev->asic_type == CHIP_VEGA20 ||
2815 #if defined(CONFIG_DRM_AMD_DC_DCN2_0)
2816             adev->asic_type == CHIP_NAVI10 ||
2817 #endif
2818             adev->asic_type == CHIP_RAVEN) {
2819                 /* Fill GFX9 params */
2820                 tiling_info->gfx9.num_pipes =
2821                         adev->gfx.config.gb_addr_config_fields.num_pipes;
2822                 tiling_info->gfx9.num_banks =
2823                         adev->gfx.config.gb_addr_config_fields.num_banks;
2824                 tiling_info->gfx9.pipe_interleave =
2825                         adev->gfx.config.gb_addr_config_fields.pipe_interleave_size;
2826                 tiling_info->gfx9.num_shader_engines =
2827                         adev->gfx.config.gb_addr_config_fields.num_se;
2828                 tiling_info->gfx9.max_compressed_frags =
2829                         adev->gfx.config.gb_addr_config_fields.max_compress_frags;
2830                 tiling_info->gfx9.num_rb_per_se =
2831                         adev->gfx.config.gb_addr_config_fields.num_rb_per_se;
2832                 tiling_info->gfx9.swizzle =
2833                         AMDGPU_TILING_GET(tiling_flags, SWIZZLE_MODE);
2834                 tiling_info->gfx9.shaderEnable = 1;
2835
2836                 ret = fill_plane_dcc_attributes(adev, afb, format, rotation,
2837                                                 plane_size, tiling_info,
2838                                                 tiling_flags, dcc, address);
2839                 if (ret)
2840                         return ret;
2841         }
2842
2843         return 0;
2844 }
2845
2846 static void
2847 fill_blending_from_plane_state(const struct drm_plane_state *plane_state,
2848                                bool *per_pixel_alpha, bool *global_alpha,
2849                                int *global_alpha_value)
2850 {
2851         *per_pixel_alpha = false;
2852         *global_alpha = false;
2853         *global_alpha_value = 0xff;
2854
2855         if (plane_state->plane->type != DRM_PLANE_TYPE_OVERLAY)
2856                 return;
2857
2858         if (plane_state->pixel_blend_mode == DRM_MODE_BLEND_PREMULTI) {
2859                 static const uint32_t alpha_formats[] = {
2860                         DRM_FORMAT_ARGB8888,
2861                         DRM_FORMAT_RGBA8888,
2862                         DRM_FORMAT_ABGR8888,
2863                 };
2864                 uint32_t format = plane_state->fb->format->format;
2865                 unsigned int i;
2866
2867                 for (i = 0; i < ARRAY_SIZE(alpha_formats); ++i) {
2868                         if (format == alpha_formats[i]) {
2869                                 *per_pixel_alpha = true;
2870                                 break;
2871                         }
2872                 }
2873         }
2874
2875         if (plane_state->alpha < 0xffff) {
2876                 *global_alpha = true;
2877                 *global_alpha_value = plane_state->alpha >> 8;
2878         }
2879 }
2880
2881 static int
2882 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
2883                             const enum surface_pixel_format format,
2884                             enum dc_color_space *color_space)
2885 {
2886         bool full_range;
2887
2888         *color_space = COLOR_SPACE_SRGB;
2889
2890         /* DRM color properties only affect non-RGB formats. */
2891         if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
2892                 return 0;
2893
2894         full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
2895
2896         switch (plane_state->color_encoding) {
2897         case DRM_COLOR_YCBCR_BT601:
2898                 if (full_range)
2899                         *color_space = COLOR_SPACE_YCBCR601;
2900                 else
2901                         *color_space = COLOR_SPACE_YCBCR601_LIMITED;
2902                 break;
2903
2904         case DRM_COLOR_YCBCR_BT709:
2905                 if (full_range)
2906                         *color_space = COLOR_SPACE_YCBCR709;
2907                 else
2908                         *color_space = COLOR_SPACE_YCBCR709_LIMITED;
2909                 break;
2910
2911         case DRM_COLOR_YCBCR_BT2020:
2912                 if (full_range)
2913                         *color_space = COLOR_SPACE_2020_YCBCR;
2914                 else
2915                         return -EINVAL;
2916                 break;
2917
2918         default:
2919                 return -EINVAL;
2920         }
2921
2922         return 0;
2923 }
2924
2925 static int
2926 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
2927                             const struct drm_plane_state *plane_state,
2928                             const uint64_t tiling_flags,
2929                             struct dc_plane_info *plane_info,
2930                             struct dc_plane_address *address)
2931 {
2932         const struct drm_framebuffer *fb = plane_state->fb;
2933         const struct amdgpu_framebuffer *afb =
2934                 to_amdgpu_framebuffer(plane_state->fb);
2935         struct drm_format_name_buf format_name;
2936         int ret;
2937
2938         memset(plane_info, 0, sizeof(*plane_info));
2939
2940         switch (fb->format->format) {
2941         case DRM_FORMAT_C8:
2942                 plane_info->format =
2943                         SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
2944                 break;
2945         case DRM_FORMAT_RGB565:
2946                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
2947                 break;
2948         case DRM_FORMAT_XRGB8888:
2949         case DRM_FORMAT_ARGB8888:
2950                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
2951                 break;
2952         case DRM_FORMAT_XRGB2101010:
2953         case DRM_FORMAT_ARGB2101010:
2954                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
2955                 break;
2956         case DRM_FORMAT_XBGR2101010:
2957         case DRM_FORMAT_ABGR2101010:
2958                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
2959                 break;
2960         case DRM_FORMAT_XBGR8888:
2961         case DRM_FORMAT_ABGR8888:
2962                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
2963                 break;
2964         case DRM_FORMAT_NV21:
2965                 plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
2966                 break;
2967         case DRM_FORMAT_NV12:
2968                 plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
2969                 break;
2970         default:
2971                 DRM_ERROR(
2972                         "Unsupported screen format %s\n",
2973                         drm_get_format_name(fb->format->format, &format_name));
2974                 return -EINVAL;
2975         }
2976
2977         switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
2978         case DRM_MODE_ROTATE_0:
2979                 plane_info->rotation = ROTATION_ANGLE_0;
2980                 break;
2981         case DRM_MODE_ROTATE_90:
2982                 plane_info->rotation = ROTATION_ANGLE_90;
2983                 break;
2984         case DRM_MODE_ROTATE_180:
2985                 plane_info->rotation = ROTATION_ANGLE_180;
2986                 break;
2987         case DRM_MODE_ROTATE_270:
2988                 plane_info->rotation = ROTATION_ANGLE_270;
2989                 break;
2990         default:
2991                 plane_info->rotation = ROTATION_ANGLE_0;
2992                 break;
2993         }
2994
2995         plane_info->visible = true;
2996         plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
2997
2998         ret = fill_plane_color_attributes(plane_state, plane_info->format,
2999                                           &plane_info->color_space);
3000         if (ret)
3001                 return ret;
3002
3003         ret = fill_plane_buffer_attributes(adev, afb, plane_info->format,
3004                                            plane_info->rotation, tiling_flags,
3005                                            &plane_info->tiling_info,
3006                                            &plane_info->plane_size,
3007                                            &plane_info->dcc, address);
3008         if (ret)
3009                 return ret;
3010
3011         fill_blending_from_plane_state(
3012                 plane_state, &plane_info->per_pixel_alpha,
3013                 &plane_info->global_alpha, &plane_info->global_alpha_value);
3014
3015         return 0;
3016 }
3017
3018 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
3019                                     struct dc_plane_state *dc_plane_state,
3020                                     struct drm_plane_state *plane_state,
3021                                     struct drm_crtc_state *crtc_state)
3022 {
3023         struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
3024         const struct amdgpu_framebuffer *amdgpu_fb =
3025                 to_amdgpu_framebuffer(plane_state->fb);
3026         struct dc_scaling_info scaling_info;
3027         struct dc_plane_info plane_info;
3028         uint64_t tiling_flags;
3029         int ret;
3030
3031         ret = fill_dc_scaling_info(plane_state, &scaling_info);
3032         if (ret)
3033                 return ret;
3034
3035         dc_plane_state->src_rect = scaling_info.src_rect;
3036         dc_plane_state->dst_rect = scaling_info.dst_rect;
3037         dc_plane_state->clip_rect = scaling_info.clip_rect;
3038         dc_plane_state->scaling_quality = scaling_info.scaling_quality;
3039
3040         ret = get_fb_info(amdgpu_fb, &tiling_flags);
3041         if (ret)
3042                 return ret;
3043
3044         ret = fill_dc_plane_info_and_addr(adev, plane_state, tiling_flags,
3045                                           &plane_info,
3046                                           &dc_plane_state->address);
3047         if (ret)
3048                 return ret;
3049
3050         dc_plane_state->format = plane_info.format;
3051         dc_plane_state->color_space = plane_info.color_space;
3052         dc_plane_state->format = plane_info.format;
3053         dc_plane_state->plane_size = plane_info.plane_size;
3054         dc_plane_state->rotation = plane_info.rotation;
3055         dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
3056         dc_plane_state->stereo_format = plane_info.stereo_format;
3057         dc_plane_state->tiling_info = plane_info.tiling_info;
3058         dc_plane_state->visible = plane_info.visible;
3059         dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
3060         dc_plane_state->global_alpha = plane_info.global_alpha;
3061         dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
3062         dc_plane_state->dcc = plane_info.dcc;
3063
3064         /*
3065          * Always set input transfer function, since plane state is refreshed
3066          * every time.
3067          */
3068         ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state, dc_plane_state);
3069         if (ret)
3070                 return ret;
3071
3072         return 0;
3073 }
3074
3075 static void update_stream_scaling_settings(const struct drm_display_mode *mode,
3076                                            const struct dm_connector_state *dm_state,
3077                                            struct dc_stream_state *stream)
3078 {
3079         enum amdgpu_rmx_type rmx_type;
3080
3081         struct rect src = { 0 }; /* viewport in composition space*/
3082         struct rect dst = { 0 }; /* stream addressable area */
3083
3084         /* no mode. nothing to be done */
3085         if (!mode)
3086                 return;
3087
3088         /* Full screen scaling by default */
3089         src.width = mode->hdisplay;
3090         src.height = mode->vdisplay;
3091         dst.width = stream->timing.h_addressable;
3092         dst.height = stream->timing.v_addressable;
3093
3094         if (dm_state) {
3095                 rmx_type = dm_state->scaling;
3096                 if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
3097                         if (src.width * dst.height <
3098                                         src.height * dst.width) {
3099                                 /* height needs less upscaling/more downscaling */
3100                                 dst.width = src.width *
3101                                                 dst.height / src.height;
3102                         } else {
3103                                 /* width needs less upscaling/more downscaling */
3104                                 dst.height = src.height *
3105                                                 dst.width / src.width;
3106                         }
3107                 } else if (rmx_type == RMX_CENTER) {
3108                         dst = src;
3109                 }
3110
3111                 dst.x = (stream->timing.h_addressable - dst.width) / 2;
3112                 dst.y = (stream->timing.v_addressable - dst.height) / 2;
3113
3114                 if (dm_state->underscan_enable) {
3115                         dst.x += dm_state->underscan_hborder / 2;
3116                         dst.y += dm_state->underscan_vborder / 2;
3117                         dst.width -= dm_state->underscan_hborder;
3118                         dst.height -= dm_state->underscan_vborder;
3119                 }
3120         }
3121
3122         stream->src = src;
3123         stream->dst = dst;
3124
3125         DRM_DEBUG_DRIVER("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
3126                         dst.x, dst.y, dst.width, dst.height);
3127
3128 }
3129
3130 static enum dc_color_depth
3131 convert_color_depth_from_display_info(const struct drm_connector *connector,
3132                                       const struct drm_connector_state *state)
3133 {
3134         uint32_t bpc = connector->display_info.bpc;
3135
3136         if (!state)
3137                 state = connector->state;
3138
3139         if (state) {
3140                 bpc = state->max_bpc;
3141                 /* Round down to the nearest even number. */
3142                 bpc = bpc - (bpc & 1);
3143         }
3144
3145         switch (bpc) {
3146         case 0:
3147                 /*
3148                  * Temporary Work around, DRM doesn't parse color depth for
3149                  * EDID revision before 1.4
3150                  * TODO: Fix edid parsing
3151                  */
3152                 return COLOR_DEPTH_888;
3153         case 6:
3154                 return COLOR_DEPTH_666;
3155         case 8:
3156                 return COLOR_DEPTH_888;
3157         case 10:
3158                 return COLOR_DEPTH_101010;
3159         case 12:
3160                 return COLOR_DEPTH_121212;
3161         case 14:
3162                 return COLOR_DEPTH_141414;
3163         case 16:
3164                 return COLOR_DEPTH_161616;
3165         default:
3166                 return COLOR_DEPTH_UNDEFINED;
3167         }
3168 }
3169
3170 static enum dc_aspect_ratio
3171 get_aspect_ratio(const struct drm_display_mode *mode_in)
3172 {
3173         /* 1-1 mapping, since both enums follow the HDMI spec. */
3174         return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
3175 }
3176
3177 static enum dc_color_space
3178 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing)
3179 {
3180         enum dc_color_space color_space = COLOR_SPACE_SRGB;
3181
3182         switch (dc_crtc_timing->pixel_encoding) {
3183         case PIXEL_ENCODING_YCBCR422:
3184         case PIXEL_ENCODING_YCBCR444:
3185         case PIXEL_ENCODING_YCBCR420:
3186         {
3187                 /*
3188                  * 27030khz is the separation point between HDTV and SDTV
3189                  * according to HDMI spec, we use YCbCr709 and YCbCr601
3190                  * respectively
3191                  */
3192                 if (dc_crtc_timing->pix_clk_100hz > 270300) {
3193                         if (dc_crtc_timing->flags.Y_ONLY)
3194                                 color_space =
3195                                         COLOR_SPACE_YCBCR709_LIMITED;
3196                         else
3197                                 color_space = COLOR_SPACE_YCBCR709;
3198                 } else {
3199                         if (dc_crtc_timing->flags.Y_ONLY)
3200                                 color_space =
3201                                         COLOR_SPACE_YCBCR601_LIMITED;
3202                         else
3203                                 color_space = COLOR_SPACE_YCBCR601;
3204                 }
3205
3206         }
3207         break;
3208         case PIXEL_ENCODING_RGB:
3209                 color_space = COLOR_SPACE_SRGB;
3210                 break;
3211
3212         default:
3213                 WARN_ON(1);
3214                 break;
3215         }
3216
3217         return color_space;
3218 }
3219
3220 static void reduce_mode_colour_depth(struct dc_crtc_timing *timing_out)
3221 {
3222         if (timing_out->display_color_depth <= COLOR_DEPTH_888)
3223                 return;
3224
3225         timing_out->display_color_depth--;
3226 }
3227
3228 static void adjust_colour_depth_from_display_info(struct dc_crtc_timing *timing_out,
3229                                                 const struct drm_display_info *info)
3230 {
3231         int normalized_clk;
3232         if (timing_out->display_color_depth <= COLOR_DEPTH_888)
3233                 return;
3234         do {
3235                 normalized_clk = timing_out->pix_clk_100hz / 10;
3236                 /* YCbCr 4:2:0 requires additional adjustment of 1/2 */
3237                 if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
3238                         normalized_clk /= 2;
3239                 /* Adjusting pix clock following on HDMI spec based on colour depth */
3240                 switch (timing_out->display_color_depth) {
3241                 case COLOR_DEPTH_101010:
3242                         normalized_clk = (normalized_clk * 30) / 24;
3243                         break;
3244                 case COLOR_DEPTH_121212:
3245                         normalized_clk = (normalized_clk * 36) / 24;
3246                         break;
3247                 case COLOR_DEPTH_161616:
3248                         normalized_clk = (normalized_clk * 48) / 24;
3249                         break;
3250                 default:
3251                         return;
3252                 }
3253                 if (normalized_clk <= info->max_tmds_clock)
3254                         return;
3255                 reduce_mode_colour_depth(timing_out);
3256
3257         } while (timing_out->display_color_depth > COLOR_DEPTH_888);
3258
3259 }
3260
3261 static void fill_stream_properties_from_drm_display_mode(
3262         struct dc_stream_state *stream,
3263         const struct drm_display_mode *mode_in,
3264         const struct drm_connector *connector,
3265         const struct drm_connector_state *connector_state,
3266         const struct dc_stream_state *old_stream)
3267 {
3268         struct dc_crtc_timing *timing_out = &stream->timing;
3269         const struct drm_display_info *info = &connector->display_info;
3270
3271         memset(timing_out, 0, sizeof(struct dc_crtc_timing));
3272
3273         timing_out->h_border_left = 0;
3274         timing_out->h_border_right = 0;
3275         timing_out->v_border_top = 0;
3276         timing_out->v_border_bottom = 0;
3277         /* TODO: un-hardcode */
3278         if (drm_mode_is_420_only(info, mode_in)
3279                         && stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
3280                 timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
3281         else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCRCB444)
3282                         && stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
3283                 timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
3284         else
3285                 timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
3286
3287         timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
3288         timing_out->display_color_depth = convert_color_depth_from_display_info(
3289                 connector, connector_state);
3290         timing_out->scan_type = SCANNING_TYPE_NODATA;
3291         timing_out->hdmi_vic = 0;
3292
3293         if(old_stream) {
3294                 timing_out->vic = old_stream->timing.vic;
3295                 timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
3296                 timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
3297         } else {
3298                 timing_out->vic = drm_match_cea_mode(mode_in);
3299                 if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
3300                         timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
3301                 if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
3302                         timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
3303         }
3304
3305         timing_out->h_addressable = mode_in->crtc_hdisplay;
3306         timing_out->h_total = mode_in->crtc_htotal;
3307         timing_out->h_sync_width =
3308                 mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
3309         timing_out->h_front_porch =
3310                 mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
3311         timing_out->v_total = mode_in->crtc_vtotal;
3312         timing_out->v_addressable = mode_in->crtc_vdisplay;
3313         timing_out->v_front_porch =
3314                 mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
3315         timing_out->v_sync_width =
3316                 mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
3317         timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
3318         timing_out->aspect_ratio = get_aspect_ratio(mode_in);
3319
3320         stream->output_color_space = get_output_color_space(timing_out);
3321
3322         stream->out_transfer_func->type = TF_TYPE_PREDEFINED;
3323         stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
3324         if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
3325                 adjust_colour_depth_from_display_info(timing_out, info);
3326 }
3327
3328 static void fill_audio_info(struct audio_info *audio_info,
3329                             const struct drm_connector *drm_connector,
3330                             const struct dc_sink *dc_sink)
3331 {
3332         int i = 0;
3333         int cea_revision = 0;
3334         const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
3335
3336         audio_info->manufacture_id = edid_caps->manufacturer_id;
3337         audio_info->product_id = edid_caps->product_id;
3338
3339         cea_revision = drm_connector->display_info.cea_rev;
3340
3341         strscpy(audio_info->display_name,
3342                 edid_caps->display_name,
3343                 AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
3344
3345         if (cea_revision >= 3) {
3346                 audio_info->mode_count = edid_caps->audio_mode_count;
3347
3348                 for (i = 0; i < audio_info->mode_count; ++i) {
3349                         audio_info->modes[i].format_code =
3350                                         (enum audio_format_code)
3351                                         (edid_caps->audio_modes[i].format_code);
3352                         audio_info->modes[i].channel_count =
3353                                         edid_caps->audio_modes[i].channel_count;
3354                         audio_info->modes[i].sample_rates.all =
3355                                         edid_caps->audio_modes[i].sample_rate;
3356                         audio_info->modes[i].sample_size =
3357                                         edid_caps->audio_modes[i].sample_size;
3358                 }
3359         }
3360
3361         audio_info->flags.all = edid_caps->speaker_flags;
3362
3363         /* TODO: We only check for the progressive mode, check for interlace mode too */
3364         if (drm_connector->latency_present[0]) {
3365                 audio_info->video_latency = drm_connector->video_latency[0];
3366                 audio_info->audio_latency = drm_connector->audio_latency[0];
3367         }
3368
3369         /* TODO: For DP, video and audio latency should be calculated from DPCD caps */
3370
3371 }
3372
3373 static void
3374 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
3375                                       struct drm_display_mode *dst_mode)
3376 {
3377         dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
3378         dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
3379         dst_mode->crtc_clock = src_mode->crtc_clock;
3380         dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
3381         dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
3382         dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
3383         dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
3384         dst_mode->crtc_htotal = src_mode->crtc_htotal;
3385         dst_mode->crtc_hskew = src_mode->crtc_hskew;
3386         dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
3387         dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
3388         dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
3389         dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
3390         dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
3391 }
3392
3393 static void
3394 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
3395                                         const struct drm_display_mode *native_mode,
3396                                         bool scale_enabled)
3397 {
3398         if (scale_enabled) {
3399                 copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
3400         } else if (native_mode->clock == drm_mode->clock &&
3401                         native_mode->htotal == drm_mode->htotal &&
3402                         native_mode->vtotal == drm_mode->vtotal) {
3403                 copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
3404         } else {
3405                &nb