Merge tag 'armsoc-dt' of git://git.kernel.org/pub/scm/linux/kernel/git/arm/arm-soc
[linux-2.6-microblaze.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
335         acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
336
337         if (acrtc) {
338                 drm_crtc_handle_vblank(&acrtc->base);
339                 amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
340         }
341 }
342
343 static int dm_set_clockgating_state(void *handle,
344                   enum amd_clockgating_state state)
345 {
346         return 0;
347 }
348
349 static int dm_set_powergating_state(void *handle,
350                   enum amd_powergating_state state)
351 {
352         return 0;
353 }
354
355 /* Prototypes of private functions */
356 static int dm_early_init(void* handle);
357
358 /* Allocate memory for FBC compressed data  */
359 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
360 {
361         struct drm_device *dev = connector->dev;
362         struct amdgpu_device *adev = dev->dev_private;
363         struct dm_comressor_info *compressor = &adev->dm.compressor;
364         struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
365         struct drm_display_mode *mode;
366         unsigned long max_size = 0;
367
368         if (adev->dm.dc->fbc_compressor == NULL)
369                 return;
370
371         if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
372                 return;
373
374         if (compressor->bo_ptr)
375                 return;
376
377
378         list_for_each_entry(mode, &connector->modes, head) {
379                 if (max_size < mode->htotal * mode->vtotal)
380                         max_size = mode->htotal * mode->vtotal;
381         }
382
383         if (max_size) {
384                 int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
385                             AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
386                             &compressor->gpu_addr, &compressor->cpu_addr);
387
388                 if (r)
389                         DRM_ERROR("DM: Failed to initialize FBC\n");
390                 else {
391                         adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
392                         DRM_INFO("DM: FBC alloc %lu\n", max_size*4);
393                 }
394
395         }
396
397 }
398
399 static int amdgpu_dm_init(struct amdgpu_device *adev)
400 {
401         struct dc_init_data init_data;
402         adev->dm.ddev = adev->ddev;
403         adev->dm.adev = adev;
404
405         /* Zero all the fields */
406         memset(&init_data, 0, sizeof(init_data));
407
408         mutex_init(&adev->dm.dc_lock);
409
410         if(amdgpu_dm_irq_init(adev)) {
411                 DRM_ERROR("amdgpu: failed to initialize DM IRQ support.\n");
412                 goto error;
413         }
414
415         init_data.asic_id.chip_family = adev->family;
416
417         init_data.asic_id.pci_revision_id = adev->rev_id;
418         init_data.asic_id.hw_internal_rev = adev->external_rev_id;
419
420         init_data.asic_id.vram_width = adev->gmc.vram_width;
421         /* TODO: initialize init_data.asic_id.vram_type here!!!! */
422         init_data.asic_id.atombios_base_address =
423                 adev->mode_info.atom_context->bios;
424
425         init_data.driver = adev;
426
427         adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
428
429         if (!adev->dm.cgs_device) {
430                 DRM_ERROR("amdgpu: failed to create cgs device.\n");
431                 goto error;
432         }
433
434         init_data.cgs_device = adev->dm.cgs_device;
435
436         init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
437
438         /*
439          * TODO debug why this doesn't work on Raven
440          */
441         if (adev->flags & AMD_IS_APU &&
442             adev->asic_type >= CHIP_CARRIZO &&
443             adev->asic_type < CHIP_RAVEN)
444                 init_data.flags.gpu_vm_support = true;
445
446         if (amdgpu_dc_feature_mask & DC_FBC_MASK)
447                 init_data.flags.fbc_support = true;
448
449         /* Display Core create. */
450         adev->dm.dc = dc_create(&init_data);
451
452         if (adev->dm.dc) {
453                 DRM_INFO("Display Core initialized with v%s!\n", DC_VER);
454         } else {
455                 DRM_INFO("Display Core failed to initialize with v%s!\n", DC_VER);
456                 goto error;
457         }
458
459         adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
460         if (!adev->dm.freesync_module) {
461                 DRM_ERROR(
462                 "amdgpu: failed to initialize freesync_module.\n");
463         } else
464                 DRM_DEBUG_DRIVER("amdgpu: freesync_module init done %p.\n",
465                                 adev->dm.freesync_module);
466
467         amdgpu_dm_init_color_mod();
468
469         if (amdgpu_dm_initialize_drm_device(adev)) {
470                 DRM_ERROR(
471                 "amdgpu: failed to initialize sw for display support.\n");
472                 goto error;
473         }
474
475         /* Update the actual used number of crtc */
476         adev->mode_info.num_crtc = adev->dm.display_indexes_num;
477
478         /* TODO: Add_display_info? */
479
480         /* TODO use dynamic cursor width */
481         adev->ddev->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
482         adev->ddev->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
483
484         if (drm_vblank_init(adev->ddev, adev->dm.display_indexes_num)) {
485                 DRM_ERROR(
486                 "amdgpu: failed to initialize sw for display support.\n");
487                 goto error;
488         }
489
490 #if defined(CONFIG_DEBUG_FS)
491         if (dtn_debugfs_init(adev))
492                 DRM_ERROR("amdgpu: failed initialize dtn debugfs support.\n");
493 #endif
494
495         DRM_DEBUG_DRIVER("KMS initialized.\n");
496
497         return 0;
498 error:
499         amdgpu_dm_fini(adev);
500
501         return -EINVAL;
502 }
503
504 static void amdgpu_dm_fini(struct amdgpu_device *adev)
505 {
506         amdgpu_dm_destroy_drm_device(&adev->dm);
507         /*
508          * TODO: pageflip, vlank interrupt
509          *
510          * amdgpu_dm_irq_fini(adev);
511          */
512
513         if (adev->dm.cgs_device) {
514                 amdgpu_cgs_destroy_device(adev->dm.cgs_device);
515                 adev->dm.cgs_device = NULL;
516         }
517         if (adev->dm.freesync_module) {
518                 mod_freesync_destroy(adev->dm.freesync_module);
519                 adev->dm.freesync_module = NULL;
520         }
521         /* DC Destroy TODO: Replace destroy DAL */
522         if (adev->dm.dc)
523                 dc_destroy(&adev->dm.dc);
524
525         mutex_destroy(&adev->dm.dc_lock);
526
527         return;
528 }
529
530 static int load_dmcu_fw(struct amdgpu_device *adev)
531 {
532         const char *fw_name_dmcu;
533         int r;
534         const struct dmcu_firmware_header_v1_0 *hdr;
535
536         switch(adev->asic_type) {
537         case CHIP_BONAIRE:
538         case CHIP_HAWAII:
539         case CHIP_KAVERI:
540         case CHIP_KABINI:
541         case CHIP_MULLINS:
542         case CHIP_TONGA:
543         case CHIP_FIJI:
544         case CHIP_CARRIZO:
545         case CHIP_STONEY:
546         case CHIP_POLARIS11:
547         case CHIP_POLARIS10:
548         case CHIP_POLARIS12:
549         case CHIP_VEGAM:
550         case CHIP_VEGA10:
551         case CHIP_VEGA12:
552         case CHIP_VEGA20:
553                 return 0;
554         case CHIP_RAVEN:
555                 fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
556                 break;
557         default:
558                 DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
559                 return -EINVAL;
560         }
561
562         if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
563                 DRM_DEBUG_KMS("dm: DMCU firmware not supported on direct or SMU loading\n");
564                 return 0;
565         }
566
567         r = request_firmware_direct(&adev->dm.fw_dmcu, fw_name_dmcu, adev->dev);
568         if (r == -ENOENT) {
569                 /* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
570                 DRM_DEBUG_KMS("dm: DMCU firmware not found\n");
571                 adev->dm.fw_dmcu = NULL;
572                 return 0;
573         }
574         if (r) {
575                 dev_err(adev->dev, "amdgpu_dm: Can't load firmware \"%s\"\n",
576                         fw_name_dmcu);
577                 return r;
578         }
579
580         r = amdgpu_ucode_validate(adev->dm.fw_dmcu);
581         if (r) {
582                 dev_err(adev->dev, "amdgpu_dm: Can't validate firmware \"%s\"\n",
583                         fw_name_dmcu);
584                 release_firmware(adev->dm.fw_dmcu);
585                 adev->dm.fw_dmcu = NULL;
586                 return r;
587         }
588
589         hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
590         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
591         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
592         adev->firmware.fw_size +=
593                 ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
594
595         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
596         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
597         adev->firmware.fw_size +=
598                 ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
599
600         adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
601
602         DRM_DEBUG_KMS("PSP loading DMCU firmware\n");
603
604         return 0;
605 }
606
607 static int dm_sw_init(void *handle)
608 {
609         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
610
611         return load_dmcu_fw(adev);
612 }
613
614 static int dm_sw_fini(void *handle)
615 {
616         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
617
618         if(adev->dm.fw_dmcu) {
619                 release_firmware(adev->dm.fw_dmcu);
620                 adev->dm.fw_dmcu = NULL;
621         }
622
623         return 0;
624 }
625
626 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
627 {
628         struct amdgpu_dm_connector *aconnector;
629         struct drm_connector *connector;
630         int ret = 0;
631
632         drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
633
634         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
635                 aconnector = to_amdgpu_dm_connector(connector);
636                 if (aconnector->dc_link->type == dc_connection_mst_branch &&
637                     aconnector->mst_mgr.aux) {
638                         DRM_DEBUG_DRIVER("DM_MST: starting TM on aconnector: %p [id: %d]\n",
639                                         aconnector, aconnector->base.base.id);
640
641                         ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
642                         if (ret < 0) {
643                                 DRM_ERROR("DM_MST: Failed to start MST\n");
644                                 ((struct dc_link *)aconnector->dc_link)->type = dc_connection_single;
645                                 return ret;
646                                 }
647                         }
648         }
649
650         drm_modeset_unlock(&dev->mode_config.connection_mutex);
651         return ret;
652 }
653
654 static int dm_late_init(void *handle)
655 {
656         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
657
658         struct dmcu_iram_parameters params;
659         unsigned int linear_lut[16];
660         int i;
661         struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
662         bool ret;
663
664         for (i = 0; i < 16; i++)
665                 linear_lut[i] = 0xFFFF * i / 15;
666
667         params.set = 0;
668         params.backlight_ramping_start = 0xCCCC;
669         params.backlight_ramping_reduction = 0xCCCCCCCC;
670         params.backlight_lut_array_size = 16;
671         params.backlight_lut_array = linear_lut;
672
673         ret = dmcu_load_iram(dmcu, params);
674
675         if (!ret)
676                 return -EINVAL;
677
678         return detect_mst_link_for_all_connectors(adev->ddev);
679 }
680
681 static void s3_handle_mst(struct drm_device *dev, bool suspend)
682 {
683         struct amdgpu_dm_connector *aconnector;
684         struct drm_connector *connector;
685
686         drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
687
688         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
689                    aconnector = to_amdgpu_dm_connector(connector);
690                    if (aconnector->dc_link->type == dc_connection_mst_branch &&
691                                    !aconnector->mst_port) {
692
693                            if (suspend)
694                                    drm_dp_mst_topology_mgr_suspend(&aconnector->mst_mgr);
695                            else
696                                    drm_dp_mst_topology_mgr_resume(&aconnector->mst_mgr);
697                    }
698         }
699
700         drm_modeset_unlock(&dev->mode_config.connection_mutex);
701 }
702
703 /**
704  * dm_hw_init() - Initialize DC device
705  * @handle: The base driver device containing the amdpgu_dm device.
706  *
707  * Initialize the &struct amdgpu_display_manager device. This involves calling
708  * the initializers of each DM component, then populating the struct with them.
709  *
710  * Although the function implies hardware initialization, both hardware and
711  * software are initialized here. Splitting them out to their relevant init
712  * hooks is a future TODO item.
713  *
714  * Some notable things that are initialized here:
715  *
716  * - Display Core, both software and hardware
717  * - DC modules that we need (freesync and color management)
718  * - DRM software states
719  * - Interrupt sources and handlers
720  * - Vblank support
721  * - Debug FS entries, if enabled
722  */
723 static int dm_hw_init(void *handle)
724 {
725         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
726         /* Create DAL display manager */
727         amdgpu_dm_init(adev);
728         amdgpu_dm_hpd_init(adev);
729
730         return 0;
731 }
732
733 /**
734  * dm_hw_fini() - Teardown DC device
735  * @handle: The base driver device containing the amdpgu_dm device.
736  *
737  * Teardown components within &struct amdgpu_display_manager that require
738  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
739  * were loaded. Also flush IRQ workqueues and disable them.
740  */
741 static int dm_hw_fini(void *handle)
742 {
743         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
744
745         amdgpu_dm_hpd_fini(adev);
746
747         amdgpu_dm_irq_fini(adev);
748         amdgpu_dm_fini(adev);
749         return 0;
750 }
751
752 static int dm_suspend(void *handle)
753 {
754         struct amdgpu_device *adev = handle;
755         struct amdgpu_display_manager *dm = &adev->dm;
756         int ret = 0;
757
758         s3_handle_mst(adev->ddev, true);
759
760         amdgpu_dm_irq_suspend(adev);
761
762         WARN_ON(adev->dm.cached_state);
763         adev->dm.cached_state = drm_atomic_helper_suspend(adev->ddev);
764
765         dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
766
767         return ret;
768 }
769
770 static struct amdgpu_dm_connector *
771 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
772                                              struct drm_crtc *crtc)
773 {
774         uint32_t i;
775         struct drm_connector_state *new_con_state;
776         struct drm_connector *connector;
777         struct drm_crtc *crtc_from_state;
778
779         for_each_new_connector_in_state(state, connector, new_con_state, i) {
780                 crtc_from_state = new_con_state->crtc;
781
782                 if (crtc_from_state == crtc)
783                         return to_amdgpu_dm_connector(connector);
784         }
785
786         return NULL;
787 }
788
789 static void emulated_link_detect(struct dc_link *link)
790 {
791         struct dc_sink_init_data sink_init_data = { 0 };
792         struct display_sink_capability sink_caps = { 0 };
793         enum dc_edid_status edid_status;
794         struct dc_context *dc_ctx = link->ctx;
795         struct dc_sink *sink = NULL;
796         struct dc_sink *prev_sink = NULL;
797
798         link->type = dc_connection_none;
799         prev_sink = link->local_sink;
800
801         if (prev_sink != NULL)
802                 dc_sink_retain(prev_sink);
803
804         switch (link->connector_signal) {
805         case SIGNAL_TYPE_HDMI_TYPE_A: {
806                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
807                 sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
808                 break;
809         }
810
811         case SIGNAL_TYPE_DVI_SINGLE_LINK: {
812                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
813                 sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
814                 break;
815         }
816
817         case SIGNAL_TYPE_DVI_DUAL_LINK: {
818                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
819                 sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
820                 break;
821         }
822
823         case SIGNAL_TYPE_LVDS: {
824                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
825                 sink_caps.signal = SIGNAL_TYPE_LVDS;
826                 break;
827         }
828
829         case SIGNAL_TYPE_EDP: {
830                 sink_caps.transaction_type =
831                         DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
832                 sink_caps.signal = SIGNAL_TYPE_EDP;
833                 break;
834         }
835
836         case SIGNAL_TYPE_DISPLAY_PORT: {
837                 sink_caps.transaction_type =
838                         DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
839                 sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
840                 break;
841         }
842
843         default:
844                 DC_ERROR("Invalid connector type! signal:%d\n",
845                         link->connector_signal);
846                 return;
847         }
848
849         sink_init_data.link = link;
850         sink_init_data.sink_signal = sink_caps.signal;
851
852         sink = dc_sink_create(&sink_init_data);
853         if (!sink) {
854                 DC_ERROR("Failed to create sink!\n");
855                 return;
856         }
857
858         link->local_sink = sink;
859
860         edid_status = dm_helpers_read_local_edid(
861                         link->ctx,
862                         link,
863                         sink);
864
865         if (edid_status != EDID_OK)
866                 DC_ERROR("Failed to read EDID");
867
868 }
869
870 static int dm_resume(void *handle)
871 {
872         struct amdgpu_device *adev = handle;
873         struct drm_device *ddev = adev->ddev;
874         struct amdgpu_display_manager *dm = &adev->dm;
875         struct amdgpu_dm_connector *aconnector;
876         struct drm_connector *connector;
877         struct drm_crtc *crtc;
878         struct drm_crtc_state *new_crtc_state;
879         struct dm_crtc_state *dm_new_crtc_state;
880         struct drm_plane *plane;
881         struct drm_plane_state *new_plane_state;
882         struct dm_plane_state *dm_new_plane_state;
883         enum dc_connection_type new_connection_type = dc_connection_none;
884         int ret;
885         int i;
886
887         /* power on hardware */
888         dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
889
890         /* program HPD filter */
891         dc_resume(dm->dc);
892
893         /* On resume we need to  rewrite the MSTM control bits to enamble MST*/
894         s3_handle_mst(ddev, false);
895
896         /*
897          * early enable HPD Rx IRQ, should be done before set mode as short
898          * pulse interrupts are used for MST
899          */
900         amdgpu_dm_irq_resume_early(adev);
901
902         /* Do detection*/
903         list_for_each_entry(connector, &ddev->mode_config.connector_list, head) {
904                 aconnector = to_amdgpu_dm_connector(connector);
905
906                 /*
907                  * this is the case when traversing through already created
908                  * MST connectors, should be skipped
909                  */
910                 if (aconnector->mst_port)
911                         continue;
912
913                 mutex_lock(&aconnector->hpd_lock);
914                 if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
915                         DRM_ERROR("KMS: Failed to detect connector\n");
916
917                 if (aconnector->base.force && new_connection_type == dc_connection_none)
918                         emulated_link_detect(aconnector->dc_link);
919                 else
920                         dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
921
922                 if (aconnector->fake_enable && aconnector->dc_link->local_sink)
923                         aconnector->fake_enable = false;
924
925                 aconnector->dc_sink = NULL;
926                 amdgpu_dm_update_connector_after_detect(aconnector);
927                 mutex_unlock(&aconnector->hpd_lock);
928         }
929
930         /* Force mode set in atomic commit */
931         for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i)
932                 new_crtc_state->active_changed = true;
933
934         /*
935          * atomic_check is expected to create the dc states. We need to release
936          * them here, since they were duplicated as part of the suspend
937          * procedure.
938          */
939         for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
940                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
941                 if (dm_new_crtc_state->stream) {
942                         WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
943                         dc_stream_release(dm_new_crtc_state->stream);
944                         dm_new_crtc_state->stream = NULL;
945                 }
946         }
947
948         for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
949                 dm_new_plane_state = to_dm_plane_state(new_plane_state);
950                 if (dm_new_plane_state->dc_state) {
951                         WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
952                         dc_plane_state_release(dm_new_plane_state->dc_state);
953                         dm_new_plane_state->dc_state = NULL;
954                 }
955         }
956
957         ret = drm_atomic_helper_resume(ddev, dm->cached_state);
958
959         dm->cached_state = NULL;
960
961         amdgpu_dm_irq_resume_late(adev);
962
963         return ret;
964 }
965
966 /**
967  * DOC: DM Lifecycle
968  *
969  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
970  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
971  * the base driver's device list to be initialized and torn down accordingly.
972  *
973  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
974  */
975
976 static const struct amd_ip_funcs amdgpu_dm_funcs = {
977         .name = "dm",
978         .early_init = dm_early_init,
979         .late_init = dm_late_init,
980         .sw_init = dm_sw_init,
981         .sw_fini = dm_sw_fini,
982         .hw_init = dm_hw_init,
983         .hw_fini = dm_hw_fini,
984         .suspend = dm_suspend,
985         .resume = dm_resume,
986         .is_idle = dm_is_idle,
987         .wait_for_idle = dm_wait_for_idle,
988         .check_soft_reset = dm_check_soft_reset,
989         .soft_reset = dm_soft_reset,
990         .set_clockgating_state = dm_set_clockgating_state,
991         .set_powergating_state = dm_set_powergating_state,
992 };
993
994 const struct amdgpu_ip_block_version dm_ip_block =
995 {
996         .type = AMD_IP_BLOCK_TYPE_DCE,
997         .major = 1,
998         .minor = 0,
999         .rev = 0,
1000         .funcs = &amdgpu_dm_funcs,
1001 };
1002
1003
1004 /**
1005  * DOC: atomic
1006  *
1007  * *WIP*
1008  */
1009
1010 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
1011         .fb_create = amdgpu_display_user_framebuffer_create,
1012         .output_poll_changed = drm_fb_helper_output_poll_changed,
1013         .atomic_check = amdgpu_dm_atomic_check,
1014         .atomic_commit = amdgpu_dm_atomic_commit,
1015 };
1016
1017 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
1018         .atomic_commit_tail = amdgpu_dm_atomic_commit_tail
1019 };
1020
1021 static void
1022 amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector)
1023 {
1024         struct drm_connector *connector = &aconnector->base;
1025         struct drm_device *dev = connector->dev;
1026         struct dc_sink *sink;
1027
1028         /* MST handled by drm_mst framework */
1029         if (aconnector->mst_mgr.mst_state == true)
1030                 return;
1031
1032
1033         sink = aconnector->dc_link->local_sink;
1034
1035         /*
1036          * Edid mgmt connector gets first update only in mode_valid hook and then
1037          * the connector sink is set to either fake or physical sink depends on link status.
1038          * Skip if already done during boot.
1039          */
1040         if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
1041                         && aconnector->dc_em_sink) {
1042
1043                 /*
1044                  * For S3 resume with headless use eml_sink to fake stream
1045                  * because on resume connector->sink is set to NULL
1046                  */
1047                 mutex_lock(&dev->mode_config.mutex);
1048
1049                 if (sink) {
1050                         if (aconnector->dc_sink) {
1051                                 amdgpu_dm_update_freesync_caps(connector, NULL);
1052                                 /*
1053                                  * retain and release below are used to
1054                                  * bump up refcount for sink because the link doesn't point
1055                                  * to it anymore after disconnect, so on next crtc to connector
1056                                  * reshuffle by UMD we will get into unwanted dc_sink release
1057                                  */
1058                                 if (aconnector->dc_sink != aconnector->dc_em_sink)
1059                                         dc_sink_release(aconnector->dc_sink);
1060                         }
1061                         aconnector->dc_sink = sink;
1062                         amdgpu_dm_update_freesync_caps(connector,
1063                                         aconnector->edid);
1064                 } else {
1065                         amdgpu_dm_update_freesync_caps(connector, NULL);
1066                         if (!aconnector->dc_sink)
1067                                 aconnector->dc_sink = aconnector->dc_em_sink;
1068                         else if (aconnector->dc_sink != aconnector->dc_em_sink)
1069                                 dc_sink_retain(aconnector->dc_sink);
1070                 }
1071
1072                 mutex_unlock(&dev->mode_config.mutex);
1073                 return;
1074         }
1075
1076         /*
1077          * TODO: temporary guard to look for proper fix
1078          * if this sink is MST sink, we should not do anything
1079          */
1080         if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
1081                 return;
1082
1083         if (aconnector->dc_sink == sink) {
1084                 /*
1085                  * We got a DP short pulse (Link Loss, DP CTS, etc...).
1086                  * Do nothing!!
1087                  */
1088                 DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: dc_sink didn't change.\n",
1089                                 aconnector->connector_id);
1090                 return;
1091         }
1092
1093         DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
1094                 aconnector->connector_id, aconnector->dc_sink, sink);
1095
1096         mutex_lock(&dev->mode_config.mutex);
1097
1098         /*
1099          * 1. Update status of the drm connector
1100          * 2. Send an event and let userspace tell us what to do
1101          */
1102         if (sink) {
1103                 /*
1104                  * TODO: check if we still need the S3 mode update workaround.
1105                  * If yes, put it here.
1106                  */
1107                 if (aconnector->dc_sink)
1108                         amdgpu_dm_update_freesync_caps(connector, NULL);
1109
1110                 aconnector->dc_sink = sink;
1111                 if (sink->dc_edid.length == 0) {
1112                         aconnector->edid = NULL;
1113                         drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
1114                 } else {
1115                         aconnector->edid =
1116                                 (struct edid *) sink->dc_edid.raw_edid;
1117
1118
1119                         drm_connector_update_edid_property(connector,
1120                                         aconnector->edid);
1121                         drm_dp_cec_set_edid(&aconnector->dm_dp_aux.aux,
1122                                             aconnector->edid);
1123                 }
1124                 amdgpu_dm_update_freesync_caps(connector, aconnector->edid);
1125
1126         } else {
1127                 drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
1128                 amdgpu_dm_update_freesync_caps(connector, NULL);
1129                 drm_connector_update_edid_property(connector, NULL);
1130                 aconnector->num_modes = 0;
1131                 aconnector->dc_sink = NULL;
1132                 aconnector->edid = NULL;
1133         }
1134
1135         mutex_unlock(&dev->mode_config.mutex);
1136 }
1137
1138 static void handle_hpd_irq(void *param)
1139 {
1140         struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
1141         struct drm_connector *connector = &aconnector->base;
1142         struct drm_device *dev = connector->dev;
1143         enum dc_connection_type new_connection_type = dc_connection_none;
1144
1145         /*
1146          * In case of failure or MST no need to update connector status or notify the OS
1147          * since (for MST case) MST does this in its own context.
1148          */
1149         mutex_lock(&aconnector->hpd_lock);
1150
1151         if (aconnector->fake_enable)
1152                 aconnector->fake_enable = false;
1153
1154         if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
1155                 DRM_ERROR("KMS: Failed to detect connector\n");
1156
1157         if (aconnector->base.force && new_connection_type == dc_connection_none) {
1158                 emulated_link_detect(aconnector->dc_link);
1159
1160
1161                 drm_modeset_lock_all(dev);
1162                 dm_restore_drm_connector_state(dev, connector);
1163                 drm_modeset_unlock_all(dev);
1164
1165                 if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
1166                         drm_kms_helper_hotplug_event(dev);
1167
1168         } else if (dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD)) {
1169                 amdgpu_dm_update_connector_after_detect(aconnector);
1170
1171
1172                 drm_modeset_lock_all(dev);
1173                 dm_restore_drm_connector_state(dev, connector);
1174                 drm_modeset_unlock_all(dev);
1175
1176                 if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
1177                         drm_kms_helper_hotplug_event(dev);
1178         }
1179         mutex_unlock(&aconnector->hpd_lock);
1180
1181 }
1182
1183 static void dm_handle_hpd_rx_irq(struct amdgpu_dm_connector *aconnector)
1184 {
1185         uint8_t esi[DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI] = { 0 };
1186         uint8_t dret;
1187         bool new_irq_handled = false;
1188         int dpcd_addr;
1189         int dpcd_bytes_to_read;
1190
1191         const int max_process_count = 30;
1192         int process_count = 0;
1193
1194         const struct dc_link_status *link_status = dc_link_get_status(aconnector->dc_link);
1195
1196         if (link_status->dpcd_caps->dpcd_rev.raw < 0x12) {
1197                 dpcd_bytes_to_read = DP_LANE0_1_STATUS - DP_SINK_COUNT;
1198                 /* DPCD 0x200 - 0x201 for downstream IRQ */
1199                 dpcd_addr = DP_SINK_COUNT;
1200         } else {
1201                 dpcd_bytes_to_read = DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI;
1202                 /* DPCD 0x2002 - 0x2005 for downstream IRQ */
1203                 dpcd_addr = DP_SINK_COUNT_ESI;
1204         }
1205
1206         dret = drm_dp_dpcd_read(
1207                 &aconnector->dm_dp_aux.aux,
1208                 dpcd_addr,
1209                 esi,
1210                 dpcd_bytes_to_read);
1211
1212         while (dret == dpcd_bytes_to_read &&
1213                 process_count < max_process_count) {
1214                 uint8_t retry;
1215                 dret = 0;
1216
1217                 process_count++;
1218
1219                 DRM_DEBUG_DRIVER("ESI %02x %02x %02x\n", esi[0], esi[1], esi[2]);
1220                 /* handle HPD short pulse irq */
1221                 if (aconnector->mst_mgr.mst_state)
1222                         drm_dp_mst_hpd_irq(
1223                                 &aconnector->mst_mgr,
1224                                 esi,
1225                                 &new_irq_handled);
1226
1227                 if (new_irq_handled) {
1228                         /* ACK at DPCD to notify down stream */
1229                         const int ack_dpcd_bytes_to_write =
1230                                 dpcd_bytes_to_read - 1;
1231
1232                         for (retry = 0; retry < 3; retry++) {
1233                                 uint8_t wret;
1234
1235                                 wret = drm_dp_dpcd_write(
1236                                         &aconnector->dm_dp_aux.aux,
1237                                         dpcd_addr + 1,
1238                                         &esi[1],
1239                                         ack_dpcd_bytes_to_write);
1240                                 if (wret == ack_dpcd_bytes_to_write)
1241                                         break;
1242                         }
1243
1244                         /* check if there is new irq to be handled */
1245                         dret = drm_dp_dpcd_read(
1246                                 &aconnector->dm_dp_aux.aux,
1247                                 dpcd_addr,
1248                                 esi,
1249                                 dpcd_bytes_to_read);
1250
1251                         new_irq_handled = false;
1252                 } else {
1253                         break;
1254                 }
1255         }
1256
1257         if (process_count == max_process_count)
1258                 DRM_DEBUG_DRIVER("Loop exceeded max iterations\n");
1259 }
1260
1261 static void handle_hpd_rx_irq(void *param)
1262 {
1263         struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
1264         struct drm_connector *connector = &aconnector->base;
1265         struct drm_device *dev = connector->dev;
1266         struct dc_link *dc_link = aconnector->dc_link;
1267         bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
1268         enum dc_connection_type new_connection_type = dc_connection_none;
1269
1270         /*
1271          * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
1272          * conflict, after implement i2c helper, this mutex should be
1273          * retired.
1274          */
1275         if (dc_link->type != dc_connection_mst_branch)
1276                 mutex_lock(&aconnector->hpd_lock);
1277
1278         if (dc_link_handle_hpd_rx_irq(dc_link, NULL, NULL) &&
1279                         !is_mst_root_connector) {
1280                 /* Downstream Port status changed. */
1281                 if (!dc_link_detect_sink(dc_link, &new_connection_type))
1282                         DRM_ERROR("KMS: Failed to detect connector\n");
1283
1284                 if (aconnector->base.force && new_connection_type == dc_connection_none) {
1285                         emulated_link_detect(dc_link);
1286
1287                         if (aconnector->fake_enable)
1288                                 aconnector->fake_enable = false;
1289
1290                         amdgpu_dm_update_connector_after_detect(aconnector);
1291
1292
1293                         drm_modeset_lock_all(dev);
1294                         dm_restore_drm_connector_state(dev, connector);
1295                         drm_modeset_unlock_all(dev);
1296
1297                         drm_kms_helper_hotplug_event(dev);
1298                 } else if (dc_link_detect(dc_link, DETECT_REASON_HPDRX)) {
1299
1300                         if (aconnector->fake_enable)
1301                                 aconnector->fake_enable = false;
1302
1303                         amdgpu_dm_update_connector_after_detect(aconnector);
1304
1305
1306                         drm_modeset_lock_all(dev);
1307                         dm_restore_drm_connector_state(dev, connector);
1308                         drm_modeset_unlock_all(dev);
1309
1310                         drm_kms_helper_hotplug_event(dev);
1311                 }
1312         }
1313         if ((dc_link->cur_link_settings.lane_count != LANE_COUNT_UNKNOWN) ||
1314             (dc_link->type == dc_connection_mst_branch))
1315                 dm_handle_hpd_rx_irq(aconnector);
1316
1317         if (dc_link->type != dc_connection_mst_branch) {
1318                 drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
1319                 mutex_unlock(&aconnector->hpd_lock);
1320         }
1321 }
1322
1323 static void register_hpd_handlers(struct amdgpu_device *adev)
1324 {
1325         struct drm_device *dev = adev->ddev;
1326         struct drm_connector *connector;
1327         struct amdgpu_dm_connector *aconnector;
1328         const struct dc_link *dc_link;
1329         struct dc_interrupt_params int_params = {0};
1330
1331         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1332         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1333
1334         list_for_each_entry(connector,
1335                         &dev->mode_config.connector_list, head) {
1336
1337                 aconnector = to_amdgpu_dm_connector(connector);
1338                 dc_link = aconnector->dc_link;
1339
1340                 if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd) {
1341                         int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1342                         int_params.irq_source = dc_link->irq_source_hpd;
1343
1344                         amdgpu_dm_irq_register_interrupt(adev, &int_params,
1345                                         handle_hpd_irq,
1346                                         (void *) aconnector);
1347                 }
1348
1349                 if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd_rx) {
1350
1351                         /* Also register for DP short pulse (hpd_rx). */
1352                         int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1353                         int_params.irq_source = dc_link->irq_source_hpd_rx;
1354
1355                         amdgpu_dm_irq_register_interrupt(adev, &int_params,
1356                                         handle_hpd_rx_irq,
1357                                         (void *) aconnector);
1358                 }
1359         }
1360 }
1361
1362 /* Register IRQ sources and initialize IRQ callbacks */
1363 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
1364 {
1365         struct dc *dc = adev->dm.dc;
1366         struct common_irq_params *c_irq_params;
1367         struct dc_interrupt_params int_params = {0};
1368         int r;
1369         int i;
1370         unsigned client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
1371
1372         if (adev->asic_type == CHIP_VEGA10 ||
1373             adev->asic_type == CHIP_VEGA12 ||
1374             adev->asic_type == CHIP_VEGA20 ||
1375             adev->asic_type == CHIP_RAVEN)
1376                 client_id = SOC15_IH_CLIENTID_DCE;
1377
1378         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1379         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1380
1381         /*
1382          * Actions of amdgpu_irq_add_id():
1383          * 1. Register a set() function with base driver.
1384          *    Base driver will call set() function to enable/disable an
1385          *    interrupt in DC hardware.
1386          * 2. Register amdgpu_dm_irq_handler().
1387          *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1388          *    coming from DC hardware.
1389          *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1390          *    for acknowledging and handling. */
1391
1392         /* Use VBLANK interrupt */
1393         for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
1394                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
1395                 if (r) {
1396                         DRM_ERROR("Failed to add crtc irq id!\n");
1397                         return r;
1398                 }
1399
1400                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1401                 int_params.irq_source =
1402                         dc_interrupt_to_irq_source(dc, i, 0);
1403
1404                 c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1405
1406                 c_irq_params->adev = adev;
1407                 c_irq_params->irq_src = int_params.irq_source;
1408
1409                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1410                                 dm_crtc_high_irq, c_irq_params);
1411         }
1412
1413         /* Use GRPH_PFLIP interrupt */
1414         for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
1415                         i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
1416                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
1417                 if (r) {
1418                         DRM_ERROR("Failed to add page flip irq id!\n");
1419                         return r;
1420                 }
1421
1422                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1423                 int_params.irq_source =
1424                         dc_interrupt_to_irq_source(dc, i, 0);
1425
1426                 c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1427
1428                 c_irq_params->adev = adev;
1429                 c_irq_params->irq_src = int_params.irq_source;
1430
1431                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1432                                 dm_pflip_high_irq, c_irq_params);
1433
1434         }
1435
1436         /* HPD */
1437         r = amdgpu_irq_add_id(adev, client_id,
1438                         VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
1439         if (r) {
1440                 DRM_ERROR("Failed to add hpd irq id!\n");
1441                 return r;
1442         }
1443
1444         register_hpd_handlers(adev);
1445
1446         return 0;
1447 }
1448
1449 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
1450 /* Register IRQ sources and initialize IRQ callbacks */
1451 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
1452 {
1453         struct dc *dc = adev->dm.dc;
1454         struct common_irq_params *c_irq_params;
1455         struct dc_interrupt_params int_params = {0};
1456         int r;
1457         int i;
1458
1459         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1460         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1461
1462         /*
1463          * Actions of amdgpu_irq_add_id():
1464          * 1. Register a set() function with base driver.
1465          *    Base driver will call set() function to enable/disable an
1466          *    interrupt in DC hardware.
1467          * 2. Register amdgpu_dm_irq_handler().
1468          *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1469          *    coming from DC hardware.
1470          *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1471          *    for acknowledging and handling.
1472          */
1473
1474         /* Use VSTARTUP interrupt */
1475         for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
1476                         i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
1477                         i++) {
1478                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
1479
1480                 if (r) {
1481                         DRM_ERROR("Failed to add crtc irq id!\n");
1482                         return r;
1483                 }
1484
1485                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1486                 int_params.irq_source =
1487                         dc_interrupt_to_irq_source(dc, i, 0);
1488
1489                 c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1490
1491                 c_irq_params->adev = adev;
1492                 c_irq_params->irq_src = int_params.irq_source;
1493
1494                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1495                                 dm_crtc_high_irq, c_irq_params);
1496         }
1497
1498         /* Use GRPH_PFLIP interrupt */
1499         for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
1500                         i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + adev->mode_info.num_crtc - 1;
1501                         i++) {
1502                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
1503                 if (r) {
1504                         DRM_ERROR("Failed to add page flip irq id!\n");
1505                         return r;
1506                 }
1507
1508                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1509                 int_params.irq_source =
1510                         dc_interrupt_to_irq_source(dc, i, 0);
1511
1512                 c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1513
1514                 c_irq_params->adev = adev;
1515                 c_irq_params->irq_src = int_params.irq_source;
1516
1517                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1518                                 dm_pflip_high_irq, c_irq_params);
1519
1520         }
1521
1522         /* HPD */
1523         r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
1524                         &adev->hpd_irq);
1525         if (r) {
1526                 DRM_ERROR("Failed to add hpd irq id!\n");
1527                 return r;
1528         }
1529
1530         register_hpd_handlers(adev);
1531
1532         return 0;
1533 }
1534 #endif
1535
1536 /*
1537  * Acquires the lock for the atomic state object and returns
1538  * the new atomic state.
1539  *
1540  * This should only be called during atomic check.
1541  */
1542 static int dm_atomic_get_state(struct drm_atomic_state *state,
1543                                struct dm_atomic_state **dm_state)
1544 {
1545         struct drm_device *dev = state->dev;
1546         struct amdgpu_device *adev = dev->dev_private;
1547         struct amdgpu_display_manager *dm = &adev->dm;
1548         struct drm_private_state *priv_state;
1549         int ret;
1550
1551         if (*dm_state)
1552                 return 0;
1553
1554         ret = drm_modeset_lock(&dm->atomic_obj_lock, state->acquire_ctx);
1555         if (ret)
1556                 return ret;
1557
1558         priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
1559         if (IS_ERR(priv_state))
1560                 return PTR_ERR(priv_state);
1561
1562         *dm_state = to_dm_atomic_state(priv_state);
1563
1564         return 0;
1565 }
1566
1567 struct dm_atomic_state *
1568 dm_atomic_get_new_state(struct drm_atomic_state *state)
1569 {
1570         struct drm_device *dev = state->dev;
1571         struct amdgpu_device *adev = dev->dev_private;
1572         struct amdgpu_display_manager *dm = &adev->dm;
1573         struct drm_private_obj *obj;
1574         struct drm_private_state *new_obj_state;
1575         int i;
1576
1577         for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
1578                 if (obj->funcs == dm->atomic_obj.funcs)
1579                         return to_dm_atomic_state(new_obj_state);
1580         }
1581
1582         return NULL;
1583 }
1584
1585 struct dm_atomic_state *
1586 dm_atomic_get_old_state(struct drm_atomic_state *state)
1587 {
1588         struct drm_device *dev = state->dev;
1589         struct amdgpu_device *adev = dev->dev_private;
1590         struct amdgpu_display_manager *dm = &adev->dm;
1591         struct drm_private_obj *obj;
1592         struct drm_private_state *old_obj_state;
1593         int i;
1594
1595         for_each_old_private_obj_in_state(state, obj, old_obj_state, i) {
1596                 if (obj->funcs == dm->atomic_obj.funcs)
1597                         return to_dm_atomic_state(old_obj_state);
1598         }
1599
1600         return NULL;
1601 }
1602
1603 static struct drm_private_state *
1604 dm_atomic_duplicate_state(struct drm_private_obj *obj)
1605 {
1606         struct dm_atomic_state *old_state, *new_state;
1607
1608         new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
1609         if (!new_state)
1610                 return NULL;
1611
1612         __drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
1613
1614         new_state->context = dc_create_state();
1615         if (!new_state->context) {
1616                 kfree(new_state);
1617                 return NULL;
1618         }
1619
1620         old_state = to_dm_atomic_state(obj->state);
1621         if (old_state && old_state->context)
1622                 dc_resource_state_copy_construct(old_state->context,
1623                                                  new_state->context);
1624
1625         return &new_state->base;
1626 }
1627
1628 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
1629                                     struct drm_private_state *state)
1630 {
1631         struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
1632
1633         if (dm_state && dm_state->context)
1634                 dc_release_state(dm_state->context);
1635
1636         kfree(dm_state);
1637 }
1638
1639 static struct drm_private_state_funcs dm_atomic_state_funcs = {
1640         .atomic_duplicate_state = dm_atomic_duplicate_state,
1641         .atomic_destroy_state = dm_atomic_destroy_state,
1642 };
1643
1644 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
1645 {
1646         struct dm_atomic_state *state;
1647         int r;
1648
1649         adev->mode_info.mode_config_initialized = true;
1650
1651         adev->ddev->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
1652         adev->ddev->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
1653
1654         adev->ddev->mode_config.max_width = 16384;
1655         adev->ddev->mode_config.max_height = 16384;
1656
1657         adev->ddev->mode_config.preferred_depth = 24;
1658         adev->ddev->mode_config.prefer_shadow = 1;
1659         /* indicates support for immediate flip */
1660         adev->ddev->mode_config.async_page_flip = true;
1661
1662         adev->ddev->mode_config.fb_base = adev->gmc.aper_base;
1663
1664         drm_modeset_lock_init(&adev->dm.atomic_obj_lock);
1665
1666         state = kzalloc(sizeof(*state), GFP_KERNEL);
1667         if (!state)
1668                 return -ENOMEM;
1669
1670         state->context = dc_create_state();
1671         if (!state->context) {
1672                 kfree(state);
1673                 return -ENOMEM;
1674         }
1675
1676         dc_resource_state_copy_construct_current(adev->dm.dc, state->context);
1677
1678         drm_atomic_private_obj_init(&adev->dm.atomic_obj,
1679                                     &state->base,
1680                                     &dm_atomic_state_funcs);
1681
1682         r = amdgpu_display_modeset_create_props(adev);
1683         if (r)
1684                 return r;
1685
1686         return 0;
1687 }
1688
1689 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
1690 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
1691
1692 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
1693         defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
1694
1695 static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm)
1696 {
1697 #if defined(CONFIG_ACPI)
1698         struct amdgpu_dm_backlight_caps caps;
1699
1700         if (dm->backlight_caps.caps_valid)
1701                 return;
1702
1703         amdgpu_acpi_get_backlight_caps(dm->adev, &caps);
1704         if (caps.caps_valid) {
1705                 dm->backlight_caps.min_input_signal = caps.min_input_signal;
1706                 dm->backlight_caps.max_input_signal = caps.max_input_signal;
1707                 dm->backlight_caps.caps_valid = true;
1708         } else {
1709                 dm->backlight_caps.min_input_signal =
1710                                 AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
1711                 dm->backlight_caps.max_input_signal =
1712                                 AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
1713         }
1714 #else
1715         dm->backlight_caps.min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
1716         dm->backlight_caps.max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
1717 #endif
1718 }
1719
1720 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
1721 {
1722         struct amdgpu_display_manager *dm = bl_get_data(bd);
1723         struct amdgpu_dm_backlight_caps caps;
1724         uint32_t brightness = bd->props.brightness;
1725
1726         amdgpu_dm_update_backlight_caps(dm);
1727         caps = dm->backlight_caps;
1728         /*
1729          * The brightness input is in the range 0-255
1730          * It needs to be rescaled to be between the
1731          * requested min and max input signal
1732          *
1733          * It also needs to be scaled up by 0x101 to
1734          * match the DC interface which has a range of
1735          * 0 to 0xffff
1736          */
1737         brightness =
1738                 brightness
1739                 * 0x101
1740                 * (caps.max_input_signal - caps.min_input_signal)
1741                 / AMDGPU_MAX_BL_LEVEL
1742                 + caps.min_input_signal * 0x101;
1743
1744         if (dc_link_set_backlight_level(dm->backlight_link,
1745                         brightness, 0, 0))
1746                 return 0;
1747         else
1748                 return 1;
1749 }
1750
1751 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
1752 {
1753         struct amdgpu_display_manager *dm = bl_get_data(bd);
1754         int ret = dc_link_get_backlight_level(dm->backlight_link);
1755
1756         if (ret == DC_ERROR_UNEXPECTED)
1757                 return bd->props.brightness;
1758         return ret;
1759 }
1760
1761 static const struct backlight_ops amdgpu_dm_backlight_ops = {
1762         .get_brightness = amdgpu_dm_backlight_get_brightness,
1763         .update_status  = amdgpu_dm_backlight_update_status,
1764 };
1765
1766 static void
1767 amdgpu_dm_register_backlight_device(struct amdgpu_display_manager *dm)
1768 {
1769         char bl_name[16];
1770         struct backlight_properties props = { 0 };
1771
1772         amdgpu_dm_update_backlight_caps(dm);
1773
1774         props.max_brightness = AMDGPU_MAX_BL_LEVEL;
1775         props.brightness = AMDGPU_MAX_BL_LEVEL;
1776         props.type = BACKLIGHT_RAW;
1777
1778         snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
1779                         dm->adev->ddev->primary->index);
1780
1781         dm->backlight_dev = backlight_device_register(bl_name,
1782                         dm->adev->ddev->dev,
1783                         dm,
1784                         &amdgpu_dm_backlight_ops,
1785                         &props);
1786
1787         if (IS_ERR(dm->backlight_dev))
1788                 DRM_ERROR("DM: Backlight registration failed!\n");
1789         else
1790                 DRM_DEBUG_DRIVER("DM: Registered Backlight device: %s\n", bl_name);
1791 }
1792
1793 #endif
1794
1795 static int initialize_plane(struct amdgpu_display_manager *dm,
1796                              struct amdgpu_mode_info *mode_info,
1797                              int plane_id)
1798 {
1799         struct drm_plane *plane;
1800         unsigned long possible_crtcs;
1801         int ret = 0;
1802
1803         plane = kzalloc(sizeof(struct drm_plane), GFP_KERNEL);
1804         mode_info->planes[plane_id] = plane;
1805
1806         if (!plane) {
1807                 DRM_ERROR("KMS: Failed to allocate plane\n");
1808                 return -ENOMEM;
1809         }
1810         plane->type = mode_info->plane_type[plane_id];
1811
1812         /*
1813          * HACK: IGT tests expect that each plane can only have
1814          * one possible CRTC. For now, set one CRTC for each
1815          * plane that is not an underlay, but still allow multiple
1816          * CRTCs for underlay planes.
1817          */
1818         possible_crtcs = 1 << plane_id;
1819         if (plane_id >= dm->dc->caps.max_streams)
1820                 possible_crtcs = 0xff;
1821
1822         ret = amdgpu_dm_plane_init(dm, mode_info->planes[plane_id], possible_crtcs);
1823
1824         if (ret) {
1825                 DRM_ERROR("KMS: Failed to initialize plane\n");
1826                 return ret;
1827         }
1828
1829         return ret;
1830 }
1831
1832
1833 static void register_backlight_device(struct amdgpu_display_manager *dm,
1834                                       struct dc_link *link)
1835 {
1836 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
1837         defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
1838
1839         if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
1840             link->type != dc_connection_none) {
1841                 /*
1842                  * Event if registration failed, we should continue with
1843                  * DM initialization because not having a backlight control
1844                  * is better then a black screen.
1845                  */
1846                 amdgpu_dm_register_backlight_device(dm);
1847
1848                 if (dm->backlight_dev)
1849                         dm->backlight_link = link;
1850         }
1851 #endif
1852 }
1853
1854
1855 /*
1856  * In this architecture, the association
1857  * connector -> encoder -> crtc
1858  * id not really requried. The crtc and connector will hold the
1859  * display_index as an abstraction to use with DAL component
1860  *
1861  * Returns 0 on success
1862  */
1863 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
1864 {
1865         struct amdgpu_display_manager *dm = &adev->dm;
1866         int32_t i;
1867         struct amdgpu_dm_connector *aconnector = NULL;
1868         struct amdgpu_encoder *aencoder = NULL;
1869         struct amdgpu_mode_info *mode_info = &adev->mode_info;
1870         uint32_t link_cnt;
1871         int32_t total_overlay_planes, total_primary_planes;
1872         enum dc_connection_type new_connection_type = dc_connection_none;
1873
1874         link_cnt = dm->dc->caps.max_links;
1875         if (amdgpu_dm_mode_config_init(dm->adev)) {
1876                 DRM_ERROR("DM: Failed to initialize mode config\n");
1877                 return -EINVAL;
1878         }
1879
1880         /* Identify the number of planes to be initialized */
1881         total_overlay_planes = dm->dc->caps.max_slave_planes;
1882         total_primary_planes = dm->dc->caps.max_planes - dm->dc->caps.max_slave_planes;
1883
1884         /* First initialize overlay planes, index starting after primary planes */
1885         for (i = (total_overlay_planes - 1); i >= 0; i--) {
1886                 if (initialize_plane(dm, mode_info, (total_primary_planes + i))) {
1887                         DRM_ERROR("KMS: Failed to initialize overlay plane\n");
1888                         goto fail;
1889                 }
1890         }
1891
1892         /* Initialize primary planes */
1893         for (i = (total_primary_planes - 1); i >= 0; i--) {
1894                 if (initialize_plane(dm, mode_info, i)) {
1895                         DRM_ERROR("KMS: Failed to initialize primary plane\n");
1896                         goto fail;
1897                 }
1898         }
1899
1900         for (i = 0; i < dm->dc->caps.max_streams; i++)
1901                 if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
1902                         DRM_ERROR("KMS: Failed to initialize crtc\n");
1903                         goto fail;
1904                 }
1905
1906         dm->display_indexes_num = dm->dc->caps.max_streams;
1907
1908         /* loops over all connectors on the board */
1909         for (i = 0; i < link_cnt; i++) {
1910                 struct dc_link *link = NULL;
1911
1912                 if (i > AMDGPU_DM_MAX_DISPLAY_INDEX) {
1913                         DRM_ERROR(
1914                                 "KMS: Cannot support more than %d display indexes\n",
1915                                         AMDGPU_DM_MAX_DISPLAY_INDEX);
1916                         continue;
1917                 }
1918
1919                 aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
1920                 if (!aconnector)
1921                         goto fail;
1922
1923                 aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
1924                 if (!aencoder)
1925                         goto fail;
1926
1927                 if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
1928                         DRM_ERROR("KMS: Failed to initialize encoder\n");
1929                         goto fail;
1930                 }
1931
1932                 if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
1933                         DRM_ERROR("KMS: Failed to initialize connector\n");
1934                         goto fail;
1935                 }
1936
1937                 link = dc_get_link_at_index(dm->dc, i);
1938
1939                 if (!dc_link_detect_sink(link, &new_connection_type))
1940                         DRM_ERROR("KMS: Failed to detect connector\n");
1941
1942                 if (aconnector->base.force && new_connection_type == dc_connection_none) {
1943                         emulated_link_detect(link);
1944                         amdgpu_dm_update_connector_after_detect(aconnector);
1945
1946                 } else if (dc_link_detect(link, DETECT_REASON_BOOT)) {
1947                         amdgpu_dm_update_connector_after_detect(aconnector);
1948                         register_backlight_device(dm, link);
1949                 }
1950
1951
1952         }
1953
1954         /* Software is initialized. Now we can register interrupt handlers. */
1955         switch (adev->asic_type) {
1956         case CHIP_BONAIRE:
1957         case CHIP_HAWAII:
1958         case CHIP_KAVERI:
1959         case CHIP_KABINI:
1960         case CHIP_MULLINS:
1961         case CHIP_TONGA:
1962         case CHIP_FIJI:
1963         case CHIP_CARRIZO:
1964         case CHIP_STONEY:
1965         case CHIP_POLARIS11:
1966         case CHIP_POLARIS10:
1967         case CHIP_POLARIS12:
1968         case CHIP_VEGAM:
1969         case CHIP_VEGA10:
1970         case CHIP_VEGA12:
1971         case CHIP_VEGA20:
1972                 if (dce110_register_irq_handlers(dm->adev)) {
1973                         DRM_ERROR("DM: Failed to initialize IRQ\n");
1974                         goto fail;
1975                 }
1976                 break;
1977 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
1978         case CHIP_RAVEN:
1979                 if (dcn10_register_irq_handlers(dm->adev)) {
1980                         DRM_ERROR("DM: Failed to initialize IRQ\n");
1981                         goto fail;
1982                 }
1983                 break;
1984 #endif
1985         default:
1986                 DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
1987                 goto fail;
1988         }
1989
1990         if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
1991                 dm->dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
1992
1993         return 0;
1994 fail:
1995         kfree(aencoder);
1996         kfree(aconnector);
1997         for (i = 0; i < dm->dc->caps.max_planes; i++)
1998                 kfree(mode_info->planes[i]);
1999         return -EINVAL;
2000 }
2001
2002 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
2003 {
2004         drm_mode_config_cleanup(dm->ddev);
2005         drm_atomic_private_obj_fini(&dm->atomic_obj);
2006         return;
2007 }
2008
2009 /******************************************************************************
2010  * amdgpu_display_funcs functions
2011  *****************************************************************************/
2012
2013 /*
2014  * dm_bandwidth_update - program display watermarks
2015  *
2016  * @adev: amdgpu_device pointer
2017  *
2018  * Calculate and program the display watermarks and line buffer allocation.
2019  */
2020 static void dm_bandwidth_update(struct amdgpu_device *adev)
2021 {
2022         /* TODO: implement later */
2023 }
2024
2025 static const struct amdgpu_display_funcs dm_display_funcs = {
2026         .bandwidth_update = dm_bandwidth_update, /* called unconditionally */
2027         .vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
2028         .backlight_set_level = NULL, /* never called for DC */
2029         .backlight_get_level = NULL, /* never called for DC */
2030         .hpd_sense = NULL,/* called unconditionally */
2031         .hpd_set_polarity = NULL, /* called unconditionally */
2032         .hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
2033         .page_flip_get_scanoutpos =
2034                 dm_crtc_get_scanoutpos,/* called unconditionally */
2035         .add_encoder = NULL, /* VBIOS parsing. DAL does it. */
2036         .add_connector = NULL, /* VBIOS parsing. DAL does it. */
2037 };
2038
2039 #if defined(CONFIG_DEBUG_KERNEL_DC)
2040
2041 static ssize_t s3_debug_store(struct device *device,
2042                               struct device_attribute *attr,
2043                               const char *buf,
2044                               size_t count)
2045 {
2046         int ret;
2047         int s3_state;
2048         struct pci_dev *pdev = to_pci_dev(device);
2049         struct drm_device *drm_dev = pci_get_drvdata(pdev);
2050         struct amdgpu_device *adev = drm_dev->dev_private;
2051
2052         ret = kstrtoint(buf, 0, &s3_state);
2053
2054         if (ret == 0) {
2055                 if (s3_state) {
2056                         dm_resume(adev);
2057                         drm_kms_helper_hotplug_event(adev->ddev);
2058                 } else
2059                         dm_suspend(adev);
2060         }
2061
2062         return ret == 0 ? count : 0;
2063 }
2064
2065 DEVICE_ATTR_WO(s3_debug);
2066
2067 #endif
2068
2069 static int dm_early_init(void *handle)
2070 {
2071         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2072
2073         switch (adev->asic_type) {
2074         case CHIP_BONAIRE:
2075         case CHIP_HAWAII:
2076                 adev->mode_info.num_crtc = 6;
2077                 adev->mode_info.num_hpd = 6;
2078                 adev->mode_info.num_dig = 6;
2079                 adev->mode_info.plane_type = dm_plane_type_default;
2080                 break;
2081         case CHIP_KAVERI:
2082                 adev->mode_info.num_crtc = 4;
2083                 adev->mode_info.num_hpd = 6;
2084                 adev->mode_info.num_dig = 7;
2085                 adev->mode_info.plane_type = dm_plane_type_default;
2086                 break;
2087         case CHIP_KABINI:
2088         case CHIP_MULLINS:
2089                 adev->mode_info.num_crtc = 2;
2090                 adev->mode_info.num_hpd = 6;
2091                 adev->mode_info.num_dig = 6;
2092                 adev->mode_info.plane_type = dm_plane_type_default;
2093                 break;
2094         case CHIP_FIJI:
2095         case CHIP_TONGA:
2096                 adev->mode_info.num_crtc = 6;
2097                 adev->mode_info.num_hpd = 6;
2098                 adev->mode_info.num_dig = 7;
2099                 adev->mode_info.plane_type = dm_plane_type_default;
2100                 break;
2101         case CHIP_CARRIZO:
2102                 adev->mode_info.num_crtc = 3;
2103                 adev->mode_info.num_hpd = 6;
2104                 adev->mode_info.num_dig = 9;
2105                 adev->mode_info.plane_type = dm_plane_type_carizzo;
2106                 break;
2107         case CHIP_STONEY:
2108                 adev->mode_info.num_crtc = 2;
2109                 adev->mode_info.num_hpd = 6;
2110                 adev->mode_info.num_dig = 9;
2111                 adev->mode_info.plane_type = dm_plane_type_stoney;
2112                 break;
2113         case CHIP_POLARIS11:
2114         case CHIP_POLARIS12:
2115                 adev->mode_info.num_crtc = 5;
2116                 adev->mode_info.num_hpd = 5;
2117                 adev->mode_info.num_dig = 5;
2118                 adev->mode_info.plane_type = dm_plane_type_default;
2119                 break;
2120         case CHIP_POLARIS10:
2121         case CHIP_VEGAM:
2122                 adev->mode_info.num_crtc = 6;
2123                 adev->mode_info.num_hpd = 6;
2124                 adev->mode_info.num_dig = 6;
2125                 adev->mode_info.plane_type = dm_plane_type_default;
2126                 break;
2127         case CHIP_VEGA10:
2128         case CHIP_VEGA12:
2129         case CHIP_VEGA20:
2130                 adev->mode_info.num_crtc = 6;
2131                 adev->mode_info.num_hpd = 6;
2132                 adev->mode_info.num_dig = 6;
2133                 adev->mode_info.plane_type = dm_plane_type_default;
2134                 break;
2135 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
2136         case CHIP_RAVEN:
2137                 adev->mode_info.num_crtc = 4;
2138                 adev->mode_info.num_hpd = 4;
2139                 adev->mode_info.num_dig = 4;
2140                 adev->mode_info.plane_type = dm_plane_type_default;
2141                 break;
2142 #endif
2143         default:
2144                 DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
2145                 return -EINVAL;
2146         }
2147
2148         amdgpu_dm_set_irq_funcs(adev);
2149
2150         if (adev->mode_info.funcs == NULL)
2151                 adev->mode_info.funcs = &dm_display_funcs;
2152
2153         /*
2154          * Note: Do NOT change adev->audio_endpt_rreg and
2155          * adev->audio_endpt_wreg because they are initialised in
2156          * amdgpu_device_init()
2157          */
2158 #if defined(CONFIG_DEBUG_KERNEL_DC)
2159         device_create_file(
2160                 adev->ddev->dev,
2161                 &dev_attr_s3_debug);
2162 #endif
2163
2164         return 0;
2165 }
2166
2167 static bool modeset_required(struct drm_crtc_state *crtc_state,
2168                              struct dc_stream_state *new_stream,
2169                              struct dc_stream_state *old_stream)
2170 {
2171         if (!drm_atomic_crtc_needs_modeset(crtc_state))
2172                 return false;
2173
2174         if (!crtc_state->enable)
2175                 return false;
2176
2177         return crtc_state->active;
2178 }
2179
2180 static bool modereset_required(struct drm_crtc_state *crtc_state)
2181 {
2182         if (!drm_atomic_crtc_needs_modeset(crtc_state))
2183                 return false;
2184
2185         return !crtc_state->enable || !crtc_state->active;
2186 }
2187
2188 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
2189 {
2190         drm_encoder_cleanup(encoder);
2191         kfree(encoder);
2192 }
2193
2194 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
2195         .destroy = amdgpu_dm_encoder_destroy,
2196 };
2197
2198 static bool fill_rects_from_plane_state(const struct drm_plane_state *state,
2199                                         struct dc_plane_state *plane_state)
2200 {
2201         plane_state->src_rect.x = state->src_x >> 16;
2202         plane_state->src_rect.y = state->src_y >> 16;
2203         /* we ignore the mantissa for now and do not deal with floating pixels :( */
2204         plane_state->src_rect.width = state->src_w >> 16;
2205
2206         if (plane_state->src_rect.width == 0)
2207                 return false;
2208
2209         plane_state->src_rect.height = state->src_h >> 16;
2210         if (plane_state->src_rect.height == 0)
2211                 return false;
2212
2213         plane_state->dst_rect.x = state->crtc_x;
2214         plane_state->dst_rect.y = state->crtc_y;
2215
2216         if (state->crtc_w == 0)
2217                 return false;
2218
2219         plane_state->dst_rect.width = state->crtc_w;
2220
2221         if (state->crtc_h == 0)
2222                 return false;
2223
2224         plane_state->dst_rect.height = state->crtc_h;
2225
2226         plane_state->clip_rect = plane_state->dst_rect;
2227
2228         switch (state->rotation & DRM_MODE_ROTATE_MASK) {
2229         case DRM_MODE_ROTATE_0:
2230                 plane_state->rotation = ROTATION_ANGLE_0;
2231                 break;
2232         case DRM_MODE_ROTATE_90:
2233                 plane_state->rotation = ROTATION_ANGLE_90;
2234                 break;
2235         case DRM_MODE_ROTATE_180:
2236                 plane_state->rotation = ROTATION_ANGLE_180;
2237                 break;
2238         case DRM_MODE_ROTATE_270:
2239                 plane_state->rotation = ROTATION_ANGLE_270;
2240                 break;
2241         default:
2242                 plane_state->rotation = ROTATION_ANGLE_0;
2243                 break;
2244         }
2245
2246         return true;
2247 }
2248 static int get_fb_info(const struct amdgpu_framebuffer *amdgpu_fb,
2249                        uint64_t *tiling_flags)
2250 {
2251         struct amdgpu_bo *rbo = gem_to_amdgpu_bo(amdgpu_fb->base.obj[0]);
2252         int r = amdgpu_bo_reserve(rbo, false);
2253
2254         if (unlikely(r)) {
2255                 /* Don't show error message when returning -ERESTARTSYS */
2256                 if (r != -ERESTARTSYS)
2257                         DRM_ERROR("Unable to reserve buffer: %d\n", r);
2258                 return r;
2259         }
2260
2261         if (tiling_flags)
2262                 amdgpu_bo_get_tiling_flags(rbo, tiling_flags);
2263
2264         amdgpu_bo_unreserve(rbo);
2265
2266         return r;
2267 }
2268
2269 static int fill_plane_attributes_from_fb(struct amdgpu_device *adev,
2270                                          struct dc_plane_state *plane_state,
2271                                          const struct amdgpu_framebuffer *amdgpu_fb)
2272 {
2273         uint64_t tiling_flags;
2274         unsigned int awidth;
2275         const struct drm_framebuffer *fb = &amdgpu_fb->base;
2276         int ret = 0;
2277         struct drm_format_name_buf format_name;
2278
2279         ret = get_fb_info(
2280                 amdgpu_fb,
2281                 &tiling_flags);
2282
2283         if (ret)
2284                 return ret;
2285
2286         switch (fb->format->format) {
2287         case DRM_FORMAT_C8:
2288                 plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
2289                 break;
2290         case DRM_FORMAT_RGB565:
2291                 plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
2292                 break;
2293         case DRM_FORMAT_XRGB8888:
2294         case DRM_FORMAT_ARGB8888:
2295                 plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
2296                 break;
2297         case DRM_FORMAT_XRGB2101010:
2298         case DRM_FORMAT_ARGB2101010:
2299                 plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
2300                 break;
2301         case DRM_FORMAT_XBGR2101010:
2302         case DRM_FORMAT_ABGR2101010:
2303                 plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
2304                 break;
2305         case DRM_FORMAT_XBGR8888:
2306         case DRM_FORMAT_ABGR8888:
2307                 plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
2308                 break;
2309         case DRM_FORMAT_NV21:
2310                 plane_state->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
2311                 break;
2312         case DRM_FORMAT_NV12:
2313                 plane_state->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
2314                 break;
2315         default:
2316                 DRM_ERROR("Unsupported screen format %s\n",
2317                           drm_get_format_name(fb->format->format, &format_name));
2318                 return -EINVAL;
2319         }
2320
2321         if (plane_state->format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN) {
2322                 plane_state->address.type = PLN_ADDR_TYPE_GRAPHICS;
2323                 plane_state->plane_size.grph.surface_size.x = 0;
2324                 plane_state->plane_size.grph.surface_size.y = 0;
2325                 plane_state->plane_size.grph.surface_size.width = fb->width;
2326                 plane_state->plane_size.grph.surface_size.height = fb->height;
2327                 plane_state->plane_size.grph.surface_pitch =
2328                                 fb->pitches[0] / fb->format->cpp[0];
2329                 /* TODO: unhardcode */
2330                 plane_state->color_space = COLOR_SPACE_SRGB;
2331
2332         } else {
2333                 awidth = ALIGN(fb->width, 64);
2334                 plane_state->address.type = PLN_ADDR_TYPE_VIDEO_PROGRESSIVE;
2335                 plane_state->plane_size.video.luma_size.x = 0;
2336                 plane_state->plane_size.video.luma_size.y = 0;
2337                 plane_state->plane_size.video.luma_size.width = awidth;
2338                 plane_state->plane_size.video.luma_size.height = fb->height;
2339                 /* TODO: unhardcode */
2340                 plane_state->plane_size.video.luma_pitch = awidth;
2341
2342                 plane_state->plane_size.video.chroma_size.x = 0;
2343                 plane_state->plane_size.video.chroma_size.y = 0;
2344                 plane_state->plane_size.video.chroma_size.width = awidth;
2345                 plane_state->plane_size.video.chroma_size.height = fb->height;
2346                 plane_state->plane_size.video.chroma_pitch = awidth / 2;
2347
2348                 /* TODO: unhardcode */
2349                 plane_state->color_space = COLOR_SPACE_YCBCR709;
2350         }
2351
2352         memset(&plane_state->tiling_info, 0, sizeof(plane_state->tiling_info));
2353
2354         /* Fill GFX8 params */
2355         if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE) == DC_ARRAY_2D_TILED_THIN1) {
2356                 unsigned int bankw, bankh, mtaspect, tile_split, num_banks;
2357
2358                 bankw = AMDGPU_TILING_GET(tiling_flags, BANK_WIDTH);
2359                 bankh = AMDGPU_TILING_GET(tiling_flags, BANK_HEIGHT);
2360                 mtaspect = AMDGPU_TILING_GET(tiling_flags, MACRO_TILE_ASPECT);
2361                 tile_split = AMDGPU_TILING_GET(tiling_flags, TILE_SPLIT);
2362                 num_banks = AMDGPU_TILING_GET(tiling_flags, NUM_BANKS);
2363
2364                 /* XXX fix me for VI */
2365                 plane_state->tiling_info.gfx8.num_banks = num_banks;
2366                 plane_state->tiling_info.gfx8.array_mode =
2367                                 DC_ARRAY_2D_TILED_THIN1;
2368                 plane_state->tiling_info.gfx8.tile_split = tile_split;
2369                 plane_state->tiling_info.gfx8.bank_width = bankw;
2370                 plane_state->tiling_info.gfx8.bank_height = bankh;
2371                 plane_state->tiling_info.gfx8.tile_aspect = mtaspect;
2372                 plane_state->tiling_info.gfx8.tile_mode =
2373                                 DC_ADDR_SURF_MICRO_TILING_DISPLAY;
2374         } else if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE)
2375                         == DC_ARRAY_1D_TILED_THIN1) {
2376                 plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_1D_TILED_THIN1;
2377         }
2378
2379         plane_state->tiling_info.gfx8.pipe_config =
2380                         AMDGPU_TILING_GET(tiling_flags, PIPE_CONFIG);
2381
2382         if (adev->asic_type == CHIP_VEGA10 ||
2383             adev->asic_type == CHIP_VEGA12 ||
2384             adev->asic_type == CHIP_VEGA20 ||
2385             adev->asic_type == CHIP_RAVEN) {
2386                 /* Fill GFX9 params */
2387                 plane_state->tiling_info.gfx9.num_pipes =
2388                         adev->gfx.config.gb_addr_config_fields.num_pipes;
2389                 plane_state->tiling_info.gfx9.num_banks =
2390                         adev->gfx.config.gb_addr_config_fields.num_banks;
2391                 plane_state->tiling_info.gfx9.pipe_interleave =
2392                         adev->gfx.config.gb_addr_config_fields.pipe_interleave_size;
2393                 plane_state->tiling_info.gfx9.num_shader_engines =
2394                         adev->gfx.config.gb_addr_config_fields.num_se;
2395                 plane_state->tiling_info.gfx9.max_compressed_frags =
2396                         adev->gfx.config.gb_addr_config_fields.max_compress_frags;
2397                 plane_state->tiling_info.gfx9.num_rb_per_se =
2398                         adev->gfx.config.gb_addr_config_fields.num_rb_per_se;
2399                 plane_state->tiling_info.gfx9.swizzle =
2400                         AMDGPU_TILING_GET(tiling_flags, SWIZZLE_MODE);
2401                 plane_state->tiling_info.gfx9.shaderEnable = 1;
2402         }
2403
2404         plane_state->visible = true;
2405         plane_state->scaling_quality.h_taps_c = 0;
2406         plane_state->scaling_quality.v_taps_c = 0;
2407
2408         /* is this needed? is plane_state zeroed at allocation? */
2409         plane_state->scaling_quality.h_taps = 0;
2410         plane_state->scaling_quality.v_taps = 0;
2411         plane_state->stereo_format = PLANE_STEREO_FORMAT_NONE;
2412
2413         return ret;
2414
2415 }
2416
2417 static int fill_plane_attributes(struct amdgpu_device *adev,
2418                                  struct dc_plane_state *dc_plane_state,
2419                                  struct drm_plane_state *plane_state,
2420                                  struct drm_crtc_state *crtc_state)
2421 {
2422         const struct amdgpu_framebuffer *amdgpu_fb =
2423                 to_amdgpu_framebuffer(plane_state->fb);
2424         const struct drm_crtc *crtc = plane_state->crtc;
2425         int ret = 0;
2426
2427         if (!fill_rects_from_plane_state(plane_state, dc_plane_state))
2428                 return -EINVAL;
2429
2430         ret = fill_plane_attributes_from_fb(
2431                 crtc->dev->dev_private,
2432                 dc_plane_state,
2433                 amdgpu_fb);
2434
2435         if (ret)
2436                 return ret;
2437
2438         /*
2439          * Always set input transfer function, since plane state is refreshed
2440          * every time.
2441          */
2442         ret = amdgpu_dm_set_degamma_lut(crtc_state, dc_plane_state);
2443         if (ret) {
2444                 dc_transfer_func_release(dc_plane_state->in_transfer_func);
2445                 dc_plane_state->in_transfer_func = NULL;
2446         }
2447
2448         return ret;
2449 }
2450
2451 static void update_stream_scaling_settings(const struct drm_display_mode *mode,
2452                                            const struct dm_connector_state *dm_state,
2453                                            struct dc_stream_state *stream)
2454 {
2455         enum amdgpu_rmx_type rmx_type;
2456
2457         struct rect src = { 0 }; /* viewport in composition space*/
2458         struct rect dst = { 0 }; /* stream addressable area */
2459
2460         /* no mode. nothing to be done */
2461         if (!mode)
2462                 return;
2463
2464         /* Full screen scaling by default */
2465         src.width = mode->hdisplay;
2466         src.height = mode->vdisplay;
2467         dst.width = stream->timing.h_addressable;
2468         dst.height = stream->timing.v_addressable;
2469
2470         if (dm_state) {
2471                 rmx_type = dm_state->scaling;
2472                 if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
2473                         if (src.width * dst.height <
2474                                         src.height * dst.width) {
2475                                 /* height needs less upscaling/more downscaling */
2476                                 dst.width = src.width *
2477                                                 dst.height / src.height;
2478                         } else {
2479                                 /* width needs less upscaling/more downscaling */
2480                                 dst.height = src.height *
2481                                                 dst.width / src.width;
2482                         }
2483                 } else if (rmx_type == RMX_CENTER) {
2484                         dst = src;
2485                 }
2486
2487                 dst.x = (stream->timing.h_addressable - dst.width) / 2;
2488                 dst.y = (stream->timing.v_addressable - dst.height) / 2;
2489
2490                 if (dm_state->underscan_enable) {
2491                         dst.x += dm_state->underscan_hborder / 2;
2492                         dst.y += dm_state->underscan_vborder / 2;
2493                         dst.width -= dm_state->underscan_hborder;
2494                         dst.height -= dm_state->underscan_vborder;
2495                 }
2496         }
2497
2498         stream->src = src;
2499         stream->dst = dst;
2500
2501         DRM_DEBUG_DRIVER("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
2502                         dst.x, dst.y, dst.width, dst.height);
2503
2504 }
2505
2506 static enum dc_color_depth
2507 convert_color_depth_from_display_info(const struct drm_connector *connector)
2508 {
2509         struct dm_connector_state *dm_conn_state =
2510                 to_dm_connector_state(connector->state);
2511         uint32_t bpc = connector->display_info.bpc;
2512
2513         /* TODO: Remove this when there's support for max_bpc in drm */
2514         if (dm_conn_state && bpc > dm_conn_state->max_bpc)
2515                 /* Round down to nearest even number. */
2516                 bpc = dm_conn_state->max_bpc - (dm_conn_state->max_bpc & 1);
2517
2518         switch (bpc) {
2519         case 0:
2520                 /*
2521                  * Temporary Work around, DRM doesn't parse color depth for
2522                  * EDID revision before 1.4
2523                  * TODO: Fix edid parsing
2524                  */
2525                 return COLOR_DEPTH_888;
2526         case 6:
2527                 return COLOR_DEPTH_666;
2528         case 8:
2529                 return COLOR_DEPTH_888;
2530         case 10:
2531                 return COLOR_DEPTH_101010;
2532         case 12:
2533                 return COLOR_DEPTH_121212;
2534         case 14:
2535                 return COLOR_DEPTH_141414;
2536         case 16:
2537                 return COLOR_DEPTH_161616;
2538         default:
2539                 return COLOR_DEPTH_UNDEFINED;
2540         }
2541 }
2542
2543 static enum dc_aspect_ratio
2544 get_aspect_ratio(const struct drm_display_mode *mode_in)
2545 {
2546         /* 1-1 mapping, since both enums follow the HDMI spec. */
2547         return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
2548 }
2549
2550 static enum dc_color_space
2551 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing)
2552 {
2553         enum dc_color_space color_space = COLOR_SPACE_SRGB;
2554
2555         switch (dc_crtc_timing->pixel_encoding) {
2556         case PIXEL_ENCODING_YCBCR422:
2557         case PIXEL_ENCODING_YCBCR444:
2558         case PIXEL_ENCODING_YCBCR420:
2559         {
2560                 /*
2561                  * 27030khz is the separation point between HDTV and SDTV
2562                  * according to HDMI spec, we use YCbCr709 and YCbCr601
2563                  * respectively
2564                  */
2565                 if (dc_crtc_timing->pix_clk_khz > 27030) {
2566                         if (dc_crtc_timing->flags.Y_ONLY)
2567                                 color_space =
2568                                         COLOR_SPACE_YCBCR709_LIMITED;
2569                         else
2570                                 color_space = COLOR_SPACE_YCBCR709;
2571                 } else {
2572                         if (dc_crtc_timing->flags.Y_ONLY)
2573                                 color_space =
2574                                         COLOR_SPACE_YCBCR601_LIMITED;
2575                         else
2576                                 color_space = COLOR_SPACE_YCBCR601;
2577                 }
2578
2579         }
2580         break;
2581         case PIXEL_ENCODING_RGB:
2582                 color_space = COLOR_SPACE_SRGB;
2583                 break;
2584
2585         default:
2586                 WARN_ON(1);
2587                 break;
2588         }
2589
2590         return color_space;
2591 }
2592
2593 static void reduce_mode_colour_depth(struct dc_crtc_timing *timing_out)
2594 {
2595         if (timing_out->display_color_depth <= COLOR_DEPTH_888)
2596                 return;
2597
2598         timing_out->display_color_depth--;
2599 }
2600
2601 static void adjust_colour_depth_from_display_info(struct dc_crtc_timing *timing_out,
2602                                                 const struct drm_display_info *info)
2603 {
2604         int normalized_clk;
2605         if (timing_out->display_color_depth <= COLOR_DEPTH_888)
2606                 return;
2607         do {
2608                 normalized_clk = timing_out->pix_clk_khz;
2609                 /* YCbCr 4:2:0 requires additional adjustment of 1/2 */
2610                 if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
2611                         normalized_clk /= 2;
2612                 /* Adjusting pix clock following on HDMI spec based on colour depth */
2613                 switch (timing_out->display_color_depth) {
2614                 case COLOR_DEPTH_101010:
2615                         normalized_clk = (normalized_clk * 30) / 24;
2616                         break;
2617                 case COLOR_DEPTH_121212:
2618                         normalized_clk = (normalized_clk * 36) / 24;
2619                         break;
2620                 case COLOR_DEPTH_161616:
2621                         normalized_clk = (normalized_clk * 48) / 24;
2622                         break;
2623                 default:
2624                         return;
2625                 }
2626                 if (normalized_clk <= info->max_tmds_clock)
2627                         return;
2628                 reduce_mode_colour_depth(timing_out);
2629
2630         } while (timing_out->display_color_depth > COLOR_DEPTH_888);
2631
2632 }
2633
2634 static void
2635 fill_stream_properties_from_drm_display_mode(struct dc_stream_state *stream,
2636                                              const struct drm_display_mode *mode_in,
2637                                              const struct drm_connector *connector,
2638                                              const struct dc_stream_state *old_stream)
2639 {
2640         struct dc_crtc_timing *timing_out = &stream->timing;
2641         const struct drm_display_info *info = &connector->display_info;
2642
2643         memset(timing_out, 0, sizeof(struct dc_crtc_timing));
2644
2645         timing_out->h_border_left = 0;
2646         timing_out->h_border_right = 0;
2647         timing_out->v_border_top = 0;
2648         timing_out->v_border_bottom = 0;
2649         /* TODO: un-hardcode */
2650         if (drm_mode_is_420_only(info, mode_in)
2651                         && stream->sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A)
2652                 timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
2653         else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCRCB444)
2654                         && stream->sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A)
2655                 timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
2656         else
2657                 timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
2658
2659         timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
2660         timing_out->display_color_depth = convert_color_depth_from_display_info(
2661                         connector);
2662         timing_out->scan_type = SCANNING_TYPE_NODATA;
2663         timing_out->hdmi_vic = 0;
2664
2665         if(old_stream) {
2666                 timing_out->vic = old_stream->timing.vic;
2667                 timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
2668                 timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
2669         } else {
2670                 timing_out->vic = drm_match_cea_mode(mode_in);
2671                 if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
2672                         timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
2673                 if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
2674                         timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
2675         }
2676
2677         timing_out->h_addressable = mode_in->crtc_hdisplay;
2678         timing_out->h_total = mode_in->crtc_htotal;
2679         timing_out->h_sync_width =
2680                 mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
2681         timing_out->h_front_porch =
2682                 mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
2683         timing_out->v_total = mode_in->crtc_vtotal;
2684         timing_out->v_addressable = mode_in->crtc_vdisplay;
2685         timing_out->v_front_porch =
2686                 mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
2687         timing_out->v_sync_width =
2688                 mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
2689         timing_out->pix_clk_khz = mode_in->crtc_clock;
2690         timing_out->aspect_ratio = get_aspect_ratio(mode_in);
2691
2692         stream->output_color_space = get_output_color_space(timing_out);
2693
2694         stream->out_transfer_func->type = TF_TYPE_PREDEFINED;
2695         stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
2696         if (stream->sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A)
2697                 adjust_colour_depth_from_display_info(timing_out, info);
2698 }
2699
2700 static void fill_audio_info(struct audio_info *audio_info,
2701                             const struct drm_connector *drm_connector,
2702                             const struct dc_sink *dc_sink)
2703 {
2704         int i = 0;
2705         int cea_revision = 0;
2706         const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
2707
2708         audio_info->manufacture_id = edid_caps->manufacturer_id;
2709         audio_info->product_id = edid_caps->product_id;
2710
2711         cea_revision = drm_connector->display_info.cea_rev;
2712
2713         strscpy(audio_info->display_name,
2714                 edid_caps->display_name,
2715                 AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
2716
2717         if (cea_revision >= 3) {
2718                 audio_info->mode_count = edid_caps->audio_mode_count;
2719
2720                 for (i = 0; i < audio_info->mode_count; ++i) {
2721                         audio_info->modes[i].format_code =
2722                                         (enum audio_format_code)
2723                                         (edid_caps->audio_modes[i].format_code);
2724                         audio_info->modes[i].channel_count =
2725                                         edid_caps->audio_modes[i].channel_count;
2726                         audio_info->modes[i].sample_rates.all =
2727                                         edid_caps->audio_modes[i].sample_rate;
2728                         audio_info->modes[i].sample_size =
2729                                         edid_caps->audio_modes[i].sample_size;
2730                 }
2731         }
2732
2733         audio_info->flags.all = edid_caps->speaker_flags;
2734
2735         /* TODO: We only check for the progressive mode, check for interlace mode too */
2736         if (drm_connector->latency_present[0]) {
2737                 audio_info->video_latency = drm_connector->video_latency[0];
2738                 audio_info->audio_latency = drm_connector->audio_latency[0];
2739         }
2740
2741         /* TODO: For DP, video and audio latency should be calculated from DPCD caps */
2742
2743 }
2744
2745 static void
2746 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
2747                                       struct drm_display_mode *dst_mode)
2748 {
2749         dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
2750         dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
2751         dst_mode->crtc_clock = src_mode->crtc_clock;
2752         dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
2753         dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
2754         dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
2755         dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
2756         dst_mode->crtc_htotal = src_mode->crtc_htotal;
2757         dst_mode->crtc_hskew = src_mode->crtc_hskew;
2758         dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
2759         dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
2760         dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
2761         dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
2762         dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
2763 }
2764
2765 static void
2766 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
2767                                         const struct drm_display_mode *native_mode,
2768                                         bool scale_enabled)
2769 {
2770         if (scale_enabled) {
2771                 copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
2772         } else if (native_mode->clock == drm_mode->clock &&
2773                         native_mode->htotal == drm_mode->htotal &&
2774                         native_mode->vtotal == drm_mode->vtotal) {
2775                 copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
2776         } else {
2777                 /* no scaling nor amdgpu inserted, no need to patch */
2778         }
2779 }
2780
2781 static struct dc_sink *
2782 create_fake_sink(struct amdgpu_dm_connector *aconnector)
2783 {
2784         struct dc_sink_init_data sink_init_data = { 0 };
2785         struct dc_sink *sink = NULL;
2786         sink_init_data.link = aconnector->dc_link;
2787         sink_init_data.sink_signal = aconnector->dc_link->connector_signal;
2788
2789         sink = dc_sink_create(&sink_init_data);
2790         if (!sink) {
2791                 DRM_ERROR("Failed to create sink!\n");
2792                 return NULL;
2793         }
2794         sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
2795
2796         return sink;
2797 }
2798
2799 static void set_multisync_trigger_params(
2800                 struct dc_stream_state *stream)
2801 {
2802         if (stream->triggered_crtc_reset.enabled) {
2803                 stream->triggered_crtc_reset.event = CRTC_EVENT_VSYNC_RISING;
2804                 stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_LINE;
2805         }
2806 }
2807
2808 static void set_master_stream(struct dc_stream_state *stream_set[],
2809                               int stream_count)
2810 {
2811         int j, highest_rfr = 0, master_stream = 0;
2812
2813         for (j = 0;  j < stream_count; j++) {
2814                 if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
2815                         int refresh_rate = 0;
2816
2817                         refresh_rate = (stream_set[j]->timing.pix_clk_khz*1000)/
2818                                 (stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
2819                         if (refresh_rate > highest_rfr) {
2820                                 highest_rfr = refresh_rate;
2821                                 master_stream = j;
2822                         }
2823                 }
2824         }
2825         for (j = 0;  j < stream_count; j++) {
2826                 if (stream_set[j])
2827                         stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
2828         }
2829 }
2830
2831 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
2832 {
2833         int i = 0;
2834
2835         if (context->stream_count < 2)
2836                 return;
2837         for (i = 0; i < context->stream_count ; i++) {
2838                 if (!context->streams[i])
2839                         continue;
2840                 /*
2841                  * TODO: add a function to read AMD VSDB bits and set
2842                  * crtc_sync_master.multi_sync_enabled flag
2843                  * For now it's set to false
2844                  */
2845                 set_multisync_trigger_params(context->streams[i]);
2846         }
2847         set_master_stream(context->streams, context->stream_count);
2848 }
2849
2850 static struct dc_stream_state *
2851 create_stream_for_sink(struct amdgpu_dm_connector *aconnector,
2852                        const struct drm_display_mode *drm_mode,
2853                        const struct dm_connector_state *dm_state,
2854                        const struct dc_stream_state *old_stream)
2855 {
2856         struct drm_display_mode *preferred_mode = NULL;
2857         struct drm_connector *drm_connector;
2858         struct dc_stream_state *stream = NULL;
2859         struct drm_display_mode mode = *drm_mode;
2860         bool native_mode_found = false;
2861         bool scale = dm_state ? (dm_state->scaling != RMX_OFF) : false;
2862         int mode_refresh;
2863         int preferred_refresh = 0;
2864
2865         struct dc_sink *sink = NULL;
2866         if (aconnector == NULL) {
2867                 DRM_ERROR("aconnector is NULL!\n");
2868                 return stream;
2869         }
2870
2871         drm_connector = &aconnector->base;
2872
2873         if (!aconnector->dc_sink) {
2874                 if (!aconnector->mst_port) {
2875                         sink = create_fake_sink(aconnector);
2876                         if (!sink)
2877                                 return stream;
2878                 }
2879         } else {
2880                 sink = aconnector->dc_sink;
2881         }
2882
2883         stream = dc_create_stream_for_sink(sink);
2884
2885         if (stream == NULL) {
2886                 DRM_ERROR("Failed to create stream for sink!\n");
2887                 goto finish;
2888         }
2889
2890         list_for_each_entry(preferred_mode, &aconnector->base.modes, head) {
2891                 /* Search for preferred mode */
2892                 if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
2893                         native_mode_found = true;
2894                         break;
2895                 }
2896         }
2897         if (!native_mode_found)
2898                 preferred_mode = list_first_entry_or_null(
2899                                 &aconnector->base.modes,
2900                                 struct drm_display_mode,
2901                                 head);
2902
2903         mode_refresh = drm_mode_vrefresh(&mode);
2904
2905         if (preferred_mode == NULL) {
2906                 /*
2907                  * This may not be an error, the use case is when we have no
2908                  * usermode calls to reset and set mode upon hotplug. In this
2909                  * case, we call set mode ourselves to restore the previous mode
2910                  * and the modelist may not be filled in in time.
2911                  */
2912                 DRM_DEBUG_DRIVER("No preferred mode found\n");
2913         } else {
2914                 decide_crtc_timing_for_drm_display_mode(
2915                                 &mode, preferred_mode,
2916                                 dm_state ? (dm_state->scaling != RMX_OFF) : false);
2917                 preferred_refresh = drm_mode_vrefresh(preferred_mode);
2918         }
2919
2920         if (!dm_state)
2921                 drm_mode_set_crtcinfo(&mode, 0);
2922
2923         /*
2924         * If scaling is enabled and refresh rate didn't change
2925         * we copy the vic and polarities of the old timings
2926         */
2927         if (!scale || mode_refresh != preferred_refresh)
2928                 fill_stream_properties_from_drm_display_mode(stream,
2929                         &mode, &aconnector->base, NULL);
2930         else
2931                 fill_stream_properties_from_drm_display_mode(stream,
2932                         &mode, &aconnector->base, old_stream);
2933
2934         update_stream_scaling_settings(&mode, dm_state, stream);
2935
2936         fill_audio_info(
2937                 &stream->audio_info,
2938                 drm_connector,
2939                 sink);
2940
2941         update_stream_signal(stream);
2942
2943         if (dm_state && dm_state->freesync_capable)
2944                 stream->ignore_msa_timing_param = true;
2945
2946 finish:
2947         if (sink && sink->sink_signal == SIGNAL_TYPE_VIRTUAL && aconnector->base.force != DRM_FORCE_ON)
2948                 dc_sink_release(sink);
2949
2950         return stream;
2951 }
2952
2953 static void amdgpu_dm_crtc_destroy(struct drm_crtc *crtc)
2954 {
2955         drm_crtc_cleanup(crtc);
2956         kfree(crtc);
2957 }
2958
2959 static void dm_crtc_destroy_state(struct drm_crtc *crtc,
2960                                   struct drm_crtc_state *state)
2961 {
2962         struct dm_crtc_state *cur = to_dm_crtc_state(state);
2963
2964         /* TODO Destroy dc_stream objects are stream object is flattened */
2965         if (cur->stream)
2966                 dc_stream_release(cur->stream);
2967
2968
2969         __drm_atomic_helper_crtc_destroy_state(state);
2970
2971
2972         kfree(state);
2973 }
2974
2975 static void dm_crtc_reset_state(struct drm_crtc *crtc)
2976 {
2977         struct dm_crtc_state *state;
2978
2979         if (crtc->state)
2980                 dm_crtc_destroy_state(crtc, crtc->state);
2981
2982         state = kzalloc(sizeof(*state), GFP_KERNEL);
2983         if (WARN_ON(!state))
2984                 return;
2985
2986         crtc->state = &state->base;
2987         crtc->state->crtc = crtc;
2988
2989 }
2990
2991 static struct drm_crtc_state *
2992 dm_crtc_duplicate_state(struct drm_crtc *crtc)
2993 {
2994         struct dm_crtc_state *state, *cur;
2995
2996         cur = to_dm_crtc_state(crtc->state);
2997
2998         if (WARN_ON(!crtc->state))
2999                 return NULL;
3000
3001         state = kzalloc(sizeof(*state), GFP_KERNEL);
3002         if (!state)
3003                 return NULL;
3004
3005         __drm_atomic_helper_crtc_duplicate_state(crtc, &state->base);
3006
3007         if (cur->stream) {
3008                 state->stream = cur->stream;
3009                 dc_stream_retain(state->stream);
3010         }
3011
3012         state->adjust = cur->adjust;
3013         state->vrr_infopacket = cur->vrr_infopacket;
3014         state->abm_level = cur->abm_level;
3015         state->vrr_supported = cur->vrr_supported;
3016         state->freesync_config = cur->freesync_config;
3017         state->crc_enabled = cur->crc_enabled;
3018
3019         /* TODO Duplicate dc_stream after objects are stream object is flattened */
3020
3021         return &state->base;
3022 }
3023
3024
3025 static inline int dm_set_vblank(struct drm_crtc *crtc, bool enable)
3026 {
3027         enum dc_irq_source irq_source;
3028         struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
3029         struct amdgpu_device *adev = crtc->dev->dev_private;
3030
3031         irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3032         return dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3033 }
3034
3035 static int dm_enable_vblank(struct drm_crtc *crtc)
3036 {
3037         return dm_set_vblank(crtc, true);
3038 }
3039
3040 static void dm_disable_vblank(struct drm_crtc *crtc)
3041 {
3042         dm_set_vblank(crtc, false);
3043 }
3044
3045 /* Implemented only the options currently availible for the driver */
3046 static const struct drm_crtc_funcs amdgpu_dm_crtc_funcs = {
3047         .reset = dm_crtc_reset_state,
3048         .destroy = amdgpu_dm_crtc_destroy,
3049         .gamma_set = drm_atomic_helper_legacy_gamma_set,
3050         .set_config = drm_atomic_helper_set_config,
3051         .page_flip = drm_atomic_helper_page_flip,
3052         .atomic_duplicate_state = dm_crtc_duplicate_state,
3053         .atomic_destroy_state = dm_crtc_destroy_state,
3054         .set_crc_source = amdgpu_dm_crtc_set_crc_source,
3055         .verify_crc_source = amdgpu_dm_crtc_verify_crc_source,
3056         .enable_vblank = dm_enable_vblank,
3057         .disable_vblank = dm_disable_vblank,
3058 };
3059
3060 static enum drm_connector_status
3061 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
3062 {
3063         bool connected;
3064         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3065
3066         /*
3067          * Notes:
3068          * 1. This interface is NOT called in context of HPD irq.
3069          * 2. This interface *is called* in context of user-mode ioctl. Which
3070          * makes it a bad place for *any* MST-related activity.
3071          */
3072
3073         if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
3074             !aconnector->fake_enable)
3075                 connected = (aconnector->dc_sink != NULL);
3076         else
3077                 connected = (aconnector->base.force == DRM_FORCE_ON);
3078
3079         return (connected ? connector_status_connected :
3080                         connector_status_disconnected);
3081 }
3082
3083 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
3084                                             struct drm_connector_state *connector_state,
3085                                             struct drm_property *property,
3086                                             uint64_t val)
3087 {
3088         struct drm_device *dev = connector->dev;
3089         struct amdgpu_device *adev = dev->dev_private;
3090         struct dm_connector_state *dm_old_state =
3091                 to_dm_connector_state(connector->state);
3092         struct dm_connector_state *dm_new_state =
3093                 to_dm_connector_state(connector_state);
3094
3095         int ret = -EINVAL;
3096
3097         if (property == dev->mode_config.scaling_mode_property) {
3098                 enum amdgpu_rmx_type rmx_type;
3099
3100                 switch (val) {
3101                 case DRM_MODE_SCALE_CENTER:
3102                         rmx_type = RMX_CENTER;
3103                         break;
3104                 case DRM_MODE_SCALE_ASPECT:
3105                         rmx_type = RMX_ASPECT;
3106                         break;
3107                 case DRM_MODE_SCALE_FULLSCREEN:
3108                         rmx_type = RMX_FULL;
3109                         break;
3110                 case DRM_MODE_SCALE_NONE:
3111                 default:
3112                         rmx_type = RMX_OFF;
3113                         break;
3114                 }
3115
3116                 if (dm_old_state->scaling == rmx_type)
3117                         return 0;
3118
3119                 dm_new_state->scaling = rmx_type;
3120                 ret = 0;
3121         } else if (property == adev->mode_info.underscan_hborder_property) {
3122                 dm_new_state->underscan_hborder = val;
3123                 ret = 0;
3124         } else if (property == adev->mode_info.underscan_vborder_property) {
3125                 dm_new_state->underscan_vborder = val;
3126                 ret = 0;
3127         } else if (property == adev->mode_info.underscan_property) {
3128                 dm_new_state->underscan_enable = val;
3129                 ret = 0;
3130         } else if (property == adev->mode_info.max_bpc_property) {
3131                 dm_new_state->max_bpc = val;
3132                 ret = 0;
3133         } else if (property == adev->mode_info.abm_level_property) {
3134                 dm_new_state->abm_level = val;
3135                 ret = 0;
3136         }
3137
3138         return ret;
3139 }
3140
3141 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
3142                                             const struct drm_connector_state *state,
3143                                             struct drm_property *property,
3144                                             uint64_t *val)
3145 {
3146         struct drm_device *dev = connector->dev;
3147         struct amdgpu_device *adev = dev->dev_private;
3148         struct dm_connector_state *dm_state =
3149                 to_dm_connector_state(state);
3150         int ret = -EINVAL;
3151
3152         if (property == dev->mode_config.scaling_mode_property) {
3153                 switch (dm_state->scaling) {
3154                 case RMX_CENTER:
3155                         *val = DRM_MODE_SCALE_CENTER;
3156                         break;
3157                 case RMX_ASPECT:
3158                         *val = DRM_MODE_SCALE_ASPECT;
3159                         break;
3160                 case RMX_FULL:
3161                         *val = DRM_MODE_SCALE_FULLSCREEN;
3162                         break;
3163                 case RMX_OFF:
3164                 default:
3165                         *val = DRM_MODE_SCALE_NONE;
3166                         break;
3167                 }
3168                 ret = 0;
3169         } else if (property == adev->mode_info.underscan_hborder_property) {
3170                 *val = dm_state->underscan_hborder;
3171                 ret = 0;
3172         } else if (property == adev->mode_info.underscan_vborder_property) {
3173                 *val = dm_state->underscan_vborder;
3174                 ret = 0;
3175         } else if (property == adev->mode_info.underscan_property) {
3176                 *val = dm_state->underscan_enable;
3177                 ret = 0;
3178         } else if (property == adev->mode_info.max_bpc_property) {
3179                 *val = dm_state->max_bpc;
3180                 ret = 0;
3181         } else if (property == adev->mode_info.abm_level_property) {
3182                 *val = dm_state->abm_level;
3183                 ret = 0;
3184         }
3185
3186         return ret;
3187 }
3188
3189 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
3190 {
3191         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3192         const struct dc_link *link = aconnector->dc_link;
3193         struct amdgpu_device *adev = connector->dev->dev_private;
3194         struct amdgpu_display_manager *dm = &adev->dm;
3195
3196 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
3197         defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
3198
3199         if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
3200             link->type != dc_connection_none &&
3201             dm->backlight_dev) {
3202                 backlight_device_unregister(dm->backlight_dev);
3203                 dm->backlight_dev = NULL;
3204         }
3205 #endif
3206         drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
3207         drm_connector_unregister(connector);
3208         drm_connector_cleanup(connector);
3209         kfree(connector);
3210 }
3211
3212 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
3213 {
3214         struct dm_connector_state *state =
3215                 to_dm_connector_state(connector->state);
3216
3217         if (connector->state)
3218                 __drm_atomic_helper_connector_destroy_state(connector->state);
3219
3220         kfree(state);
3221
3222         state = kzalloc(sizeof(*state), GFP_KERNEL);
3223
3224         if (state) {
3225                 state->scaling = RMX_OFF;
3226                 state->underscan_enable = false;
3227                 state->underscan_hborder = 0;
3228                 state->underscan_vborder = 0;
3229                 state->max_bpc = 8;
3230
3231                 __drm_atomic_helper_connector_reset(connector, &state->base);
3232         }
3233 }
3234
3235 struct drm_connector_state *
3236 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
3237 {
3238         struct dm_connector_state *state =
3239                 to_dm_connector_state(connector->state);
3240
3241         struct dm_connector_state *new_state =
3242                         kmemdup(state, sizeof(*state), GFP_KERNEL);
3243
3244         if (!new_state)
3245                 return NULL;
3246
3247         __drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
3248
3249         new_state->freesync_capable = state->freesync_capable;
3250         new_state->abm_level = state->abm_level;
3251         new_state->scaling = state->scaling;
3252         new_state->underscan_enable = state->underscan_enable;
3253         new_state->underscan_hborder = state->underscan_hborder;
3254         new_state->underscan_vborder = state->underscan_vborder;
3255         new_state->max_bpc = state->max_bpc;
3256
3257         return &new_state->base;
3258 }
3259
3260 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
3261         .reset = amdgpu_dm_connector_funcs_reset,
3262         .detect = amdgpu_dm_connector_detect,
3263         .fill_modes = drm_helper_probe_single_connector_modes,
3264         .destroy = amdgpu_dm_connector_destroy,
3265         .atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
3266         .atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
3267         .atomic_set_property = amdgpu_dm_connector_atomic_set_property,
3268         .atomic_get_property = amdgpu_dm_connector_atomic_get_property
3269 };
3270
3271 static int get_modes(struct drm_connector *connector)
3272 {
3273         return amdgpu_dm_connector_get_modes(connector);
3274 }
3275
3276 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
3277 {
3278         struct dc_sink_init_data init_params = {
3279                         .link = aconnector->dc_link,
3280                         .sink_signal = SIGNAL_TYPE_VIRTUAL
3281         };
3282         struct edid *edid;
3283
3284         if (!aconnector->base.edid_blob_ptr) {
3285                 DRM_ERROR("No EDID firmware found on connector: %s ,forcing to OFF!\n",
3286                                 aconnector->base.name);
3287
3288                 aconnector->base.force = DRM_FORCE_OFF;
3289                 aconnector->base.override_edid = false;
3290                 return;
3291         }
3292
3293         edid = (struct edid *) aconnector->base.edid_blob_ptr->data;
3294
3295         aconnector->edid = edid;
3296
3297         aconnector->dc_em_sink = dc_link_add_remote_sink(
3298                 aconnector->dc_link,
3299                 (uint8_t *)edid,
3300                 (edid->extensions + 1) * EDID_LENGTH,
3301                 &init_params);
3302
3303         if (aconnector->base.force == DRM_FORCE_ON)
3304                 aconnector->dc_sink = aconnector->dc_link->local_sink ?
3305                 aconnector->dc_link->local_sink :
3306                 aconnector->dc_em_sink;
3307 }
3308
3309 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
3310 {
3311         struct dc_link *link = (struct dc_link *)aconnector->dc_link;
3312
3313         /*
3314          * In case of headless boot with force on for DP managed connector
3315          * Those settings have to be != 0 to get initial modeset
3316          */
3317         if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
3318                 link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
3319                 link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
3320         }
3321
3322
3323         aconnector->base.override_edid = true;
3324         create_eml_sink(aconnector);
3325 }
3326
3327 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
3328                                    struct drm_display_mode *mode)
3329 {
3330         int result = MODE_ERROR;
3331         struct dc_sink *dc_sink;
3332         struct amdgpu_device *adev = connector->dev->dev_private;
3333         /* TODO: Unhardcode stream count */
3334         struct dc_stream_state *stream;
3335         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3336         enum dc_status dc_result = DC_OK;
3337
3338         if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
3339                         (mode->flags & DRM_MODE_FLAG_DBLSCAN))
3340                 return result;
3341
3342         /*
3343          * Only run this the first time mode_valid is called to initilialize
3344          * EDID mgmt
3345          */
3346         if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
3347                 !aconnector->dc_em_sink)
3348                 handle_edid_mgmt(aconnector);
3349
3350         dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
3351
3352         if (dc_sink == NULL) {
3353                 DRM_ERROR("dc_sink is NULL!\n");
3354                 goto fail;
3355         }
3356
3357         stream = create_stream_for_sink(aconnector, mode, NULL, NULL);
3358         if (stream == NULL) {
3359                 DRM_ERROR("Failed to create stream for sink!\n");
3360                 goto fail;
3361         }
3362
3363         dc_result = dc_validate_stream(adev->dm.dc, stream);
3364
3365         if (dc_result == DC_OK)
3366                 result = MODE_OK;
3367         else
3368                 DRM_DEBUG_KMS("Mode %dx%d (clk %d) failed DC validation with error %d\n",
3369                               mode->vdisplay,
3370                               mode->hdisplay,
3371                               mode->clock,
3372                               dc_result);
3373
3374         dc_stream_release(stream);
3375
3376 fail:
3377         /* TODO: error handling*/
3378         return result;
3379 }
3380
3381 static const struct drm_connector_helper_funcs
3382 amdgpu_dm_connector_helper_funcs = {
3383         /*
3384          * If hotplugging a second bigger display in FB Con mode, bigger resolution
3385          * modes will be filtered by drm_mode_validate_size(), and those modes
3386          * are missing after user start lightdm. So we need to renew modes list.
3387          * in get_modes call back, not just return the modes count
3388          */
3389         .get_modes = get_modes,
3390         .mode_valid = amdgpu_dm_connector_mode_valid,
3391 };
3392
3393 static void dm_crtc_helper_disable(struct drm_crtc *crtc)
3394 {
3395 }
3396
3397 static int dm_crtc_helper_atomic_check(struct drm_crtc *crtc,
3398                                        struct drm_crtc_state *state)
3399 {
3400         struct amdgpu_device *adev = crtc->dev->dev_private;
3401         struct dc *dc = adev->dm.dc;
3402         struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(state);
3403         int ret = -EINVAL;
3404
3405         if (unlikely(!dm_crtc_state->stream &&
3406                      modeset_required(state, NULL, dm_crtc_state->stream))) {
3407                 WARN_ON(1);
3408                 return ret;
3409         }
3410
3411         /* In some use cases, like reset, no stream is attached */
3412         if (!dm_crtc_state->stream)
3413                 return 0;
3414
3415         if (dc_validate_stream(dc, dm_crtc_state->stream) == DC_OK)
3416                 return 0;
3417
3418         return ret;
3419 }
3420
3421 static bool dm_crtc_helper_mode_fixup(struct drm_crtc *crtc,
3422                                       const struct drm_display_mode *mode,
3423                                       struct drm_display_mode *adjusted_mode)
3424 {
3425         return true;
3426 }
3427
3428 static const struct drm_crtc_helper_funcs amdgpu_dm_crtc_helper_funcs = {
3429         .disable = dm_crtc_helper_disable,
3430         .atomic_check = dm_crtc_helper_atomic_check,
3431         .mode_fixup = dm_crtc_helper_mode_fixup
3432 };
3433
3434 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
3435 {
3436
3437 }
3438
3439 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
3440                                           struct drm_crtc_state *crtc_state,
3441                                           struct drm_connector_state *conn_state)
3442 {
3443         return 0;
3444 }
3445
3446 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
3447         .disable = dm_encoder_helper_disable,
3448         .atomic_check = dm_encoder_helper_atomic_check
3449 };
3450
3451 static void dm_drm_plane_reset(struct drm_plane *plane)
3452 {
3453         struct dm_plane_state *amdgpu_state = NULL;
3454
3455         if (plane->state)
3456                 plane->funcs->atomic_destroy_state(plane, plane->state);
3457
3458         amdgpu_state = kzalloc(sizeof(*amdgpu_state), GFP_KERNEL);
3459         WARN_ON(amdgpu_state == NULL);
3460
3461         if (amdgpu_state) {
3462                 plane->state = &amdgpu_state->base;
3463                 plane->state->plane = plane;
3464                 plane->state->rotation = DRM_MODE_ROTATE_0;
3465         }
3466 }
3467
3468 static struct drm_plane_state *
3469 dm_drm_plane_duplicate_state(struct drm_plane *plane)
3470 {
3471         struct dm_plane_state *dm_plane_state, *old_dm_plane_state;
3472
3473         old_dm_plane_state = to_dm_plane_state(plane->state);
3474         dm_plane_state = kzalloc(sizeof(*dm_plane_state), GFP_KERNEL);
3475         if (!dm_plane_state)
3476                 return NULL;
3477
3478         __drm_atomic_helper_plane_duplicate_state(plane, &dm_plane_state->base);
3479
3480         if (old_dm_plane_state->dc_state) {
3481                 dm_plane_state->dc_state = old_dm_plane_state->dc_state;
3482                 dc_plane_state_retain(dm_plane_state->dc_state);
3483         }
3484
3485         return &dm_plane_state->base;
3486 }
3487
3488 void dm_drm_plane_destroy_state(struct drm_plane *plane,
3489                                 struct drm_plane_state *state)
3490 {
3491         struct dm_plane_state *dm_plane_state = to_dm_plane_state(state);
3492
3493         if (dm_plane_state->dc_state)
3494                 dc_plane_state_release(dm_plane_state->dc_state);
3495
3496         drm_atomic_helper_plane_destroy_state(plane, state);
3497 }
3498
3499 static const struct drm_plane_funcs dm_plane_funcs = {
3500         .update_plane   = drm_atomic_helper_update_plane,
3501         .disable_plane  = drm_atomic_helper_disable_plane,
3502         .destroy        = drm_primary_helper_destroy,
3503         .reset = dm_drm_plane_reset,
3504         .atomic_duplicate_state = dm_drm_plane_duplicate_state,
3505         .atomic_destroy_state = dm_drm_plane_destroy_state,
3506 };
3507
3508 static int dm_plane_helper_prepare_fb(struct drm_plane *plane,
3509                                       struct drm_plane_state *new_state)
3510 {
3511         struct amdgpu_framebuffer *afb;
3512         struct drm_gem_object *obj;
3513         struct amdgpu_device *adev;
3514         struct amdgpu_bo *rbo;
3515         uint64_t chroma_addr = 0;
3516         struct dm_plane_state *dm_plane_state_new, *dm_plane_state_old;
3517         unsigned int awidth;
3518         uint32_t domain;
3519         int r;
3520
3521         dm_plane_state_old = to_dm_plane_state(plane->state);
3522         dm_plane_state_new = to_dm_plane_state(new_state);
3523
3524         if (!new_state->fb) {
3525                 DRM_DEBUG_DRIVER("No FB bound\n");
3526                 return 0;
3527         }
3528
3529         afb = to_amdgpu_framebuffer(new_state->fb);
3530         obj = new_state->fb->obj[0];
3531         rbo = gem_to_amdgpu_bo(obj);
3532         adev = amdgpu_ttm_adev(rbo->tbo.bdev);
3533         r = amdgpu_bo_reserve(rbo, false);
3534         if (unlikely(r != 0))
3535                 return r;
3536
3537         if (plane->type != DRM_PLANE_TYPE_CURSOR)
3538                 domain = amdgpu_display_supported_domains(adev);
3539         else
3540                 domain = AMDGPU_GEM_DOMAIN_VRAM;
3541
3542         r = amdgpu_bo_pin(rbo, domain);
3543         if (unlikely(r != 0)) {
3544                 if (r != -ERESTARTSYS)
3545                         DRM_ERROR("Failed to pin framebuffer with error %d\n", r);
3546                 amdgpu_bo_unreserve(rbo);
3547                 return r;
3548         }
3549
3550         r = amdgpu_ttm_alloc_gart(&rbo->tbo);
3551         if (unlikely(r != 0)) {
3552                 amdgpu_bo_unpin(rbo);
3553                 amdgpu_bo_unreserve(rbo);
3554                 DRM_ERROR("%p bind failed\n", rbo);
3555                 return r;
3556         }
3557         amdgpu_bo_unreserve(rbo);
3558
3559         afb->address = amdgpu_bo_gpu_offset(rbo);
3560
3561         amdgpu_bo_ref(rbo);
3562
3563         if (dm_plane_state_new->dc_state &&
3564                         dm_plane_state_old->dc_state != dm_plane_state_new->dc_state) {
3565                 struct dc_plane_state *plane_state = dm_plane_state_new->dc_state;
3566
3567                 if (plane_state->format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN) {
3568                         plane_state->address.grph.addr.low_part = lower_32_bits(afb->address);
3569                         plane_state->address.grph.addr.high_part = upper_32_bits(afb->address);
3570                 } else {
3571                         awidth = ALIGN(new_state->fb->width, 64);
3572                         plane_state->address.type = PLN_ADDR_TYPE_VIDEO_PROGRESSIVE;
3573                         plane_state->address.video_progressive.luma_addr.low_part
3574                                                         = lower_32_bits(afb->address);
3575                         plane_state->address.video_progressive.luma_addr.high_part
3576                                                         = upper_32_bits(afb->address);
3577                         chroma_addr = afb->address + (u64)awidth * new_state->fb->height;
3578                         plane_state->address.video_progressive.chroma_addr.low_part
3579                                                         = lower_32_bits(chroma_addr);
3580                         plane_state->address.video_progressive.chroma_addr.high_part
3581                                                         = upper_32_bits(chroma_addr);
3582                 }
3583         }
3584
3585         return 0;
3586 }
3587
3588 static void dm_plane_helper_cleanup_fb(struct drm_plane *plane,
3589                                        struct drm_plane_state *old_state)
3590 {
3591         struct amdgpu_bo *rbo;
3592         int r;
3593
3594         if (!old_state->fb)
3595                 return;
3596
3597         rbo = gem_to_amdgpu_bo(old_state->fb->obj[0]);
3598         r = amdgpu_bo_reserve(rbo, false);
3599         if (unlikely(r)) {
3600                 DRM_ERROR("failed to reserve rbo before unpin\n");
3601                 return;
3602         }
3603
3604         amdgpu_bo_unpin(rbo);
3605         amdgpu_bo_unreserve(rbo);
3606         amdgpu_bo_unref(&rbo);
3607 }
3608
3609 static int dm_plane_atomic_check(struct drm_plane *plane,
3610                                  struct drm_plane_state *state)
3611 {
3612         struct amdgpu_device *adev = plane->dev->dev_private;
3613         struct dc *dc = adev->dm.dc;
3614         struct dm_plane_state *dm_plane_state = to_dm_plane_state(state);
3615
3616         if (!dm_plane_state->dc_state)
3617                 return 0;
3618
3619         if (!fill_rects_from_plane_state(state, dm_plane_state->dc_state))
3620                 return -EINVAL;
3621
3622         if (dc_validate_plane(dc, dm_plane_state->dc_state) == DC_OK)
3623                 return 0;
3624
3625         return -EINVAL;
3626 }
3627
3628 static int dm_plane_atomic_async_check(struct drm_plane *plane,
3629                                        struct drm_plane_state *new_plane_state)
3630 {
3631         /* Only support async updates on cursor planes. */
3632         if (plane->type != DRM_PLANE_TYPE_CURSOR)
3633                 return -EINVAL;
3634
3635         return 0;
3636 }
3637
3638 static void dm_plane_atomic_async_update(struct drm_plane *plane,
3639                                          struct drm_plane_state *new_state)
3640 {
3641         struct drm_plane_state *old_state =
3642                 drm_atomic_get_old_plane_state(new_state->state, plane);
3643
3644         if (plane->state->fb != new_state->fb)
3645                 drm_atomic_set_fb_for_plane(plane->state, new_state->fb);
3646
3647         plane->state->src_x = new_state->src_x;
3648         plane->state->src_y = new_state->src_y;
3649         plane->state->src_w = new_state->src_w;
3650         plane->state->src_h = new_state->src_h;
3651         plane->state->crtc_x = new_state->crtc_x;
3652         plane->state->crtc_y = new_state->crtc_y;
3653         plane->state->crtc_w = new_state->crtc_w;
3654         plane->state->crtc_h = new_state->crtc_h;
3655
3656         handle_cursor_update(plane, old_state);
3657 }
3658
3659 static const struct drm_plane_helper_funcs dm_plane_helper_funcs = {
3660         .prepare_fb = dm_plane_helper_prepare_fb,
3661         .cleanup_fb = dm_plane_helper_cleanup_fb,
3662         .atomic_check = dm_plane_atomic_check,
3663         .atomic_async_check = dm_plane_atomic_async_check,
3664         .atomic_async_update = dm_plane_atomic_async_update
3665 };
3666
3667 /*
3668  * TODO: these are currently initialized to rgb formats only.
3669  * For future use cases we should either initialize them dynamically based on
3670  * plane capabilities, or initialize this array to all formats, so internal drm
3671  * check will succeed, and let DC implement proper check
3672  */
3673 static const uint32_t rgb_formats[] = {
3674         DRM_FORMAT_RGB888,
3675         DRM_FORMAT_XRGB8888,
3676         DRM_FORMAT_ARGB8888,
3677         DRM_FORMAT_RGBA8888,
3678         DRM_FORMAT_XRGB2101010,
3679         DRM_FORMAT_XBGR2101010,
3680         DRM_FORMAT_ARGB2101010,
3681         DRM_FORMAT_ABGR2101010,
3682         DRM_FORMAT_XBGR8888,
3683         DRM_FORMAT_ABGR8888,
3684 };
3685
3686 static const uint32_t yuv_formats[] = {
3687         DRM_FORMAT_NV12,
3688         DRM_FORMAT_NV21,
3689 };
3690
3691 static const u32 cursor_formats[] = {
3692         DRM_FORMAT_ARGB8888
3693 };
3694
3695 static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
3696                                 struct drm_plane *plane,
3697                                 unsigned long possible_crtcs)
3698 {
3699         int res = -EPERM;
3700
3701         switch (plane->type) {
3702         case DRM_PLANE_TYPE_PRIMARY:
3703                 res = drm_universal_plane_init(
3704                                 dm->adev->ddev,
3705                                 plane,
3706                                 possible_crtcs,
3707                                 &dm_plane_funcs,
3708                                 rgb_formats,
3709                                 ARRAY_SIZE(rgb_formats),
3710                                 NULL, plane->type, NULL);
3711                 break;
3712         case DRM_PLANE_TYPE_OVERLAY:
3713                 res = drm_universal_plane_init(
3714                                 dm->adev->ddev,
3715                                 plane,
3716                                 possible_crtcs,
3717                                 &dm_plane_funcs,
3718                                 yuv_formats,
3719                                 ARRAY_SIZE(yuv_formats),
3720                                 NULL, plane->type, NULL);
3721                 break;
3722         case DRM_PLANE_TYPE_CURSOR:
3723                 res = drm_universal_plane_init(
3724                                 dm->adev->ddev,
3725                                 plane,
3726                                 possible_crtcs,
3727                                 &dm_plane_funcs,
3728                                 cursor_formats,
3729                                 ARRAY_SIZE(cursor_formats),
3730                                 NULL, plane->type, NULL);
3731                 break;
3732         }
3733
3734         drm_plane_helper_add(plane, &dm_plane_helper_funcs);
3735
3736         /* Create (reset) the plane state */
3737         if (plane->funcs->reset)
3738                 plane->funcs->reset(plane);
3739
3740
3741         return res;
3742 }
3743
3744 static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
3745                                struct drm_plane *plane,
3746                                uint32_t crtc_index)
3747 {
3748         struct amdgpu_crtc *acrtc = NULL;
3749         struct drm_plane *cursor_plane;
3750
3751         int res = -ENOMEM;
3752
3753         cursor_plane = kzalloc(sizeof(*cursor_plane), GFP_KERNEL);
3754         if (!cursor_plane)
3755                 goto fail;
3756
3757         cursor_plane->type = DRM_PLANE_TYPE_CURSOR;
3758         res = amdgpu_dm_plane_init(dm, cursor_plane, 0);
3759
3760         acrtc = kzalloc(sizeof(struct amdgpu_crtc), GFP_KERNEL);
3761         if (!acrtc)
3762                 goto fail;
3763
3764         res = drm_crtc_init_with_planes(
3765                         dm->ddev,
3766                         &acrtc->base,
3767                         plane,
3768                         cursor_plane,
3769                         &amdgpu_dm_crtc_funcs, NULL);
3770
3771         if (res)
3772                 goto fail;
3773
3774         drm_crtc_helper_add(&acrtc->base, &amdgpu_dm_crtc_helper_funcs);
3775
3776         /* Create (reset) the plane state */
3777         if (acrtc->base.funcs->reset)
3778                 acrtc->base.funcs->reset(&acrtc->base);
3779
3780         acrtc->max_cursor_width = dm->adev->dm.dc->caps.max_cursor_size;
3781         acrtc->max_cursor_height = dm->adev->dm.dc->caps.max_cursor_size;
3782
3783         acrtc->crtc_id = crtc_index;
3784         acrtc->base.enabled = false;
3785         acrtc->otg_inst = -1;
3786
3787         dm->adev->mode_info.crtcs[crtc_index] = acrtc;
3788         drm_crtc_enable_color_mgmt(&acrtc->base, MAX_COLOR_LUT_ENTRIES,
3789                                    true, MAX_COLOR_LUT_ENTRIES);
3790         drm_mode_crtc_set_gamma_size(&acrtc->base, MAX_COLOR_LEGACY_LUT_ENTRIES);
3791
3792         return 0;
3793
3794 fail:
3795         kfree(acrtc);
3796         kfree(cursor_plane);
3797         return res;
3798 }
3799
3800
3801 static int to_drm_connector_type(enum signal_type st)
3802 {
3803         switch (st) {
3804         case SIGNAL_TYPE_HDMI_TYPE_A:
3805                 return DRM_MODE_CONNECTOR_HDMIA;
3806         case SIGNAL_TYPE_EDP:
3807                 return DRM_MODE_CONNECTOR_eDP;
3808         case SIGNAL_TYPE_LVDS:
3809                 return DRM_MODE_CONNECTOR_LVDS;
3810         case SIGNAL_TYPE_RGB:
3811                 return DRM_MODE_CONNECTOR_VGA;
3812         case SIGNAL_TYPE_DISPLAY_PORT:
3813         case SIGNAL_TYPE_DISPLAY_PORT_MST:
3814                 return DRM_MODE_CONNECTOR_DisplayPort;
3815         case SIGNAL_TYPE_DVI_DUAL_LINK:
3816         case SIGNAL_TYPE_DVI_SINGLE_LINK:
3817                 return DRM_MODE_CONNECTOR_DVID;
3818         case SIGNAL_TYPE_VIRTUAL:
3819                 return DRM_MODE_CONNECTOR_VIRTUAL;
3820
3821         default:
3822                 return DRM_MODE_CONNECTOR_Unknown;
3823         }
3824 }
3825
3826 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
3827 {
3828         return drm_encoder_find(connector->dev, NULL, connector->encoder_ids[0]);
3829 }
3830
3831 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
3832 {
3833         struct drm_encoder *encoder;
3834         struct amdgpu_encoder *amdgpu_encoder;
3835
3836         encoder = amdgpu_dm_connector_to_encoder(connector);
3837
3838         if (encoder == NULL)
3839                 return;
3840
3841         amdgpu_encoder = to_amdgpu_encoder(encoder);
3842
3843         amdgpu_encoder->native_mode.clock = 0;
3844
3845         if (!list_empty(&connector->probed_modes)) {
3846                 struct drm_display_mode *preferred_mode = NULL;
3847
3848                 list_for_each_entry(preferred_mode,
3849                                     &connector->probed_modes,
3850                                     head) {
3851                         if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
3852                                 amdgpu_encoder->native_mode = *preferred_mode;
3853
3854                         break;
3855                 }
3856
3857         }
3858 }
3859
3860 static struct drm_display_mode *
3861 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
3862                              char *name,
3863                              int hdisplay, int vdisplay)
3864 {
3865         struct drm_device *dev = encoder->dev;
3866         struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
3867         struct drm_display_mode *mode = NULL;
3868         struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
3869
3870         mode = drm_mode_duplicate(dev, native_mode);
3871
3872         if (mode == NULL)
3873                 return NULL;
3874
3875         mode->hdisplay = hdisplay;
3876         mode->vdisplay = vdisplay;
3877         mode->type &= ~DRM_MODE_TYPE_PREFERRED;
3878         strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
3879
3880         return mode;
3881
3882 }
3883
3884 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
3885                                                  struct drm_connector *connector)
3886 {
3887         struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
3888         struct drm_display_mode *mode = NULL;
3889         struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
3890         struct amdgpu_dm_connector *amdgpu_dm_connector =
3891                                 to_amdgpu_dm_connector(connector);
3892         int i;
3893         int n;
3894         struct mode_size {
3895                 char name[DRM_DISPLAY_MODE_LEN];
3896                 int w;
3897                 int h;
3898         } common_modes[] = {
3899                 {  "640x480",  640,  480},
3900                 {  "800x600",  800,  600},
3901                 { "1024x768", 1024,  768},
3902                 { "1280x720", 1280,  720},
3903                 { "1280x800", 1280,  800},
3904                 {"1280x1024", 1280, 1024},
3905                 { "1440x900", 1440,  900},
3906                 {"1680x1050", 1680, 1050},
3907                 {"1600x1200", 1600, 1200},
3908                 {"1920x1080", 1920, 1080},
3909                 {"1920x1200", 1920, 1200}
3910         };
3911
3912         n = ARRAY_SIZE(common_modes);
3913
3914         for (i = 0; i < n; i++) {
3915                 struct drm_display_mode *curmode = NULL;
3916                 bool mode_existed = false;
3917
3918                 if (common_modes[i].w > native_mode->hdisplay ||
3919                     common_modes[i].h > native_mode->vdisplay ||
3920                    (common_modes[i].w == native_mode->hdisplay &&
3921                     common_modes[i].h == native_mode->vdisplay))
3922                         continue;
3923
3924                 list_for_each_entry(curmode, &connector->probed_modes, head) {
3925                         if (common_modes[i].w == curmode->hdisplay &&
3926                             common_modes[i].h == curmode->vdisplay) {
3927                                 mode_existed = true;
3928                                 break;
3929                         }
3930                 }
3931
3932                 if (mode_existed)
3933                         continue;
3934
3935                 mode = amdgpu_dm_create_common_mode(encoder,
3936                                 common_modes[i].name, common_modes[i].w,
3937                                 common_modes[i].h);
3938                 drm_mode_probed_add(connector, mode);
3939                 amdgpu_dm_connector->num_modes++;
3940         }
3941 }
3942
3943 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
3944                                               struct edid *edid)
3945 {
3946         struct amdgpu_dm_connector *amdgpu_dm_connector =
3947                         to_amdgpu_dm_connector(connector);
3948
3949         if (edid) {
3950                 /* empty probed_modes */
3951                 INIT_LIST_HEAD(&connector->probed_modes);
3952                 amdgpu_dm_connector->num_modes =
3953                                 drm_add_edid_modes(connector, edid);
3954
3955                 amdgpu_dm_get_native_mode(connector);
3956         } else {
3957                 amdgpu_dm_connector->num_modes = 0;
3958         }
3959 }
3960
3961 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
3962 {
3963         struct amdgpu_dm_connector *amdgpu_dm_connector =
3964                         to_amdgpu_dm_connector(connector);
3965         struct drm_encoder *encoder;
3966         struct edid *edid = amdgpu_dm_connector->edid;
3967
3968         encoder = amdgpu_dm_connector_to_encoder(connector);
3969
3970         if (!edid || !drm_edid_is_valid(edid)) {
3971                 amdgpu_dm_connector->num_modes =
3972                                 drm_add_modes_noedid(connector, 640, 480);
3973         } else {
3974                 amdgpu_dm_connector_ddc_get_modes(connector, edid);
3975                 amdgpu_dm_connector_add_common_modes(encoder, connector);
3976         }
3977         amdgpu_dm_fbc_init(connector);
3978
3979         return amdgpu_dm_connector->num_modes;
3980 }
3981
3982 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
3983                                      struct amdgpu_dm_connector *aconnector,
3984                                      int connector_type,
3985                                      struct dc_link *link,
3986                                      int link_index)
3987 {
3988         struct amdgpu_device *adev = dm->ddev->dev_private;
3989
3990         aconnector->connector_id = link_index;
3991         aconnector->dc_link = link;
3992         aconnector->base.interlace_allowed = false;
3993         aconnector->base.doublescan_allowed = false;
3994         aconnector->base.stereo_allowed = false;
3995         aconnector->base.dpms = DRM_MODE_DPMS_OFF;
3996         aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
3997         mutex_init(&aconnector->hpd_lock);
3998
3999         /*
4000          * configure support HPD hot plug connector_>polled default value is 0
4001          * which means HPD hot plug not supported
4002          */
4003         switch (connector_type) {
4004         case DRM_MODE_CONNECTOR_HDMIA:
4005                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
4006                 aconnector->base.ycbcr_420_allowed =
4007                         link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
4008                 break;
4009         case DRM_MODE_CONNECTOR_DisplayPort:
4010                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
4011                 aconnector->base.ycbcr_420_allowed =
4012                         link->link_enc->features.dp_ycbcr420_supported ? true : false;
4013                 break;
4014         case DRM_MODE_CONNECTOR_DVID:
4015                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
4016                 break;
4017         default:
4018                 break;
4019         }
4020
4021         drm_object_attach_property(&aconnector->base.base,
4022                                 dm->ddev->mode_config.scaling_mode_property,
4023                                 DRM_MODE_SCALE_NONE);
4024
4025         drm_object_attach_property(&aconnector->base.base,
4026                                 adev->mode_info.underscan_property,
4027                                 UNDERSCAN_OFF);
4028         drm_object_attach_property(&aconnector->base.base,
4029                                 adev->mode_info.underscan_hborder_property,
4030                                 0);
4031         drm_object_attach_property(&aconnector->base.base,
4032                                 adev->mode_info.underscan_vborder_property,
4033                                 0);
4034         drm_object_attach_property(&aconnector->base.base,
4035                                 adev->mode_info.max_bpc_property,
4036                                 0);
4037
4038         if (connector_type == DRM_MODE_CONNECTOR_eDP &&
4039             dc_is_dmcu_initialized(adev->dm.dc)) {
4040                 drm_object_attach_property(&aconnector->base.base,
4041                                 adev->mode_info.abm_level_property, 0);
4042         }
4043
4044         if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
4045             connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
4046                 drm_connector_attach_vrr_capable_property(
4047                         &aconnector->base);
4048         }
4049 }
4050
4051 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
4052                               struct i2c_msg *msgs, int num)
4053 {
4054         struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
4055         struct ddc_service *ddc_service = i2c->ddc_service;
4056         struct i2c_command cmd;
4057         int i;
4058         int result = -EIO;
4059
4060         cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
4061
4062         if (!cmd.payloads)
4063                 return result;
4064
4065         cmd.number_of_payloads = num;
4066         cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
4067         cmd.speed = 100;
4068
4069         for (i = 0; i < num; i++) {
4070                 cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
4071                 cmd.payloads[i].address = msgs[i].addr;
4072                 cmd.payloads[i].length = msgs[i].len;
4073                 cmd.payloads[i].data = msgs[i].buf;
4074         }
4075
4076         if (dc_submit_i2c(
4077                         ddc_service->ctx->dc,
4078                         ddc_service->ddc_pin->hw_info.ddc_channel,
4079                         &cmd))
4080                 result = num;
4081
4082         kfree(cmd.payloads);
4083         return result;
4084 }
4085
4086 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
4087 {
4088         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
4089 }
4090
4091 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
4092         .master_xfer = amdgpu_dm_i2c_xfer,
4093         .functionality = amdgpu_dm_i2c_func,
4094 };
4095
4096 static struct amdgpu_i2c_adapter *
4097 create_i2c(struct ddc_service *ddc_service,
4098            int link_index,
4099            int *res)
4100 {
4101         struct amdgpu_device *adev = ddc_service->ctx->driver_context;
4102         struct amdgpu_i2c_adapter *i2c;
4103
4104         i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
4105         if (!i2c)
4106                 return NULL;
4107         i2c->base.owner = THIS_MODULE;
4108         i2c->base.class = I2C_CLASS_DDC;
4109         i2c->base.dev.parent = &adev->pdev->dev;
4110         i2c->base.algo = &amdgpu_dm_i2c_algo;
4111         snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
4112         i2c_set_adapdata(&i2c->base, i2c);
4113         i2c->ddc_service = ddc_service;
4114         i2c->ddc_service->ddc_pin->hw_info.ddc_channel = link_index;
4115
4116         return i2c;
4117 }
4118
4119
4120 /*
4121  * Note: this function assumes that dc_link_detect() was called for the
4122  * dc_link which will be represented by this aconnector.
4123  */
4124 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
4125                                     struct amdgpu_dm_connector *aconnector,
4126                                     uint32_t link_index,
4127                                     struct amdgpu_encoder *aencoder)
4128 {
4129         int res = 0;
4130         int connector_type;
4131         struct dc *dc = dm->dc;
4132         struct dc_link *link = dc_get_link_at_index(dc, link_index);
4133         struct amdgpu_i2c_adapter *i2c;
4134
4135         link->priv = aconnector;
4136
4137         DRM_DEBUG_DRIVER("%s()\n", __func__);
4138
4139         i2c = create_i2c(link->ddc, link->link_index, &res);
4140         if (!i2c) {
4141                 DRM_ERROR("Failed to create i2c adapter data\n");
4142                 return -ENOMEM;
4143         }
4144
4145         aconnector->i2c = i2c;
4146         res = i2c_add_adapter(&i2c->base);
4147
4148         if (res) {
4149                 DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
4150                 goto out_free;
4151         }
4152
4153         connector_type = to_drm_connector_type(link->connector_signal);
4154
4155         res = drm_connector_init(
4156                         dm->ddev,
4157                         &aconnector->base,
4158                         &amdgpu_dm_connector_funcs,
4159                         connector_type);
4160
4161         if (res) {
4162                 DRM_ERROR("connector_init failed\n");
4163                 aconnector->connector_id = -1;
4164                 goto out_free;
4165         }
4166
4167         drm_connector_helper_add(
4168                         &aconnector->base,
4169                         &amdgpu_dm_connector_helper_funcs);
4170
4171         if (aconnector->base.funcs->reset)
4172                 aconnector->base.funcs->reset(&aconnector->base);
4173
4174         amdgpu_dm_connector_init_helper(
4175                 dm,
4176                 aconnector,
4177                 connector_type,
4178                 link,
4179                 link_index);
4180
4181         drm_connector_attach_encoder(
4182                 &aconnector->base, &aencoder->base);
4183
4184         drm_connector_register(&aconnector->base);
4185 #if defined(CONFIG_DEBUG_FS)
4186         res = connector_debugfs_init(aconnector);
4187         if (res) {
4188                 DRM_ERROR("Failed to create debugfs for connector");
4189                 goto out_free;
4190         }
4191 #endif
4192
4193         if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
4194                 || connector_type == DRM_MODE_CONNECTOR_eDP)
4195                 amdgpu_dm_initialize_dp_connector(dm, aconnector);
4196
4197 out_free:
4198         if (res) {
4199                 kfree(i2c);
4200                 aconnector->i2c = NULL;
4201         }
4202         return res;
4203 }
4204
4205 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
4206 {
4207         switch (adev->mode_info.num_crtc) {
4208         case 1:
4209                 return 0x1;
4210         case 2:
4211                 return 0x3;
4212         case 3:
4213                 return 0x7;
4214         case 4:
4215                 return 0xf;
4216         case 5:
4217                 return 0x1f;
4218         case 6:
4219         default:
4220                 return 0x3f;
4221         }
4222 }
4223
4224 static int amdgpu_dm_encoder_init(struct drm_device *dev,
4225                                   struct amdgpu_encoder *aencoder,
4226                                   uint32_t link_index)
4227 {
4228         struct amdgpu_device *adev = dev->dev_private;
4229
4230         int res = drm_encoder_init(dev,
4231                                    &aencoder->base,
4232                                    &amdgpu_dm_encoder_funcs,
4233                                    DRM_MODE_ENCODER_TMDS,
4234                                    NULL);
4235
4236         aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
4237
4238         if (!res)
4239                 aencoder->encoder_id = link_index;
4240         else
4241                 aencoder->encoder_id = -1;
4242
4243         drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
4244
4245         return res;
4246 }
4247
4248 static void manage_dm_interrupts(struct amdgpu_device *adev,
4249                                  struct amdgpu_crtc *acrtc,
4250                                  bool enable)
4251 {
4252         /*
4253          * this is not correct translation but will work as soon as VBLANK
4254          * constant is the same as PFLIP
4255          */
4256         int irq_type =
4257                 amdgpu_display_crtc_idx_to_irq_type(
4258                         adev,
4259                         acrtc->crtc_id);
4260
4261         if (enable) {
4262                 drm_crtc_vblank_on(&acrtc->base);
4263                 amdgpu_irq_get(
4264                         adev,
4265                         &adev->pageflip_irq,
4266                         irq_type);
4267         } else {
4268
4269                 amdgpu_irq_put(
4270                         adev,
4271                         &adev->pageflip_irq,
4272                         irq_type);
4273                 drm_crtc_vblank_off(&acrtc->base);
4274         }
4275 }
4276
4277 static bool
4278 is_scaling_state_different(const struct dm_connector_state *dm_state,
4279                            const struct dm_connector_state *old_dm_state)
4280 {
4281         if (dm_state->scaling != old_dm_state->scaling)
4282                 return true;
4283         if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
4284                 if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
4285                         return true;
4286         } else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
4287                 if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
4288                         return true;
4289         } else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
4290                    dm_state->underscan_vborder != old_dm_state->underscan_vborder)
4291                 return true;
4292         return false;
4293 }
4294
4295 static void remove_stream(struct amdgpu_device *adev,
4296                           struct amdgpu_crtc *acrtc,
4297                           struct dc_stream_state *stream)
4298 {
4299         /* this is the update mode case */
4300
4301         acrtc->otg_inst = -1;
4302         acrtc->enabled = false;
4303 }
4304
4305 static int get_cursor_position(struct drm_plane *plane, struct drm_crtc *crtc,
4306                                struct dc_cursor_position *position)
4307 {
4308         struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
4309         int x, y;
4310         int xorigin = 0, yorigin = 0;
4311
4312         if (!crtc || !plane->state->fb) {
4313                 position->enable = false;
4314                 position->x = 0;
4315                 position->y = 0;
4316                 return 0;
4317         }
4318
4319         if ((plane->state->crtc_w > amdgpu_crtc->max_cursor_width) ||
4320             (plane->state->crtc_h > amdgpu_crtc->max_cursor_height)) {
4321                 DRM_ERROR("%s: bad cursor width or height %d x %d\n",
4322                           __func__,
4323                           plane->state->crtc_w,
4324                           plane->state->crtc_h);
4325                 return -EINVAL;
4326         }
4327
4328         x = plane->state->crtc_x;
4329         y = plane->state->crtc_y;
4330         /* avivo cursor are offset into the total surface */
4331         x += crtc->primary->state->src_x >> 16;
4332         y += crtc->primary->state->src_y >> 16;
4333         if (x < 0) {
4334                 xorigin = min(-x, amdgpu_crtc->max_cursor_width - 1);
4335                 x = 0;
4336         }
4337         if (y < 0) {
4338                 yorigin = min(-y, amdgpu_crtc->max_cursor_height - 1);
4339                 y = 0;
4340         }
4341         position->enable = true;
4342         position->x = x;
4343         position->y = y;
4344         position->x_hotspot = xorigin;
4345         position->y_hotspot = yorigin;
4346
4347         return 0;
4348 }
4349
4350 static void handle_cursor_update(struct drm_plane *plane,
4351                                  struct drm_plane_state *old_plane_state)
4352 {
4353         struct amdgpu_device *adev = plane->dev->dev_private;
4354         struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
4355         struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
4356         struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
4357         struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
4358         uint64_t address = afb ? afb->address : 0;
4359         struct dc_cursor_position position;
4360         struct dc_cursor_attributes attributes;
4361         int ret;
4362
4363         if (!plane->state->fb && !old_plane_state->fb)
4364                 return;
4365
4366         DRM_DEBUG_DRIVER("%s: crtc_id=%d with size %d to %d\n",
4367                          __func__,
4368                          amdgpu_crtc->crtc_id,
4369                          plane->state->crtc_w,
4370                          plane->state->crtc_h);
4371
4372         ret = get_cursor_position(plane, crtc, &position);
4373         if (ret)
4374                 return;
4375
4376         if (!position.enable) {
4377                 /* turn off cursor */
4378                 if (crtc_state && crtc_state->stream) {
4379                         mutex_lock(&adev->dm.dc_lock);
4380                         dc_stream_set_cursor_position(crtc_state->stream,
4381                                                       &position);
4382                         mutex_unlock(&adev->dm.dc_lock);
4383                 }
4384                 return;
4385         }
4386
4387         amdgpu_crtc->cursor_width = plane->state->crtc_w;
4388         amdgpu_crtc->cursor_height = plane->state->crtc_h;
4389
4390         attributes.address.high_part = upper_32_bits(address);
4391         attributes.address.low_part  = lower_32_bits(address);
4392         attributes.width             = plane->state->crtc_w;
4393         attributes.height            = plane->state->crtc_h;
4394         attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
4395         attributes.rotation_angle    = 0;
4396         attributes.attribute_flags.value = 0;
4397
4398         attributes.pitch = attributes.width;
4399
4400         if (crtc_state->stream) {
4401                 mutex_lock(&adev->dm.dc_lock);
4402                 if (!dc_stream_set_cursor_attributes(crtc_state->stream,
4403                                                          &attributes))
4404                         DRM_ERROR("DC failed to set cursor attributes\n");
4405
4406                 if (!dc_stream_set_cursor_position(crtc_state->stream,
4407                                                    &position))
4408                         DRM_ERROR("DC failed to set cursor position\n");
4409                 mutex_unlock(&adev->dm.dc_lock);
4410         }
4411 }
4412
4413 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
4414 {
4415
4416         assert_spin_locked(&acrtc->base.dev->event_lock);
4417         WARN_ON(acrtc->event);
4418
4419         acrtc->event = acrtc->base.state->event;
4420
4421         /* Set the flip status */
4422         acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
4423
4424         /* Mark this event as consumed */
4425         acrtc->base.state->event = NULL;
4426
4427         DRM_DEBUG_DRIVER("crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
4428                                                  acrtc->crtc_id);
4429 }
4430
4431 struct dc_stream_status *dc_state_get_stream_status(
4432         struct dc_state *state,
4433         struct dc_stream_state *stream)
4434 {
4435         uint8_t i;
4436
4437         for (i = 0; i < state->stream_count; i++) {
4438                 if (stream == state->streams[i])
4439                         return &state->stream_status[i];
4440         }
4441
4442         return NULL;
4443 }
4444
4445 static void update_freesync_state_on_stream(
4446         struct amdgpu_display_manager *dm,
4447         struct dm_crtc_state *new_crtc_state,
4448         struct dc_stream_state *new_stream)
4449 {
4450         struct mod_vrr_params vrr = {0};
4451         struct dc_info_packet vrr_infopacket = {0};
4452         struct mod_freesync_config config = new_crtc_state->freesync_config;
4453
4454         if (!new_stream)
4455                 return;
4456
4457         /*
4458          * TODO: Determine why min/max totals and vrefresh can be 0 here.
4459          * For now it's sufficient to just guard against these conditions.
4460          */
4461
4462         if (!new_stream->timing.h_total || !new_stream->timing.v_total)
4463                 return;
4464
4465         if (new_crtc_state->vrr_supported &&
4466             config.min_refresh_in_uhz &&
4467             config.max_refresh_in_uhz) {
4468                 config.state = new_crtc_state->base.vrr_enabled ?
4469                         VRR_STATE_ACTIVE_VARIABLE :
4470                         VRR_STATE_INACTIVE;
4471         } else {
4472                 config.state = VRR_STATE_UNSUPPORTED;
4473         }
4474
4475         mod_freesync_build_vrr_params(dm->freesync_module,
4476                                       new_stream,
4477                                       &config, &vrr);
4478
4479         mod_freesync_build_vrr_infopacket(
4480                 dm->freesync_module,
4481                 new_stream,
4482                 &vrr,
4483                 PACKET_TYPE_VRR,
4484                 TRANSFER_FUNC_UNKNOWN,
4485                 &vrr_infopacket);
4486
4487         new_crtc_state->freesync_timing_changed =
4488                 (memcmp(&new_crtc_state->adjust,
4489                         &vrr.adjust,
4490                         sizeof(vrr.adjust)) != 0);
4491
4492         new_crtc_state->freesync_vrr_info_changed =
4493                 (memcmp(&new_crtc_state->vrr_infopacket,
4494                         &vrr_infopacket,
4495                         sizeof(vrr_infopacket)) != 0);
4496
4497         new_crtc_state->adjust = vrr.adjust;
4498         new_crtc_state->vrr_infopacket = vrr_infopacket;
4499
4500         new_stream->adjust = new_crtc_state->adjust;
4501         new_stream->vrr_infopacket = vrr_infopacket;
4502
4503         if (new_crtc_state->freesync_vrr_info_changed)
4504                 DRM_DEBUG_KMS("VRR packet update: crtc=%u enabled=%d state=%d",
4505                               new_crtc_state->base.crtc->base.id,
4506                               (int)new_crtc_state->base.vrr_enabled,
4507                               (int)vrr.state);
4508
4509         if (new_crtc_state->freesync_timing_changed)
4510                 DRM_DEBUG_KMS("VRR timing update: crtc=%u min=%u max=%u\n",
4511                               new_crtc_state->base.crtc->base.id,
4512                               vrr.adjust.v_total_min,
4513                               vrr.adjust.v_total_max);
4514 }
4515
4516 /*
4517  * Executes flip
4518  *
4519  * Waits on all BO's fences and for proper vblank count
4520  */
4521 static void amdgpu_dm_do_flip(struct drm_crtc *crtc,
4522                               struct drm_framebuffer *fb,
4523                               uint32_t target,
4524                               struct dc_state *state)
4525 {
4526         unsigned long flags;
4527         uint32_t target_vblank;
4528         int r, vpos, hpos;
4529         struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4530         struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
4531         struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
4532         struct amdgpu_device *adev = crtc->dev->dev_private;
4533         bool async_flip = (crtc->state->pageflip_flags & DRM_MODE_PAGE_FLIP_ASYNC) != 0;
4534         struct dc_flip_addrs addr = { {0} };
4535         /* TODO eliminate or rename surface_update */
4536         struct dc_surface_update surface_updates[1] = { {0} };
4537         struct dc_stream_update stream_update = {0};
4538         struct dm_crtc_state *acrtc_state = to_dm_crtc_state(crtc->state);
4539         struct dc_stream_status *stream_status;
4540
4541
4542         /* Prepare wait for target vblank early - before the fence-waits */
4543         target_vblank = target - (uint32_t)drm_crtc_vblank_count(crtc) +
4544                         amdgpu_get_vblank_counter_kms(crtc->dev, acrtc->crtc_id);
4545
4546         /*
4547          * TODO This might fail and hence better not used, wait
4548          * explicitly on fences instead
4549          * and in general should be called for
4550          * blocking commit to as per framework helpers
4551          */
4552         r = amdgpu_bo_reserve(abo, true);
4553         if (unlikely(r != 0)) {
4554                 DRM_ERROR("failed to reserve buffer before flip\n");
4555                 WARN_ON(1);
4556         }
4557
4558         /* Wait for all fences on this FB */
4559         WARN_ON(reservation_object_wait_timeout_rcu(abo->tbo.resv, true, false,
4560                                                                     MAX_SCHEDULE_TIMEOUT) < 0);
4561
4562         amdgpu_bo_unreserve(abo);
4563
4564         /*
4565          * Wait until we're out of the vertical blank period before the one
4566          * targeted by the flip
4567          */
4568         while ((acrtc->enabled &&
4569                 (amdgpu_display_get_crtc_scanoutpos(adev->ddev, acrtc->crtc_id,
4570                                                     0, &vpos, &hpos, NULL,
4571                                                     NULL, &crtc->hwmode)
4572                  & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
4573                 (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
4574                 (int)(target_vblank -
4575                   amdgpu_get_vblank_counter_kms(adev->ddev, acrtc->crtc_id)) > 0)) {
4576                 usleep_range(1000, 1100);
4577         }
4578
4579         /* Flip */
4580         spin_lock_irqsave(&crtc->dev->event_lock, flags);
4581
4582         WARN_ON(acrtc->pflip_status != AMDGPU_FLIP_NONE);
4583         WARN_ON(!acrtc_state->stream);
4584
4585         addr.address.grph.addr.low_part = lower_32_bits(afb->address);
4586         addr.address.grph.addr.high_part = upper_32_bits(afb->address);
4587         addr.flip_immediate = async_flip;
4588
4589
4590         if (acrtc->base.state->event)
4591                 prepare_flip_isr(acrtc);
4592
4593         spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
4594
4595         stream_status = dc_stream_get_status(acrtc_state->stream);
4596         if (!stream_status) {
4597                 DRM_ERROR("No stream status for CRTC: id=%d\n",
4598                         acrtc->crtc_id);
4599                 return;
4600         }
4601
4602         surface_updates->surface = stream_status->plane_states[0];
4603         if (!surface_updates->surface) {
4604                 DRM_ERROR("No surface for CRTC: id=%d\n",
4605                         acrtc->crtc_id);
4606                 return;
4607         }
4608         surface_updates->flip_addr = &addr;
4609
4610         if (acrtc_state->stream) {
4611                 update_freesync_state_on_stream(
4612                         &adev->dm,
4613                         acrtc_state,
4614                         acrtc_state->stream);
4615
4616                 if (acrtc_state->freesync_timing_changed)
4617                         stream_update.adjust =
4618                                 &acrtc_state->stream->adjust;
4619
4620                 if (acrtc_state->freesync_vrr_info_changed)
4621                         stream_update.vrr_infopacket =
4622                                 &acrtc_state->stream->vrr_infopacket;
4623         }
4624
4625         mutex_lock(&adev->dm.dc_lock);
4626         dc_commit_updates_for_stream(adev->dm.dc,
4627                                              surface_updates,
4628                                              1,
4629                                              acrtc_state->stream,
4630                                              &stream_update,
4631                                              &surface_updates->surface,
4632                                              state);
4633         mutex_unlock(&adev->dm.dc_lock);
4634
4635         DRM_DEBUG_DRIVER("%s Flipping to hi: 0x%x, low: 0x%x \n",
4636                          __func__,
4637                          addr.address.grph.addr.high_part,
4638                          addr.address.grph.addr.low_part);
4639 }
4640
4641 /*
4642  * TODO this whole function needs to go
4643  *
4644  * dc_surface_update is needlessly complex. See if we can just replace this
4645  * with a dc_plane_state and follow the atomic model a bit more closely here.
4646  */
4647 static bool commit_planes_to_stream(
4648                 struct amdgpu_display_manager *dm,
4649                 struct dc *dc,
4650                 struct dc_plane_state **plane_states,
4651                 uint8_t new_plane_count,
4652                 struct dm_crtc_state *dm_new_crtc_state,
4653                 struct dm_crtc_state *dm_old_crtc_state,
4654                 struct dc_state *state)
4655 {
4656         /* no need to dynamically allocate this. it's pretty small */
4657         struct dc_surface_update updates[MAX_SURFACES];
4658         struct dc_flip_addrs *flip_addr;
4659         struct dc_plane_info *plane_info;
4660         struct dc_scaling_info *scaling_info;
4661         int i;
4662         struct dc_stream_state *dc_stream = dm_new_crtc_state->stream;
4663         struct dc_stream_update *stream_update =
4664                         kzalloc(sizeof(struct dc_stream_update), GFP_KERNEL);
4665         unsigned int abm_level;
4666
4667         if (!stream_update) {
4668                 BREAK_TO_DEBUGGER();
4669                 return false;
4670         }
4671
4672         flip_addr = kcalloc(MAX_SURFACES, sizeof(struct dc_flip_addrs),
4673                             GFP_KERNEL);
4674         plane_info = kcalloc(MAX_SURFACES, sizeof(struct dc_plane_info),
4675                              GFP_KERNEL);
4676         scaling_info = kcalloc(MAX_SURFACES, sizeof(struct dc_scaling_info),
4677                                GFP_KERNEL);
4678
4679         if (!flip_addr || !plane_info || !scaling_info) {
4680                 kfree(flip_addr);
4681                 kfree(plane_info);
4682                 kfree(scaling_info);
4683                 kfree(stream_update);
4684                 return false;
4685         }
4686
4687         memset(updates, 0, sizeof(updates));
4688
4689         stream_update->src = dc_stream->src;
4690         stream_update->dst = dc_stream->dst;
4691         stream_update->out_transfer_func = dc_stream->out_transfer_func;
4692
4693         if (dm_new_crtc_state->abm_level != dm_old_crtc_state->abm_level) {
4694                 abm_level = dm_new_crtc_state->abm_level;
4695                 stream_update->abm_level = &abm_level;
4696         }
4697
4698         for (i = 0; i < new_plane_count; i++) {
4699                 updates[i].surface = plane_states[i];
4700                 updates[i].gamma =
4701                         (struct dc_gamma *)plane_states[i]->gamma_correction;
4702                 updates[i].in_transfer_func = plane_states[i]->in_transfer_func;
4703                 flip_addr[i].address = plane_states[i]->address;
4704                 flip_addr[i].flip_immediate = plane_states[i]->flip_immediate;
4705                 plane_info[i].color_space = plane_states[i]->color_space;
4706                 plane_info[i].format = plane_states[i]->format;
4707                 plane_info[i].plane_size = plane_states[i]->plane_size;
4708                 plane_info[i].rotation = plane_states[i]->rotation;
4709                 plane_info[i].horizontal_mirror = plane_states[i]->horizontal_mirror;
4710                 plane_info[i].stereo_format = plane_states[i]->stereo_format;
4711                 plane_info[i].tiling_info = plane_states[i]->tiling_info;
4712                 plane_info[i].visible = plane_states[i]->visible;
4713                 plane_info[i].per_pixel_alpha = plane_states[i]->per_pixel_alpha;
4714                 plane_info[i].dcc = plane_states[i]->dcc;
4715                 scaling_info[i].scaling_quality = plane_states[i]->scaling_quality;
4716                 scaling_info[i].src_rect = plane_states[i]->src_rect;
4717                 scaling_info[i].dst_rect = plane_states[i]->dst_rect;
4718                 scaling_info[i].clip_rect = plane_states[i]->clip_rect;
4719
4720                 updates[i].flip_addr = &flip_addr[i];
4721                 updates[i].plane_info = &plane_info[i];
4722                 updates[i].scaling_info = &scaling_info[i];
4723         }
4724
4725         mutex_lock(&dm->dc_lock);
4726         dc_commit_updates_for_stream(
4727                         dc,
4728                         updates,
4729                         new_plane_count,
4730                         dc_stream, stream_update, plane_states, state);
4731         mutex_unlock(&dm->dc_lock);
4732
4733         kfree(flip_addr);
4734         kfree(plane_info);
4735         kfree(scaling_info);
4736         kfree(stream_update);
4737         return true;
4738 }
4739
4740 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
4741                                     struct dc_state *dc_state,
4742                                     struct drm_device *dev,
4743                                     struct amdgpu_display_manager *dm,
4744                                     struct drm_crtc *pcrtc,
4745                                     bool *wait_for_vblank)
4746 {
4747         uint32_t i;
4748         struct drm_plane *plane;
4749         struct drm_plane_state *old_plane_state, *new_plane_state;
4750         struct dc_stream_state *dc_stream_attach;
4751         struct dc_plane_state *plane_states_constructed[MAX_SURFACES];
4752         struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
4753         struct drm_crtc_state *new_pcrtc_state =
4754                         drm_atomic_get_new_crtc_state(state, pcrtc);
4755         struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
4756         struct dm_crtc_state *dm_old_crtc_state =
4757                         to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
4758         int planes_count = 0;
4759         unsigned long flags;
4760
4761         /* update planes when needed */
4762         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
4763                 struct drm_crtc *crtc = new_plane_state->crtc;
4764                 struct drm_crtc_state *new_crtc_state;
4765                 struct drm_framebuffer *fb = new_plane_state->fb;
4766                 bool pflip_needed;
4767                 struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
4768
4769                 if (plane->type == DRM_PLANE_TYPE_CURSOR) {
4770                         handle_cursor_update(plane, old_plane_state);
4771                         continue;
4772                 }
4773
4774                 if (!fb || !crtc || pcrtc != crtc)
4775                         continue;
4776
4777                 new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
4778                 if (!new_crtc_state->active)
4779                         continue;
4780
4781                 pflip_needed = !state->allow_modeset;
4782
4783                 spin_lock_irqsave(&crtc->dev->event_lock, flags);
4784                 if (acrtc_attach->pflip_status != AMDGPU_FLIP_NONE) {
4785                         DRM_ERROR("%s: acrtc %d, already busy\n",
4786                                   __func__,
4787                                   acrtc_attach->crtc_id);
4788                         /* In commit tail framework this cannot happen */
4789                         WARN_ON(1);
4790                 }
4791                 spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
4792
4793                 if (!pflip_needed || plane->type == DRM_PLANE_TYPE_OVERLAY) {
4794                         WARN_ON(!dm_new_plane_state->dc_state);
4795
4796                         plane_states_constructed[planes_count] = dm_new_plane_state->dc_state;
4797
4798                         dc_stream_attach = acrtc_state->stream;
4799                         planes_count++;
4800
4801                 } else if (new_crtc_state->planes_changed) {
4802                         /* Assume even ONE crtc with immediate flip means
4803                          * entire can't wait for VBLANK
4804                          * TODO Check if it's correct
4805                          */
4806                         *wait_for_vblank =
4807                                         new_pcrtc_state->pageflip_flags & DRM_MODE_PAGE_FLIP_ASYNC ?
4808                                 false : true;
4809
4810                         /* TODO: Needs rework for multiplane flip */
4811                         if (plane->type == DRM_PLANE_TYPE_PRIMARY)
4812                                 drm_crtc_vblank_get(crtc);
4813
4814                         amdgpu_dm_do_flip(
4815                                 crtc,
4816                                 fb,
4817                                 (uint32_t)drm_crtc_vblank_count(crtc) + *wait_for_vblank,
4818                                 dc_state);
4819                 }
4820
4821         }
4822
4823         if (planes_count) {
4824                 unsigned long flags;
4825
4826                 if (new_pcrtc_state->event) {
4827
4828                         drm_crtc_vblank_get(pcrtc);
4829
4830                         spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
4831                         prepare_flip_isr(acrtc_attach);
4832                         spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
4833                 }
4834
4835                 dc_stream_attach->abm_level = acrtc_state->abm_level;
4836
4837                 if (false == commit_planes_to_stream(dm,
4838                                                         dm->dc,
4839                                                         plane_states_constructed,
4840                                                         planes_count,
4841                                                         acrtc_state,
4842                                                         dm_old_crtc_state,
4843                                                         dc_state))
4844                         dm_error("%s: Failed to attach plane!\n", __func__);
4845         } else {
4846                 /*TODO BUG Here should go disable planes on CRTC. */
4847         }
4848 }
4849
4850 /*
4851  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
4852  * @crtc_state: the DRM CRTC state
4853  * @stream_state: the DC stream state.
4854  *
4855  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
4856  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
4857  */
4858 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
4859                                                 struct dc_stream_state *stream_state)
4860 {
4861         stream_state->mode_changed = crtc_state->mode_changed;
4862 }
4863
4864 static int amdgpu_dm_atomic_commit(struct drm_device *dev,
4865                                    struct drm_atomic_state *state,
4866                                    bool nonblock)
4867 {
4868         struct drm_crtc *crtc;
4869         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4870         struct amdgpu_device *adev = dev->dev_private;
4871         int i;
4872
4873         /*
4874          * We evade vblanks and pflips on crtc that
4875          * should be changed. We do it here to flush & disable
4876          * interrupts before drm_swap_state is called in drm_atomic_helper_commit
4877          * it will update crtc->dm_crtc_state->stream pointer which is used in
4878          * the ISRs.
4879          */
4880         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4881                 struct dm_crtc_state *dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4882                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4883
4884                 if (drm_atomic_crtc_needs_modeset(new_crtc_state) && dm_old_crtc_state->stream)
4885                         manage_dm_interrupts(adev, acrtc, false);
4886         }
4887         /*
4888          * Add check here for SoC's that support hardware cursor plane, to
4889          * unset legacy_cursor_update
4890          */
4891
4892         return drm_atomic_helper_commit(dev, state, nonblock);
4893
4894         /*TODO Handle EINTR, reenable IRQ*/
4895 }
4896
4897 /**
4898  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
4899  * @state: The atomic state to commit
4900  *
4901  * This will tell DC to commit the constructed DC state from atomic_check,
4902  * programming the hardware. Any failures here implies a hardware failure, since
4903  * atomic check should have filtered anything non-kosher.
4904  */
4905 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
4906 {
4907         struct drm_device *dev = state->dev;
4908         struct amdgpu_device *adev = dev->dev_private;
4909         struct amdgpu_display_manager *dm = &adev->dm;
4910         struct dm_atomic_state *dm_state;
4911         struct dc_state *dc_state = NULL, *dc_state_temp = NULL;
4912         uint32_t i, j;
4913         struct drm_crtc *crtc;
4914         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4915         unsigned long flags;
4916         bool wait_for_vblank = true;
4917         struct drm_connector *connector;
4918         struct drm_connector_state *old_con_state, *new_con_state;
4919         struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
4920         int crtc_disable_count = 0;
4921
4922         drm_atomic_helper_update_legacy_modeset_state(dev, state);
4923
4924         dm_state = dm_atomic_get_new_state(state);
4925         if (dm_state && dm_state->context) {
4926                 dc_state = dm_state->context;
4927         } else {
4928                 /* No state changes, retain current state. */
4929                 dc_state_temp = dc_create_state();
4930                 ASSERT(dc_state_temp);
4931                 dc_state = dc_state_temp;
4932                 dc_resource_state_copy_construct_current(dm->dc, dc_state);
4933         }
4934
4935         /* update changed items */
4936         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4937                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4938
4939                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4940                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4941
4942                 DRM_DEBUG_DRIVER(
4943                         "amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
4944                         "planes_changed:%d, mode_changed:%d,active_changed:%d,"
4945                         "connectors_changed:%d\n",
4946                         acrtc->crtc_id,
4947                         new_crtc_state->enable,
4948                         new_crtc_state->active,
4949                         new_crtc_state->planes_changed,
4950                         new_crtc_state->mode_changed,
4951                         new_crtc_state->active_changed,
4952                         new_crtc_state->connectors_changed);
4953
4954                 /* Copy all transient state flags into dc state */
4955                 if (dm_new_crtc_state->stream) {
4956                         amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
4957                                                             dm_new_crtc_state->stream);
4958                 }
4959
4960                 /* handles headless hotplug case, updating new_state and
4961                  * aconnector as needed
4962                  */
4963
4964                 if (modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
4965
4966                         DRM_DEBUG_DRIVER("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
4967
4968                         if (!dm_new_crtc_state->stream) {
4969                                 /*
4970                                  * this could happen because of issues with
4971                                  * userspace notifications delivery.
4972                                  * In this case userspace tries to set mode on
4973                                  * display which is disconnected in fact.
4974                                  * dc_sink is NULL in this case on aconnector.
4975                                  * We expect reset mode will come soon.
4976                                  *
4977                                  * This can also happen when unplug is done
4978                                  * during resume sequence ended
4979                                  *
4980                                  * In this case, we want to pretend we still
4981                                  * have a sink to keep the pipe running so that
4982                                  * hw state is consistent with the sw state
4983                                  */
4984                                 DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
4985                                                 __func__, acrtc->base.base.id);
4986                                 continue;
4987                         }
4988
4989                         if (dm_old_crtc_state->stream)
4990                                 remove_stream(adev, acrtc, dm_old_crtc_state->stream);
4991
4992                         pm_runtime_get_noresume(dev->dev);
4993
4994                         acrtc->enabled = true;
4995                         acrtc->hw_mode = new_crtc_state->mode;
4996                         crtc->hwmode = new_crtc_state->mode;
4997                 } else if (modereset_required(new_crtc_state)) {
4998                         DRM_DEBUG_DRIVER("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
4999
5000                         /* i.e. reset mode */
5001                         if (dm_old_crtc_state->stream)
5002                                 remove_stream(adev, acrtc, dm_old_crtc_state->stream);
5003                 }
5004         } /* for_each_crtc_in_state() */
5005
5006         if (dc_state) {
5007                 dm_enable_per_frame_crtc_master_sync(dc_state);
5008                 mutex_lock(&dm->dc_lock);
5009                 WARN_ON(!dc_commit_state(dm->dc, dc_state));
5010                 mutex_unlock(&dm->dc_lock);
5011         }
5012
5013         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
5014                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
5015
5016                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5017
5018                 if (dm_new_crtc_state->stream != NULL) {
5019                         const struct dc_stream_status *status =
5020                                         dc_stream_get_status(dm_new_crtc_state->stream);
5021
5022                         if (!status)
5023                                 status = dc_state_get_stream_status(dc_state,
5024                                                                     dm_new_crtc_state->stream);
5025
5026                         if (!status)
5027                                 DC_ERR("got no status for stream %p on acrtc%p\n", dm_new_crtc_state->stream, acrtc);
5028                         else
5029                                 acrtc->otg_inst = status->primary_otg_inst;
5030                 }
5031         }
5032
5033         /* Handle scaling, underscan, and abm changes*/
5034         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
5035                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
5036                 struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
5037                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
5038                 struct dc_stream_status *status = NULL;
5039
5040                 if (acrtc) {
5041                         new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
5042                         old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
5043                 }
5044
5045                 /* Skip any modesets/resets */
5046                 if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
5047                         continue;
5048
5049
5050                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5051                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5052
5053                 /* Skip anything that is not scaling or underscan changes */
5054                 if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state) &&
5055                                 (dm_new_crtc_state->abm_level == dm_old_crtc_state->abm_level))
5056                         continue;
5057
5058                 update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
5059                                 dm_new_con_state, (struct dc_stream_state *)dm_new_crtc_state->stream);
5060
5061                 if (!dm_new_crtc_state->stream)
5062                         continue;
5063
5064                 status = dc_stream_get_status(dm_new_crtc_state->stream);
5065                 WARN_ON(!status);
5066                 WARN_ON(!status->plane_count);
5067
5068                 dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
5069
5070                 /*TODO How it works with MPO ?*/
5071                 if (!commit_planes_to_stream(
5072                                 dm,
5073                                 dm->dc,
5074                                 status->plane_states,
5075                                 status->plane_count,
5076                                 dm_new_crtc_state,
5077                                 to_dm_crtc_state(old_crtc_state),
5078                                 dc_state))
5079                         dm_error("%s: Failed to update stream scaling!\n", __func__);
5080         }
5081
5082         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
5083                         new_crtc_state, i) {
5084                 /*
5085                  * loop to enable interrupts on newly arrived crtc
5086                  */
5087                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
5088                 bool modeset_needed;
5089
5090                 if (old_crtc_state->active && !new_crtc_state->active)
5091                         crtc_disable_count++;
5092
5093                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5094                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5095                 modeset_needed = modeset_required(
5096                                 new_crtc_state,
5097                                 dm_new_crtc_state->stream,
5098                                 dm_old_crtc_state->stream);
5099
5100                 if (dm_new_crtc_state->stream == NULL || !modeset_needed)
5101                         continue;
5102
5103                 manage_dm_interrupts(adev, acrtc, true);
5104         }
5105
5106         /* update planes when needed per crtc*/
5107         for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
5108                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5109
5110                 if (dm_new_crtc_state->stream)
5111                         amdgpu_dm_commit_planes(state, dc_state, dev,
5112                                                 dm, crtc, &wait_for_vblank);
5113         }
5114
5115
5116         /*
5117          * send vblank event on all events not handled in flip and
5118          * mark consumed event for drm_atomic_helper_commit_hw_done
5119          */
5120         spin_lock_irqsave(&adev->ddev->event_lock, flags);
5121         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
5122
5123                 if (new_crtc_state->event)
5124                         drm_send_event_locked(dev, &new_crtc_state->event->base);
5125
5126                 new_crtc_state->event = NULL;
5127         }
5128         spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
5129
5130
5131         if (wait_for_vblank)
5132                 drm_atomic_helper_wait_for_flip_done(dev, state);
5133
5134         /*
5135          * FIXME:
5136          * Delay hw_done() until flip_done() is signaled. This is to block
5137          * another commit from freeing the CRTC state while we're still
5138          * waiting on flip_done.
5139          */
5140         drm_atomic_helper_commit_hw_done(state);
5141
5142         drm_atomic_helper_cleanup_planes(dev, state);
5143
5144         /*
5145          * Finally, drop a runtime PM reference for each newly disabled CRTC,
5146          * so we can put the GPU into runtime suspend if we're not driving any
5147          * displays anymore
5148          */
5149         for (i = 0; i < crtc_disable_count; i++)
5150                 pm_runtime_put_autosuspend(dev->dev);
5151         pm_runtime_mark_last_busy(dev->dev);
5152
5153         if (dc_state_temp)
5154                 dc_release_state(dc_state_temp);
5155 }
5156
5157
5158 static int dm_force_atomic_commit(struct drm_connector *connector)
5159 {
5160         int ret = 0;
5161         struct drm_device *ddev = connector->dev;
5162         struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
5163         struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
5164         struct drm_plane *plane = disconnected_acrtc->base.primary;
5165         struct drm_connector_state *conn_state;
5166         struct drm_crtc_state *crtc_state;
5167         struct drm_plane_state *plane_state;
5168
5169         if (!state)
5170                 return -ENOMEM;
5171
5172         state->acquire_ctx = ddev->mode_config.acquire_ctx;
5173
5174         /* Construct an atomic state to restore previous display setting */
5175
5176         /*
5177          * Attach connectors to drm_atomic_state
5178          */
5179         conn_state = drm_atomic_get_connector_state(state, connector);
5180
5181         ret = PTR_ERR_OR_ZERO(conn_state);
5182         if (ret)
5183                 goto err;
5184
5185         /* Attach crtc to drm_atomic_state*/
5186         crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
5187
5188         ret = PTR_ERR_OR_ZERO(crtc_state);
5189         if (ret)
5190                 goto err;
5191
5192         /* force a restore */
5193         crtc_state->mode_changed = true;
5194
5195         /* Attach plane to drm_atomic_state */
5196         plane_state = drm_atomic_get_plane_state(state, plane);
5197
5198         ret = PTR_ERR_OR_ZERO(plane_state);
5199         if (ret)
5200                 goto err;
5201
5202
5203         /* Call commit internally with the state we just constructed */
5204         ret = drm_atomic_commit(state);
5205         if (!ret)
5206                 return 0;
5207
5208 err:
5209         DRM_ERROR("Restoring old state failed with %i\n", ret);
5210         drm_atomic_state_put(state);
5211
5212         return ret;
5213 }
5214
5215 /*
5216  * This function handles all cases when set mode does not come upon hotplug.
5217  * This includes when a display is unplugged then plugged back into the
5218  * same port and when running without usermode desktop manager supprot
5219  */
5220 void dm_restore_drm_connector_state(struct drm_device *dev,
5221                                     struct drm_connector *connector)
5222 {
5223         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5224         struct amdgpu_crtc *disconnected_acrtc;
5225         struct dm_crtc_state *acrtc_state;
5226
5227         if (!aconnector->dc_sink || !connector->state || !connector->encoder)
5228                 return;
5229
5230         disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
5231         if (!disconnected_acrtc)
5232                 return;
5233
5234         acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
5235         if (!acrtc_state->stream)
5236                 return;
5237
5238         /*
5239          * If the previous sink is not released and different from the current,
5240          * we deduce we are in a state where we can not rely on usermode call
5241          * to turn on the display, so we do it here
5242          */
5243         if (acrtc_state->stream->sink != aconnector->dc_sink)
5244                 dm_force_atomic_commit(&aconnector->base);
5245 }
5246
5247 /*
5248  * Grabs all modesetting locks to serialize against any blocking commits,
5249  * Waits for completion of all non blocking commits.
5250  */
5251 static int do_aquire_global_lock(struct drm_device *dev,
5252                                  struct drm_atomic_state *state)
5253 {
5254         struct drm_crtc *crtc;
5255         struct drm_crtc_commit *commit;
5256         long ret;
5257
5258         /*
5259          * Adding all modeset locks to aquire_ctx will
5260          * ensure that when the framework release it the
5261          * extra locks we are locking here will get released to
5262          */
5263         ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
5264         if (ret)
5265                 return ret;
5266
5267         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
5268                 spin_lock(&crtc->commit_lock);
5269                 commit = list_first_entry_or_null(&crtc->commit_list,
5270                                 struct drm_crtc_commit, commit_entry);
5271                 if (commit)
5272                         drm_crtc_commit_get(commit);
5273                 spin_unlock(&crtc->commit_lock);
5274
5275                 if (!commit)
5276                         continue;
5277
5278                 /*
5279                  * Make sure all pending HW programming completed and
5280                  * page flips done
5281                  */
5282                 ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
5283
5284                 if (ret > 0)
5285                         ret = wait_for_completion_interruptible_timeout(
5286                                         &commit->flip_done, 10*HZ);
5287
5288                 if (ret == 0)
5289                         DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done "
5290                                   "timed out\n", crtc->base.id, crtc->name);
5291
5292                 drm_crtc_commit_put(commit);
5293         }
5294
5295         return ret < 0 ? ret : 0;
5296 }
5297
5298 static void get_freesync_config_for_crtc(
5299         struct dm_crtc_state *new_crtc_state,
5300         struct dm_connector_state *new_con_state)
5301 {
5302         struct mod_freesync_config config = {0};
5303         struct amdgpu_dm_connector *aconnector =
5304                         to_amdgpu_dm_connector(new_con_state->base.connector);
5305
5306         new_crtc_state->vrr_supported = new_con_state->freesync_capable;
5307
5308         if (new_con_state->freesync_capable) {
5309                 config.state = new_crtc_state->base.vrr_enabled ?
5310                                 VRR_STATE_ACTIVE_VARIABLE :
5311                                 VRR_STATE_INACTIVE;
5312                 config.min_refresh_in_uhz =
5313                                 aconnector->min_vfreq * 1000000;
5314                 config.max_refresh_in_uhz =
5315                                 aconnector->max_vfreq * 1000000;
5316                 config.vsif_supported = true;
5317         }
5318
5319         new_crtc_state->freesync_config = config;
5320 }
5321
5322 static void reset_freesync_config_for_crtc(
5323         struct dm_crtc_state *new_crtc_state)
5324 {
5325         new_crtc_state->vrr_supported = false;
5326
5327         memset(&new_crtc_state->adjust, 0,
5328                sizeof(new_crtc_state->adjust));
5329         memset(&new_crtc_state->vrr_infopacket, 0,
5330                sizeof(new_crtc_state->vrr_infopacket));
5331 }
5332
5333 static int dm_update_crtcs_state(struct amdgpu_display_manager *dm,
5334                                  struct drm_atomic_state *state,
5335                                  bool enable,
5336                                  bool *lock_and_validation_needed)
5337 {
5338         struct dm_atomic_state *dm_state = NULL;
5339         struct drm_crtc *crtc;
5340         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5341         int i;
5342         struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
5343         struct dc_stream_state *new_stream;
5344         int ret = 0;
5345
5346         /*
5347          * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
5348          * update changed items
5349          */
5350         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
5351                 struct amdgpu_crtc *acrtc = NULL;
5352                 struct amdgpu_dm_connector *aconnector = NULL;
5353                 struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
5354                 struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
5355                 struct drm_plane_state *new_plane_state = NULL;
5356
5357                 new_stream = NULL;
5358
5359                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5360                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5361                 acrtc = to_amdgpu_crtc(crtc);
5362
5363                 new_plane_state = drm_atomic_get_new_plane_state(state, new_crtc_state->crtc->primary);
5364
5365                 if (new_crtc_state->enable && new_plane_state && !new_plane_state->fb) {
5366                         ret = -EINVAL;
5367                         goto fail;
5368                 }
5369
5370                 aconnector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
5371
5372                 /* TODO This hack should go away */
5373                 if (aconnector && enable) {
5374                         /* Make sure fake sink is created in plug-in scenario */
5375                         drm_new_conn_state = drm_atomic_get_new_connector_state(state,
5376                                                                     &aconnector->base);
5377                         drm_old_conn_state = drm_atomic_get_old_connector_state(state,
5378                                                                     &aconnector->base);
5379
5380                         if (IS_ERR(drm_new_conn_state)) {
5381                                 ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
5382                                 break;
5383                         }
5384
5385                         dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
5386                         dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
5387
5388                         new_stream = create_stream_for_sink(aconnector,
5389                                                              &new_crtc_state->mode,
5390                                                             dm_new_conn_state,
5391                                                             dm_old_crtc_state->stream);
5392
5393                         /*
5394                          * we can have no stream on ACTION_SET if a display
5395                          * was disconnected during S3, in this case it is not an
5396                          * error, the OS will be updated after detection, and
5397                          * will do the right thing on next atomic commit
5398                          */
5399
5400                         if (!new_stream) {
5401                                 DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
5402                                                 __func__, acrtc->base.base.id);
5403                                 break;
5404                         }
5405
5406                         dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
5407
5408                         if (dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
5409                             dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
5410                                 new_crtc_state->mode_changed = false;
5411                                 DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
5412                                                  new_crtc_state->mode_changed);
5413                         }
5414                 }
5415
5416                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
5417                         goto next_crtc;
5418
5419                 DRM_DEBUG_DRIVER(
5420                         "amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
5421                         "planes_changed:%d, mode_changed:%d,active_changed:%d,"
5422                         "connectors_changed:%d\n",
5423                         acrtc->crtc_id,
5424                         new_crtc_state->enable,
5425                         new_crtc_state->active,
5426                         new_crtc_state->planes_changed,
5427                         new_crtc_state->mode_changed,
5428                         new_crtc_state->active_changed,
5429                         new_crtc_state->connectors_changed);
5430
5431                 /* Remove stream for any changed/disabled CRTC */
5432                 if (!enable) {
5433
5434                         if (!dm_old_crtc_state->stream)
5435                                 goto next_crtc;
5436
5437                         ret = dm_atomic_get_state(state, &dm_state);
5438                         if (ret)
5439                                 goto fail;
5440
5441                         DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
5442                                         crtc->base.id);
5443
5444                         /* i.e. reset mode */
5445                         if (dc_remove_stream_from_ctx(
5446                                         dm->dc,
5447                                         dm_state->context,
5448                                         dm_old_crtc_state->stream) != DC_OK) {
5449                                 ret = -EINVAL;
5450                                 goto fail;
5451                         }
5452
5453                         dc_stream_release(dm_old_crtc_state->stream);
5454                         dm_new_crtc_state->stream = NULL;
5455
5456                         reset_freesync_config_for_crtc(dm_new_crtc_state);
5457
5458                         *lock_and_validation_needed = true;
5459
5460                 } else {/* Add stream for any updated/enabled CRTC */
5461                         /*
5462                          * Quick fix to prevent NULL pointer on new_stream when
5463                          * added MST connectors not found in existing crtc_state in the chained mode
5464                          * TODO: need to dig out the root cause of that
5465                          */
5466                         if (!aconnector || (!aconnector->dc_sink && aconnector->mst_port))
5467                                 goto next_crtc;
5468
5469                         if (modereset_required(new_crtc_state))
5470                                 goto next_crtc;
5471
5472                         if (modeset_required(new_crtc_state, new_stream,
5473                                              dm_old_crtc_state->stream)) {
5474
5475                                 WARN_ON(dm_new_crtc_state->stream);
5476
5477                                 ret = dm_atomic_get_state(state, &dm_state);
5478                                 if (ret)
5479                                         goto fail;
5480
5481                                 dm_new_crtc_state->stream = new_stream;
5482
5483                                 dc_stream_retain(new_stream);
5484
5485                                 DRM_DEBUG_DRIVER("Enabling DRM crtc: %d\n",
5486                                                         crtc->base.id);
5487
5488                                 if (dc_add_stream_to_ctx(
5489                                                 dm->dc,
5490                                                 dm_state->context,
5491                                                 dm_new_crtc_state->stream) != DC_OK) {
5492                                         ret = -EINVAL;
5493                                         goto fail;
5494                                 }
5495
5496                                 *lock_and_validation_needed = true;
5497                         }
5498                 }
5499
5500 next_crtc:
5501                 /* Release extra reference */
5502                 if (new_stream)
5503                          dc_stream_release(new_stream);
5504
5505                 /*
5506                  * We want to do dc stream updates that do not require a
5507                  * full modeset below.
5508                  */
5509                 if (!(enable && aconnector && new_crtc_state->enable &&
5510                       new_crtc_state->active))
5511                         continue;
5512                 /*
5513                  * Given above conditions, the dc state cannot be NULL because:
5514                  * 1. We're in the process of enabling CRTCs (just been added
5515                  *    to the dc context, or already is on the context)
5516                  * 2. Has a valid connector attached, and
5517                  * 3. Is currently active and enabled.
5518                  * => The dc stream state currently exists.
5519                  */
5520                 BUG_ON(dm_new_crtc_state->stream == NULL);
5521
5522                 /* Scaling or underscan settings */
5523                 if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state))
5524                         update_stream_scaling_settings(
5525                                 &new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
5526
5527                 /*
5528                  * Color management settings. We also update color properties
5529                  * when a modeset is needed, to ensure it gets reprogrammed.
5530                  */
5531                 if (dm_new_crtc_state->base.color_mgmt_changed ||
5532                     drm_atomic_crtc_needs_modeset(new_crtc_state)) {
5533                         ret = amdgpu_dm_set_regamma_lut(dm_new_crtc_state);
5534                         if (ret)
5535                                 goto fail;
5536                         amdgpu_dm_set_ctm(dm_new_crtc_state);
5537                 }
5538
5539                 /* Update Freesync settings. */
5540                 get_freesync_config_for_crtc(dm_new_crtc_state,
5541                                              dm_new_conn_state);
5542         }
5543
5544         return ret;
5545
5546 fail:
5547         if (new_stream)
5548                 dc_stream_release(new_stream);
5549         return ret;
5550 }
5551
5552 static int dm_update_planes_state(struct dc *dc,
5553                                   struct drm_atomic_state *state,
5554                                   bool enable,
5555                                   bool *lock_and_validation_needed)
5556 {
5557
5558         struct dm_atomic_state *dm_state = NULL;
5559         struct drm_crtc *new_plane_crtc, *old_plane_crtc;
5560         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5561         struct drm_plane *plane;
5562         struct drm_plane_state *old_plane_state, *new_plane_state;
5563         struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
5564         struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
5565         int i ;
5566         /* TODO return page_flip_needed() function */
5567         bool pflip_needed  = !state->allow_modeset;
5568         int ret = 0;
5569
5570
5571         /* Add new planes, in reverse order as DC expectation */
5572         for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
5573                 new_plane_crtc = new_plane_state->crtc;
5574                 old_plane_crtc = old_plane_state->crtc;
5575                 dm_new_plane_state = to_dm_plane_state(new_plane_state);
5576                 dm_old_plane_state = to_dm_plane_state(old_plane_state);
5577
5578                 /*TODO Implement atomic check for cursor plane */
5579                 if (plane->type == DRM_PLANE_TYPE_CURSOR)
5580                         continue;
5581
5582                 /* Remove any changed/removed planes */
5583                 if (!enable) {
5584                         if (pflip_needed &&
5585                             plane->type != DRM_PLANE_TYPE_OVERLAY)
5586                                 continue;
5587
5588                         if (!old_plane_crtc)
5589                                 continue;
5590
5591                         old_crtc_state = drm_atomic_get_old_crtc_state(
5592                                         state, old_plane_crtc);
5593                         dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5594
5595                         if (!dm_old_crtc_state->stream)
5596                                 continue;
5597
5598                         DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
5599                                         plane->base.id, old_plane_crtc->base.id);
5600
5601                         ret = dm_atomic_get_state(state, &dm_state);
5602                         if (ret)
5603                                 return ret;
5604
5605                         if (!dc_remove_plane_from_context(
5606                                         dc,
5607                                         dm_old_crtc_state->stream,
5608                                         dm_old_plane_state->dc_state,
5609                                         dm_state->context)) {
5610
5611                                 ret = EINVAL;
5612                                 return ret;
5613                         }
5614
5615
5616                         dc_plane_state_release(dm_old_plane_state->dc_state);
5617                         dm_new_plane_state->dc_state = NULL;
5618
5619                         *lock_and_validation_needed = true;
5620
5621                 } else { /* Add new planes */
5622                         struct dc_plane_state *dc_new_plane_state;
5623
5624                         if (drm_atomic_plane_disabling(plane->state, new_plane_state))
5625                                 continue;
5626
5627                         if (!new_plane_crtc)
5628                                 continue;
5629
5630                         new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
5631                         dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5632
5633                         if (!dm_new_crtc_state->stream)
5634                                 continue;
5635
5636                         if (pflip_needed &&
5637                             plane->type != DRM_PLANE_TYPE_OVERLAY)
5638                                 continue;
5639
5640                         WARN_ON(dm_new_plane_state->dc_state);
5641
5642                         dc_new_plane_state = dc_create_plane_state(dc);
5643                         if (!dc_new_plane_state)
5644                                 return -ENOMEM;
5645
5646                         DRM_DEBUG_DRIVER("Enabling DRM plane: %d on DRM crtc %d\n",
5647                                         plane->base.id, new_plane_crtc->base.id);
5648
5649                         ret = fill_plane_attributes(
5650                                 new_plane_crtc->dev->dev_private,
5651                                 dc_new_plane_state,
5652                                 new_plane_state,
5653                                 new_crtc_state);
5654                         if (ret) {
5655                                 dc_plane_state_release(dc_new_plane_state);
5656                                 return ret;
5657                         }
5658
5659                         ret = dm_atomic_get_state(state, &dm_state);
5660                         if (ret) {
5661                                 dc_plane_state_release(dc_new_plane_state);
5662                                 return ret;
5663                         }
5664
5665                         /*
5666                          * Any atomic check errors that occur after this will
5667                          * not need a release. The plane state will be attached
5668                          * to the stream, and therefore part of the atomic
5669                          * state. It'll be released when the atomic state is
5670                          * cleaned.
5671                          */
5672                         if (!dc_add_plane_to_context(
5673                                         dc,
5674                                         dm_new_crtc_state->stream,
5675                                         dc_new_plane_state,
5676                                         dm_state->context)) {
5677
5678                                 dc_plane_state_release(dc_new_plane_state);
5679                                 return -EINVAL;
5680                         }
5681
5682                         dm_new_plane_state->dc_state = dc_new_plane_state;
5683
5684                         /* Tell DC to do a full surface update every time there
5685                          * is a plane change. Inefficient, but works for now.
5686                          */
5687                         dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
5688
5689                         *lock_and_validation_needed = true;
5690                 }
5691         }
5692
5693
5694         return ret;
5695 }
5696
5697 static int
5698 dm_determine_update_type_for_commit(struct dc *dc,
5699                                     struct drm_atomic_state *state,
5700                                     enum surface_update_type *out_type)
5701 {
5702         struct dm_atomic_state *dm_state = NULL, *old_dm_state = NULL;
5703         int i, j, num_plane, ret = 0;
5704         struct drm_plane_state *old_plane_state, *new_plane_state;
5705         struct dm_plane_state *new_dm_plane_state, *old_dm_plane_state;
5706         struct drm_crtc *new_plane_crtc, *old_plane_crtc;
5707         struct drm_plane *plane;
5708
5709         struct drm_crtc *crtc;
5710         struct drm_crtc_state *new_crtc_state, *old_crtc_state;
5711         struct dm_crtc_state *new_dm_crtc_state, *old_dm_crtc_state;
5712         struct dc_stream_status *status = NULL;
5713
5714         struct dc_surface_update *updates = kzalloc(MAX_SURFACES * sizeof(struct dc_surface_update), GFP_KERNEL);
5715         struct dc_plane_state *surface = kzalloc(MAX_SURFACES * sizeof(struct dc_plane_state), GFP_KERNEL);
5716         struct dc_stream_update stream_update;
5717         enum surface_update_type update_type = UPDATE_TYPE_FAST;
5718
5719         if (!updates || !surface) {
5720                 DRM_ERROR("Plane or surface update failed to allocate");
5721                 /* Set type to FULL to avoid crashing in DC*/
5722                 update_type = UPDATE_TYPE_FULL;
5723                 goto cleanup;
5724         }
5725
5726         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
5727                 new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
5728                 old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
5729                 num_plane = 0;
5730
5731                 if (new_dm_crtc_state->stream) {
5732
5733                         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, j) {
5734                                 new_plane_crtc = new_plane_state->crtc;
5735                                 old_plane_crtc = old_plane_state->crtc;
5736                                 new_dm_plane_state = to_dm_plane_state(new_plane_state);
5737                                 old_dm_plane_state = to_dm_plane_state(old_plane_state);
5738
5739                                 if (plane->type == DRM_PLANE_TYPE_CURSOR)
5740                                         continue;
5741
5742                                 if (!state->allow_modeset)
5743                                         continue;
5744
5745                                 if (crtc == new_plane_crtc) {
5746                                         updates[num_plane].surface = &surface[num_plane];
5747
5748                                         if (new_crtc_state->mode_changed) {
5749                                                 updates[num_plane].surface->src_rect =
5750                                                                         new_dm_plane_state->dc_state->src_rect;
5751                                                 updates[num_plane].surface->dst_rect =
5752                                                                         new_dm_plane_state->dc_state->dst_rect;
5753                                                 updates[num_plane].surface->rotation =
5754                                                                         new_dm_plane_state->dc_state->rotation;
5755                                                 updates[num_plane].surface->in_transfer_func =
5756                                                                         new_dm_plane_state->dc_state->in_transfer_func;
5757                                                 stream_update.dst = new_dm_crtc_state->stream->dst;
5758                                                 stream_update.src = new_dm_crtc_state->stream->src;
5759                                         }
5760
5761                                         if (new_crtc_state->color_mgmt_changed) {
5762                                                 updates[num_plane].gamma =
5763                                                                 new_dm_plane_state->dc_state->gamma_correction;
5764                                                 updates[num_plane].in_transfer_func =
5765                                                                 new_dm_plane_state->dc_state->in_transfer_func;
5766                                                 stream_update.gamut_remap =
5767                                                                 &new_dm_crtc_state->stream->gamut_remap_matrix;
5768                                                 stream_update.out_transfer_func =
5769                                                                 new_dm_crtc_state->stream->out_transfer_func;
5770                                         }
5771
5772                                         num_plane++;
5773                                 }
5774                         }
5775
5776                         if (num_plane > 0) {
5777                                 ret = dm_atomic_get_state(state, &dm_state);
5778                                 if (ret)
5779                                         goto cleanup;
5780
5781                                 old_dm_state = dm_atomic_get_old_state(state);
5782                                 if (!old_dm_state) {
5783                                         ret = -EINVAL;
5784                                         goto cleanup;
5785                                 }
5786
5787                                 status = dc_state_get_stream_status(old_dm_state->context,
5788                                                                     new_dm_crtc_state->stream);
5789
5790                                 update_type = dc_check_update_surfaces_for_stream(dc, updates, num_plane,
5791                                                                                   &stream_update, status);
5792
5793                                 if (update_type > UPDATE_TYPE_MED) {
5794                                         update_type = UPDATE_TYPE_FULL;
5795                                         goto cleanup;
5796                                 }
5797                         }
5798
5799                 } else if (!new_dm_crtc_state->stream && old_dm_crtc_state->stream) {
5800                         update_type = UPDATE_TYPE_FULL;
5801                         goto cleanup;
5802                 }
5803         }
5804
5805 cleanup:
5806         kfree(updates);
5807         kfree(surface);
5808
5809         *out_type = update_type;
5810         return ret;
5811 }
5812
5813 /**
5814  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
5815  * @dev: The DRM device
5816  * @state: The atomic state to commit
5817  *
5818  * Validate that the given atomic state is programmable by DC into hardware.
5819  * This involves constructing a &struct dc_state reflecting the new hardware
5820  * state we wish to commit, then querying DC to see if it is programmable. It's
5821  * important not to modify the existing DC state. Otherwise, atomic_check
5822  * may unexpectedly commit hardware changes.
5823  *
5824  * When validating the DC state, it's important that the right locks are
5825  * acquired. For full updates case which removes/adds/updates streams on one
5826  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
5827  * that any such full update commit will wait for completion of any outstanding
5828  * flip using DRMs synchronization events. See
5829  * dm_determine_update_type_for_commit()
5830  *
5831  * Note that DM adds the affected connectors for all CRTCs in state, when that
5832  * might not seem necessary. This is because DC stream creation requires the
5833  * DC sink, which is tied to the DRM connector state. Cleaning this up should
5834  * be possible but non-trivial - a possible TODO item.
5835  *
5836  * Return: -Error code if validation failed.
5837  */
5838 static int amdgpu_dm_atomic_check(struct drm_device *dev,
5839                                   struct drm_atomic_state *state)
5840 {
5841         struct amdgpu_device *adev = dev->dev_private;
5842         struct dm_atomic_state *dm_state = NULL;
5843         struct dc *dc = adev->dm.dc;
5844         struct drm_connector *connector;
5845         struct drm_connector_state *old_con_state, *new_con_state;
5846         struct drm_crtc *crtc;
5847         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5848         enum surface_update_type update_type = UPDATE_TYPE_FAST;
5849         enum surface_update_type overall_update_type = UPDATE_TYPE_FAST;
5850
5851         int ret, i;
5852
5853         /*
5854          * This bool will be set for true for any modeset/reset
5855          * or plane update which implies non fast surface update.
5856          */
5857         bool lock_and_validation_needed = false;
5858
5859         ret = drm_atomic_helper_check_modeset(dev, state);
5860         if (ret)
5861                 goto fail;
5862
5863         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
5864                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
5865                     !new_crtc_state->color_mgmt_changed &&
5866                     !new_crtc_state->vrr_enabled)
5867                         continue;
5868
5869                 if (!new_crtc_state->enable)
5870                         continue;
5871
5872                 ret = drm_atomic_add_affected_connectors(state, crtc);
5873                 if (ret)
5874                         return ret;
5875
5876                 ret = drm_atomic_add_affected_planes(state, crtc);
5877                 if (ret)
5878                         goto fail;
5879         }
5880
5881         /* Remove exiting planes if they are modified */
5882         ret = dm_update_planes_state(dc, state, false, &lock_and_validation_needed);
5883         if (ret) {
5884                 goto fail;
5885         }
5886
5887         /* Disable all crtcs which require disable */
5888         ret = dm_update_crtcs_state(&adev->dm, state, false, &lock_and_validation_needed);
5889         if (ret) {
5890                 goto fail;
5891         }
5892
5893         /* Enable all crtcs which require enable */
5894         ret = dm_update_crtcs_state(&adev->dm, state, true, &lock_and_validation_needed);
5895         if (ret) {
5896                 goto fail;
5897         }
5898
5899         /* Add new/modified planes */
5900         ret = dm_update_planes_state(dc, state, true, &lock_and_validation_needed);
5901         if (ret) {
5902                 goto fail;
5903         }
5904
5905         /* Run this here since we want to validate the streams we created */
5906         ret = drm_atomic_helper_check_planes(dev, state);
5907         if (ret)
5908                 goto fail;
5909
5910         /* Check scaling and underscan changes*/
5911         /* TODO Removed scaling changes validation due to inability to commit
5912          * new stream into context w\o causing full reset. Need to
5913          * decide how to handle.
5914          */
5915         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
5916                 struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
5917                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
5918                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
5919
5920                 /* Skip any modesets/resets */
5921                 if (!acrtc || drm_atomic_crtc_needs_modeset(
5922                                 drm_atomic_get_new_crtc_state(state, &acrtc->base)))
5923                         continue;
5924
5925                 /* Skip any thing not scale or underscan changes */
5926                 if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
5927                         continue;
5928
5929                 overall_update_type = UPDATE_TYPE_FULL;
5930                 lock_and_validation_needed = true;
5931         }
5932
5933         ret = dm_determine_update_type_for_commit(dc, state, &update_type);
5934         if (ret)
5935                 goto fail;
5936
5937         if (overall_update_type < update_type)
5938                 overall_update_type = update_type;
5939
5940         /*
5941          * lock_and_validation_needed was an old way to determine if we need to set
5942          * the global lock. Leaving it in to check if we broke any corner cases
5943          * lock_and_validation_needed true = UPDATE_TYPE_FULL or UPDATE_TYPE_MED
5944          * lock_and_validation_needed false = UPDATE_TYPE_FAST
5945          */
5946         if (lock_and_validation_needed && overall_update_type <= UPDATE_TYPE_FAST)
5947                 WARN(1, "Global lock should be Set, overall_update_type should be UPDATE_TYPE_MED or UPDATE_TYPE_FULL");
5948         else if (!lock_and_validation_needed && overall_update_type > UPDATE_TYPE_FAST)
5949                 WARN(1, "Global lock should NOT be set, overall_update_type should be UPDATE_TYPE_FAST");
5950
5951
5952         if (overall_update_type > UPDATE_TYPE_FAST) {
5953                 ret = dm_atomic_get_state(state, &dm_state);
5954                 if (ret)
5955                         goto fail;
5956
5957                 ret = do_aquire_global_lock(dev, state);
5958                 if (ret)
5959                         goto fail;
5960
5961                 if (dc_validate_global_state(dc, dm_state->context) != DC_OK) {
5962                         ret = -EINVAL;
5963                         goto fail;
5964                 }
5965         } else if (state->legacy_cursor_update) {
5966                 /*
5967                  * This is a fast cursor update coming from the plane update
5968                  * helper, check if it can be done asynchronously for better
5969                  * performance.
5970                  */
5971                 state->async_update = !drm_atomic_helper_async_check(dev, state);
5972         }
5973
5974         /* Must be success */
5975         WARN_ON(ret);
5976         return ret;
5977
5978 fail:
5979         if (ret == -EDEADLK)
5980                 DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
5981         else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
5982                 DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
5983         else
5984                 DRM_DEBUG_DRIVER("Atomic check failed with err: %d \n", ret);
5985
5986         return ret;
5987 }
5988
5989 static bool is_dp_capable_without_timing_msa(struct dc *dc,
5990                                              struct amdgpu_dm_connector *amdgpu_dm_connector)
5991 {
5992         uint8_t dpcd_data;
5993         bool capable = false;
5994
5995         if (amdgpu_dm_connector->dc_link &&
5996                 dm_helpers_dp_read_dpcd(
5997                                 NULL,
5998                                 amdgpu_dm_connector->dc_link,
5999                                 DP_DOWN_STREAM_PORT_COUNT,
6000                                 &dpcd_data,
6001                                 sizeof(dpcd_data))) {
6002                 capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
6003         }
6004
6005         return capable;
6006 }
6007 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
6008                                         struct edid *edid)
6009 {
6010         int i;
6011         bool edid_check_required;
6012         struct detailed_timing *timing;
6013         struct detailed_non_pixel *data;
6014         struct detailed_data_monitor_range *range;
6015         struct amdgpu_dm_connector *amdgpu_dm_connector =
6016                         to_amdgpu_dm_connector(connector);
6017         struct dm_connector_state *dm_con_state = NULL;
6018
6019         struct drm_device *dev = connector->dev;
6020         struct amdgpu_device *adev = dev->dev_private;
6021         bool freesync_capable = false;
6022
6023         if (!connector->state) {
6024                 DRM_ERROR("%s - Connector has no state", __func__);
6025                 goto update;
6026         }
6027
6028         if (!edid) {
6029                 dm_con_state = to_dm_connector_state(connector->state);
6030
6031                 amdgpu_dm_connector->min_vfreq = 0;
6032                 amdgpu_dm_connector->max_vfreq = 0;
6033                 amdgpu_dm_connector->pixel_clock_mhz = 0;
6034
6035                 goto update;
6036         }
6037
6038         dm_con_state = to_dm_connector_state(connector->state);
6039
6040         edid_check_required = false;
6041         if (!amdgpu_dm_connector->dc_sink) {
6042                 DRM_ERROR("dc_sink NULL, could not add free_sync module.\n");
6043                 goto update;
6044         }
6045         if (!adev->dm.freesync_module)
6046                 goto update;
6047         /*
6048          * if edid non zero restrict freesync only for dp and edp
6049          */
6050         if (edid) {
6051                 if (amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
6052                         || amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_EDP) {
6053                         edid_check_required = is_dp_capable_without_timing_msa(
6054                                                 adev->dm.dc,
6055                                                 amdgpu_dm_connector);
6056                 }
6057         }
6058         if (edid_check_required == true && (edid->version > 1 ||
6059            (edid->version == 1 && edid->revision > 1))) {
6060                 for (i = 0; i < 4; i++) {
6061
6062                         timing  = &edid->detailed_timings[i];
6063                         data    = &timing->data.other_data;
6064                         range   = &data->data.range;
6065                         /*
6066                          * Check if monitor has continuous frequency mode
6067                          */
6068                         if (data->type != EDID_DETAIL_MONITOR_RANGE)
6069                                 continue;
6070                         /*
6071                          * Check for flag range limits only. If flag == 1 then
6072                          * no additional timing information provided.
6073                          * Default GTF, GTF Secondary curve and CVT are not
6074                          * supported
6075                          */
6076                         if (range->flags != 1)
6077                                 continue;
6078
6079                         amdgpu_dm_connector->min_vfreq = range->min_vfreq;
6080                         amdgpu_dm_connector->max_vfreq = range->max_vfreq;
6081                         amdgpu_dm_connector->pixel_clock_mhz =
6082                                 range->pixel_clock_mhz * 10;
6083                         break;
6084                 }
6085
6086                 if (amdgpu_dm_connector->max_vfreq -
6087                     amdgpu_dm_connector->min_vfreq > 10) {
6088
6089                         freesync_capable = true;
6090                 }
6091         }
6092
6093 update:
6094         if (dm_con_state)
6095                 dm_con_state->freesync_capable = freesync_capable;
6096
6097         if (connector->vrr_capable_property)
6098                 drm_connector_set_vrr_capable_property(connector,
6099                                                        freesync_capable);
6100 }
6101