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