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