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