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