]> Git Repo - linux.git/blob - drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c
drm/amdgpu: allocate gart memory when it's required (v3)
[linux.git] / drivers / gpu / drm / amd / display / amdgpu_dm / amdgpu_dm.c
1 /*
2  * Copyright 2015 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  * Authors: AMD
23  *
24  */
25
26 #include "dm_services_types.h"
27 #include "dc.h"
28 #include "dc/inc/core_types.h"
29
30 #include "vid.h"
31 #include "amdgpu.h"
32 #include "amdgpu_display.h"
33 #include "atom.h"
34 #include "amdgpu_dm.h"
35 #include "amdgpu_pm.h"
36
37 #include "amd_shared.h"
38 #include "amdgpu_dm_irq.h"
39 #include "dm_helpers.h"
40 #include "dm_services_types.h"
41 #include "amdgpu_dm_mst_types.h"
42 #if defined(CONFIG_DEBUG_FS)
43 #include "amdgpu_dm_debugfs.h"
44 #endif
45
46 #include "ivsrcid/ivsrcid_vislands30.h"
47
48 #include <linux/module.h>
49 #include <linux/moduleparam.h>
50 #include <linux/version.h>
51 #include <linux/types.h>
52 #include <linux/pm_runtime.h>
53
54 #include <drm/drmP.h>
55 #include <drm/drm_atomic.h>
56 #include <drm/drm_atomic_helper.h>
57 #include <drm/drm_dp_mst_helper.h>
58 #include <drm/drm_fb_helper.h>
59 #include <drm/drm_edid.h>
60
61 #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_mode_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_mode_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);
3098         if (unlikely(r != 0)) {
3099                 if (r != -ERESTARTSYS)
3100                         DRM_ERROR("Failed to pin framebuffer with error %d\n", r);
3101                 amdgpu_bo_unreserve(rbo);
3102                 return r;
3103         }
3104
3105         r = amdgpu_ttm_alloc_gart(&rbo->tbo);
3106         if (unlikely(r != 0)) {
3107                 amdgpu_bo_unpin(rbo);
3108                 amdgpu_bo_unreserve(rbo);
3109                 DRM_ERROR("%p bind failed\n", rbo);
3110                 return r;
3111         }
3112         amdgpu_bo_unreserve(rbo);
3113
3114         afb->address = amdgpu_bo_gpu_offset(rbo);
3115
3116         amdgpu_bo_ref(rbo);
3117
3118         if (dm_plane_state_new->dc_state &&
3119                         dm_plane_state_old->dc_state != dm_plane_state_new->dc_state) {
3120                 struct dc_plane_state *plane_state = dm_plane_state_new->dc_state;
3121
3122                 if (plane_state->format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN) {
3123                         plane_state->address.grph.addr.low_part = lower_32_bits(afb->address);
3124                         plane_state->address.grph.addr.high_part = upper_32_bits(afb->address);
3125                 } else {
3126                         awidth = ALIGN(new_state->fb->width, 64);
3127                         plane_state->address.type = PLN_ADDR_TYPE_VIDEO_PROGRESSIVE;
3128                         plane_state->address.video_progressive.luma_addr.low_part
3129                                                         = lower_32_bits(afb->address);
3130                         plane_state->address.video_progressive.luma_addr.high_part
3131                                                         = upper_32_bits(afb->address);
3132                         chroma_addr = afb->address + (u64)awidth * new_state->fb->height;
3133                         plane_state->address.video_progressive.chroma_addr.low_part
3134                                                         = lower_32_bits(chroma_addr);
3135                         plane_state->address.video_progressive.chroma_addr.high_part
3136                                                         = upper_32_bits(chroma_addr);
3137                 }
3138         }
3139
3140         return 0;
3141 }
3142
3143 static void dm_plane_helper_cleanup_fb(struct drm_plane *plane,
3144                                        struct drm_plane_state *old_state)
3145 {
3146         struct amdgpu_bo *rbo;
3147         int r;
3148
3149         if (!old_state->fb)
3150                 return;
3151
3152         rbo = gem_to_amdgpu_bo(old_state->fb->obj[0]);
3153         r = amdgpu_bo_reserve(rbo, false);
3154         if (unlikely(r)) {
3155                 DRM_ERROR("failed to reserve rbo before unpin\n");
3156                 return;
3157         }
3158
3159         amdgpu_bo_unpin(rbo);
3160         amdgpu_bo_unreserve(rbo);
3161         amdgpu_bo_unref(&rbo);
3162 }
3163
3164 static int dm_plane_atomic_check(struct drm_plane *plane,
3165                                  struct drm_plane_state *state)
3166 {
3167         struct amdgpu_device *adev = plane->dev->dev_private;
3168         struct dc *dc = adev->dm.dc;
3169         struct dm_plane_state *dm_plane_state = to_dm_plane_state(state);
3170
3171         if (!dm_plane_state->dc_state)
3172                 return 0;
3173
3174         if (!fill_rects_from_plane_state(state, dm_plane_state->dc_state))
3175                 return -EINVAL;
3176
3177         if (dc_validate_plane(dc, dm_plane_state->dc_state) == DC_OK)
3178                 return 0;
3179
3180         return -EINVAL;
3181 }
3182
3183 static const struct drm_plane_helper_funcs dm_plane_helper_funcs = {
3184         .prepare_fb = dm_plane_helper_prepare_fb,
3185         .cleanup_fb = dm_plane_helper_cleanup_fb,
3186         .atomic_check = dm_plane_atomic_check,
3187 };
3188
3189 /*
3190  * TODO: these are currently initialized to rgb formats only.
3191  * For future use cases we should either initialize them dynamically based on
3192  * plane capabilities, or initialize this array to all formats, so internal drm
3193  * check will succeed, and let DC to implement proper check
3194  */
3195 static const uint32_t rgb_formats[] = {
3196         DRM_FORMAT_RGB888,
3197         DRM_FORMAT_XRGB8888,
3198         DRM_FORMAT_ARGB8888,
3199         DRM_FORMAT_RGBA8888,
3200         DRM_FORMAT_XRGB2101010,
3201         DRM_FORMAT_XBGR2101010,
3202         DRM_FORMAT_ARGB2101010,
3203         DRM_FORMAT_ABGR2101010,
3204 };
3205
3206 static const uint32_t yuv_formats[] = {
3207         DRM_FORMAT_NV12,
3208         DRM_FORMAT_NV21,
3209 };
3210
3211 static const u32 cursor_formats[] = {
3212         DRM_FORMAT_ARGB8888
3213 };
3214
3215 static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
3216                                 struct amdgpu_plane *aplane,
3217                                 unsigned long possible_crtcs)
3218 {
3219         int res = -EPERM;
3220
3221         switch (aplane->base.type) {
3222         case DRM_PLANE_TYPE_PRIMARY:
3223                 res = drm_universal_plane_init(
3224                                 dm->adev->ddev,
3225                                 &aplane->base,
3226                                 possible_crtcs,
3227                                 &dm_plane_funcs,
3228                                 rgb_formats,
3229                                 ARRAY_SIZE(rgb_formats),
3230                                 NULL, aplane->base.type, NULL);
3231                 break;
3232         case DRM_PLANE_TYPE_OVERLAY:
3233                 res = drm_universal_plane_init(
3234                                 dm->adev->ddev,
3235                                 &aplane->base,
3236                                 possible_crtcs,
3237                                 &dm_plane_funcs,
3238                                 yuv_formats,
3239                                 ARRAY_SIZE(yuv_formats),
3240                                 NULL, aplane->base.type, NULL);
3241                 break;
3242         case DRM_PLANE_TYPE_CURSOR:
3243                 res = drm_universal_plane_init(
3244                                 dm->adev->ddev,
3245                                 &aplane->base,
3246                                 possible_crtcs,
3247                                 &dm_plane_funcs,
3248                                 cursor_formats,
3249                                 ARRAY_SIZE(cursor_formats),
3250                                 NULL, aplane->base.type, NULL);
3251                 break;
3252         }
3253
3254         drm_plane_helper_add(&aplane->base, &dm_plane_helper_funcs);
3255
3256         /* Create (reset) the plane state */
3257         if (aplane->base.funcs->reset)
3258                 aplane->base.funcs->reset(&aplane->base);
3259
3260
3261         return res;
3262 }
3263
3264 static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
3265                                struct drm_plane *plane,
3266                                uint32_t crtc_index)
3267 {
3268         struct amdgpu_crtc *acrtc = NULL;
3269         struct amdgpu_plane *cursor_plane;
3270
3271         int res = -ENOMEM;
3272
3273         cursor_plane = kzalloc(sizeof(*cursor_plane), GFP_KERNEL);
3274         if (!cursor_plane)
3275                 goto fail;
3276
3277         cursor_plane->base.type = DRM_PLANE_TYPE_CURSOR;
3278         res = amdgpu_dm_plane_init(dm, cursor_plane, 0);
3279
3280         acrtc = kzalloc(sizeof(struct amdgpu_crtc), GFP_KERNEL);
3281         if (!acrtc)
3282                 goto fail;
3283
3284         res = drm_crtc_init_with_planes(
3285                         dm->ddev,
3286                         &acrtc->base,
3287                         plane,
3288                         &cursor_plane->base,
3289                         &amdgpu_dm_crtc_funcs, NULL);
3290
3291         if (res)
3292                 goto fail;
3293
3294         drm_crtc_helper_add(&acrtc->base, &amdgpu_dm_crtc_helper_funcs);
3295
3296         /* Create (reset) the plane state */
3297         if (acrtc->base.funcs->reset)
3298                 acrtc->base.funcs->reset(&acrtc->base);
3299
3300         acrtc->max_cursor_width = dm->adev->dm.dc->caps.max_cursor_size;
3301         acrtc->max_cursor_height = dm->adev->dm.dc->caps.max_cursor_size;
3302
3303         acrtc->crtc_id = crtc_index;
3304         acrtc->base.enabled = false;
3305
3306         dm->adev->mode_info.crtcs[crtc_index] = acrtc;
3307         drm_crtc_enable_color_mgmt(&acrtc->base, MAX_COLOR_LUT_ENTRIES,
3308                                    true, MAX_COLOR_LUT_ENTRIES);
3309         drm_mode_crtc_set_gamma_size(&acrtc->base, MAX_COLOR_LEGACY_LUT_ENTRIES);
3310
3311         return 0;
3312
3313 fail:
3314         kfree(acrtc);
3315         kfree(cursor_plane);
3316         return res;
3317 }
3318
3319
3320 static int to_drm_connector_type(enum signal_type st)
3321 {
3322         switch (st) {
3323         case SIGNAL_TYPE_HDMI_TYPE_A:
3324                 return DRM_MODE_CONNECTOR_HDMIA;
3325         case SIGNAL_TYPE_EDP:
3326                 return DRM_MODE_CONNECTOR_eDP;
3327         case SIGNAL_TYPE_RGB:
3328                 return DRM_MODE_CONNECTOR_VGA;
3329         case SIGNAL_TYPE_DISPLAY_PORT:
3330         case SIGNAL_TYPE_DISPLAY_PORT_MST:
3331                 return DRM_MODE_CONNECTOR_DisplayPort;
3332         case SIGNAL_TYPE_DVI_DUAL_LINK:
3333         case SIGNAL_TYPE_DVI_SINGLE_LINK:
3334                 return DRM_MODE_CONNECTOR_DVID;
3335         case SIGNAL_TYPE_VIRTUAL:
3336                 return DRM_MODE_CONNECTOR_VIRTUAL;
3337
3338         default:
3339                 return DRM_MODE_CONNECTOR_Unknown;
3340         }
3341 }
3342
3343 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
3344 {
3345         const struct drm_connector_helper_funcs *helper =
3346                 connector->helper_private;
3347         struct drm_encoder *encoder;
3348         struct amdgpu_encoder *amdgpu_encoder;
3349
3350         encoder = helper->best_encoder(connector);
3351
3352         if (encoder == NULL)
3353                 return;
3354
3355         amdgpu_encoder = to_amdgpu_encoder(encoder);
3356
3357         amdgpu_encoder->native_mode.clock = 0;
3358
3359         if (!list_empty(&connector->probed_modes)) {
3360                 struct drm_display_mode *preferred_mode = NULL;
3361
3362                 list_for_each_entry(preferred_mode,
3363                                     &connector->probed_modes,
3364                                     head) {
3365                         if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
3366                                 amdgpu_encoder->native_mode = *preferred_mode;
3367
3368                         break;
3369                 }
3370
3371         }
3372 }
3373
3374 static struct drm_display_mode *
3375 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
3376                              char *name,
3377                              int hdisplay, int vdisplay)
3378 {
3379         struct drm_device *dev = encoder->dev;
3380         struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
3381         struct drm_display_mode *mode = NULL;
3382         struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
3383
3384         mode = drm_mode_duplicate(dev, native_mode);
3385
3386         if (mode == NULL)
3387                 return NULL;
3388
3389         mode->hdisplay = hdisplay;
3390         mode->vdisplay = vdisplay;
3391         mode->type &= ~DRM_MODE_TYPE_PREFERRED;
3392         strncpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
3393
3394         return mode;
3395
3396 }
3397
3398 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
3399                                                  struct drm_connector *connector)
3400 {
3401         struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
3402         struct drm_display_mode *mode = NULL;
3403         struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
3404         struct amdgpu_dm_connector *amdgpu_dm_connector =
3405                                 to_amdgpu_dm_connector(connector);
3406         int i;
3407         int n;
3408         struct mode_size {
3409                 char name[DRM_DISPLAY_MODE_LEN];
3410                 int w;
3411                 int h;
3412         } common_modes[] = {
3413                 {  "640x480",  640,  480},
3414                 {  "800x600",  800,  600},
3415                 { "1024x768", 1024,  768},
3416                 { "1280x720", 1280,  720},
3417                 { "1280x800", 1280,  800},
3418                 {"1280x1024", 1280, 1024},
3419                 { "1440x900", 1440,  900},
3420                 {"1680x1050", 1680, 1050},
3421                 {"1600x1200", 1600, 1200},
3422                 {"1920x1080", 1920, 1080},
3423                 {"1920x1200", 1920, 1200}
3424         };
3425
3426         n = ARRAY_SIZE(common_modes);
3427
3428         for (i = 0; i < n; i++) {
3429                 struct drm_display_mode *curmode = NULL;
3430                 bool mode_existed = false;
3431
3432                 if (common_modes[i].w > native_mode->hdisplay ||
3433                     common_modes[i].h > native_mode->vdisplay ||
3434                    (common_modes[i].w == native_mode->hdisplay &&
3435                     common_modes[i].h == native_mode->vdisplay))
3436                         continue;
3437
3438                 list_for_each_entry(curmode, &connector->probed_modes, head) {
3439                         if (common_modes[i].w == curmode->hdisplay &&
3440                             common_modes[i].h == curmode->vdisplay) {
3441                                 mode_existed = true;
3442                                 break;
3443                         }
3444                 }
3445
3446                 if (mode_existed)
3447                         continue;
3448
3449                 mode = amdgpu_dm_create_common_mode(encoder,
3450                                 common_modes[i].name, common_modes[i].w,
3451                                 common_modes[i].h);
3452                 drm_mode_probed_add(connector, mode);
3453                 amdgpu_dm_connector->num_modes++;
3454         }
3455 }
3456
3457 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
3458                                               struct edid *edid)
3459 {
3460         struct amdgpu_dm_connector *amdgpu_dm_connector =
3461                         to_amdgpu_dm_connector(connector);
3462
3463         if (edid) {
3464                 /* empty probed_modes */
3465                 INIT_LIST_HEAD(&connector->probed_modes);
3466                 amdgpu_dm_connector->num_modes =
3467                                 drm_add_edid_modes(connector, edid);
3468
3469                 amdgpu_dm_get_native_mode(connector);
3470         } else {
3471                 amdgpu_dm_connector->num_modes = 0;
3472         }
3473 }
3474
3475 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
3476 {
3477         const struct drm_connector_helper_funcs *helper =
3478                         connector->helper_private;
3479         struct amdgpu_dm_connector *amdgpu_dm_connector =
3480                         to_amdgpu_dm_connector(connector);
3481         struct drm_encoder *encoder;
3482         struct edid *edid = amdgpu_dm_connector->edid;
3483
3484         encoder = helper->best_encoder(connector);
3485
3486         if (!edid || !drm_edid_is_valid(edid)) {
3487                 drm_add_modes_noedid(connector, 640, 480);
3488         } else {
3489                 amdgpu_dm_connector_ddc_get_modes(connector, edid);
3490                 amdgpu_dm_connector_add_common_modes(encoder, connector);
3491         }
3492         amdgpu_dm_fbc_init(connector);
3493
3494         return amdgpu_dm_connector->num_modes;
3495 }
3496
3497 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
3498                                      struct amdgpu_dm_connector *aconnector,
3499                                      int connector_type,
3500                                      struct dc_link *link,
3501                                      int link_index)
3502 {
3503         struct amdgpu_device *adev = dm->ddev->dev_private;
3504
3505         aconnector->connector_id = link_index;
3506         aconnector->dc_link = link;
3507         aconnector->base.interlace_allowed = false;
3508         aconnector->base.doublescan_allowed = false;
3509         aconnector->base.stereo_allowed = false;
3510         aconnector->base.dpms = DRM_MODE_DPMS_OFF;
3511         aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
3512
3513         mutex_init(&aconnector->hpd_lock);
3514
3515         /* configure support HPD hot plug connector_>polled default value is 0
3516          * which means HPD hot plug not supported
3517          */
3518         switch (connector_type) {
3519         case DRM_MODE_CONNECTOR_HDMIA:
3520                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
3521                 break;
3522         case DRM_MODE_CONNECTOR_DisplayPort:
3523                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
3524                 break;
3525         case DRM_MODE_CONNECTOR_DVID:
3526                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
3527                 break;
3528         default:
3529                 break;
3530         }
3531
3532         drm_object_attach_property(&aconnector->base.base,
3533                                 dm->ddev->mode_config.scaling_mode_property,
3534                                 DRM_MODE_SCALE_NONE);
3535
3536         drm_object_attach_property(&aconnector->base.base,
3537                                 adev->mode_info.underscan_property,
3538                                 UNDERSCAN_OFF);
3539         drm_object_attach_property(&aconnector->base.base,
3540                                 adev->mode_info.underscan_hborder_property,
3541                                 0);
3542         drm_object_attach_property(&aconnector->base.base,
3543                                 adev->mode_info.underscan_vborder_property,
3544                                 0);
3545
3546 }
3547
3548 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
3549                               struct i2c_msg *msgs, int num)
3550 {
3551         struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
3552         struct ddc_service *ddc_service = i2c->ddc_service;
3553         struct i2c_command cmd;
3554         int i;
3555         int result = -EIO;
3556
3557         cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
3558
3559         if (!cmd.payloads)
3560                 return result;
3561
3562         cmd.number_of_payloads = num;
3563         cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
3564         cmd.speed = 100;
3565
3566         for (i = 0; i < num; i++) {
3567                 cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
3568                 cmd.payloads[i].address = msgs[i].addr;
3569                 cmd.payloads[i].length = msgs[i].len;
3570                 cmd.payloads[i].data = msgs[i].buf;
3571         }
3572
3573         if (dal_i2caux_submit_i2c_command(
3574                         ddc_service->ctx->i2caux,
3575                         ddc_service->ddc_pin,
3576                         &cmd))
3577                 result = num;
3578
3579         kfree(cmd.payloads);
3580         return result;
3581 }
3582
3583 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
3584 {
3585         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
3586 }
3587
3588 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
3589         .master_xfer = amdgpu_dm_i2c_xfer,
3590         .functionality = amdgpu_dm_i2c_func,
3591 };
3592
3593 static struct amdgpu_i2c_adapter *
3594 create_i2c(struct ddc_service *ddc_service,
3595            int link_index,
3596            int *res)
3597 {
3598         struct amdgpu_device *adev = ddc_service->ctx->driver_context;
3599         struct amdgpu_i2c_adapter *i2c;
3600
3601         i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
3602         if (!i2c)
3603                 return NULL;
3604         i2c->base.owner = THIS_MODULE;
3605         i2c->base.class = I2C_CLASS_DDC;
3606         i2c->base.dev.parent = &adev->pdev->dev;
3607         i2c->base.algo = &amdgpu_dm_i2c_algo;
3608         snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
3609         i2c_set_adapdata(&i2c->base, i2c);
3610         i2c->ddc_service = ddc_service;
3611
3612         return i2c;
3613 }
3614
3615
3616 /* Note: this function assumes that dc_link_detect() was called for the
3617  * dc_link which will be represented by this aconnector.
3618  */
3619 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
3620                                     struct amdgpu_dm_connector *aconnector,
3621                                     uint32_t link_index,
3622                                     struct amdgpu_encoder *aencoder)
3623 {
3624         int res = 0;
3625         int connector_type;
3626         struct dc *dc = dm->dc;
3627         struct dc_link *link = dc_get_link_at_index(dc, link_index);
3628         struct amdgpu_i2c_adapter *i2c;
3629
3630         link->priv = aconnector;
3631
3632         DRM_DEBUG_DRIVER("%s()\n", __func__);
3633
3634         i2c = create_i2c(link->ddc, link->link_index, &res);
3635         if (!i2c) {
3636                 DRM_ERROR("Failed to create i2c adapter data\n");
3637                 return -ENOMEM;
3638         }
3639
3640         aconnector->i2c = i2c;
3641         res = i2c_add_adapter(&i2c->base);
3642
3643         if (res) {
3644                 DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
3645                 goto out_free;
3646         }
3647
3648         connector_type = to_drm_connector_type(link->connector_signal);
3649
3650         res = drm_connector_init(
3651                         dm->ddev,
3652                         &aconnector->base,
3653                         &amdgpu_dm_connector_funcs,
3654                         connector_type);
3655
3656         if (res) {
3657                 DRM_ERROR("connector_init failed\n");
3658                 aconnector->connector_id = -1;
3659                 goto out_free;
3660         }
3661
3662         drm_connector_helper_add(
3663                         &aconnector->base,
3664                         &amdgpu_dm_connector_helper_funcs);
3665
3666         if (aconnector->base.funcs->reset)
3667                 aconnector->base.funcs->reset(&aconnector->base);
3668
3669         amdgpu_dm_connector_init_helper(
3670                 dm,
3671                 aconnector,
3672                 connector_type,
3673                 link,
3674                 link_index);
3675
3676         drm_mode_connector_attach_encoder(
3677                 &aconnector->base, &aencoder->base);
3678
3679         drm_connector_register(&aconnector->base);
3680 #if defined(CONFIG_DEBUG_FS)
3681         res = connector_debugfs_init(aconnector);
3682         if (res) {
3683                 DRM_ERROR("Failed to create debugfs for connector");
3684                 goto out_free;
3685         }
3686 #endif
3687
3688         if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
3689                 || connector_type == DRM_MODE_CONNECTOR_eDP)
3690                 amdgpu_dm_initialize_dp_connector(dm, aconnector);
3691
3692 out_free:
3693         if (res) {
3694                 kfree(i2c);
3695                 aconnector->i2c = NULL;
3696         }
3697         return res;
3698 }
3699
3700 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
3701 {
3702         switch (adev->mode_info.num_crtc) {
3703         case 1:
3704                 return 0x1;
3705         case 2:
3706                 return 0x3;
3707         case 3:
3708                 return 0x7;
3709         case 4:
3710                 return 0xf;
3711         case 5:
3712                 return 0x1f;
3713         case 6:
3714         default:
3715                 return 0x3f;
3716         }
3717 }
3718
3719 static int amdgpu_dm_encoder_init(struct drm_device *dev,
3720                                   struct amdgpu_encoder *aencoder,
3721                                   uint32_t link_index)
3722 {
3723         struct amdgpu_device *adev = dev->dev_private;
3724
3725         int res = drm_encoder_init(dev,
3726                                    &aencoder->base,
3727                                    &amdgpu_dm_encoder_funcs,
3728                                    DRM_MODE_ENCODER_TMDS,
3729                                    NULL);
3730
3731         aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
3732
3733         if (!res)
3734                 aencoder->encoder_id = link_index;
3735         else
3736                 aencoder->encoder_id = -1;
3737
3738         drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
3739
3740         return res;
3741 }
3742
3743 static void manage_dm_interrupts(struct amdgpu_device *adev,
3744                                  struct amdgpu_crtc *acrtc,
3745                                  bool enable)
3746 {
3747         /*
3748          * this is not correct translation but will work as soon as VBLANK
3749          * constant is the same as PFLIP
3750          */
3751         int irq_type =
3752                 amdgpu_display_crtc_idx_to_irq_type(
3753                         adev,
3754                         acrtc->crtc_id);
3755
3756         if (enable) {
3757                 drm_crtc_vblank_on(&acrtc->base);
3758                 amdgpu_irq_get(
3759                         adev,
3760                         &adev->pageflip_irq,
3761                         irq_type);
3762         } else {
3763
3764                 amdgpu_irq_put(
3765                         adev,
3766                         &adev->pageflip_irq,
3767                         irq_type);
3768                 drm_crtc_vblank_off(&acrtc->base);
3769         }
3770 }
3771
3772 static bool
3773 is_scaling_state_different(const struct dm_connector_state *dm_state,
3774                            const struct dm_connector_state *old_dm_state)
3775 {
3776         if (dm_state->scaling != old_dm_state->scaling)
3777                 return true;
3778         if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
3779                 if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
3780                         return true;
3781         } else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
3782                 if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
3783                         return true;
3784         } else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
3785                    dm_state->underscan_vborder != old_dm_state->underscan_vborder)
3786                 return true;
3787         return false;
3788 }
3789
3790 static void remove_stream(struct amdgpu_device *adev,
3791                           struct amdgpu_crtc *acrtc,
3792                           struct dc_stream_state *stream)
3793 {
3794         /* this is the update mode case */
3795         if (adev->dm.freesync_module)
3796                 mod_freesync_remove_stream(adev->dm.freesync_module, stream);
3797
3798         acrtc->otg_inst = -1;
3799         acrtc->enabled = false;
3800 }
3801
3802 static int get_cursor_position(struct drm_plane *plane, struct drm_crtc *crtc,
3803                                struct dc_cursor_position *position)
3804 {
3805         struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
3806         int x, y;
3807         int xorigin = 0, yorigin = 0;
3808
3809         if (!crtc || !plane->state->fb) {
3810                 position->enable = false;
3811                 position->x = 0;
3812                 position->y = 0;
3813                 return 0;
3814         }
3815
3816         if ((plane->state->crtc_w > amdgpu_crtc->max_cursor_width) ||
3817             (plane->state->crtc_h > amdgpu_crtc->max_cursor_height)) {
3818                 DRM_ERROR("%s: bad cursor width or height %d x %d\n",
3819                           __func__,
3820                           plane->state->crtc_w,
3821                           plane->state->crtc_h);
3822                 return -EINVAL;
3823         }
3824
3825         x = plane->state->crtc_x;
3826         y = plane->state->crtc_y;
3827         /* avivo cursor are offset into the total surface */
3828         x += crtc->primary->state->src_x >> 16;
3829         y += crtc->primary->state->src_y >> 16;
3830         if (x < 0) {
3831                 xorigin = min(-x, amdgpu_crtc->max_cursor_width - 1);
3832                 x = 0;
3833         }
3834         if (y < 0) {
3835                 yorigin = min(-y, amdgpu_crtc->max_cursor_height - 1);
3836                 y = 0;
3837         }
3838         position->enable = true;
3839         position->x = x;
3840         position->y = y;
3841         position->x_hotspot = xorigin;
3842         position->y_hotspot = yorigin;
3843
3844         return 0;
3845 }
3846
3847 static void handle_cursor_update(struct drm_plane *plane,
3848                                  struct drm_plane_state *old_plane_state)
3849 {
3850         struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
3851         struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
3852         struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
3853         struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
3854         uint64_t address = afb ? afb->address : 0;
3855         struct dc_cursor_position position;
3856         struct dc_cursor_attributes attributes;
3857         int ret;
3858
3859         if (!plane->state->fb && !old_plane_state->fb)
3860                 return;
3861
3862         DRM_DEBUG_DRIVER("%s: crtc_id=%d with size %d to %d\n",
3863                          __func__,
3864                          amdgpu_crtc->crtc_id,
3865                          plane->state->crtc_w,
3866                          plane->state->crtc_h);
3867
3868         ret = get_cursor_position(plane, crtc, &position);
3869         if (ret)
3870                 return;
3871
3872         if (!position.enable) {
3873                 /* turn off cursor */
3874                 if (crtc_state && crtc_state->stream)
3875                         dc_stream_set_cursor_position(crtc_state->stream,
3876                                                       &position);
3877                 return;
3878         }
3879
3880         amdgpu_crtc->cursor_width = plane->state->crtc_w;
3881         amdgpu_crtc->cursor_height = plane->state->crtc_h;
3882
3883         attributes.address.high_part = upper_32_bits(address);
3884         attributes.address.low_part  = lower_32_bits(address);
3885         attributes.width             = plane->state->crtc_w;
3886         attributes.height            = plane->state->crtc_h;
3887         attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
3888         attributes.rotation_angle    = 0;
3889         attributes.attribute_flags.value = 0;
3890
3891         attributes.pitch = attributes.width;
3892
3893         if (crtc_state->stream) {
3894                 if (!dc_stream_set_cursor_attributes(crtc_state->stream,
3895                                                          &attributes))
3896                         DRM_ERROR("DC failed to set cursor attributes\n");
3897
3898                 if (!dc_stream_set_cursor_position(crtc_state->stream,
3899                                                    &position))
3900                         DRM_ERROR("DC failed to set cursor position\n");
3901         }
3902 }
3903
3904 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
3905 {
3906
3907         assert_spin_locked(&acrtc->base.dev->event_lock);
3908         WARN_ON(acrtc->event);
3909
3910         acrtc->event = acrtc->base.state->event;
3911
3912         /* Set the flip status */
3913         acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
3914
3915         /* Mark this event as consumed */
3916         acrtc->base.state->event = NULL;
3917
3918         DRM_DEBUG_DRIVER("crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
3919                                                  acrtc->crtc_id);
3920 }
3921
3922 /*
3923  * Executes flip
3924  *
3925  * Waits on all BO's fences and for proper vblank count
3926  */
3927 static void amdgpu_dm_do_flip(struct drm_crtc *crtc,
3928                               struct drm_framebuffer *fb,
3929                               uint32_t target,
3930                               struct dc_state *state)
3931 {
3932         unsigned long flags;
3933         uint32_t target_vblank;
3934         int r, vpos, hpos;
3935         struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
3936         struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
3937         struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
3938         struct amdgpu_device *adev = crtc->dev->dev_private;
3939         bool async_flip = (crtc->state->pageflip_flags & DRM_MODE_PAGE_FLIP_ASYNC) != 0;
3940         struct dc_flip_addrs addr = { {0} };
3941         /* TODO eliminate or rename surface_update */
3942         struct dc_surface_update surface_updates[1] = { {0} };
3943         struct dm_crtc_state *acrtc_state = to_dm_crtc_state(crtc->state);
3944
3945
3946         /* Prepare wait for target vblank early - before the fence-waits */
3947         target_vblank = target - (uint32_t)drm_crtc_vblank_count(crtc) +
3948                         amdgpu_get_vblank_counter_kms(crtc->dev, acrtc->crtc_id);
3949
3950         /* TODO This might fail and hence better not used, wait
3951          * explicitly on fences instead
3952          * and in general should be called for
3953          * blocking commit to as per framework helpers
3954          */
3955         r = amdgpu_bo_reserve(abo, true);
3956         if (unlikely(r != 0)) {
3957                 DRM_ERROR("failed to reserve buffer before flip\n");
3958                 WARN_ON(1);
3959         }
3960
3961         /* Wait for all fences on this FB */
3962         WARN_ON(reservation_object_wait_timeout_rcu(abo->tbo.resv, true, false,
3963                                                                     MAX_SCHEDULE_TIMEOUT) < 0);
3964
3965         amdgpu_bo_unreserve(abo);
3966
3967         /* Wait until we're out of the vertical blank period before the one
3968          * targeted by the flip
3969          */
3970         while ((acrtc->enabled &&
3971                 (amdgpu_display_get_crtc_scanoutpos(adev->ddev, acrtc->crtc_id,
3972                                                     0, &vpos, &hpos, NULL,
3973                                                     NULL, &crtc->hwmode)
3974                  & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
3975                 (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
3976                 (int)(target_vblank -
3977                   amdgpu_get_vblank_counter_kms(adev->ddev, acrtc->crtc_id)) > 0)) {
3978                 usleep_range(1000, 1100);
3979         }
3980
3981         /* Flip */
3982         spin_lock_irqsave(&crtc->dev->event_lock, flags);
3983
3984         WARN_ON(acrtc->pflip_status != AMDGPU_FLIP_NONE);
3985         WARN_ON(!acrtc_state->stream);
3986
3987         addr.address.grph.addr.low_part = lower_32_bits(afb->address);
3988         addr.address.grph.addr.high_part = upper_32_bits(afb->address);
3989         addr.flip_immediate = async_flip;
3990
3991
3992         if (acrtc->base.state->event)
3993                 prepare_flip_isr(acrtc);
3994
3995         spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
3996
3997         surface_updates->surface = dc_stream_get_status(acrtc_state->stream)->plane_states[0];
3998         surface_updates->flip_addr = &addr;
3999
4000         dc_commit_updates_for_stream(adev->dm.dc,
4001                                              surface_updates,
4002                                              1,
4003                                              acrtc_state->stream,
4004                                              NULL,
4005                                              &surface_updates->surface,
4006                                              state);
4007
4008         DRM_DEBUG_DRIVER("%s Flipping to hi: 0x%x, low: 0x%x \n",
4009                          __func__,
4010                          addr.address.grph.addr.high_part,
4011                          addr.address.grph.addr.low_part);
4012 }
4013
4014 /*
4015  * TODO this whole function needs to go
4016  *
4017  * dc_surface_update is needlessly complex. See if we can just replace this
4018  * with a dc_plane_state and follow the atomic model a bit more closely here.
4019  */
4020 static bool commit_planes_to_stream(
4021                 struct dc *dc,
4022                 struct dc_plane_state **plane_states,
4023                 uint8_t new_plane_count,
4024                 struct dm_crtc_state *dm_new_crtc_state,
4025                 struct dm_crtc_state *dm_old_crtc_state,
4026                 struct dc_state *state)
4027 {
4028         /* no need to dynamically allocate this. it's pretty small */
4029         struct dc_surface_update updates[MAX_SURFACES];
4030         struct dc_flip_addrs *flip_addr;
4031         struct dc_plane_info *plane_info;
4032         struct dc_scaling_info *scaling_info;
4033         int i;
4034         struct dc_stream_state *dc_stream = dm_new_crtc_state->stream;
4035         struct dc_stream_update *stream_update =
4036                         kzalloc(sizeof(struct dc_stream_update), GFP_KERNEL);
4037
4038         if (!stream_update) {
4039                 BREAK_TO_DEBUGGER();
4040                 return false;
4041         }
4042
4043         flip_addr = kcalloc(MAX_SURFACES, sizeof(struct dc_flip_addrs),
4044                             GFP_KERNEL);
4045         plane_info = kcalloc(MAX_SURFACES, sizeof(struct dc_plane_info),
4046                              GFP_KERNEL);
4047         scaling_info = kcalloc(MAX_SURFACES, sizeof(struct dc_scaling_info),
4048                                GFP_KERNEL);
4049
4050         if (!flip_addr || !plane_info || !scaling_info) {
4051                 kfree(flip_addr);
4052                 kfree(plane_info);
4053                 kfree(scaling_info);
4054                 kfree(stream_update);
4055                 return false;
4056         }
4057
4058         memset(updates, 0, sizeof(updates));
4059
4060         stream_update->src = dc_stream->src;
4061         stream_update->dst = dc_stream->dst;
4062         stream_update->out_transfer_func = dc_stream->out_transfer_func;
4063
4064         for (i = 0; i < new_plane_count; i++) {
4065                 updates[i].surface = plane_states[i];
4066                 updates[i].gamma =
4067                         (struct dc_gamma *)plane_states[i]->gamma_correction;
4068                 updates[i].in_transfer_func = plane_states[i]->in_transfer_func;
4069                 flip_addr[i].address = plane_states[i]->address;
4070                 flip_addr[i].flip_immediate = plane_states[i]->flip_immediate;
4071                 plane_info[i].color_space = plane_states[i]->color_space;
4072                 plane_info[i].format = plane_states[i]->format;
4073                 plane_info[i].plane_size = plane_states[i]->plane_size;
4074                 plane_info[i].rotation = plane_states[i]->rotation;
4075                 plane_info[i].horizontal_mirror = plane_states[i]->horizontal_mirror;
4076                 plane_info[i].stereo_format = plane_states[i]->stereo_format;
4077                 plane_info[i].tiling_info = plane_states[i]->tiling_info;
4078                 plane_info[i].visible = plane_states[i]->visible;
4079                 plane_info[i].per_pixel_alpha = plane_states[i]->per_pixel_alpha;
4080                 plane_info[i].dcc = plane_states[i]->dcc;
4081                 scaling_info[i].scaling_quality = plane_states[i]->scaling_quality;
4082                 scaling_info[i].src_rect = plane_states[i]->src_rect;
4083                 scaling_info[i].dst_rect = plane_states[i]->dst_rect;
4084                 scaling_info[i].clip_rect = plane_states[i]->clip_rect;
4085
4086                 updates[i].flip_addr = &flip_addr[i];
4087                 updates[i].plane_info = &plane_info[i];
4088                 updates[i].scaling_info = &scaling_info[i];
4089         }
4090
4091         dc_commit_updates_for_stream(
4092                         dc,
4093                         updates,
4094                         new_plane_count,
4095                         dc_stream, stream_update, plane_states, state);
4096
4097         kfree(flip_addr);
4098         kfree(plane_info);
4099         kfree(scaling_info);
4100         kfree(stream_update);
4101         return true;
4102 }
4103
4104 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
4105                                     struct drm_device *dev,
4106                                     struct amdgpu_display_manager *dm,
4107                                     struct drm_crtc *pcrtc,
4108                                     bool *wait_for_vblank)
4109 {
4110         uint32_t i;
4111         struct drm_plane *plane;
4112         struct drm_plane_state *old_plane_state, *new_plane_state;
4113         struct dc_stream_state *dc_stream_attach;
4114         struct dc_plane_state *plane_states_constructed[MAX_SURFACES];
4115         struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
4116         struct drm_crtc_state *new_pcrtc_state =
4117                         drm_atomic_get_new_crtc_state(state, pcrtc);
4118         struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
4119         struct dm_crtc_state *dm_old_crtc_state =
4120                         to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
4121         struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4122         int planes_count = 0;
4123         unsigned long flags;
4124
4125         /* update planes when needed */
4126         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
4127                 struct drm_crtc *crtc = new_plane_state->crtc;
4128                 struct drm_crtc_state *new_crtc_state;
4129                 struct drm_framebuffer *fb = new_plane_state->fb;
4130                 bool pflip_needed;
4131                 struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
4132
4133                 if (plane->type == DRM_PLANE_TYPE_CURSOR) {
4134                         handle_cursor_update(plane, old_plane_state);
4135                         continue;
4136                 }
4137
4138                 if (!fb || !crtc || pcrtc != crtc)
4139                         continue;
4140
4141                 new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
4142                 if (!new_crtc_state->active)
4143                         continue;
4144
4145                 pflip_needed = !state->allow_modeset;
4146
4147                 spin_lock_irqsave(&crtc->dev->event_lock, flags);
4148                 if (acrtc_attach->pflip_status != AMDGPU_FLIP_NONE) {
4149                         DRM_ERROR("%s: acrtc %d, already busy\n",
4150                                   __func__,
4151                                   acrtc_attach->crtc_id);
4152                         /* In commit tail framework this cannot happen */
4153                         WARN_ON(1);
4154                 }
4155                 spin_unlock_irqrestore(&crtc->dev->event_lock, flags);
4156
4157                 if (!pflip_needed || plane->type == DRM_PLANE_TYPE_OVERLAY) {
4158                         WARN_ON(!dm_new_plane_state->dc_state);
4159
4160                         plane_states_constructed[planes_count] = dm_new_plane_state->dc_state;
4161
4162                         dc_stream_attach = acrtc_state->stream;
4163                         planes_count++;
4164
4165                 } else if (new_crtc_state->planes_changed) {
4166                         /* Assume even ONE crtc with immediate flip means
4167                          * entire can't wait for VBLANK
4168                          * TODO Check if it's correct
4169                          */
4170                         *wait_for_vblank =
4171                                         new_pcrtc_state->pageflip_flags & DRM_MODE_PAGE_FLIP_ASYNC ?
4172                                 false : true;
4173
4174                         /* TODO: Needs rework for multiplane flip */
4175                         if (plane->type == DRM_PLANE_TYPE_PRIMARY)
4176                                 drm_crtc_vblank_get(crtc);
4177
4178                         amdgpu_dm_do_flip(
4179                                 crtc,
4180                                 fb,
4181                                 (uint32_t)drm_crtc_vblank_count(crtc) + *wait_for_vblank,
4182                                 dm_state->context);
4183                 }
4184
4185         }
4186
4187         if (planes_count) {
4188                 unsigned long flags;
4189
4190                 if (new_pcrtc_state->event) {
4191
4192                         drm_crtc_vblank_get(pcrtc);
4193
4194                         spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
4195                         prepare_flip_isr(acrtc_attach);
4196                         spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
4197                 }
4198
4199
4200                 if (false == commit_planes_to_stream(dm->dc,
4201                                                         plane_states_constructed,
4202                                                         planes_count,
4203                                                         acrtc_state,
4204                                                         dm_old_crtc_state,
4205                                                         dm_state->context))
4206                         dm_error("%s: Failed to attach plane!\n", __func__);
4207         } else {
4208                 /*TODO BUG Here should go disable planes on CRTC. */
4209         }
4210 }
4211
4212 /**
4213  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
4214  * @crtc_state: the DRM CRTC state
4215  * @stream_state: the DC stream state.
4216  *
4217  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
4218  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
4219  */
4220 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
4221                                                 struct dc_stream_state *stream_state)
4222 {
4223         stream_state->mode_changed = crtc_state->mode_changed;
4224 }
4225
4226 static int amdgpu_dm_atomic_commit(struct drm_device *dev,
4227                                    struct drm_atomic_state *state,
4228                                    bool nonblock)
4229 {
4230         struct drm_crtc *crtc;
4231         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4232         struct amdgpu_device *adev = dev->dev_private;
4233         int i;
4234
4235         /*
4236          * We evade vblanks and pflips on crtc that
4237          * should be changed. We do it here to flush & disable
4238          * interrupts before drm_swap_state is called in drm_atomic_helper_commit
4239          * it will update crtc->dm_crtc_state->stream pointer which is used in
4240          * the ISRs.
4241          */
4242         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4243                 struct dm_crtc_state *dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4244                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4245
4246                 if (drm_atomic_crtc_needs_modeset(new_crtc_state) && dm_old_crtc_state->stream)
4247                         manage_dm_interrupts(adev, acrtc, false);
4248         }
4249         /* Add check here for SoC's that support hardware cursor plane, to
4250          * unset legacy_cursor_update */
4251
4252         return drm_atomic_helper_commit(dev, state, nonblock);
4253
4254         /*TODO Handle EINTR, reenable IRQ*/
4255 }
4256
4257 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
4258 {
4259         struct drm_device *dev = state->dev;
4260         struct amdgpu_device *adev = dev->dev_private;
4261         struct amdgpu_display_manager *dm = &adev->dm;
4262         struct dm_atomic_state *dm_state;
4263         uint32_t i, j;
4264         struct drm_crtc *crtc;
4265         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4266         unsigned long flags;
4267         bool wait_for_vblank = true;
4268         struct drm_connector *connector;
4269         struct drm_connector_state *old_con_state, *new_con_state;
4270         struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
4271         int crtc_disable_count = 0;
4272
4273         drm_atomic_helper_update_legacy_modeset_state(dev, state);
4274
4275         dm_state = to_dm_atomic_state(state);
4276
4277         /* update changed items */
4278         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4279                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4280
4281                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4282                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4283
4284                 DRM_DEBUG_DRIVER(
4285                         "amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
4286                         "planes_changed:%d, mode_changed:%d,active_changed:%d,"
4287                         "connectors_changed:%d\n",
4288                         acrtc->crtc_id,
4289                         new_crtc_state->enable,
4290                         new_crtc_state->active,
4291                         new_crtc_state->planes_changed,
4292                         new_crtc_state->mode_changed,
4293                         new_crtc_state->active_changed,
4294                         new_crtc_state->connectors_changed);
4295
4296                 /* Copy all transient state flags into dc state */
4297                 if (dm_new_crtc_state->stream) {
4298                         amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
4299                                                             dm_new_crtc_state->stream);
4300                 }
4301
4302                 /* handles headless hotplug case, updating new_state and
4303                  * aconnector as needed
4304                  */
4305
4306                 if (modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
4307
4308                         DRM_DEBUG_DRIVER("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
4309
4310                         if (!dm_new_crtc_state->stream) {
4311                                 /*
4312                                  * this could happen because of issues with
4313                                  * userspace notifications delivery.
4314                                  * In this case userspace tries to set mode on
4315                                  * display which is disconnect in fact.
4316                                  * dc_sink in NULL in this case on aconnector.
4317                                  * We expect reset mode will come soon.
4318                                  *
4319                                  * This can also happen when unplug is done
4320                                  * during resume sequence ended
4321                                  *
4322                                  * In this case, we want to pretend we still
4323                                  * have a sink to keep the pipe running so that
4324                                  * hw state is consistent with the sw state
4325                                  */
4326                                 DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
4327                                                 __func__, acrtc->base.base.id);
4328                                 continue;
4329                         }
4330
4331                         if (dm_old_crtc_state->stream)
4332                                 remove_stream(adev, acrtc, dm_old_crtc_state->stream);
4333
4334                         pm_runtime_get_noresume(dev->dev);
4335
4336                         acrtc->enabled = true;
4337                         acrtc->hw_mode = new_crtc_state->mode;
4338                         crtc->hwmode = new_crtc_state->mode;
4339                 } else if (modereset_required(new_crtc_state)) {
4340                         DRM_DEBUG_DRIVER("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
4341
4342                         /* i.e. reset mode */
4343                         if (dm_old_crtc_state->stream)
4344                                 remove_stream(adev, acrtc, dm_old_crtc_state->stream);
4345                 }
4346         } /* for_each_crtc_in_state() */
4347
4348         /*
4349          * Add streams after required streams from new and replaced streams
4350          * are removed from freesync module
4351          */
4352         if (adev->dm.freesync_module) {
4353                 for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
4354                                               new_crtc_state, i) {
4355                         struct amdgpu_dm_connector *aconnector = NULL;
4356                         struct dm_connector_state *dm_new_con_state = NULL;
4357                         struct amdgpu_crtc *acrtc = NULL;
4358                         bool modeset_needed;
4359
4360                         dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4361                         dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4362                         modeset_needed = modeset_required(
4363                                         new_crtc_state,
4364                                         dm_new_crtc_state->stream,
4365                                         dm_old_crtc_state->stream);
4366                         /* We add stream to freesync if:
4367                          * 1. Said stream is not null, and
4368                          * 2. A modeset is requested. This means that the
4369                          *    stream was removed previously, and needs to be
4370                          *    replaced.
4371                          */
4372                         if (dm_new_crtc_state->stream == NULL ||
4373                                         !modeset_needed)
4374                                 continue;
4375
4376                         acrtc = to_amdgpu_crtc(crtc);
4377
4378                         aconnector =
4379                                 amdgpu_dm_find_first_crtc_matching_connector(
4380                                         state, crtc);
4381                         if (!aconnector) {
4382                                 DRM_DEBUG_DRIVER("Atomic commit: Failed to "
4383                                                  "find connector for acrtc "
4384                                                  "id:%d skipping freesync "
4385                                                  "init\n",
4386                                                  acrtc->crtc_id);
4387                                 continue;
4388                         }
4389
4390                         mod_freesync_add_stream(adev->dm.freesync_module,
4391                                                 dm_new_crtc_state->stream,
4392                                                 &aconnector->caps);
4393                         new_con_state = drm_atomic_get_new_connector_state(
4394                                         state, &aconnector->base);
4395                         dm_new_con_state = to_dm_connector_state(new_con_state);
4396
4397                         mod_freesync_set_user_enable(adev->dm.freesync_module,
4398                                                      &dm_new_crtc_state->stream,
4399                                                      1,
4400                                                      &dm_new_con_state->user_enable);
4401                 }
4402         }
4403
4404         if (dm_state->context) {
4405                 dm_enable_per_frame_crtc_master_sync(dm_state->context);
4406                 WARN_ON(!dc_commit_state(dm->dc, dm_state->context));
4407         }
4408
4409         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
4410                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4411
4412                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4413
4414                 if (dm_new_crtc_state->stream != NULL) {
4415                         const struct dc_stream_status *status =
4416                                         dc_stream_get_status(dm_new_crtc_state->stream);
4417
4418                         if (!status)
4419                                 DC_ERR("got no status for stream %p on acrtc%p\n", dm_new_crtc_state->stream, acrtc);
4420                         else
4421                                 acrtc->otg_inst = status->primary_otg_inst;
4422                 }
4423         }
4424
4425         /* Handle scaling and underscan changes*/
4426         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
4427                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
4428                 struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
4429                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
4430                 struct dc_stream_status *status = NULL;
4431
4432                 if (acrtc) {
4433                         new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
4434                         old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
4435                 }
4436
4437                 /* Skip any modesets/resets */
4438                 if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
4439                         continue;
4440
4441                 /* Skip any thing not scale or underscan changes */
4442                 if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
4443                         continue;
4444
4445                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4446
4447                 update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
4448                                 dm_new_con_state, (struct dc_stream_state *)dm_new_crtc_state->stream);
4449
4450                 if (!dm_new_crtc_state->stream)
4451                         continue;
4452
4453                 status = dc_stream_get_status(dm_new_crtc_state->stream);
4454                 WARN_ON(!status);
4455                 WARN_ON(!status->plane_count);
4456
4457                 /*TODO How it works with MPO ?*/
4458                 if (!commit_planes_to_stream(
4459                                 dm->dc,
4460                                 status->plane_states,
4461                                 status->plane_count,
4462                                 dm_new_crtc_state,
4463                                 to_dm_crtc_state(old_crtc_state),
4464                                 dm_state->context))
4465                         dm_error("%s: Failed to update stream scaling!\n", __func__);
4466         }
4467
4468         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
4469                         new_crtc_state, i) {
4470                 /*
4471                  * loop to enable interrupts on newly arrived crtc
4472                  */
4473                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4474                 bool modeset_needed;
4475
4476                 if (old_crtc_state->active && !new_crtc_state->active)
4477                         crtc_disable_count++;
4478
4479                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4480                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4481                 modeset_needed = modeset_required(
4482                                 new_crtc_state,
4483                                 dm_new_crtc_state->stream,
4484                                 dm_old_crtc_state->stream);
4485
4486                 if (dm_new_crtc_state->stream == NULL || !modeset_needed)
4487                         continue;
4488
4489                 if (adev->dm.freesync_module)
4490                         mod_freesync_notify_mode_change(
4491                                 adev->dm.freesync_module,
4492                                 &dm_new_crtc_state->stream, 1);
4493
4494                 manage_dm_interrupts(adev, acrtc, true);
4495         }
4496
4497         /* update planes when needed per crtc*/
4498         for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
4499                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4500
4501                 if (dm_new_crtc_state->stream)
4502                         amdgpu_dm_commit_planes(state, dev, dm, crtc, &wait_for_vblank);
4503         }
4504
4505
4506         /*
4507          * send vblank event on all events not handled in flip and
4508          * mark consumed event for drm_atomic_helper_commit_hw_done
4509          */
4510         spin_lock_irqsave(&adev->ddev->event_lock, flags);
4511         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
4512
4513                 if (new_crtc_state->event)
4514                         drm_send_event_locked(dev, &new_crtc_state->event->base);
4515
4516                 new_crtc_state->event = NULL;
4517         }
4518         spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
4519
4520         /* Signal HW programming completion */
4521         drm_atomic_helper_commit_hw_done(state);
4522
4523         if (wait_for_vblank)
4524                 drm_atomic_helper_wait_for_flip_done(dev, state);
4525
4526         drm_atomic_helper_cleanup_planes(dev, state);
4527
4528         /* Finally, drop a runtime PM reference for each newly disabled CRTC,
4529          * so we can put the GPU into runtime suspend if we're not driving any
4530          * displays anymore
4531          */
4532         for (i = 0; i < crtc_disable_count; i++)
4533                 pm_runtime_put_autosuspend(dev->dev);
4534         pm_runtime_mark_last_busy(dev->dev);
4535 }
4536
4537
4538 static int dm_force_atomic_commit(struct drm_connector *connector)
4539 {
4540         int ret = 0;
4541         struct drm_device *ddev = connector->dev;
4542         struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
4543         struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
4544         struct drm_plane *plane = disconnected_acrtc->base.primary;
4545         struct drm_connector_state *conn_state;
4546         struct drm_crtc_state *crtc_state;
4547         struct drm_plane_state *plane_state;
4548
4549         if (!state)
4550                 return -ENOMEM;
4551
4552         state->acquire_ctx = ddev->mode_config.acquire_ctx;
4553
4554         /* Construct an atomic state to restore previous display setting */
4555
4556         /*
4557          * Attach connectors to drm_atomic_state
4558          */
4559         conn_state = drm_atomic_get_connector_state(state, connector);
4560
4561         ret = PTR_ERR_OR_ZERO(conn_state);
4562         if (ret)
4563                 goto err;
4564
4565         /* Attach crtc to drm_atomic_state*/
4566         crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
4567
4568         ret = PTR_ERR_OR_ZERO(crtc_state);
4569         if (ret)
4570                 goto err;
4571
4572         /* force a restore */
4573         crtc_state->mode_changed = true;
4574
4575         /* Attach plane to drm_atomic_state */
4576         plane_state = drm_atomic_get_plane_state(state, plane);
4577
4578         ret = PTR_ERR_OR_ZERO(plane_state);
4579         if (ret)
4580                 goto err;
4581
4582
4583         /* Call commit internally with the state we just constructed */
4584         ret = drm_atomic_commit(state);
4585         if (!ret)
4586                 return 0;
4587
4588 err:
4589         DRM_ERROR("Restoring old state failed with %i\n", ret);
4590         drm_atomic_state_put(state);
4591
4592         return ret;
4593 }
4594
4595 /*
4596  * This functions handle all cases when set mode does not come upon hotplug.
4597  * This include when the same display is unplugged then plugged back into the
4598  * same port and when we are running without usermode desktop manager supprot
4599  */
4600 void dm_restore_drm_connector_state(struct drm_device *dev,
4601                                     struct drm_connector *connector)
4602 {
4603         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
4604         struct amdgpu_crtc *disconnected_acrtc;
4605         struct dm_crtc_state *acrtc_state;
4606
4607         if (!aconnector->dc_sink || !connector->state || !connector->encoder)
4608                 return;
4609
4610         disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
4611         if (!disconnected_acrtc)
4612                 return;
4613
4614         acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
4615         if (!acrtc_state->stream)
4616                 return;
4617
4618         /*
4619          * If the previous sink is not released and different from the current,
4620          * we deduce we are in a state where we can not rely on usermode call
4621          * to turn on the display, so we do it here
4622          */
4623         if (acrtc_state->stream->sink != aconnector->dc_sink)
4624                 dm_force_atomic_commit(&aconnector->base);
4625 }
4626
4627 /*`
4628  * Grabs all modesetting locks to serialize against any blocking commits,
4629  * Waits for completion of all non blocking commits.
4630  */
4631 static int do_aquire_global_lock(struct drm_device *dev,
4632                                  struct drm_atomic_state *state)
4633 {
4634         struct drm_crtc *crtc;
4635         struct drm_crtc_commit *commit;
4636         long ret;
4637
4638         /* Adding all modeset locks to aquire_ctx will
4639          * ensure that when the framework release it the
4640          * extra locks we are locking here will get released to
4641          */
4642         ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
4643         if (ret)
4644                 return ret;
4645
4646         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
4647                 spin_lock(&crtc->commit_lock);
4648                 commit = list_first_entry_or_null(&crtc->commit_list,
4649                                 struct drm_crtc_commit, commit_entry);
4650                 if (commit)
4651                         drm_crtc_commit_get(commit);
4652                 spin_unlock(&crtc->commit_lock);
4653
4654                 if (!commit)
4655                         continue;
4656
4657                 /* Make sure all pending HW programming completed and
4658                  * page flips done
4659                  */
4660                 ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
4661
4662                 if (ret > 0)
4663                         ret = wait_for_completion_interruptible_timeout(
4664                                         &commit->flip_done, 10*HZ);
4665
4666                 if (ret == 0)
4667                         DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done "
4668                                   "timed out\n", crtc->base.id, crtc->name);
4669
4670                 drm_crtc_commit_put(commit);
4671         }
4672
4673         return ret < 0 ? ret : 0;
4674 }
4675
4676 static int dm_update_crtcs_state(struct dc *dc,
4677                                  struct drm_atomic_state *state,
4678                                  bool enable,
4679                                  bool *lock_and_validation_needed)
4680 {
4681         struct drm_crtc *crtc;
4682         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4683         int i;
4684         struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
4685         struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4686         struct dc_stream_state *new_stream;
4687         int ret = 0;
4688
4689         /*TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set */
4690         /* update changed items */
4691         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4692                 struct amdgpu_crtc *acrtc = NULL;
4693                 struct amdgpu_dm_connector *aconnector = NULL;
4694                 struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
4695                 struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
4696                 struct drm_plane_state *new_plane_state = NULL;
4697
4698                 new_stream = NULL;
4699
4700                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4701                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4702                 acrtc = to_amdgpu_crtc(crtc);
4703
4704                 new_plane_state = drm_atomic_get_new_plane_state(state, new_crtc_state->crtc->primary);
4705
4706                 if (new_crtc_state->enable && new_plane_state && !new_plane_state->fb) {
4707                         ret = -EINVAL;
4708                         goto fail;
4709                 }
4710
4711                 aconnector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
4712
4713                 /* TODO This hack should go away */
4714                 if (aconnector && enable) {
4715                         // Make sure fake sink is created in plug-in scenario
4716                         drm_new_conn_state = drm_atomic_get_new_connector_state(state,
4717                                                                     &aconnector->base);
4718                         drm_old_conn_state = drm_atomic_get_old_connector_state(state,
4719                                                                     &aconnector->base);
4720
4721                         if (IS_ERR(drm_new_conn_state)) {
4722                                 ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
4723                                 break;
4724                         }
4725
4726                         dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
4727                         dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
4728
4729                         new_stream = create_stream_for_sink(aconnector,
4730                                                              &new_crtc_state->mode,
4731                                                             dm_new_conn_state);
4732
4733                         /*
4734                          * we can have no stream on ACTION_SET if a display
4735                          * was disconnected during S3, in this case it not and
4736                          * error, the OS will be updated after detection, and
4737                          * do the right thing on next atomic commit
4738                          */
4739
4740                         if (!new_stream) {
4741                                 DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
4742                                                 __func__, acrtc->base.base.id);
4743                                 break;
4744                         }
4745
4746                         if (dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
4747                             dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
4748                                 new_crtc_state->mode_changed = false;
4749                                 DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
4750                                                  new_crtc_state->mode_changed);
4751                         }
4752                 }
4753
4754                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
4755                         goto next_crtc;
4756
4757                 DRM_DEBUG_DRIVER(
4758                         "amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
4759                         "planes_changed:%d, mode_changed:%d,active_changed:%d,"
4760                         "connectors_changed:%d\n",
4761                         acrtc->crtc_id,
4762                         new_crtc_state->enable,
4763                         new_crtc_state->active,
4764                         new_crtc_state->planes_changed,
4765                         new_crtc_state->mode_changed,
4766                         new_crtc_state->active_changed,
4767                         new_crtc_state->connectors_changed);
4768
4769                 /* Remove stream for any changed/disabled CRTC */
4770                 if (!enable) {
4771
4772                         if (!dm_old_crtc_state->stream)
4773                                 goto next_crtc;
4774
4775                         DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
4776                                         crtc->base.id);
4777
4778                         /* i.e. reset mode */
4779                         if (dc_remove_stream_from_ctx(
4780                                         dc,
4781                                         dm_state->context,
4782                                         dm_old_crtc_state->stream) != DC_OK) {
4783                                 ret = -EINVAL;
4784                                 goto fail;
4785                         }
4786
4787                         dc_stream_release(dm_old_crtc_state->stream);
4788                         dm_new_crtc_state->stream = NULL;
4789
4790                         *lock_and_validation_needed = true;
4791
4792                 } else {/* Add stream for any updated/enabled CRTC */
4793                         /*
4794                          * Quick fix to prevent NULL pointer on new_stream when
4795                          * added MST connectors not found in existing crtc_state in the chained mode
4796                          * TODO: need to dig out the root cause of that
4797                          */
4798                         if (!aconnector || (!aconnector->dc_sink && aconnector->mst_port))
4799                                 goto next_crtc;
4800
4801                         if (modereset_required(new_crtc_state))
4802                                 goto next_crtc;
4803
4804                         if (modeset_required(new_crtc_state, new_stream,
4805                                              dm_old_crtc_state->stream)) {
4806
4807                                 WARN_ON(dm_new_crtc_state->stream);
4808
4809                                 dm_new_crtc_state->stream = new_stream;
4810
4811                                 dc_stream_retain(new_stream);
4812
4813                                 DRM_DEBUG_DRIVER("Enabling DRM crtc: %d\n",
4814                                                         crtc->base.id);
4815
4816                                 if (dc_add_stream_to_ctx(
4817                                                 dc,
4818                                                 dm_state->context,
4819                                                 dm_new_crtc_state->stream) != DC_OK) {
4820                                         ret = -EINVAL;
4821                                         goto fail;
4822                                 }
4823
4824                                 *lock_and_validation_needed = true;
4825                         }
4826                 }
4827
4828 next_crtc:
4829                 /* Release extra reference */
4830                 if (new_stream)
4831                          dc_stream_release(new_stream);
4832
4833                 /*
4834                  * We want to do dc stream updates that do not require a
4835                  * full modeset below.
4836                  */
4837                 if (!(enable && aconnector && new_crtc_state->enable &&
4838                       new_crtc_state->active))
4839                         continue;
4840                 /*
4841                  * Given above conditions, the dc state cannot be NULL because:
4842                  * 1. We're in the process of enabling CRTCs (just been added
4843                  *    to the dc context, or already is on the context)
4844                  * 2. Has a valid connector attached, and
4845                  * 3. Is currently active and enabled.
4846                  * => The dc stream state currently exists.
4847                  */
4848                 BUG_ON(dm_new_crtc_state->stream == NULL);
4849
4850                 /* Scaling or underscan settings */
4851                 if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state))
4852                         update_stream_scaling_settings(
4853                                 &new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
4854
4855                 /*
4856                  * Color management settings. We also update color properties
4857                  * when a modeset is needed, to ensure it gets reprogrammed.
4858                  */
4859                 if (dm_new_crtc_state->base.color_mgmt_changed ||
4860                     drm_atomic_crtc_needs_modeset(new_crtc_state)) {
4861                         ret = amdgpu_dm_set_regamma_lut(dm_new_crtc_state);
4862                         if (ret)
4863                                 goto fail;
4864                         amdgpu_dm_set_ctm(dm_new_crtc_state);
4865                 }
4866         }
4867
4868         return ret;
4869
4870 fail:
4871         if (new_stream)
4872                 dc_stream_release(new_stream);
4873         return ret;
4874 }
4875
4876 static int dm_update_planes_state(struct dc *dc,
4877                                   struct drm_atomic_state *state,
4878                                   bool enable,
4879                                   bool *lock_and_validation_needed)
4880 {
4881         struct drm_crtc *new_plane_crtc, *old_plane_crtc;
4882         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4883         struct drm_plane *plane;
4884         struct drm_plane_state *old_plane_state, *new_plane_state;
4885         struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
4886         struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4887         struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
4888         int i ;
4889         /* TODO return page_flip_needed() function */
4890         bool pflip_needed  = !state->allow_modeset;
4891         int ret = 0;
4892
4893
4894         /* Add new planes, in reverse order as DC expectation */
4895         for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
4896                 new_plane_crtc = new_plane_state->crtc;
4897                 old_plane_crtc = old_plane_state->crtc;
4898                 dm_new_plane_state = to_dm_plane_state(new_plane_state);
4899                 dm_old_plane_state = to_dm_plane_state(old_plane_state);
4900
4901                 /*TODO Implement atomic check for cursor plane */
4902                 if (plane->type == DRM_PLANE_TYPE_CURSOR)
4903                         continue;
4904
4905                 /* Remove any changed/removed planes */
4906                 if (!enable) {
4907                         if (pflip_needed &&
4908                             plane->type != DRM_PLANE_TYPE_OVERLAY)
4909                                 continue;
4910
4911                         if (!old_plane_crtc)
4912                                 continue;
4913
4914                         old_crtc_state = drm_atomic_get_old_crtc_state(
4915                                         state, old_plane_crtc);
4916                         dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4917
4918                         if (!dm_old_crtc_state->stream)
4919                                 continue;
4920
4921                         DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
4922                                         plane->base.id, old_plane_crtc->base.id);
4923
4924                         if (!dc_remove_plane_from_context(
4925                                         dc,
4926                                         dm_old_crtc_state->stream,
4927                                         dm_old_plane_state->dc_state,
4928                                         dm_state->context)) {
4929
4930                                 ret = EINVAL;
4931                                 return ret;
4932                         }
4933
4934
4935                         dc_plane_state_release(dm_old_plane_state->dc_state);
4936                         dm_new_plane_state->dc_state = NULL;
4937
4938                         *lock_and_validation_needed = true;
4939
4940                 } else { /* Add new planes */
4941                         struct dc_plane_state *dc_new_plane_state;
4942
4943                         if (drm_atomic_plane_disabling(plane->state, new_plane_state))
4944                                 continue;
4945
4946                         if (!new_plane_crtc)
4947                                 continue;
4948
4949                         new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
4950                         dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4951
4952                         if (!dm_new_crtc_state->stream)
4953                                 continue;
4954
4955                         if (pflip_needed &&
4956                             plane->type != DRM_PLANE_TYPE_OVERLAY)
4957                                 continue;
4958
4959                         WARN_ON(dm_new_plane_state->dc_state);
4960
4961                         dc_new_plane_state = dc_create_plane_state(dc);
4962                         if (!dc_new_plane_state)
4963                                 return -ENOMEM;
4964
4965                         DRM_DEBUG_DRIVER("Enabling DRM plane: %d on DRM crtc %d\n",
4966                                         plane->base.id, new_plane_crtc->base.id);
4967
4968                         ret = fill_plane_attributes(
4969                                 new_plane_crtc->dev->dev_private,
4970                                 dc_new_plane_state,
4971                                 new_plane_state,
4972                                 new_crtc_state);
4973                         if (ret) {
4974                                 dc_plane_state_release(dc_new_plane_state);
4975                                 return ret;
4976                         }
4977
4978                         /*
4979                          * Any atomic check errors that occur after this will
4980                          * not need a release. The plane state will be attached
4981                          * to the stream, and therefore part of the atomic
4982                          * state. It'll be released when the atomic state is
4983                          * cleaned.
4984                          */
4985                         if (!dc_add_plane_to_context(
4986                                         dc,
4987                                         dm_new_crtc_state->stream,
4988                                         dc_new_plane_state,
4989                                         dm_state->context)) {
4990
4991                                 dc_plane_state_release(dc_new_plane_state);
4992                                 return -EINVAL;
4993                         }
4994
4995                         dm_new_plane_state->dc_state = dc_new_plane_state;
4996
4997                         /* Tell DC to do a full surface update every time there
4998                          * is a plane change. Inefficient, but works for now.
4999                          */
5000                         dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
5001
5002                         *lock_and_validation_needed = true;
5003                 }
5004         }
5005
5006
5007         return ret;
5008 }
5009
5010 static int amdgpu_dm_atomic_check(struct drm_device *dev,
5011                                   struct drm_atomic_state *state)
5012 {
5013         struct amdgpu_device *adev = dev->dev_private;
5014         struct dc *dc = adev->dm.dc;
5015         struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
5016         struct drm_connector *connector;
5017         struct drm_connector_state *old_con_state, *new_con_state;
5018         struct drm_crtc *crtc;
5019         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5020         int ret, i;
5021
5022         /*
5023          * This bool will be set for true for any modeset/reset
5024          * or plane update which implies non fast surface update.
5025          */
5026         bool lock_and_validation_needed = false;
5027
5028         ret = drm_atomic_helper_check_modeset(dev, state);
5029         if (ret)
5030                 goto fail;
5031
5032         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
5033                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
5034                     !new_crtc_state->color_mgmt_changed)
5035                         continue;
5036
5037                 if (!new_crtc_state->enable)
5038                         continue;
5039
5040                 ret = drm_atomic_add_affected_connectors(state, crtc);
5041                 if (ret)
5042                         return ret;
5043
5044                 ret = drm_atomic_add_affected_planes(state, crtc);
5045                 if (ret)
5046                         goto fail;
5047         }
5048
5049         dm_state->context = dc_create_state();
5050         ASSERT(dm_state->context);
5051         dc_resource_state_copy_construct_current(dc, dm_state->context);
5052
5053         /* Remove exiting planes if they are modified */
5054         ret = dm_update_planes_state(dc, state, false, &lock_and_validation_needed);
5055         if (ret) {
5056                 goto fail;
5057         }
5058
5059         /* Disable all crtcs which require disable */
5060         ret = dm_update_crtcs_state(dc, state, false, &lock_and_validation_needed);
5061         if (ret) {
5062                 goto fail;
5063         }
5064
5065         /* Enable all crtcs which require enable */
5066         ret = dm_update_crtcs_state(dc, state, true, &lock_and_validation_needed);
5067         if (ret) {
5068                 goto fail;
5069         }
5070
5071         /* Add new/modified planes */
5072         ret = dm_update_planes_state(dc, state, true, &lock_and_validation_needed);
5073         if (ret) {
5074                 goto fail;
5075         }
5076
5077         /* Run this here since we want to validate the streams we created */
5078         ret = drm_atomic_helper_check_planes(dev, state);
5079         if (ret)
5080                 goto fail;
5081
5082         /* Check scaling and underscan changes*/
5083         /*TODO Removed scaling changes validation due to inability to commit
5084          * new stream into context w\o causing full reset. Need to
5085          * decide how to handle.
5086          */
5087         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
5088                 struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
5089                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
5090                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
5091
5092                 /* Skip any modesets/resets */
5093                 if (!acrtc || drm_atomic_crtc_needs_modeset(
5094                                 drm_atomic_get_new_crtc_state(state, &acrtc->base)))
5095                         continue;
5096
5097                 /* Skip any thing not scale or underscan changes */
5098                 if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
5099                         continue;
5100
5101                 lock_and_validation_needed = true;
5102         }
5103
5104         /*
5105          * For full updates case when
5106          * removing/adding/updating  streams on once CRTC while flipping
5107          * on another CRTC,
5108          * acquiring global lock  will guarantee that any such full
5109          * update commit
5110          * will wait for completion of any outstanding flip using DRMs
5111          * synchronization events.
5112          */
5113
5114         if (lock_and_validation_needed) {
5115
5116                 ret = do_aquire_global_lock(dev, state);
5117                 if (ret)
5118                         goto fail;
5119
5120                 if (dc_validate_global_state(dc, dm_state->context) != DC_OK) {
5121                         ret = -EINVAL;
5122                         goto fail;
5123                 }
5124         }
5125
5126         /* Must be success */
5127         WARN_ON(ret);
5128         return ret;
5129
5130 fail:
5131         if (ret == -EDEADLK)
5132                 DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
5133         else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
5134                 DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
5135         else
5136                 DRM_DEBUG_DRIVER("Atomic check failed with err: %d \n", ret);
5137
5138         return ret;
5139 }
5140
5141 static bool is_dp_capable_without_timing_msa(struct dc *dc,
5142                                              struct amdgpu_dm_connector *amdgpu_dm_connector)
5143 {
5144         uint8_t dpcd_data;
5145         bool capable = false;
5146
5147         if (amdgpu_dm_connector->dc_link &&
5148                 dm_helpers_dp_read_dpcd(
5149                                 NULL,
5150                                 amdgpu_dm_connector->dc_link,
5151                                 DP_DOWN_STREAM_PORT_COUNT,
5152                                 &dpcd_data,
5153                                 sizeof(dpcd_data))) {
5154                 capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
5155         }
5156
5157         return capable;
5158 }
5159 void amdgpu_dm_add_sink_to_freesync_module(struct drm_connector *connector,
5160                                            struct edid *edid)
5161 {
5162         int i;
5163         bool edid_check_required;
5164         struct detailed_timing *timing;
5165         struct detailed_non_pixel *data;
5166         struct detailed_data_monitor_range *range;
5167         struct amdgpu_dm_connector *amdgpu_dm_connector =
5168                         to_amdgpu_dm_connector(connector);
5169         struct dm_connector_state *dm_con_state;
5170
5171         struct drm_device *dev = connector->dev;
5172         struct amdgpu_device *adev = dev->dev_private;
5173
5174         if (!connector->state) {
5175                 DRM_ERROR("%s - Connector has no state", __func__);
5176                 return;
5177         }
5178
5179         dm_con_state = to_dm_connector_state(connector->state);
5180
5181         edid_check_required = false;
5182         if (!amdgpu_dm_connector->dc_sink) {
5183                 DRM_ERROR("dc_sink NULL, could not add free_sync module.\n");
5184                 return;
5185         }
5186         if (!adev->dm.freesync_module)
5187                 return;
5188         /*
5189          * if edid non zero restrict freesync only for dp and edp
5190          */
5191         if (edid) {
5192                 if (amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
5193                         || amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_EDP) {
5194                         edid_check_required = is_dp_capable_without_timing_msa(
5195                                                 adev->dm.dc,
5196                                                 amdgpu_dm_connector);
5197                 }
5198         }
5199         dm_con_state->freesync_capable = false;
5200         if (edid_check_required == true && (edid->version > 1 ||
5201            (edid->version == 1 && edid->revision > 1))) {
5202                 for (i = 0; i < 4; i++) {
5203
5204                         timing  = &edid->detailed_timings[i];
5205                         data    = &timing->data.other_data;
5206                         range   = &data->data.range;
5207                         /*
5208                          * Check if monitor has continuous frequency mode
5209                          */
5210                         if (data->type != EDID_DETAIL_MONITOR_RANGE)
5211                                 continue;
5212                         /*
5213                          * Check for flag range limits only. If flag == 1 then
5214                          * no additional timing information provided.
5215                          * Default GTF, GTF Secondary curve and CVT are not
5216                          * supported
5217                          */
5218                         if (range->flags != 1)
5219                                 continue;
5220
5221                         amdgpu_dm_connector->min_vfreq = range->min_vfreq;
5222                         amdgpu_dm_connector->max_vfreq = range->max_vfreq;
5223                         amdgpu_dm_connector->pixel_clock_mhz =
5224                                 range->pixel_clock_mhz * 10;
5225                         break;
5226                 }
5227
5228                 if (amdgpu_dm_connector->max_vfreq -
5229                                 amdgpu_dm_connector->min_vfreq > 10) {
5230                         amdgpu_dm_connector->caps.supported = true;
5231                         amdgpu_dm_connector->caps.min_refresh_in_micro_hz =
5232                                         amdgpu_dm_connector->min_vfreq * 1000000;
5233                         amdgpu_dm_connector->caps.max_refresh_in_micro_hz =
5234                                         amdgpu_dm_connector->max_vfreq * 1000000;
5235                         dm_con_state->freesync_capable = true;
5236                 }
5237         }
5238
5239         /*
5240          * TODO figure out how to notify user-mode or DRM of freesync caps
5241          * once we figure out how to deal with freesync in an upstreamable
5242          * fashion
5243          */
5244
5245 }
5246
5247 void amdgpu_dm_remove_sink_from_freesync_module(struct drm_connector *connector)
5248 {
5249         /*
5250          * TODO fill in once we figure out how to deal with freesync in
5251          * an upstreamable fashion
5252          */
5253 }
This page took 0.364039 seconds and 4 git commands to generate.