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