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