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