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