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