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