Merge tag 'for-5.5/dm-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/device...
[linux-2.6-microblaze.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 /* The caprices of the preprocessor require that this be declared right here */
27 #define CREATE_TRACE_POINTS
28
29 #include "dm_services_types.h"
30 #include "dc.h"
31 #include "dc/inc/core_types.h"
32 #include "dal_asic_id.h"
33
34 #include "vid.h"
35 #include "amdgpu.h"
36 #include "amdgpu_display.h"
37 #include "amdgpu_ucode.h"
38 #include "atom.h"
39 #include "amdgpu_dm.h"
40 #ifdef CONFIG_DRM_AMD_DC_HDCP
41 #include "amdgpu_dm_hdcp.h"
42 #endif
43 #include "amdgpu_pm.h"
44
45 #include "amd_shared.h"
46 #include "amdgpu_dm_irq.h"
47 #include "dm_helpers.h"
48 #include "amdgpu_dm_mst_types.h"
49 #if defined(CONFIG_DEBUG_FS)
50 #include "amdgpu_dm_debugfs.h"
51 #endif
52
53 #include "ivsrcid/ivsrcid_vislands30.h"
54
55 #include <linux/module.h>
56 #include <linux/moduleparam.h>
57 #include <linux/version.h>
58 #include <linux/types.h>
59 #include <linux/pm_runtime.h>
60 #include <linux/pci.h>
61 #include <linux/firmware.h>
62 #include <linux/component.h>
63
64 #include <drm/drm_atomic.h>
65 #include <drm/drm_atomic_uapi.h>
66 #include <drm/drm_atomic_helper.h>
67 #include <drm/drm_dp_mst_helper.h>
68 #include <drm/drm_fb_helper.h>
69 #include <drm/drm_fourcc.h>
70 #include <drm/drm_edid.h>
71 #include <drm/drm_vblank.h>
72 #include <drm/drm_audio_component.h>
73 #include <drm/drm_hdcp.h>
74
75 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
76 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
77
78 #include "dcn/dcn_1_0_offset.h"
79 #include "dcn/dcn_1_0_sh_mask.h"
80 #include "soc15_hw_ip.h"
81 #include "vega10_ip_offset.h"
82
83 #include "soc15_common.h"
84 #endif
85
86 #include "modules/inc/mod_freesync.h"
87 #include "modules/power/power_helpers.h"
88 #include "modules/inc/mod_info_packet.h"
89
90 #define FIRMWARE_RAVEN_DMCU             "amdgpu/raven_dmcu.bin"
91 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
92
93 /**
94  * DOC: overview
95  *
96  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
97  * **dm**) sits between DRM and DC. It acts as a liason, converting DRM
98  * requests into DC requests, and DC responses into DRM responses.
99  *
100  * The root control structure is &struct amdgpu_display_manager.
101  */
102
103 /* basic init/fini API */
104 static int amdgpu_dm_init(struct amdgpu_device *adev);
105 static void amdgpu_dm_fini(struct amdgpu_device *adev);
106
107 /*
108  * initializes drm_device display related structures, based on the information
109  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
110  * drm_encoder, drm_mode_config
111  *
112  * Returns 0 on success
113  */
114 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
115 /* removes and deallocates the drm structures, created by the above function */
116 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
117
118 static void
119 amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector);
120
121 static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
122                                 struct drm_plane *plane,
123                                 unsigned long possible_crtcs,
124                                 const struct dc_plane_cap *plane_cap);
125 static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
126                                struct drm_plane *plane,
127                                uint32_t link_index);
128 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
129                                     struct amdgpu_dm_connector *amdgpu_dm_connector,
130                                     uint32_t link_index,
131                                     struct amdgpu_encoder *amdgpu_encoder);
132 static int amdgpu_dm_encoder_init(struct drm_device *dev,
133                                   struct amdgpu_encoder *aencoder,
134                                   uint32_t link_index);
135
136 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
137
138 static int amdgpu_dm_atomic_commit(struct drm_device *dev,
139                                    struct drm_atomic_state *state,
140                                    bool nonblock);
141
142 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
143
144 static int amdgpu_dm_atomic_check(struct drm_device *dev,
145                                   struct drm_atomic_state *state);
146
147 static void handle_cursor_update(struct drm_plane *plane,
148                                  struct drm_plane_state *old_plane_state);
149
150 static void amdgpu_dm_set_psr_caps(struct dc_link *link);
151 static bool amdgpu_dm_psr_enable(struct dc_stream_state *stream);
152 static bool amdgpu_dm_link_setup_psr(struct dc_stream_state *stream);
153 static bool amdgpu_dm_psr_disable(struct dc_stream_state *stream);
154
155
156 /*
157  * dm_vblank_get_counter
158  *
159  * @brief
160  * Get counter for number of vertical blanks
161  *
162  * @param
163  * struct amdgpu_device *adev - [in] desired amdgpu device
164  * int disp_idx - [in] which CRTC to get the counter from
165  *
166  * @return
167  * Counter for vertical blanks
168  */
169 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
170 {
171         if (crtc >= adev->mode_info.num_crtc)
172                 return 0;
173         else {
174                 struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
175                 struct dm_crtc_state *acrtc_state = to_dm_crtc_state(
176                                 acrtc->base.state);
177
178
179                 if (acrtc_state->stream == NULL) {
180                         DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
181                                   crtc);
182                         return 0;
183                 }
184
185                 return dc_stream_get_vblank_counter(acrtc_state->stream);
186         }
187 }
188
189 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
190                                   u32 *vbl, u32 *position)
191 {
192         uint32_t v_blank_start, v_blank_end, h_position, v_position;
193
194         if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
195                 return -EINVAL;
196         else {
197                 struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
198                 struct dm_crtc_state *acrtc_state = to_dm_crtc_state(
199                                                 acrtc->base.state);
200
201                 if (acrtc_state->stream ==  NULL) {
202                         DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
203                                   crtc);
204                         return 0;
205                 }
206
207                 /*
208                  * TODO rework base driver to use values directly.
209                  * for now parse it back into reg-format
210                  */
211                 dc_stream_get_scanoutpos(acrtc_state->stream,
212                                          &v_blank_start,
213                                          &v_blank_end,
214                                          &h_position,
215                                          &v_position);
216
217                 *position = v_position | (h_position << 16);
218                 *vbl = v_blank_start | (v_blank_end << 16);
219         }
220
221         return 0;
222 }
223
224 static bool dm_is_idle(void *handle)
225 {
226         /* XXX todo */
227         return true;
228 }
229
230 static int dm_wait_for_idle(void *handle)
231 {
232         /* XXX todo */
233         return 0;
234 }
235
236 static bool dm_check_soft_reset(void *handle)
237 {
238         return false;
239 }
240
241 static int dm_soft_reset(void *handle)
242 {
243         /* XXX todo */
244         return 0;
245 }
246
247 static struct amdgpu_crtc *
248 get_crtc_by_otg_inst(struct amdgpu_device *adev,
249                      int otg_inst)
250 {
251         struct drm_device *dev = adev->ddev;
252         struct drm_crtc *crtc;
253         struct amdgpu_crtc *amdgpu_crtc;
254
255         if (otg_inst == -1) {
256                 WARN_ON(1);
257                 return adev->mode_info.crtcs[0];
258         }
259
260         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
261                 amdgpu_crtc = to_amdgpu_crtc(crtc);
262
263                 if (amdgpu_crtc->otg_inst == otg_inst)
264                         return amdgpu_crtc;
265         }
266
267         return NULL;
268 }
269
270 static inline bool amdgpu_dm_vrr_active(struct dm_crtc_state *dm_state)
271 {
272         return dm_state->freesync_config.state == VRR_STATE_ACTIVE_VARIABLE ||
273                dm_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
274 }
275
276 /**
277  * dm_pflip_high_irq() - Handle pageflip interrupt
278  * @interrupt_params: ignored
279  *
280  * Handles the pageflip interrupt by notifying all interested parties
281  * that the pageflip has been completed.
282  */
283 static void dm_pflip_high_irq(void *interrupt_params)
284 {
285         struct amdgpu_crtc *amdgpu_crtc;
286         struct common_irq_params *irq_params = interrupt_params;
287         struct amdgpu_device *adev = irq_params->adev;
288         unsigned long flags;
289         struct drm_pending_vblank_event *e;
290         struct dm_crtc_state *acrtc_state;
291         uint32_t vpos, hpos, v_blank_start, v_blank_end;
292         bool vrr_active;
293
294         amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
295
296         /* IRQ could occur when in initial stage */
297         /* TODO work and BO cleanup */
298         if (amdgpu_crtc == NULL) {
299                 DRM_DEBUG_DRIVER("CRTC is null, returning.\n");
300                 return;
301         }
302
303         spin_lock_irqsave(&adev->ddev->event_lock, flags);
304
305         if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED){
306                 DRM_DEBUG_DRIVER("amdgpu_crtc->pflip_status = %d !=AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p] \n",
307                                                  amdgpu_crtc->pflip_status,
308                                                  AMDGPU_FLIP_SUBMITTED,
309                                                  amdgpu_crtc->crtc_id,
310                                                  amdgpu_crtc);
311                 spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
312                 return;
313         }
314
315         /* page flip completed. */
316         e = amdgpu_crtc->event;
317         amdgpu_crtc->event = NULL;
318
319         if (!e)
320                 WARN_ON(1);
321
322         acrtc_state = to_dm_crtc_state(amdgpu_crtc->base.state);
323         vrr_active = amdgpu_dm_vrr_active(acrtc_state);
324
325         /* Fixed refresh rate, or VRR scanout position outside front-porch? */
326         if (!vrr_active ||
327             !dc_stream_get_scanoutpos(acrtc_state->stream, &v_blank_start,
328                                       &v_blank_end, &hpos, &vpos) ||
329             (vpos < v_blank_start)) {
330                 /* Update to correct count and vblank timestamp if racing with
331                  * vblank irq. This also updates to the correct vblank timestamp
332                  * even in VRR mode, as scanout is past the front-porch atm.
333                  */
334                 drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
335
336                 /* Wake up userspace by sending the pageflip event with proper
337                  * count and timestamp of vblank of flip completion.
338                  */
339                 if (e) {
340                         drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
341
342                         /* Event sent, so done with vblank for this flip */
343                         drm_crtc_vblank_put(&amdgpu_crtc->base);
344                 }
345         } else if (e) {
346                 /* VRR active and inside front-porch: vblank count and
347                  * timestamp for pageflip event will only be up to date after
348                  * drm_crtc_handle_vblank() has been executed from late vblank
349                  * irq handler after start of back-porch (vline 0). We queue the
350                  * pageflip event for send-out by drm_crtc_handle_vblank() with
351                  * updated timestamp and count, once it runs after us.
352                  *
353                  * We need to open-code this instead of using the helper
354                  * drm_crtc_arm_vblank_event(), as that helper would
355                  * call drm_crtc_accurate_vblank_count(), which we must
356                  * not call in VRR mode while we are in front-porch!
357                  */
358
359                 /* sequence will be replaced by real count during send-out. */
360                 e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
361                 e->pipe = amdgpu_crtc->crtc_id;
362
363                 list_add_tail(&e->base.link, &adev->ddev->vblank_event_list);
364                 e = NULL;
365         }
366
367         /* Keep track of vblank of this flip for flip throttling. We use the
368          * cooked hw counter, as that one incremented at start of this vblank
369          * of pageflip completion, so last_flip_vblank is the forbidden count
370          * for queueing new pageflips if vsync + VRR is enabled.
371          */
372         amdgpu_crtc->last_flip_vblank = amdgpu_get_vblank_counter_kms(adev->ddev,
373                                                         amdgpu_crtc->crtc_id);
374
375         amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
376         spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
377
378         DRM_DEBUG_DRIVER("crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
379                          amdgpu_crtc->crtc_id, amdgpu_crtc,
380                          vrr_active, (int) !e);
381 }
382
383 static void dm_vupdate_high_irq(void *interrupt_params)
384 {
385         struct common_irq_params *irq_params = interrupt_params;
386         struct amdgpu_device *adev = irq_params->adev;
387         struct amdgpu_crtc *acrtc;
388         struct dm_crtc_state *acrtc_state;
389         unsigned long flags;
390
391         acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
392
393         if (acrtc) {
394                 acrtc_state = to_dm_crtc_state(acrtc->base.state);
395
396                 DRM_DEBUG_DRIVER("crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
397                                  amdgpu_dm_vrr_active(acrtc_state));
398
399                 /* Core vblank handling is done here after end of front-porch in
400                  * vrr mode, as vblank timestamping will give valid results
401                  * while now done after front-porch. This will also deliver
402                  * page-flip completion events that have been queued to us
403                  * if a pageflip happened inside front-porch.
404                  */
405                 if (amdgpu_dm_vrr_active(acrtc_state)) {
406                         drm_crtc_handle_vblank(&acrtc->base);
407
408                         /* BTR processing for pre-DCE12 ASICs */
409                         if (acrtc_state->stream &&
410                             adev->family < AMDGPU_FAMILY_AI) {
411                                 spin_lock_irqsave(&adev->ddev->event_lock, flags);
412                                 mod_freesync_handle_v_update(
413                                     adev->dm.freesync_module,
414                                     acrtc_state->stream,
415                                     &acrtc_state->vrr_params);
416
417                                 dc_stream_adjust_vmin_vmax(
418                                     adev->dm.dc,
419                                     acrtc_state->stream,
420                                     &acrtc_state->vrr_params.adjust);
421                                 spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
422                         }
423                 }
424         }
425 }
426
427 /**
428  * dm_crtc_high_irq() - Handles CRTC interrupt
429  * @interrupt_params: ignored
430  *
431  * Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
432  * event handler.
433  */
434 static void dm_crtc_high_irq(void *interrupt_params)
435 {
436         struct common_irq_params *irq_params = interrupt_params;
437         struct amdgpu_device *adev = irq_params->adev;
438         struct amdgpu_crtc *acrtc;
439         struct dm_crtc_state *acrtc_state;
440         unsigned long flags;
441
442         acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
443
444         if (acrtc) {
445                 acrtc_state = to_dm_crtc_state(acrtc->base.state);
446
447                 DRM_DEBUG_DRIVER("crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
448                                  amdgpu_dm_vrr_active(acrtc_state));
449
450                 /* Core vblank handling at start of front-porch is only possible
451                  * in non-vrr mode, as only there vblank timestamping will give
452                  * valid results while done in front-porch. Otherwise defer it
453                  * to dm_vupdate_high_irq after end of front-porch.
454                  */
455                 if (!amdgpu_dm_vrr_active(acrtc_state))
456                         drm_crtc_handle_vblank(&acrtc->base);
457
458                 /* Following stuff must happen at start of vblank, for crc
459                  * computation and below-the-range btr support in vrr mode.
460                  */
461                 amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
462
463                 if (acrtc_state->stream && adev->family >= AMDGPU_FAMILY_AI &&
464                     acrtc_state->vrr_params.supported &&
465                     acrtc_state->freesync_config.state == VRR_STATE_ACTIVE_VARIABLE) {
466                         spin_lock_irqsave(&adev->ddev->event_lock, flags);
467                         mod_freesync_handle_v_update(
468                                 adev->dm.freesync_module,
469                                 acrtc_state->stream,
470                                 &acrtc_state->vrr_params);
471
472                         dc_stream_adjust_vmin_vmax(
473                                 adev->dm.dc,
474                                 acrtc_state->stream,
475                                 &acrtc_state->vrr_params.adjust);
476                         spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
477                 }
478         }
479 }
480
481 static int dm_set_clockgating_state(void *handle,
482                   enum amd_clockgating_state state)
483 {
484         return 0;
485 }
486
487 static int dm_set_powergating_state(void *handle,
488                   enum amd_powergating_state state)
489 {
490         return 0;
491 }
492
493 /* Prototypes of private functions */
494 static int dm_early_init(void* handle);
495
496 /* Allocate memory for FBC compressed data  */
497 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
498 {
499         struct drm_device *dev = connector->dev;
500         struct amdgpu_device *adev = dev->dev_private;
501         struct dm_comressor_info *compressor = &adev->dm.compressor;
502         struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
503         struct drm_display_mode *mode;
504         unsigned long max_size = 0;
505
506         if (adev->dm.dc->fbc_compressor == NULL)
507                 return;
508
509         if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
510                 return;
511
512         if (compressor->bo_ptr)
513                 return;
514
515
516         list_for_each_entry(mode, &connector->modes, head) {
517                 if (max_size < mode->htotal * mode->vtotal)
518                         max_size = mode->htotal * mode->vtotal;
519         }
520
521         if (max_size) {
522                 int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
523                             AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
524                             &compressor->gpu_addr, &compressor->cpu_addr);
525
526                 if (r)
527                         DRM_ERROR("DM: Failed to initialize FBC\n");
528                 else {
529                         adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
530                         DRM_INFO("DM: FBC alloc %lu\n", max_size*4);
531                 }
532
533         }
534
535 }
536
537 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
538                                           int pipe, bool *enabled,
539                                           unsigned char *buf, int max_bytes)
540 {
541         struct drm_device *dev = dev_get_drvdata(kdev);
542         struct amdgpu_device *adev = dev->dev_private;
543         struct drm_connector *connector;
544         struct drm_connector_list_iter conn_iter;
545         struct amdgpu_dm_connector *aconnector;
546         int ret = 0;
547
548         *enabled = false;
549
550         mutex_lock(&adev->dm.audio_lock);
551
552         drm_connector_list_iter_begin(dev, &conn_iter);
553         drm_for_each_connector_iter(connector, &conn_iter) {
554                 aconnector = to_amdgpu_dm_connector(connector);
555                 if (aconnector->audio_inst != port)
556                         continue;
557
558                 *enabled = true;
559                 ret = drm_eld_size(connector->eld);
560                 memcpy(buf, connector->eld, min(max_bytes, ret));
561
562                 break;
563         }
564         drm_connector_list_iter_end(&conn_iter);
565
566         mutex_unlock(&adev->dm.audio_lock);
567
568         DRM_DEBUG_KMS("Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
569
570         return ret;
571 }
572
573 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
574         .get_eld = amdgpu_dm_audio_component_get_eld,
575 };
576
577 static int amdgpu_dm_audio_component_bind(struct device *kdev,
578                                        struct device *hda_kdev, void *data)
579 {
580         struct drm_device *dev = dev_get_drvdata(kdev);
581         struct amdgpu_device *adev = dev->dev_private;
582         struct drm_audio_component *acomp = data;
583
584         acomp->ops = &amdgpu_dm_audio_component_ops;
585         acomp->dev = kdev;
586         adev->dm.audio_component = acomp;
587
588         return 0;
589 }
590
591 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
592                                           struct device *hda_kdev, void *data)
593 {
594         struct drm_device *dev = dev_get_drvdata(kdev);
595         struct amdgpu_device *adev = dev->dev_private;
596         struct drm_audio_component *acomp = data;
597
598         acomp->ops = NULL;
599         acomp->dev = NULL;
600         adev->dm.audio_component = NULL;
601 }
602
603 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
604         .bind   = amdgpu_dm_audio_component_bind,
605         .unbind = amdgpu_dm_audio_component_unbind,
606 };
607
608 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
609 {
610         int i, ret;
611
612         if (!amdgpu_audio)
613                 return 0;
614
615         adev->mode_info.audio.enabled = true;
616
617         adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
618
619         for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
620                 adev->mode_info.audio.pin[i].channels = -1;
621                 adev->mode_info.audio.pin[i].rate = -1;
622                 adev->mode_info.audio.pin[i].bits_per_sample = -1;
623                 adev->mode_info.audio.pin[i].status_bits = 0;
624                 adev->mode_info.audio.pin[i].category_code = 0;
625                 adev->mode_info.audio.pin[i].connected = false;
626                 adev->mode_info.audio.pin[i].id =
627                         adev->dm.dc->res_pool->audios[i]->inst;
628                 adev->mode_info.audio.pin[i].offset = 0;
629         }
630
631         ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
632         if (ret < 0)
633                 return ret;
634
635         adev->dm.audio_registered = true;
636
637         return 0;
638 }
639
640 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
641 {
642         if (!amdgpu_audio)
643                 return;
644
645         if (!adev->mode_info.audio.enabled)
646                 return;
647
648         if (adev->dm.audio_registered) {
649                 component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
650                 adev->dm.audio_registered = false;
651         }
652
653         /* TODO: Disable audio? */
654
655         adev->mode_info.audio.enabled = false;
656 }
657
658 void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
659 {
660         struct drm_audio_component *acomp = adev->dm.audio_component;
661
662         if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
663                 DRM_DEBUG_KMS("Notify ELD: %d\n", pin);
664
665                 acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
666                                                  pin, -1);
667         }
668 }
669
670 static int amdgpu_dm_init(struct amdgpu_device *adev)
671 {
672         struct dc_init_data init_data;
673 #ifdef CONFIG_DRM_AMD_DC_HDCP
674         struct dc_callback_init init_params;
675 #endif
676
677         adev->dm.ddev = adev->ddev;
678         adev->dm.adev = adev;
679
680         /* Zero all the fields */
681         memset(&init_data, 0, sizeof(init_data));
682 #ifdef CONFIG_DRM_AMD_DC_HDCP
683         memset(&init_params, 0, sizeof(init_params));
684 #endif
685
686         mutex_init(&adev->dm.dc_lock);
687         mutex_init(&adev->dm.audio_lock);
688
689         if(amdgpu_dm_irq_init(adev)) {
690                 DRM_ERROR("amdgpu: failed to initialize DM IRQ support.\n");
691                 goto error;
692         }
693
694         init_data.asic_id.chip_family = adev->family;
695
696         init_data.asic_id.pci_revision_id = adev->rev_id;
697         init_data.asic_id.hw_internal_rev = adev->external_rev_id;
698
699         init_data.asic_id.vram_width = adev->gmc.vram_width;
700         /* TODO: initialize init_data.asic_id.vram_type here!!!! */
701         init_data.asic_id.atombios_base_address =
702                 adev->mode_info.atom_context->bios;
703
704         init_data.driver = adev;
705
706         adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
707
708         if (!adev->dm.cgs_device) {
709                 DRM_ERROR("amdgpu: failed to create cgs device.\n");
710                 goto error;
711         }
712
713         init_data.cgs_device = adev->dm.cgs_device;
714
715         init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
716
717         /*
718          * TODO debug why this doesn't work on Raven
719          */
720         if (adev->flags & AMD_IS_APU &&
721             adev->asic_type >= CHIP_CARRIZO &&
722             adev->asic_type < CHIP_RAVEN)
723                 init_data.flags.gpu_vm_support = true;
724
725         if (amdgpu_dc_feature_mask & DC_FBC_MASK)
726                 init_data.flags.fbc_support = true;
727
728         if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
729                 init_data.flags.multi_mon_pp_mclk_switch = true;
730
731         if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
732                 init_data.flags.disable_fractional_pwm = true;
733
734         init_data.flags.power_down_display_on_boot = true;
735
736 #ifdef CONFIG_DRM_AMD_DC_DCN2_0
737         init_data.soc_bounding_box = adev->dm.soc_bounding_box;
738 #endif
739
740         /* Display Core create. */
741         adev->dm.dc = dc_create(&init_data);
742
743         if (adev->dm.dc) {
744                 DRM_INFO("Display Core initialized with v%s!\n", DC_VER);
745         } else {
746                 DRM_INFO("Display Core failed to initialize with v%s!\n", DC_VER);
747                 goto error;
748         }
749
750         dc_hardware_init(adev->dm.dc);
751
752         adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
753         if (!adev->dm.freesync_module) {
754                 DRM_ERROR(
755                 "amdgpu: failed to initialize freesync_module.\n");
756         } else
757                 DRM_DEBUG_DRIVER("amdgpu: freesync_module init done %p.\n",
758                                 adev->dm.freesync_module);
759
760         amdgpu_dm_init_color_mod();
761
762 #ifdef CONFIG_DRM_AMD_DC_HDCP
763         if (adev->asic_type >= CHIP_RAVEN) {
764                 adev->dm.hdcp_workqueue = hdcp_create_workqueue(&adev->psp, &init_params.cp_psp, adev->dm.dc);
765
766                 if (!adev->dm.hdcp_workqueue)
767                         DRM_ERROR("amdgpu: failed to initialize hdcp_workqueue.\n");
768                 else
769                         DRM_DEBUG_DRIVER("amdgpu: hdcp_workqueue init done %p.\n", adev->dm.hdcp_workqueue);
770
771                 dc_init_callbacks(adev->dm.dc, &init_params);
772         }
773 #endif
774         if (amdgpu_dm_initialize_drm_device(adev)) {
775                 DRM_ERROR(
776                 "amdgpu: failed to initialize sw for display support.\n");
777                 goto error;
778         }
779
780         /* Update the actual used number of crtc */
781         adev->mode_info.num_crtc = adev->dm.display_indexes_num;
782
783         /* TODO: Add_display_info? */
784
785         /* TODO use dynamic cursor width */
786         adev->ddev->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
787         adev->ddev->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
788
789         if (drm_vblank_init(adev->ddev, adev->dm.display_indexes_num)) {
790                 DRM_ERROR(
791                 "amdgpu: failed to initialize sw for display support.\n");
792                 goto error;
793         }
794
795 #if defined(CONFIG_DEBUG_FS)
796         if (dtn_debugfs_init(adev))
797                 DRM_ERROR("amdgpu: failed initialize dtn debugfs support.\n");
798 #endif
799
800         DRM_DEBUG_DRIVER("KMS initialized.\n");
801
802         return 0;
803 error:
804         amdgpu_dm_fini(adev);
805
806         return -EINVAL;
807 }
808
809 static void amdgpu_dm_fini(struct amdgpu_device *adev)
810 {
811         amdgpu_dm_audio_fini(adev);
812
813         amdgpu_dm_destroy_drm_device(&adev->dm);
814
815 #ifdef CONFIG_DRM_AMD_DC_HDCP
816         if (adev->dm.hdcp_workqueue) {
817                 hdcp_destroy(adev->dm.hdcp_workqueue);
818                 adev->dm.hdcp_workqueue = NULL;
819         }
820
821         if (adev->dm.dc)
822                 dc_deinit_callbacks(adev->dm.dc);
823 #endif
824
825         /* DC Destroy TODO: Replace destroy DAL */
826         if (adev->dm.dc)
827                 dc_destroy(&adev->dm.dc);
828         /*
829          * TODO: pageflip, vlank interrupt
830          *
831          * amdgpu_dm_irq_fini(adev);
832          */
833
834         if (adev->dm.cgs_device) {
835                 amdgpu_cgs_destroy_device(adev->dm.cgs_device);
836                 adev->dm.cgs_device = NULL;
837         }
838         if (adev->dm.freesync_module) {
839                 mod_freesync_destroy(adev->dm.freesync_module);
840                 adev->dm.freesync_module = NULL;
841         }
842
843         mutex_destroy(&adev->dm.audio_lock);
844         mutex_destroy(&adev->dm.dc_lock);
845
846         return;
847 }
848
849 static int load_dmcu_fw(struct amdgpu_device *adev)
850 {
851         const char *fw_name_dmcu = NULL;
852         int r;
853         const struct dmcu_firmware_header_v1_0 *hdr;
854
855         switch(adev->asic_type) {
856         case CHIP_BONAIRE:
857         case CHIP_HAWAII:
858         case CHIP_KAVERI:
859         case CHIP_KABINI:
860         case CHIP_MULLINS:
861         case CHIP_TONGA:
862         case CHIP_FIJI:
863         case CHIP_CARRIZO:
864         case CHIP_STONEY:
865         case CHIP_POLARIS11:
866         case CHIP_POLARIS10:
867         case CHIP_POLARIS12:
868         case CHIP_VEGAM:
869         case CHIP_VEGA10:
870         case CHIP_VEGA12:
871         case CHIP_VEGA20:
872         case CHIP_NAVI10:
873         case CHIP_NAVI14:
874         case CHIP_NAVI12:
875         case CHIP_RENOIR:
876                 return 0;
877         case CHIP_RAVEN:
878                 if (ASICREV_IS_PICASSO(adev->external_rev_id))
879                         fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
880                 else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
881                         fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
882                 else
883                         return 0;
884                 break;
885         default:
886                 DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
887                 return -EINVAL;
888         }
889
890         if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
891                 DRM_DEBUG_KMS("dm: DMCU firmware not supported on direct or SMU loading\n");
892                 return 0;
893         }
894
895         r = request_firmware_direct(&adev->dm.fw_dmcu, fw_name_dmcu, adev->dev);
896         if (r == -ENOENT) {
897                 /* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
898                 DRM_DEBUG_KMS("dm: DMCU firmware not found\n");
899                 adev->dm.fw_dmcu = NULL;
900                 return 0;
901         }
902         if (r) {
903                 dev_err(adev->dev, "amdgpu_dm: Can't load firmware \"%s\"\n",
904                         fw_name_dmcu);
905                 return r;
906         }
907
908         r = amdgpu_ucode_validate(adev->dm.fw_dmcu);
909         if (r) {
910                 dev_err(adev->dev, "amdgpu_dm: Can't validate firmware \"%s\"\n",
911                         fw_name_dmcu);
912                 release_firmware(adev->dm.fw_dmcu);
913                 adev->dm.fw_dmcu = NULL;
914                 return r;
915         }
916
917         hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
918         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
919         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
920         adev->firmware.fw_size +=
921                 ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
922
923         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
924         adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
925         adev->firmware.fw_size +=
926                 ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
927
928         adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
929
930         DRM_DEBUG_KMS("PSP loading DMCU firmware\n");
931
932         return 0;
933 }
934
935 static int dm_sw_init(void *handle)
936 {
937         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
938
939         return load_dmcu_fw(adev);
940 }
941
942 static int dm_sw_fini(void *handle)
943 {
944         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
945
946         if(adev->dm.fw_dmcu) {
947                 release_firmware(adev->dm.fw_dmcu);
948                 adev->dm.fw_dmcu = NULL;
949         }
950
951         return 0;
952 }
953
954 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
955 {
956         struct amdgpu_dm_connector *aconnector;
957         struct drm_connector *connector;
958         struct drm_connector_list_iter iter;
959         int ret = 0;
960
961         drm_connector_list_iter_begin(dev, &iter);
962         drm_for_each_connector_iter(connector, &iter) {
963                 aconnector = to_amdgpu_dm_connector(connector);
964                 if (aconnector->dc_link->type == dc_connection_mst_branch &&
965                     aconnector->mst_mgr.aux) {
966                         DRM_DEBUG_DRIVER("DM_MST: starting TM on aconnector: %p [id: %d]\n",
967                                          aconnector,
968                                          aconnector->base.base.id);
969
970                         ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
971                         if (ret < 0) {
972                                 DRM_ERROR("DM_MST: Failed to start MST\n");
973                                 aconnector->dc_link->type =
974                                         dc_connection_single;
975                                 break;
976                         }
977                 }
978         }
979         drm_connector_list_iter_end(&iter);
980
981         return ret;
982 }
983
984 static int dm_late_init(void *handle)
985 {
986         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
987
988         struct dmcu_iram_parameters params;
989         unsigned int linear_lut[16];
990         int i;
991         struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
992         bool ret = false;
993
994         for (i = 0; i < 16; i++)
995                 linear_lut[i] = 0xFFFF * i / 15;
996
997         params.set = 0;
998         params.backlight_ramping_start = 0xCCCC;
999         params.backlight_ramping_reduction = 0xCCCCCCCC;
1000         params.backlight_lut_array_size = 16;
1001         params.backlight_lut_array = linear_lut;
1002
1003         /* Min backlight level after ABM reduction,  Don't allow below 1%
1004          * 0xFFFF x 0.01 = 0x28F
1005          */
1006         params.min_abm_backlight = 0x28F;
1007
1008         /* todo will enable for navi10 */
1009         if (adev->asic_type <= CHIP_RAVEN) {
1010                 ret = dmcu_load_iram(dmcu, params);
1011
1012                 if (!ret)
1013                         return -EINVAL;
1014         }
1015
1016         return detect_mst_link_for_all_connectors(adev->ddev);
1017 }
1018
1019 static void s3_handle_mst(struct drm_device *dev, bool suspend)
1020 {
1021         struct amdgpu_dm_connector *aconnector;
1022         struct drm_connector *connector;
1023         struct drm_connector_list_iter iter;
1024         struct drm_dp_mst_topology_mgr *mgr;
1025         int ret;
1026         bool need_hotplug = false;
1027
1028         drm_connector_list_iter_begin(dev, &iter);
1029         drm_for_each_connector_iter(connector, &iter) {
1030                 aconnector = to_amdgpu_dm_connector(connector);
1031                 if (aconnector->dc_link->type != dc_connection_mst_branch ||
1032                     aconnector->mst_port)
1033                         continue;
1034
1035                 mgr = &aconnector->mst_mgr;
1036
1037                 if (suspend) {
1038                         drm_dp_mst_topology_mgr_suspend(mgr);
1039                 } else {
1040                         ret = drm_dp_mst_topology_mgr_resume(mgr, true);
1041                         if (ret < 0) {
1042                                 drm_dp_mst_topology_mgr_set_mst(mgr, false);
1043                                 need_hotplug = true;
1044                         }
1045                 }
1046         }
1047         drm_connector_list_iter_end(&iter);
1048
1049         if (need_hotplug)
1050                 drm_kms_helper_hotplug_event(dev);
1051 }
1052
1053 /**
1054  * dm_hw_init() - Initialize DC device
1055  * @handle: The base driver device containing the amdgpu_dm device.
1056  *
1057  * Initialize the &struct amdgpu_display_manager device. This involves calling
1058  * the initializers of each DM component, then populating the struct with them.
1059  *
1060  * Although the function implies hardware initialization, both hardware and
1061  * software are initialized here. Splitting them out to their relevant init
1062  * hooks is a future TODO item.
1063  *
1064  * Some notable things that are initialized here:
1065  *
1066  * - Display Core, both software and hardware
1067  * - DC modules that we need (freesync and color management)
1068  * - DRM software states
1069  * - Interrupt sources and handlers
1070  * - Vblank support
1071  * - Debug FS entries, if enabled
1072  */
1073 static int dm_hw_init(void *handle)
1074 {
1075         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
1076         /* Create DAL display manager */
1077         amdgpu_dm_init(adev);
1078         amdgpu_dm_hpd_init(adev);
1079
1080         return 0;
1081 }
1082
1083 /**
1084  * dm_hw_fini() - Teardown DC device
1085  * @handle: The base driver device containing the amdgpu_dm device.
1086  *
1087  * Teardown components within &struct amdgpu_display_manager that require
1088  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
1089  * were loaded. Also flush IRQ workqueues and disable them.
1090  */
1091 static int dm_hw_fini(void *handle)
1092 {
1093         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
1094
1095         amdgpu_dm_hpd_fini(adev);
1096
1097         amdgpu_dm_irq_fini(adev);
1098         amdgpu_dm_fini(adev);
1099         return 0;
1100 }
1101
1102 static int dm_suspend(void *handle)
1103 {
1104         struct amdgpu_device *adev = handle;
1105         struct amdgpu_display_manager *dm = &adev->dm;
1106         int ret = 0;
1107
1108         WARN_ON(adev->dm.cached_state);
1109         adev->dm.cached_state = drm_atomic_helper_suspend(adev->ddev);
1110
1111         s3_handle_mst(adev->ddev, true);
1112
1113         amdgpu_dm_irq_suspend(adev);
1114
1115
1116         dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
1117
1118         return ret;
1119 }
1120
1121 static struct amdgpu_dm_connector *
1122 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
1123                                              struct drm_crtc *crtc)
1124 {
1125         uint32_t i;
1126         struct drm_connector_state *new_con_state;
1127         struct drm_connector *connector;
1128         struct drm_crtc *crtc_from_state;
1129
1130         for_each_new_connector_in_state(state, connector, new_con_state, i) {
1131                 crtc_from_state = new_con_state->crtc;
1132
1133                 if (crtc_from_state == crtc)
1134                         return to_amdgpu_dm_connector(connector);
1135         }
1136
1137         return NULL;
1138 }
1139
1140 static void emulated_link_detect(struct dc_link *link)
1141 {
1142         struct dc_sink_init_data sink_init_data = { 0 };
1143         struct display_sink_capability sink_caps = { 0 };
1144         enum dc_edid_status edid_status;
1145         struct dc_context *dc_ctx = link->ctx;
1146         struct dc_sink *sink = NULL;
1147         struct dc_sink *prev_sink = NULL;
1148
1149         link->type = dc_connection_none;
1150         prev_sink = link->local_sink;
1151
1152         if (prev_sink != NULL)
1153                 dc_sink_retain(prev_sink);
1154
1155         switch (link->connector_signal) {
1156         case SIGNAL_TYPE_HDMI_TYPE_A: {
1157                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1158                 sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
1159                 break;
1160         }
1161
1162         case SIGNAL_TYPE_DVI_SINGLE_LINK: {
1163                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1164                 sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
1165                 break;
1166         }
1167
1168         case SIGNAL_TYPE_DVI_DUAL_LINK: {
1169                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1170                 sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
1171                 break;
1172         }
1173
1174         case SIGNAL_TYPE_LVDS: {
1175                 sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1176                 sink_caps.signal = SIGNAL_TYPE_LVDS;
1177                 break;
1178         }
1179
1180         case SIGNAL_TYPE_EDP: {
1181                 sink_caps.transaction_type =
1182                         DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
1183                 sink_caps.signal = SIGNAL_TYPE_EDP;
1184                 break;
1185         }
1186
1187         case SIGNAL_TYPE_DISPLAY_PORT: {
1188                 sink_caps.transaction_type =
1189                         DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
1190                 sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
1191                 break;
1192         }
1193
1194         default:
1195                 DC_ERROR("Invalid connector type! signal:%d\n",
1196                         link->connector_signal);
1197                 return;
1198         }
1199
1200         sink_init_data.link = link;
1201         sink_init_data.sink_signal = sink_caps.signal;
1202
1203         sink = dc_sink_create(&sink_init_data);
1204         if (!sink) {
1205                 DC_ERROR("Failed to create sink!\n");
1206                 return;
1207         }
1208
1209         /* dc_sink_create returns a new reference */
1210         link->local_sink = sink;
1211
1212         edid_status = dm_helpers_read_local_edid(
1213                         link->ctx,
1214                         link,
1215                         sink);
1216
1217         if (edid_status != EDID_OK)
1218                 DC_ERROR("Failed to read EDID");
1219
1220 }
1221
1222 static int dm_resume(void *handle)
1223 {
1224         struct amdgpu_device *adev = handle;
1225         struct drm_device *ddev = adev->ddev;
1226         struct amdgpu_display_manager *dm = &adev->dm;
1227         struct amdgpu_dm_connector *aconnector;
1228         struct drm_connector *connector;
1229         struct drm_connector_list_iter iter;
1230         struct drm_crtc *crtc;
1231         struct drm_crtc_state *new_crtc_state;
1232         struct dm_crtc_state *dm_new_crtc_state;
1233         struct drm_plane *plane;
1234         struct drm_plane_state *new_plane_state;
1235         struct dm_plane_state *dm_new_plane_state;
1236         struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
1237         enum dc_connection_type new_connection_type = dc_connection_none;
1238         int i;
1239
1240         /* Recreate dc_state - DC invalidates it when setting power state to S3. */
1241         dc_release_state(dm_state->context);
1242         dm_state->context = dc_create_state(dm->dc);
1243         /* TODO: Remove dc_state->dccg, use dc->dccg directly. */
1244         dc_resource_state_construct(dm->dc, dm_state->context);
1245
1246         /* power on hardware */
1247         dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
1248
1249         /* program HPD filter */
1250         dc_resume(dm->dc);
1251
1252         /*
1253          * early enable HPD Rx IRQ, should be done before set mode as short
1254          * pulse interrupts are used for MST
1255          */
1256         amdgpu_dm_irq_resume_early(adev);
1257
1258         /* On resume we need to rewrite the MSTM control bits to enable MST*/
1259         s3_handle_mst(ddev, false);
1260
1261         /* Do detection*/
1262         drm_connector_list_iter_begin(ddev, &iter);
1263         drm_for_each_connector_iter(connector, &iter) {
1264                 aconnector = to_amdgpu_dm_connector(connector);
1265
1266                 /*
1267                  * this is the case when traversing through already created
1268                  * MST connectors, should be skipped
1269                  */
1270                 if (aconnector->mst_port)
1271                         continue;
1272
1273                 mutex_lock(&aconnector->hpd_lock);
1274                 if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
1275                         DRM_ERROR("KMS: Failed to detect connector\n");
1276
1277                 if (aconnector->base.force && new_connection_type == dc_connection_none)
1278                         emulated_link_detect(aconnector->dc_link);
1279                 else
1280                         dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
1281
1282                 if (aconnector->fake_enable && aconnector->dc_link->local_sink)
1283                         aconnector->fake_enable = false;
1284
1285                 if (aconnector->dc_sink)
1286                         dc_sink_release(aconnector->dc_sink);
1287                 aconnector->dc_sink = NULL;
1288                 amdgpu_dm_update_connector_after_detect(aconnector);
1289                 mutex_unlock(&aconnector->hpd_lock);
1290         }
1291         drm_connector_list_iter_end(&iter);
1292
1293         /* Force mode set in atomic commit */
1294         for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i)
1295                 new_crtc_state->active_changed = true;
1296
1297         /*
1298          * atomic_check is expected to create the dc states. We need to release
1299          * them here, since they were duplicated as part of the suspend
1300          * procedure.
1301          */
1302         for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
1303                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
1304                 if (dm_new_crtc_state->stream) {
1305                         WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
1306                         dc_stream_release(dm_new_crtc_state->stream);
1307                         dm_new_crtc_state->stream = NULL;
1308                 }
1309         }
1310
1311         for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
1312                 dm_new_plane_state = to_dm_plane_state(new_plane_state);
1313                 if (dm_new_plane_state->dc_state) {
1314                         WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
1315                         dc_plane_state_release(dm_new_plane_state->dc_state);
1316                         dm_new_plane_state->dc_state = NULL;
1317                 }
1318         }
1319
1320         drm_atomic_helper_resume(ddev, dm->cached_state);
1321
1322         dm->cached_state = NULL;
1323
1324         amdgpu_dm_irq_resume_late(adev);
1325
1326         return 0;
1327 }
1328
1329 /**
1330  * DOC: DM Lifecycle
1331  *
1332  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
1333  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
1334  * the base driver's device list to be initialized and torn down accordingly.
1335  *
1336  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
1337  */
1338
1339 static const struct amd_ip_funcs amdgpu_dm_funcs = {
1340         .name = "dm",
1341         .early_init = dm_early_init,
1342         .late_init = dm_late_init,
1343         .sw_init = dm_sw_init,
1344         .sw_fini = dm_sw_fini,
1345         .hw_init = dm_hw_init,
1346         .hw_fini = dm_hw_fini,
1347         .suspend = dm_suspend,
1348         .resume = dm_resume,
1349         .is_idle = dm_is_idle,
1350         .wait_for_idle = dm_wait_for_idle,
1351         .check_soft_reset = dm_check_soft_reset,
1352         .soft_reset = dm_soft_reset,
1353         .set_clockgating_state = dm_set_clockgating_state,
1354         .set_powergating_state = dm_set_powergating_state,
1355 };
1356
1357 const struct amdgpu_ip_block_version dm_ip_block =
1358 {
1359         .type = AMD_IP_BLOCK_TYPE_DCE,
1360         .major = 1,
1361         .minor = 0,
1362         .rev = 0,
1363         .funcs = &amdgpu_dm_funcs,
1364 };
1365
1366
1367 /**
1368  * DOC: atomic
1369  *
1370  * *WIP*
1371  */
1372
1373 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
1374         .fb_create = amdgpu_display_user_framebuffer_create,
1375         .output_poll_changed = drm_fb_helper_output_poll_changed,
1376         .atomic_check = amdgpu_dm_atomic_check,
1377         .atomic_commit = amdgpu_dm_atomic_commit,
1378 };
1379
1380 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
1381         .atomic_commit_tail = amdgpu_dm_atomic_commit_tail
1382 };
1383
1384 static void
1385 amdgpu_dm_update_connector_after_detect(struct amdgpu_dm_connector *aconnector)
1386 {
1387         struct drm_connector *connector = &aconnector->base;
1388         struct drm_device *dev = connector->dev;
1389         struct dc_sink *sink;
1390
1391         /* MST handled by drm_mst framework */
1392         if (aconnector->mst_mgr.mst_state == true)
1393                 return;
1394
1395
1396         sink = aconnector->dc_link->local_sink;
1397         if (sink)
1398                 dc_sink_retain(sink);
1399
1400         /*
1401          * Edid mgmt connector gets first update only in mode_valid hook and then
1402          * the connector sink is set to either fake or physical sink depends on link status.
1403          * Skip if already done during boot.
1404          */
1405         if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
1406                         && aconnector->dc_em_sink) {
1407
1408                 /*
1409                  * For S3 resume with headless use eml_sink to fake stream
1410                  * because on resume connector->sink is set to NULL
1411                  */
1412                 mutex_lock(&dev->mode_config.mutex);
1413
1414                 if (sink) {
1415                         if (aconnector->dc_sink) {
1416                                 amdgpu_dm_update_freesync_caps(connector, NULL);
1417                                 /*
1418                                  * retain and release below are used to
1419                                  * bump up refcount for sink because the link doesn't point
1420                                  * to it anymore after disconnect, so on next crtc to connector
1421                                  * reshuffle by UMD we will get into unwanted dc_sink release
1422                                  */
1423                                 dc_sink_release(aconnector->dc_sink);
1424                         }
1425                         aconnector->dc_sink = sink;
1426                         dc_sink_retain(aconnector->dc_sink);
1427                         amdgpu_dm_update_freesync_caps(connector,
1428                                         aconnector->edid);
1429                 } else {
1430                         amdgpu_dm_update_freesync_caps(connector, NULL);
1431                         if (!aconnector->dc_sink) {
1432                                 aconnector->dc_sink = aconnector->dc_em_sink;
1433                                 dc_sink_retain(aconnector->dc_sink);
1434                         }
1435                 }
1436
1437                 mutex_unlock(&dev->mode_config.mutex);
1438
1439                 if (sink)
1440                         dc_sink_release(sink);
1441                 return;
1442         }
1443
1444         /*
1445          * TODO: temporary guard to look for proper fix
1446          * if this sink is MST sink, we should not do anything
1447          */
1448         if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
1449                 dc_sink_release(sink);
1450                 return;
1451         }
1452
1453         if (aconnector->dc_sink == sink) {
1454                 /*
1455                  * We got a DP short pulse (Link Loss, DP CTS, etc...).
1456                  * Do nothing!!
1457                  */
1458                 DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: dc_sink didn't change.\n",
1459                                 aconnector->connector_id);
1460                 if (sink)
1461                         dc_sink_release(sink);
1462                 return;
1463         }
1464
1465         DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
1466                 aconnector->connector_id, aconnector->dc_sink, sink);
1467
1468         mutex_lock(&dev->mode_config.mutex);
1469
1470         /*
1471          * 1. Update status of the drm connector
1472          * 2. Send an event and let userspace tell us what to do
1473          */
1474         if (sink) {
1475                 /*
1476                  * TODO: check if we still need the S3 mode update workaround.
1477                  * If yes, put it here.
1478                  */
1479                 if (aconnector->dc_sink)
1480                         amdgpu_dm_update_freesync_caps(connector, NULL);
1481
1482                 aconnector->dc_sink = sink;
1483                 dc_sink_retain(aconnector->dc_sink);
1484                 if (sink->dc_edid.length == 0) {
1485                         aconnector->edid = NULL;
1486                         drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
1487                 } else {
1488                         aconnector->edid =
1489                                 (struct edid *) sink->dc_edid.raw_edid;
1490
1491
1492                         drm_connector_update_edid_property(connector,
1493                                         aconnector->edid);
1494                         drm_dp_cec_set_edid(&aconnector->dm_dp_aux.aux,
1495                                             aconnector->edid);
1496                 }
1497                 amdgpu_dm_update_freesync_caps(connector, aconnector->edid);
1498
1499         } else {
1500                 drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
1501                 amdgpu_dm_update_freesync_caps(connector, NULL);
1502                 drm_connector_update_edid_property(connector, NULL);
1503                 aconnector->num_modes = 0;
1504                 dc_sink_release(aconnector->dc_sink);
1505                 aconnector->dc_sink = NULL;
1506                 aconnector->edid = NULL;
1507 #ifdef CONFIG_DRM_AMD_DC_HDCP
1508                 /* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
1509                 if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
1510                         connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
1511 #endif
1512         }
1513
1514         mutex_unlock(&dev->mode_config.mutex);
1515
1516         if (sink)
1517                 dc_sink_release(sink);
1518 }
1519
1520 static void handle_hpd_irq(void *param)
1521 {
1522         struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
1523         struct drm_connector *connector = &aconnector->base;
1524         struct drm_device *dev = connector->dev;
1525         enum dc_connection_type new_connection_type = dc_connection_none;
1526 #ifdef CONFIG_DRM_AMD_DC_HDCP
1527         struct amdgpu_device *adev = dev->dev_private;
1528 #endif
1529
1530         /*
1531          * In case of failure or MST no need to update connector status or notify the OS
1532          * since (for MST case) MST does this in its own context.
1533          */
1534         mutex_lock(&aconnector->hpd_lock);
1535
1536 #ifdef CONFIG_DRM_AMD_DC_HDCP
1537         if (adev->asic_type >= CHIP_RAVEN)
1538                 hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
1539 #endif
1540         if (aconnector->fake_enable)
1541                 aconnector->fake_enable = false;
1542
1543         if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
1544                 DRM_ERROR("KMS: Failed to detect connector\n");
1545
1546         if (aconnector->base.force && new_connection_type == dc_connection_none) {
1547                 emulated_link_detect(aconnector->dc_link);
1548
1549
1550                 drm_modeset_lock_all(dev);
1551                 dm_restore_drm_connector_state(dev, connector);
1552                 drm_modeset_unlock_all(dev);
1553
1554                 if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
1555                         drm_kms_helper_hotplug_event(dev);
1556
1557         } else if (dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD)) {
1558                 amdgpu_dm_update_connector_after_detect(aconnector);
1559
1560
1561                 drm_modeset_lock_all(dev);
1562                 dm_restore_drm_connector_state(dev, connector);
1563                 drm_modeset_unlock_all(dev);
1564
1565                 if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
1566                         drm_kms_helper_hotplug_event(dev);
1567         }
1568         mutex_unlock(&aconnector->hpd_lock);
1569
1570 }
1571
1572 static void dm_handle_hpd_rx_irq(struct amdgpu_dm_connector *aconnector)
1573 {
1574         uint8_t esi[DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI] = { 0 };
1575         uint8_t dret;
1576         bool new_irq_handled = false;
1577         int dpcd_addr;
1578         int dpcd_bytes_to_read;
1579
1580         const int max_process_count = 30;
1581         int process_count = 0;
1582
1583         const struct dc_link_status *link_status = dc_link_get_status(aconnector->dc_link);
1584
1585         if (link_status->dpcd_caps->dpcd_rev.raw < 0x12) {
1586                 dpcd_bytes_to_read = DP_LANE0_1_STATUS - DP_SINK_COUNT;
1587                 /* DPCD 0x200 - 0x201 for downstream IRQ */
1588                 dpcd_addr = DP_SINK_COUNT;
1589         } else {
1590                 dpcd_bytes_to_read = DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI;
1591                 /* DPCD 0x2002 - 0x2005 for downstream IRQ */
1592                 dpcd_addr = DP_SINK_COUNT_ESI;
1593         }
1594
1595         dret = drm_dp_dpcd_read(
1596                 &aconnector->dm_dp_aux.aux,
1597                 dpcd_addr,
1598                 esi,
1599                 dpcd_bytes_to_read);
1600
1601         while (dret == dpcd_bytes_to_read &&
1602                 process_count < max_process_count) {
1603                 uint8_t retry;
1604                 dret = 0;
1605
1606                 process_count++;
1607
1608                 DRM_DEBUG_DRIVER("ESI %02x %02x %02x\n", esi[0], esi[1], esi[2]);
1609                 /* handle HPD short pulse irq */
1610                 if (aconnector->mst_mgr.mst_state)
1611                         drm_dp_mst_hpd_irq(
1612                                 &aconnector->mst_mgr,
1613                                 esi,
1614                                 &new_irq_handled);
1615
1616                 if (new_irq_handled) {
1617                         /* ACK at DPCD to notify down stream */
1618                         const int ack_dpcd_bytes_to_write =
1619                                 dpcd_bytes_to_read - 1;
1620
1621                         for (retry = 0; retry < 3; retry++) {
1622                                 uint8_t wret;
1623
1624                                 wret = drm_dp_dpcd_write(
1625                                         &aconnector->dm_dp_aux.aux,
1626                                         dpcd_addr + 1,
1627                                         &esi[1],
1628                                         ack_dpcd_bytes_to_write);
1629                                 if (wret == ack_dpcd_bytes_to_write)
1630                                         break;
1631                         }
1632
1633                         /* check if there is new irq to be handled */
1634                         dret = drm_dp_dpcd_read(
1635                                 &aconnector->dm_dp_aux.aux,
1636                                 dpcd_addr,
1637                                 esi,
1638                                 dpcd_bytes_to_read);
1639
1640                         new_irq_handled = false;
1641                 } else {
1642                         break;
1643                 }
1644         }
1645
1646         if (process_count == max_process_count)
1647                 DRM_DEBUG_DRIVER("Loop exceeded max iterations\n");
1648 }
1649
1650 static void handle_hpd_rx_irq(void *param)
1651 {
1652         struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
1653         struct drm_connector *connector = &aconnector->base;
1654         struct drm_device *dev = connector->dev;
1655         struct dc_link *dc_link = aconnector->dc_link;
1656         bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
1657         enum dc_connection_type new_connection_type = dc_connection_none;
1658 #ifdef CONFIG_DRM_AMD_DC_HDCP
1659         union hpd_irq_data hpd_irq_data;
1660         struct amdgpu_device *adev = dev->dev_private;
1661
1662         memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
1663 #endif
1664
1665         /*
1666          * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
1667          * conflict, after implement i2c helper, this mutex should be
1668          * retired.
1669          */
1670         if (dc_link->type != dc_connection_mst_branch)
1671                 mutex_lock(&aconnector->hpd_lock);
1672
1673
1674 #ifdef CONFIG_DRM_AMD_DC_HDCP
1675         if (dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data, NULL) &&
1676 #else
1677         if (dc_link_handle_hpd_rx_irq(dc_link, NULL, NULL) &&
1678 #endif
1679                         !is_mst_root_connector) {
1680                 /* Downstream Port status changed. */
1681                 if (!dc_link_detect_sink(dc_link, &new_connection_type))
1682                         DRM_ERROR("KMS: Failed to detect connector\n");
1683
1684                 if (aconnector->base.force && new_connection_type == dc_connection_none) {
1685                         emulated_link_detect(dc_link);
1686
1687                         if (aconnector->fake_enable)
1688                                 aconnector->fake_enable = false;
1689
1690                         amdgpu_dm_update_connector_after_detect(aconnector);
1691
1692
1693                         drm_modeset_lock_all(dev);
1694                         dm_restore_drm_connector_state(dev, connector);
1695                         drm_modeset_unlock_all(dev);
1696
1697                         drm_kms_helper_hotplug_event(dev);
1698                 } else if (dc_link_detect(dc_link, DETECT_REASON_HPDRX)) {
1699
1700                         if (aconnector->fake_enable)
1701                                 aconnector->fake_enable = false;
1702
1703                         amdgpu_dm_update_connector_after_detect(aconnector);
1704
1705
1706                         drm_modeset_lock_all(dev);
1707                         dm_restore_drm_connector_state(dev, connector);
1708                         drm_modeset_unlock_all(dev);
1709
1710                         drm_kms_helper_hotplug_event(dev);
1711                 }
1712         }
1713 #ifdef CONFIG_DRM_AMD_DC_HDCP
1714         if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ)
1715                 hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
1716 #endif
1717         if ((dc_link->cur_link_settings.lane_count != LANE_COUNT_UNKNOWN) ||
1718             (dc_link->type == dc_connection_mst_branch))
1719                 dm_handle_hpd_rx_irq(aconnector);
1720
1721         if (dc_link->type != dc_connection_mst_branch) {
1722                 drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
1723                 mutex_unlock(&aconnector->hpd_lock);
1724         }
1725 }
1726
1727 static void register_hpd_handlers(struct amdgpu_device *adev)
1728 {
1729         struct drm_device *dev = adev->ddev;
1730         struct drm_connector *connector;
1731         struct amdgpu_dm_connector *aconnector;
1732         const struct dc_link *dc_link;
1733         struct dc_interrupt_params int_params = {0};
1734
1735         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1736         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1737
1738         list_for_each_entry(connector,
1739                         &dev->mode_config.connector_list, head) {
1740
1741                 aconnector = to_amdgpu_dm_connector(connector);
1742                 dc_link = aconnector->dc_link;
1743
1744                 if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd) {
1745                         int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1746                         int_params.irq_source = dc_link->irq_source_hpd;
1747
1748                         amdgpu_dm_irq_register_interrupt(adev, &int_params,
1749                                         handle_hpd_irq,
1750                                         (void *) aconnector);
1751                 }
1752
1753                 if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd_rx) {
1754
1755                         /* Also register for DP short pulse (hpd_rx). */
1756                         int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
1757                         int_params.irq_source = dc_link->irq_source_hpd_rx;
1758
1759                         amdgpu_dm_irq_register_interrupt(adev, &int_params,
1760                                         handle_hpd_rx_irq,
1761                                         (void *) aconnector);
1762                 }
1763         }
1764 }
1765
1766 /* Register IRQ sources and initialize IRQ callbacks */
1767 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
1768 {
1769         struct dc *dc = adev->dm.dc;
1770         struct common_irq_params *c_irq_params;
1771         struct dc_interrupt_params int_params = {0};
1772         int r;
1773         int i;
1774         unsigned client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
1775
1776         if (adev->asic_type >= CHIP_VEGA10)
1777                 client_id = SOC15_IH_CLIENTID_DCE;
1778
1779         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1780         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1781
1782         /*
1783          * Actions of amdgpu_irq_add_id():
1784          * 1. Register a set() function with base driver.
1785          *    Base driver will call set() function to enable/disable an
1786          *    interrupt in DC hardware.
1787          * 2. Register amdgpu_dm_irq_handler().
1788          *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1789          *    coming from DC hardware.
1790          *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1791          *    for acknowledging and handling. */
1792
1793         /* Use VBLANK interrupt */
1794         for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
1795                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
1796                 if (r) {
1797                         DRM_ERROR("Failed to add crtc irq id!\n");
1798                         return r;
1799                 }
1800
1801                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1802                 int_params.irq_source =
1803                         dc_interrupt_to_irq_source(dc, i, 0);
1804
1805                 c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1806
1807                 c_irq_params->adev = adev;
1808                 c_irq_params->irq_src = int_params.irq_source;
1809
1810                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1811                                 dm_crtc_high_irq, c_irq_params);
1812         }
1813
1814         /* Use VUPDATE interrupt */
1815         for (i = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT; i <= VISLANDS30_IV_SRCID_D6_V_UPDATE_INT; i += 2) {
1816                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->vupdate_irq);
1817                 if (r) {
1818                         DRM_ERROR("Failed to add vupdate irq id!\n");
1819                         return r;
1820                 }
1821
1822                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1823                 int_params.irq_source =
1824                         dc_interrupt_to_irq_source(dc, i, 0);
1825
1826                 c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
1827
1828                 c_irq_params->adev = adev;
1829                 c_irq_params->irq_src = int_params.irq_source;
1830
1831                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1832                                 dm_vupdate_high_irq, c_irq_params);
1833         }
1834
1835         /* Use GRPH_PFLIP interrupt */
1836         for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
1837                         i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
1838                 r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
1839                 if (r) {
1840                         DRM_ERROR("Failed to add page flip irq id!\n");
1841                         return r;
1842                 }
1843
1844                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1845                 int_params.irq_source =
1846                         dc_interrupt_to_irq_source(dc, i, 0);
1847
1848                 c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1849
1850                 c_irq_params->adev = adev;
1851                 c_irq_params->irq_src = int_params.irq_source;
1852
1853                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1854                                 dm_pflip_high_irq, c_irq_params);
1855
1856         }
1857
1858         /* HPD */
1859         r = amdgpu_irq_add_id(adev, client_id,
1860                         VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
1861         if (r) {
1862                 DRM_ERROR("Failed to add hpd irq id!\n");
1863                 return r;
1864         }
1865
1866         register_hpd_handlers(adev);
1867
1868         return 0;
1869 }
1870
1871 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
1872 /* Register IRQ sources and initialize IRQ callbacks */
1873 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
1874 {
1875         struct dc *dc = adev->dm.dc;
1876         struct common_irq_params *c_irq_params;
1877         struct dc_interrupt_params int_params = {0};
1878         int r;
1879         int i;
1880
1881         int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
1882         int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
1883
1884         /*
1885          * Actions of amdgpu_irq_add_id():
1886          * 1. Register a set() function with base driver.
1887          *    Base driver will call set() function to enable/disable an
1888          *    interrupt in DC hardware.
1889          * 2. Register amdgpu_dm_irq_handler().
1890          *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
1891          *    coming from DC hardware.
1892          *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
1893          *    for acknowledging and handling.
1894          */
1895
1896         /* Use VSTARTUP interrupt */
1897         for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
1898                         i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
1899                         i++) {
1900                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
1901
1902                 if (r) {
1903                         DRM_ERROR("Failed to add crtc irq id!\n");
1904                         return r;
1905                 }
1906
1907                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1908                 int_params.irq_source =
1909                         dc_interrupt_to_irq_source(dc, i, 0);
1910
1911                 c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
1912
1913                 c_irq_params->adev = adev;
1914                 c_irq_params->irq_src = int_params.irq_source;
1915
1916                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1917                                 dm_crtc_high_irq, c_irq_params);
1918         }
1919
1920         /* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
1921          * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
1922          * to trigger at end of each vblank, regardless of state of the lock,
1923          * matching DCE behaviour.
1924          */
1925         for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
1926              i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
1927              i++) {
1928                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
1929
1930                 if (r) {
1931                         DRM_ERROR("Failed to add vupdate irq id!\n");
1932                         return r;
1933                 }
1934
1935                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1936                 int_params.irq_source =
1937                         dc_interrupt_to_irq_source(dc, i, 0);
1938
1939                 c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
1940
1941                 c_irq_params->adev = adev;
1942                 c_irq_params->irq_src = int_params.irq_source;
1943
1944                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1945                                 dm_vupdate_high_irq, c_irq_params);
1946         }
1947
1948         /* Use GRPH_PFLIP interrupt */
1949         for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
1950                         i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + adev->mode_info.num_crtc - 1;
1951                         i++) {
1952                 r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
1953                 if (r) {
1954                         DRM_ERROR("Failed to add page flip irq id!\n");
1955                         return r;
1956                 }
1957
1958                 int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
1959                 int_params.irq_source =
1960                         dc_interrupt_to_irq_source(dc, i, 0);
1961
1962                 c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
1963
1964                 c_irq_params->adev = adev;
1965                 c_irq_params->irq_src = int_params.irq_source;
1966
1967                 amdgpu_dm_irq_register_interrupt(adev, &int_params,
1968                                 dm_pflip_high_irq, c_irq_params);
1969
1970         }
1971
1972         /* HPD */
1973         r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
1974                         &adev->hpd_irq);
1975         if (r) {
1976                 DRM_ERROR("Failed to add hpd irq id!\n");
1977                 return r;
1978         }
1979
1980         register_hpd_handlers(adev);
1981
1982         return 0;
1983 }
1984 #endif
1985
1986 /*
1987  * Acquires the lock for the atomic state object and returns
1988  * the new atomic state.
1989  *
1990  * This should only be called during atomic check.
1991  */
1992 static int dm_atomic_get_state(struct drm_atomic_state *state,
1993                                struct dm_atomic_state **dm_state)
1994 {
1995         struct drm_device *dev = state->dev;
1996         struct amdgpu_device *adev = dev->dev_private;
1997         struct amdgpu_display_manager *dm = &adev->dm;
1998         struct drm_private_state *priv_state;
1999
2000         if (*dm_state)
2001                 return 0;
2002
2003         priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
2004         if (IS_ERR(priv_state))
2005                 return PTR_ERR(priv_state);
2006
2007         *dm_state = to_dm_atomic_state(priv_state);
2008
2009         return 0;
2010 }
2011
2012 struct dm_atomic_state *
2013 dm_atomic_get_new_state(struct drm_atomic_state *state)
2014 {
2015         struct drm_device *dev = state->dev;
2016         struct amdgpu_device *adev = dev->dev_private;
2017         struct amdgpu_display_manager *dm = &adev->dm;
2018         struct drm_private_obj *obj;
2019         struct drm_private_state *new_obj_state;
2020         int i;
2021
2022         for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
2023                 if (obj->funcs == dm->atomic_obj.funcs)
2024                         return to_dm_atomic_state(new_obj_state);
2025         }
2026
2027         return NULL;
2028 }
2029
2030 struct dm_atomic_state *
2031 dm_atomic_get_old_state(struct drm_atomic_state *state)
2032 {
2033         struct drm_device *dev = state->dev;
2034         struct amdgpu_device *adev = dev->dev_private;
2035         struct amdgpu_display_manager *dm = &adev->dm;
2036         struct drm_private_obj *obj;
2037         struct drm_private_state *old_obj_state;
2038         int i;
2039
2040         for_each_old_private_obj_in_state(state, obj, old_obj_state, i) {
2041                 if (obj->funcs == dm->atomic_obj.funcs)
2042                         return to_dm_atomic_state(old_obj_state);
2043         }
2044
2045         return NULL;
2046 }
2047
2048 static struct drm_private_state *
2049 dm_atomic_duplicate_state(struct drm_private_obj *obj)
2050 {
2051         struct dm_atomic_state *old_state, *new_state;
2052
2053         new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
2054         if (!new_state)
2055                 return NULL;
2056
2057         __drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
2058
2059         old_state = to_dm_atomic_state(obj->state);
2060
2061         if (old_state && old_state->context)
2062                 new_state->context = dc_copy_state(old_state->context);
2063
2064         if (!new_state->context) {
2065                 kfree(new_state);
2066                 return NULL;
2067         }
2068
2069         return &new_state->base;
2070 }
2071
2072 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
2073                                     struct drm_private_state *state)
2074 {
2075         struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
2076
2077         if (dm_state && dm_state->context)
2078                 dc_release_state(dm_state->context);
2079
2080         kfree(dm_state);
2081 }
2082
2083 static struct drm_private_state_funcs dm_atomic_state_funcs = {
2084         .atomic_duplicate_state = dm_atomic_duplicate_state,
2085         .atomic_destroy_state = dm_atomic_destroy_state,
2086 };
2087
2088 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
2089 {
2090         struct dm_atomic_state *state;
2091         int r;
2092
2093         adev->mode_info.mode_config_initialized = true;
2094
2095         adev->ddev->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
2096         adev->ddev->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
2097
2098         adev->ddev->mode_config.max_width = 16384;
2099         adev->ddev->mode_config.max_height = 16384;
2100
2101         adev->ddev->mode_config.preferred_depth = 24;
2102         adev->ddev->mode_config.prefer_shadow = 1;
2103         /* indicates support for immediate flip */
2104         adev->ddev->mode_config.async_page_flip = true;
2105
2106         adev->ddev->mode_config.fb_base = adev->gmc.aper_base;
2107
2108         state = kzalloc(sizeof(*state), GFP_KERNEL);
2109         if (!state)
2110                 return -ENOMEM;
2111
2112         state->context = dc_create_state(adev->dm.dc);
2113         if (!state->context) {
2114                 kfree(state);
2115                 return -ENOMEM;
2116         }
2117
2118         dc_resource_state_copy_construct_current(adev->dm.dc, state->context);
2119
2120         drm_atomic_private_obj_init(adev->ddev,
2121                                     &adev->dm.atomic_obj,
2122                                     &state->base,
2123                                     &dm_atomic_state_funcs);
2124
2125         r = amdgpu_display_modeset_create_props(adev);
2126         if (r)
2127                 return r;
2128
2129         r = amdgpu_dm_audio_init(adev);
2130         if (r)
2131                 return r;
2132
2133         return 0;
2134 }
2135
2136 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
2137 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
2138
2139 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
2140         defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
2141
2142 static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm)
2143 {
2144 #if defined(CONFIG_ACPI)
2145         struct amdgpu_dm_backlight_caps caps;
2146
2147         if (dm->backlight_caps.caps_valid)
2148                 return;
2149
2150         amdgpu_acpi_get_backlight_caps(dm->adev, &caps);
2151         if (caps.caps_valid) {
2152                 dm->backlight_caps.min_input_signal = caps.min_input_signal;
2153                 dm->backlight_caps.max_input_signal = caps.max_input_signal;
2154                 dm->backlight_caps.caps_valid = true;
2155         } else {
2156                 dm->backlight_caps.min_input_signal =
2157                                 AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
2158                 dm->backlight_caps.max_input_signal =
2159                                 AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
2160         }
2161 #else
2162         dm->backlight_caps.min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
2163         dm->backlight_caps.max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
2164 #endif
2165 }
2166
2167 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
2168 {
2169         struct amdgpu_display_manager *dm = bl_get_data(bd);
2170         struct amdgpu_dm_backlight_caps caps;
2171         uint32_t brightness = bd->props.brightness;
2172
2173         amdgpu_dm_update_backlight_caps(dm);
2174         caps = dm->backlight_caps;
2175         /*
2176          * The brightness input is in the range 0-255
2177          * It needs to be rescaled to be between the
2178          * requested min and max input signal
2179          *
2180          * It also needs to be scaled up by 0x101 to
2181          * match the DC interface which has a range of
2182          * 0 to 0xffff
2183          */
2184         brightness =
2185                 brightness
2186                 * 0x101
2187                 * (caps.max_input_signal - caps.min_input_signal)
2188                 / AMDGPU_MAX_BL_LEVEL
2189                 + caps.min_input_signal * 0x101;
2190
2191         if (dc_link_set_backlight_level(dm->backlight_link,
2192                         brightness, 0))
2193                 return 0;
2194         else
2195                 return 1;
2196 }
2197
2198 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
2199 {
2200         struct amdgpu_display_manager *dm = bl_get_data(bd);
2201         int ret = dc_link_get_backlight_level(dm->backlight_link);
2202
2203         if (ret == DC_ERROR_UNEXPECTED)
2204                 return bd->props.brightness;
2205         return ret;
2206 }
2207
2208 static const struct backlight_ops amdgpu_dm_backlight_ops = {
2209         .options = BL_CORE_SUSPENDRESUME,
2210         .get_brightness = amdgpu_dm_backlight_get_brightness,
2211         .update_status  = amdgpu_dm_backlight_update_status,
2212 };
2213
2214 static void
2215 amdgpu_dm_register_backlight_device(struct amdgpu_display_manager *dm)
2216 {
2217         char bl_name[16];
2218         struct backlight_properties props = { 0 };
2219
2220         amdgpu_dm_update_backlight_caps(dm);
2221
2222         props.max_brightness = AMDGPU_MAX_BL_LEVEL;
2223         props.brightness = AMDGPU_MAX_BL_LEVEL;
2224         props.type = BACKLIGHT_RAW;
2225
2226         snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
2227                         dm->adev->ddev->primary->index);
2228
2229         dm->backlight_dev = backlight_device_register(bl_name,
2230                         dm->adev->ddev->dev,
2231                         dm,
2232                         &amdgpu_dm_backlight_ops,
2233                         &props);
2234
2235         if (IS_ERR(dm->backlight_dev))
2236                 DRM_ERROR("DM: Backlight registration failed!\n");
2237         else
2238                 DRM_DEBUG_DRIVER("DM: Registered Backlight device: %s\n", bl_name);
2239 }
2240
2241 #endif
2242
2243 static int initialize_plane(struct amdgpu_display_manager *dm,
2244                             struct amdgpu_mode_info *mode_info, int plane_id,
2245                             enum drm_plane_type plane_type,
2246                             const struct dc_plane_cap *plane_cap)
2247 {
2248         struct drm_plane *plane;
2249         unsigned long possible_crtcs;
2250         int ret = 0;
2251
2252         plane = kzalloc(sizeof(struct drm_plane), GFP_KERNEL);
2253         if (!plane) {
2254                 DRM_ERROR("KMS: Failed to allocate plane\n");
2255                 return -ENOMEM;
2256         }
2257         plane->type = plane_type;
2258
2259         /*
2260          * HACK: IGT tests expect that the primary plane for a CRTC
2261          * can only have one possible CRTC. Only expose support for
2262          * any CRTC if they're not going to be used as a primary plane
2263          * for a CRTC - like overlay or underlay planes.
2264          */
2265         possible_crtcs = 1 << plane_id;
2266         if (plane_id >= dm->dc->caps.max_streams)
2267                 possible_crtcs = 0xff;
2268
2269         ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
2270
2271         if (ret) {
2272                 DRM_ERROR("KMS: Failed to initialize plane\n");
2273                 kfree(plane);
2274                 return ret;
2275         }
2276
2277         if (mode_info)
2278                 mode_info->planes[plane_id] = plane;
2279
2280         return ret;
2281 }
2282
2283
2284 static void register_backlight_device(struct amdgpu_display_manager *dm,
2285                                       struct dc_link *link)
2286 {
2287 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
2288         defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
2289
2290         if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
2291             link->type != dc_connection_none) {
2292                 /*
2293                  * Event if registration failed, we should continue with
2294                  * DM initialization because not having a backlight control
2295                  * is better then a black screen.
2296                  */
2297                 amdgpu_dm_register_backlight_device(dm);
2298
2299                 if (dm->backlight_dev)
2300                         dm->backlight_link = link;
2301         }
2302 #endif
2303 }
2304
2305
2306 /*
2307  * In this architecture, the association
2308  * connector -> encoder -> crtc
2309  * id not really requried. The crtc and connector will hold the
2310  * display_index as an abstraction to use with DAL component
2311  *
2312  * Returns 0 on success
2313  */
2314 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
2315 {
2316         struct amdgpu_display_manager *dm = &adev->dm;
2317         int32_t i;
2318         struct amdgpu_dm_connector *aconnector = NULL;
2319         struct amdgpu_encoder *aencoder = NULL;
2320         struct amdgpu_mode_info *mode_info = &adev->mode_info;
2321         uint32_t link_cnt;
2322         int32_t primary_planes;
2323         enum dc_connection_type new_connection_type = dc_connection_none;
2324         const struct dc_plane_cap *plane;
2325
2326         link_cnt = dm->dc->caps.max_links;
2327         if (amdgpu_dm_mode_config_init(dm->adev)) {
2328                 DRM_ERROR("DM: Failed to initialize mode config\n");
2329                 return -EINVAL;
2330         }
2331
2332         /* There is one primary plane per CRTC */
2333         primary_planes = dm->dc->caps.max_streams;
2334         ASSERT(primary_planes <= AMDGPU_MAX_PLANES);
2335
2336         /*
2337          * Initialize primary planes, implicit planes for legacy IOCTLS.
2338          * Order is reversed to match iteration order in atomic check.
2339          */
2340         for (i = (primary_planes - 1); i >= 0; i--) {
2341                 plane = &dm->dc->caps.planes[i];
2342
2343                 if (initialize_plane(dm, mode_info, i,
2344                                      DRM_PLANE_TYPE_PRIMARY, plane)) {
2345                         DRM_ERROR("KMS: Failed to initialize primary plane\n");
2346                         goto fail;
2347                 }
2348         }
2349
2350         /*
2351          * Initialize overlay planes, index starting after primary planes.
2352          * These planes have a higher DRM index than the primary planes since
2353          * they should be considered as having a higher z-order.
2354          * Order is reversed to match iteration order in atomic check.
2355          *
2356          * Only support DCN for now, and only expose one so we don't encourage
2357          * userspace to use up all the pipes.
2358          */
2359         for (i = 0; i < dm->dc->caps.max_planes; ++i) {
2360                 struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
2361
2362                 if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
2363                         continue;
2364
2365                 if (!plane->blends_with_above || !plane->blends_with_below)
2366                         continue;
2367
2368                 if (!plane->pixel_format_support.argb8888)
2369                         continue;
2370
2371                 if (initialize_plane(dm, NULL, primary_planes + i,
2372                                      DRM_PLANE_TYPE_OVERLAY, plane)) {
2373                         DRM_ERROR("KMS: Failed to initialize overlay plane\n");
2374                         goto fail;
2375                 }
2376
2377                 /* Only create one overlay plane. */
2378                 break;
2379         }
2380
2381         for (i = 0; i < dm->dc->caps.max_streams; i++)
2382                 if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
2383                         DRM_ERROR("KMS: Failed to initialize crtc\n");
2384                         goto fail;
2385                 }
2386
2387         dm->display_indexes_num = dm->dc->caps.max_streams;
2388
2389         /* loops over all connectors on the board */
2390         for (i = 0; i < link_cnt; i++) {
2391                 struct dc_link *link = NULL;
2392
2393                 if (i > AMDGPU_DM_MAX_DISPLAY_INDEX) {
2394                         DRM_ERROR(
2395                                 "KMS: Cannot support more than %d display indexes\n",
2396                                         AMDGPU_DM_MAX_DISPLAY_INDEX);
2397                         continue;
2398                 }
2399
2400                 aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
2401                 if (!aconnector)
2402                         goto fail;
2403
2404                 aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
2405                 if (!aencoder)
2406                         goto fail;
2407
2408                 if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
2409                         DRM_ERROR("KMS: Failed to initialize encoder\n");
2410                         goto fail;
2411                 }
2412
2413                 if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
2414                         DRM_ERROR("KMS: Failed to initialize connector\n");
2415                         goto fail;
2416                 }
2417
2418                 link = dc_get_link_at_index(dm->dc, i);
2419
2420                 if (!dc_link_detect_sink(link, &new_connection_type))
2421                         DRM_ERROR("KMS: Failed to detect connector\n");
2422
2423                 if (aconnector->base.force && new_connection_type == dc_connection_none) {
2424                         emulated_link_detect(link);
2425                         amdgpu_dm_update_connector_after_detect(aconnector);
2426
2427                 } else if (dc_link_detect(link, DETECT_REASON_BOOT)) {
2428                         amdgpu_dm_update_connector_after_detect(aconnector);
2429                         register_backlight_device(dm, link);
2430                         if (amdgpu_dc_feature_mask & DC_PSR_MASK)
2431                                 amdgpu_dm_set_psr_caps(link);
2432                 }
2433
2434
2435         }
2436
2437         /* Software is initialized. Now we can register interrupt handlers. */
2438         switch (adev->asic_type) {
2439         case CHIP_BONAIRE:
2440         case CHIP_HAWAII:
2441         case CHIP_KAVERI:
2442         case CHIP_KABINI:
2443         case CHIP_MULLINS:
2444         case CHIP_TONGA:
2445         case CHIP_FIJI:
2446         case CHIP_CARRIZO:
2447         case CHIP_STONEY:
2448         case CHIP_POLARIS11:
2449         case CHIP_POLARIS10:
2450         case CHIP_POLARIS12:
2451         case CHIP_VEGAM:
2452         case CHIP_VEGA10:
2453         case CHIP_VEGA12:
2454         case CHIP_VEGA20:
2455                 if (dce110_register_irq_handlers(dm->adev)) {
2456                         DRM_ERROR("DM: Failed to initialize IRQ\n");
2457                         goto fail;
2458                 }
2459                 break;
2460 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
2461         case CHIP_RAVEN:
2462 #if defined(CONFIG_DRM_AMD_DC_DCN2_0)
2463         case CHIP_NAVI12:
2464         case CHIP_NAVI10:
2465         case CHIP_NAVI14:
2466 #endif
2467 #if defined(CONFIG_DRM_AMD_DC_DCN2_1)
2468         case CHIP_RENOIR:
2469 #endif
2470                 if (dcn10_register_irq_handlers(dm->adev)) {
2471                         DRM_ERROR("DM: Failed to initialize IRQ\n");
2472                         goto fail;
2473                 }
2474                 break;
2475 #endif
2476         default:
2477                 DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
2478                 goto fail;
2479         }
2480
2481         if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2482                 dm->dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2483
2484         return 0;
2485 fail:
2486         kfree(aencoder);
2487         kfree(aconnector);
2488
2489         return -EINVAL;
2490 }
2491
2492 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
2493 {
2494         drm_mode_config_cleanup(dm->ddev);
2495         drm_atomic_private_obj_fini(&dm->atomic_obj);
2496         return;
2497 }
2498
2499 /******************************************************************************
2500  * amdgpu_display_funcs functions
2501  *****************************************************************************/
2502
2503 /*
2504  * dm_bandwidth_update - program display watermarks
2505  *
2506  * @adev: amdgpu_device pointer
2507  *
2508  * Calculate and program the display watermarks and line buffer allocation.
2509  */
2510 static void dm_bandwidth_update(struct amdgpu_device *adev)
2511 {
2512         /* TODO: implement later */
2513 }
2514
2515 static const struct amdgpu_display_funcs dm_display_funcs = {
2516         .bandwidth_update = dm_bandwidth_update, /* called unconditionally */
2517         .vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
2518         .backlight_set_level = NULL, /* never called for DC */
2519         .backlight_get_level = NULL, /* never called for DC */
2520         .hpd_sense = NULL,/* called unconditionally */
2521         .hpd_set_polarity = NULL, /* called unconditionally */
2522         .hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
2523         .page_flip_get_scanoutpos =
2524                 dm_crtc_get_scanoutpos,/* called unconditionally */
2525         .add_encoder = NULL, /* VBIOS parsing. DAL does it. */
2526         .add_connector = NULL, /* VBIOS parsing. DAL does it. */
2527 };
2528
2529 #if defined(CONFIG_DEBUG_KERNEL_DC)
2530
2531 static ssize_t s3_debug_store(struct device *device,
2532                               struct device_attribute *attr,
2533                               const char *buf,
2534                               size_t count)
2535 {
2536         int ret;
2537         int s3_state;
2538         struct drm_device *drm_dev = dev_get_drvdata(device);
2539         struct amdgpu_device *adev = drm_dev->dev_private;
2540
2541         ret = kstrtoint(buf, 0, &s3_state);
2542
2543         if (ret == 0) {
2544                 if (s3_state) {
2545                         dm_resume(adev);
2546                         drm_kms_helper_hotplug_event(adev->ddev);
2547                 } else
2548                         dm_suspend(adev);
2549         }
2550
2551         return ret == 0 ? count : 0;
2552 }
2553
2554 DEVICE_ATTR_WO(s3_debug);
2555
2556 #endif
2557
2558 static int dm_early_init(void *handle)
2559 {
2560         struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2561
2562         switch (adev->asic_type) {
2563         case CHIP_BONAIRE:
2564         case CHIP_HAWAII:
2565                 adev->mode_info.num_crtc = 6;
2566                 adev->mode_info.num_hpd = 6;
2567                 adev->mode_info.num_dig = 6;
2568                 break;
2569         case CHIP_KAVERI:
2570                 adev->mode_info.num_crtc = 4;
2571                 adev->mode_info.num_hpd = 6;
2572                 adev->mode_info.num_dig = 7;
2573                 break;
2574         case CHIP_KABINI:
2575         case CHIP_MULLINS:
2576                 adev->mode_info.num_crtc = 2;
2577                 adev->mode_info.num_hpd = 6;
2578                 adev->mode_info.num_dig = 6;
2579                 break;
2580         case CHIP_FIJI:
2581         case CHIP_TONGA:
2582                 adev->mode_info.num_crtc = 6;
2583                 adev->mode_info.num_hpd = 6;
2584                 adev->mode_info.num_dig = 7;
2585                 break;
2586         case CHIP_CARRIZO:
2587                 adev->mode_info.num_crtc = 3;
2588                 adev->mode_info.num_hpd = 6;
2589                 adev->mode_info.num_dig = 9;
2590                 break;
2591         case CHIP_STONEY:
2592                 adev->mode_info.num_crtc = 2;
2593                 adev->mode_info.num_hpd = 6;
2594                 adev->mode_info.num_dig = 9;
2595                 break;
2596         case CHIP_POLARIS11:
2597         case CHIP_POLARIS12:
2598                 adev->mode_info.num_crtc = 5;
2599                 adev->mode_info.num_hpd = 5;
2600                 adev->mode_info.num_dig = 5;
2601                 break;
2602         case CHIP_POLARIS10:
2603         case CHIP_VEGAM:
2604                 adev->mode_info.num_crtc = 6;
2605                 adev->mode_info.num_hpd = 6;
2606                 adev->mode_info.num_dig = 6;
2607                 break;
2608         case CHIP_VEGA10:
2609         case CHIP_VEGA12:
2610         case CHIP_VEGA20:
2611                 adev->mode_info.num_crtc = 6;
2612                 adev->mode_info.num_hpd = 6;
2613                 adev->mode_info.num_dig = 6;
2614                 break;
2615 #if defined(CONFIG_DRM_AMD_DC_DCN1_0)
2616         case CHIP_RAVEN:
2617                 adev->mode_info.num_crtc = 4;
2618                 adev->mode_info.num_hpd = 4;
2619                 adev->mode_info.num_dig = 4;
2620                 break;
2621 #endif
2622 #if defined(CONFIG_DRM_AMD_DC_DCN2_0)
2623         case CHIP_NAVI10:
2624         case CHIP_NAVI12:
2625                 adev->mode_info.num_crtc = 6;
2626                 adev->mode_info.num_hpd = 6;
2627                 adev->mode_info.num_dig = 6;
2628                 break;
2629         case CHIP_NAVI14:
2630                 adev->mode_info.num_crtc = 5;
2631                 adev->mode_info.num_hpd = 5;
2632                 adev->mode_info.num_dig = 5;
2633                 break;
2634 #endif
2635 #if defined(CONFIG_DRM_AMD_DC_DCN2_1)
2636         case CHIP_RENOIR:
2637                 adev->mode_info.num_crtc = 4;
2638                 adev->mode_info.num_hpd = 4;
2639                 adev->mode_info.num_dig = 4;
2640                 break;
2641 #endif
2642         default:
2643                 DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
2644                 return -EINVAL;
2645         }
2646
2647         amdgpu_dm_set_irq_funcs(adev);
2648
2649         if (adev->mode_info.funcs == NULL)
2650                 adev->mode_info.funcs = &dm_display_funcs;
2651
2652         /*
2653          * Note: Do NOT change adev->audio_endpt_rreg and
2654          * adev->audio_endpt_wreg because they are initialised in
2655          * amdgpu_device_init()
2656          */
2657 #if defined(CONFIG_DEBUG_KERNEL_DC)
2658         device_create_file(
2659                 adev->ddev->dev,
2660                 &dev_attr_s3_debug);
2661 #endif
2662
2663         return 0;
2664 }
2665
2666 static bool modeset_required(struct drm_crtc_state *crtc_state,
2667                              struct dc_stream_state *new_stream,
2668                              struct dc_stream_state *old_stream)
2669 {
2670         if (!drm_atomic_crtc_needs_modeset(crtc_state))
2671                 return false;
2672
2673         if (!crtc_state->enable)
2674                 return false;
2675
2676         return crtc_state->active;
2677 }
2678
2679 static bool modereset_required(struct drm_crtc_state *crtc_state)
2680 {
2681         if (!drm_atomic_crtc_needs_modeset(crtc_state))
2682                 return false;
2683
2684         return !crtc_state->enable || !crtc_state->active;
2685 }
2686
2687 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
2688 {
2689         drm_encoder_cleanup(encoder);
2690         kfree(encoder);
2691 }
2692
2693 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
2694         .destroy = amdgpu_dm_encoder_destroy,
2695 };
2696
2697
2698 static int fill_dc_scaling_info(const struct drm_plane_state *state,
2699                                 struct dc_scaling_info *scaling_info)
2700 {
2701         int scale_w, scale_h;
2702
2703         memset(scaling_info, 0, sizeof(*scaling_info));
2704
2705         /* Source is fixed 16.16 but we ignore mantissa for now... */
2706         scaling_info->src_rect.x = state->src_x >> 16;
2707         scaling_info->src_rect.y = state->src_y >> 16;
2708
2709         scaling_info->src_rect.width = state->src_w >> 16;
2710         if (scaling_info->src_rect.width == 0)
2711                 return -EINVAL;
2712
2713         scaling_info->src_rect.height = state->src_h >> 16;
2714         if (scaling_info->src_rect.height == 0)
2715                 return -EINVAL;
2716
2717         scaling_info->dst_rect.x = state->crtc_x;
2718         scaling_info->dst_rect.y = state->crtc_y;
2719
2720         if (state->crtc_w == 0)
2721                 return -EINVAL;
2722
2723         scaling_info->dst_rect.width = state->crtc_w;
2724
2725         if (state->crtc_h == 0)
2726                 return -EINVAL;
2727
2728         scaling_info->dst_rect.height = state->crtc_h;
2729
2730         /* DRM doesn't specify clipping on destination output. */
2731         scaling_info->clip_rect = scaling_info->dst_rect;
2732
2733         /* TODO: Validate scaling per-format with DC plane caps */
2734         scale_w = scaling_info->dst_rect.width * 1000 /
2735                   scaling_info->src_rect.width;
2736
2737         if (scale_w < 250 || scale_w > 16000)
2738                 return -EINVAL;
2739
2740         scale_h = scaling_info->dst_rect.height * 1000 /
2741                   scaling_info->src_rect.height;
2742
2743         if (scale_h < 250 || scale_h > 16000)
2744                 return -EINVAL;
2745
2746         /*
2747          * The "scaling_quality" can be ignored for now, quality = 0 has DC
2748          * assume reasonable defaults based on the format.
2749          */
2750
2751         return 0;
2752 }
2753
2754 static int get_fb_info(const struct amdgpu_framebuffer *amdgpu_fb,
2755                        uint64_t *tiling_flags)
2756 {
2757         struct amdgpu_bo *rbo = gem_to_amdgpu_bo(amdgpu_fb->base.obj[0]);
2758         int r = amdgpu_bo_reserve(rbo, false);
2759
2760         if (unlikely(r)) {
2761                 /* Don't show error message when returning -ERESTARTSYS */
2762                 if (r != -ERESTARTSYS)
2763                         DRM_ERROR("Unable to reserve buffer: %d\n", r);
2764                 return r;
2765         }
2766
2767         if (tiling_flags)
2768                 amdgpu_bo_get_tiling_flags(rbo, tiling_flags);
2769
2770         amdgpu_bo_unreserve(rbo);
2771
2772         return r;
2773 }
2774
2775 static inline uint64_t get_dcc_address(uint64_t address, uint64_t tiling_flags)
2776 {
2777         uint32_t offset = AMDGPU_TILING_GET(tiling_flags, DCC_OFFSET_256B);
2778
2779         return offset ? (address + offset * 256) : 0;
2780 }
2781
2782 static int
2783 fill_plane_dcc_attributes(struct amdgpu_device *adev,
2784                           const struct amdgpu_framebuffer *afb,
2785                           const enum surface_pixel_format format,
2786                           const enum dc_rotation_angle rotation,
2787                           const struct plane_size *plane_size,
2788                           const union dc_tiling_info *tiling_info,
2789                           const uint64_t info,
2790                           struct dc_plane_dcc_param *dcc,
2791                           struct dc_plane_address *address)
2792 {
2793         struct dc *dc = adev->dm.dc;
2794         struct dc_dcc_surface_param input;
2795         struct dc_surface_dcc_cap output;
2796         uint32_t offset = AMDGPU_TILING_GET(info, DCC_OFFSET_256B);
2797         uint32_t i64b = AMDGPU_TILING_GET(info, DCC_INDEPENDENT_64B) != 0;
2798         uint64_t dcc_address;
2799
2800         memset(&input, 0, sizeof(input));
2801         memset(&output, 0, sizeof(output));
2802
2803         if (!offset)
2804                 return 0;
2805
2806         if (format >= SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
2807                 return 0;
2808
2809         if (!dc->cap_funcs.get_dcc_compression_cap)
2810                 return -EINVAL;
2811
2812         input.format = format;
2813         input.surface_size.width = plane_size->surface_size.width;
2814         input.surface_size.height = plane_size->surface_size.height;
2815         input.swizzle_mode = tiling_info->gfx9.swizzle;
2816
2817         if (rotation == ROTATION_ANGLE_0 || rotation == ROTATION_ANGLE_180)
2818                 input.scan = SCAN_DIRECTION_HORIZONTAL;
2819         else if (rotation == ROTATION_ANGLE_90 || rotation == ROTATION_ANGLE_270)
2820                 input.scan = SCAN_DIRECTION_VERTICAL;
2821
2822         if (!dc->cap_funcs.get_dcc_compression_cap(dc, &input, &output))
2823                 return -EINVAL;
2824
2825         if (!output.capable)
2826                 return -EINVAL;
2827
2828         if (i64b == 0 && output.grph.rgb.independent_64b_blks != 0)
2829                 return -EINVAL;
2830
2831         dcc->enable = 1;
2832         dcc->meta_pitch =
2833                 AMDGPU_TILING_GET(info, DCC_PITCH_MAX) + 1;
2834         dcc->independent_64b_blks = i64b;
2835
2836         dcc_address = get_dcc_address(afb->address, info);
2837         address->grph.meta_addr.low_part = lower_32_bits(dcc_address);
2838         address->grph.meta_addr.high_part = upper_32_bits(dcc_address);
2839
2840         return 0;
2841 }
2842
2843 static int
2844 fill_plane_buffer_attributes(struct amdgpu_device *adev,
2845                              const struct amdgpu_framebuffer *afb,
2846                              const enum surface_pixel_format format,
2847                              const enum dc_rotation_angle rotation,
2848                              const uint64_t tiling_flags,
2849                              union dc_tiling_info *tiling_info,
2850                              struct plane_size *plane_size,
2851                              struct dc_plane_dcc_param *dcc,
2852                              struct dc_plane_address *address)
2853 {
2854         const struct drm_framebuffer *fb = &afb->base;
2855         int ret;
2856
2857         memset(tiling_info, 0, sizeof(*tiling_info));
2858         memset(plane_size, 0, sizeof(*plane_size));
2859         memset(dcc, 0, sizeof(*dcc));
2860         memset(address, 0, sizeof(*address));
2861
2862         if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN) {
2863                 plane_size->surface_size.x = 0;
2864                 plane_size->surface_size.y = 0;
2865                 plane_size->surface_size.width = fb->width;
2866                 plane_size->surface_size.height = fb->height;
2867                 plane_size->surface_pitch =
2868                         fb->pitches[0] / fb->format->cpp[0];
2869
2870                 address->type = PLN_ADDR_TYPE_GRAPHICS;
2871                 address->grph.addr.low_part = lower_32_bits(afb->address);
2872                 address->grph.addr.high_part = upper_32_bits(afb->address);
2873         } else if (format < SURFACE_PIXEL_FORMAT_INVALID) {
2874                 uint64_t chroma_addr = afb->address + fb->offsets[1];
2875
2876                 plane_size->surface_size.x = 0;
2877                 plane_size->surface_size.y = 0;
2878                 plane_size->surface_size.width = fb->width;
2879                 plane_size->surface_size.height = fb->height;
2880                 plane_size->surface_pitch =
2881                         fb->pitches[0] / fb->format->cpp[0];
2882
2883                 plane_size->chroma_size.x = 0;
2884                 plane_size->chroma_size.y = 0;
2885                 /* TODO: set these based on surface format */
2886                 plane_size->chroma_size.width = fb->width / 2;
2887                 plane_size->chroma_size.height = fb->height / 2;
2888
2889                 plane_size->chroma_pitch =
2890                         fb->pitches[1] / fb->format->cpp[1];
2891
2892                 address->type = PLN_ADDR_TYPE_VIDEO_PROGRESSIVE;
2893                 address->video_progressive.luma_addr.low_part =
2894                         lower_32_bits(afb->address);
2895                 address->video_progressive.luma_addr.high_part =
2896                         upper_32_bits(afb->address);
2897                 address->video_progressive.chroma_addr.low_part =
2898                         lower_32_bits(chroma_addr);
2899                 address->video_progressive.chroma_addr.high_part =
2900                         upper_32_bits(chroma_addr);
2901         }
2902
2903         /* Fill GFX8 params */
2904         if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE) == DC_ARRAY_2D_TILED_THIN1) {
2905                 unsigned int bankw, bankh, mtaspect, tile_split, num_banks;
2906
2907                 bankw = AMDGPU_TILING_GET(tiling_flags, BANK_WIDTH);
2908                 bankh = AMDGPU_TILING_GET(tiling_flags, BANK_HEIGHT);
2909                 mtaspect = AMDGPU_TILING_GET(tiling_flags, MACRO_TILE_ASPECT);
2910                 tile_split = AMDGPU_TILING_GET(tiling_flags, TILE_SPLIT);
2911                 num_banks = AMDGPU_TILING_GET(tiling_flags, NUM_BANKS);
2912
2913                 /* XXX fix me for VI */
2914                 tiling_info->gfx8.num_banks = num_banks;
2915                 tiling_info->gfx8.array_mode =
2916                                 DC_ARRAY_2D_TILED_THIN1;
2917                 tiling_info->gfx8.tile_split = tile_split;
2918                 tiling_info->gfx8.bank_width = bankw;
2919                 tiling_info->gfx8.bank_height = bankh;
2920                 tiling_info->gfx8.tile_aspect = mtaspect;
2921                 tiling_info->gfx8.tile_mode =
2922                                 DC_ADDR_SURF_MICRO_TILING_DISPLAY;
2923         } else if (AMDGPU_TILING_GET(tiling_flags, ARRAY_MODE)
2924                         == DC_ARRAY_1D_TILED_THIN1) {
2925                 tiling_info->gfx8.array_mode = DC_ARRAY_1D_TILED_THIN1;
2926         }
2927
2928         tiling_info->gfx8.pipe_config =
2929                         AMDGPU_TILING_GET(tiling_flags, PIPE_CONFIG);
2930
2931         if (adev->asic_type == CHIP_VEGA10 ||
2932             adev->asic_type == CHIP_VEGA12 ||
2933             adev->asic_type == CHIP_VEGA20 ||
2934 #if defined(CONFIG_DRM_AMD_DC_DCN2_0)
2935             adev->asic_type == CHIP_NAVI10 ||
2936             adev->asic_type == CHIP_NAVI14 ||
2937             adev->asic_type == CHIP_NAVI12 ||
2938 #endif
2939 #if defined(CONFIG_DRM_AMD_DC_DCN2_1)
2940             adev->asic_type == CHIP_RENOIR ||
2941 #endif
2942             adev->asic_type == CHIP_RAVEN) {
2943                 /* Fill GFX9 params */
2944                 tiling_info->gfx9.num_pipes =
2945                         adev->gfx.config.gb_addr_config_fields.num_pipes;
2946                 tiling_info->gfx9.num_banks =
2947                         adev->gfx.config.gb_addr_config_fields.num_banks;
2948                 tiling_info->gfx9.pipe_interleave =
2949                         adev->gfx.config.gb_addr_config_fields.pipe_interleave_size;
2950                 tiling_info->gfx9.num_shader_engines =
2951                         adev->gfx.config.gb_addr_config_fields.num_se;
2952                 tiling_info->gfx9.max_compressed_frags =
2953                         adev->gfx.config.gb_addr_config_fields.max_compress_frags;
2954                 tiling_info->gfx9.num_rb_per_se =
2955                         adev->gfx.config.gb_addr_config_fields.num_rb_per_se;
2956                 tiling_info->gfx9.swizzle =
2957                         AMDGPU_TILING_GET(tiling_flags, SWIZZLE_MODE);
2958                 tiling_info->gfx9.shaderEnable = 1;
2959
2960                 ret = fill_plane_dcc_attributes(adev, afb, format, rotation,
2961                                                 plane_size, tiling_info,
2962                                                 tiling_flags, dcc, address);
2963                 if (ret)
2964                         return ret;
2965         }
2966
2967         return 0;
2968 }
2969
2970 static void
2971 fill_blending_from_plane_state(const struct drm_plane_state *plane_state,
2972                                bool *per_pixel_alpha, bool *global_alpha,
2973                                int *global_alpha_value)
2974 {
2975         *per_pixel_alpha = false;
2976         *global_alpha = false;
2977         *global_alpha_value = 0xff;
2978
2979         if (plane_state->plane->type != DRM_PLANE_TYPE_OVERLAY)
2980                 return;
2981
2982         if (plane_state->pixel_blend_mode == DRM_MODE_BLEND_PREMULTI) {
2983                 static const uint32_t alpha_formats[] = {
2984                         DRM_FORMAT_ARGB8888,
2985                         DRM_FORMAT_RGBA8888,
2986                         DRM_FORMAT_ABGR8888,
2987                 };
2988                 uint32_t format = plane_state->fb->format->format;
2989                 unsigned int i;
2990
2991                 for (i = 0; i < ARRAY_SIZE(alpha_formats); ++i) {
2992                         if (format == alpha_formats[i]) {
2993                                 *per_pixel_alpha = true;
2994                                 break;
2995                         }
2996                 }
2997         }
2998
2999         if (plane_state->alpha < 0xffff) {
3000                 *global_alpha = true;
3001                 *global_alpha_value = plane_state->alpha >> 8;
3002         }
3003 }
3004
3005 static int
3006 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
3007                             const enum surface_pixel_format format,
3008                             enum dc_color_space *color_space)
3009 {
3010         bool full_range;
3011
3012         *color_space = COLOR_SPACE_SRGB;
3013
3014         /* DRM color properties only affect non-RGB formats. */
3015         if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
3016                 return 0;
3017
3018         full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
3019
3020         switch (plane_state->color_encoding) {
3021         case DRM_COLOR_YCBCR_BT601:
3022                 if (full_range)
3023                         *color_space = COLOR_SPACE_YCBCR601;
3024                 else
3025                         *color_space = COLOR_SPACE_YCBCR601_LIMITED;
3026                 break;
3027
3028         case DRM_COLOR_YCBCR_BT709:
3029                 if (full_range)
3030                         *color_space = COLOR_SPACE_YCBCR709;
3031                 else
3032                         *color_space = COLOR_SPACE_YCBCR709_LIMITED;
3033                 break;
3034
3035         case DRM_COLOR_YCBCR_BT2020:
3036                 if (full_range)
3037                         *color_space = COLOR_SPACE_2020_YCBCR;
3038                 else
3039                         return -EINVAL;
3040                 break;
3041
3042         default:
3043                 return -EINVAL;
3044         }
3045
3046         return 0;
3047 }
3048
3049 static int
3050 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
3051                             const struct drm_plane_state *plane_state,
3052                             const uint64_t tiling_flags,
3053                             struct dc_plane_info *plane_info,
3054                             struct dc_plane_address *address)
3055 {
3056         const struct drm_framebuffer *fb = plane_state->fb;
3057         const struct amdgpu_framebuffer *afb =
3058                 to_amdgpu_framebuffer(plane_state->fb);
3059         struct drm_format_name_buf format_name;
3060         int ret;
3061
3062         memset(plane_info, 0, sizeof(*plane_info));
3063
3064         switch (fb->format->format) {
3065         case DRM_FORMAT_C8:
3066                 plane_info->format =
3067                         SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
3068                 break;
3069         case DRM_FORMAT_RGB565:
3070                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
3071                 break;
3072         case DRM_FORMAT_XRGB8888:
3073         case DRM_FORMAT_ARGB8888:
3074                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
3075                 break;
3076         case DRM_FORMAT_XRGB2101010:
3077         case DRM_FORMAT_ARGB2101010:
3078                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
3079                 break;
3080         case DRM_FORMAT_XBGR2101010:
3081         case DRM_FORMAT_ABGR2101010:
3082                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
3083                 break;
3084         case DRM_FORMAT_XBGR8888:
3085         case DRM_FORMAT_ABGR8888:
3086                 plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
3087                 break;
3088         case DRM_FORMAT_NV21:
3089                 plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
3090                 break;
3091         case DRM_FORMAT_NV12:
3092                 plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
3093                 break;
3094         default:
3095                 DRM_ERROR(
3096                         "Unsupported screen format %s\n",
3097                         drm_get_format_name(fb->format->format, &format_name));
3098                 return -EINVAL;
3099         }
3100
3101         switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
3102         case DRM_MODE_ROTATE_0:
3103                 plane_info->rotation = ROTATION_ANGLE_0;
3104                 break;
3105         case DRM_MODE_ROTATE_90:
3106                 plane_info->rotation = ROTATION_ANGLE_90;
3107                 break;
3108         case DRM_MODE_ROTATE_180:
3109                 plane_info->rotation = ROTATION_ANGLE_180;
3110                 break;
3111         case DRM_MODE_ROTATE_270:
3112                 plane_info->rotation = ROTATION_ANGLE_270;
3113                 break;
3114         default:
3115                 plane_info->rotation = ROTATION_ANGLE_0;
3116                 break;
3117         }
3118
3119         plane_info->visible = true;
3120         plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
3121
3122         plane_info->layer_index = 0;
3123
3124         ret = fill_plane_color_attributes(plane_state, plane_info->format,
3125                                           &plane_info->color_space);
3126         if (ret)
3127                 return ret;
3128
3129         ret = fill_plane_buffer_attributes(adev, afb, plane_info->format,
3130                                            plane_info->rotation, tiling_flags,
3131                                            &plane_info->tiling_info,
3132                                            &plane_info->plane_size,
3133                                            &plane_info->dcc, address);
3134         if (ret)
3135                 return ret;
3136
3137         fill_blending_from_plane_state(
3138                 plane_state, &plane_info->per_pixel_alpha,
3139                 &plane_info->global_alpha, &plane_info->global_alpha_value);
3140
3141         return 0;
3142 }
3143
3144 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
3145                                     struct dc_plane_state *dc_plane_state,
3146                                     struct drm_plane_state *plane_state,
3147                                     struct drm_crtc_state *crtc_state)
3148 {
3149         struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
3150         const struct amdgpu_framebuffer *amdgpu_fb =
3151                 to_amdgpu_framebuffer(plane_state->fb);
3152         struct dc_scaling_info scaling_info;
3153         struct dc_plane_info plane_info;
3154         uint64_t tiling_flags;
3155         int ret;
3156
3157         ret = fill_dc_scaling_info(plane_state, &scaling_info);
3158         if (ret)
3159                 return ret;
3160
3161         dc_plane_state->src_rect = scaling_info.src_rect;
3162         dc_plane_state->dst_rect = scaling_info.dst_rect;
3163         dc_plane_state->clip_rect = scaling_info.clip_rect;
3164         dc_plane_state->scaling_quality = scaling_info.scaling_quality;
3165
3166         ret = get_fb_info(amdgpu_fb, &tiling_flags);
3167         if (ret)
3168                 return ret;
3169
3170         ret = fill_dc_plane_info_and_addr(adev, plane_state, tiling_flags,
3171                                           &plane_info,
3172                                           &dc_plane_state->address);
3173         if (ret)
3174                 return ret;
3175
3176         dc_plane_state->format = plane_info.format;
3177         dc_plane_state->color_space = plane_info.color_space;
3178         dc_plane_state->format = plane_info.format;
3179         dc_plane_state->plane_size = plane_info.plane_size;
3180         dc_plane_state->rotation = plane_info.rotation;
3181         dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
3182         dc_plane_state->stereo_format = plane_info.stereo_format;
3183         dc_plane_state->tiling_info = plane_info.tiling_info;
3184         dc_plane_state->visible = plane_info.visible;
3185         dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
3186         dc_plane_state->global_alpha = plane_info.global_alpha;
3187         dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
3188         dc_plane_state->dcc = plane_info.dcc;
3189         dc_plane_state->layer_index = plane_info.layer_index; // Always returns 0
3190
3191         /*
3192          * Always set input transfer function, since plane state is refreshed
3193          * every time.
3194          */
3195         ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state, dc_plane_state);
3196         if (ret)
3197                 return ret;
3198
3199         return 0;
3200 }
3201
3202 static void update_stream_scaling_settings(const struct drm_display_mode *mode,
3203                                            const struct dm_connector_state *dm_state,
3204                                            struct dc_stream_state *stream)
3205 {
3206         enum amdgpu_rmx_type rmx_type;
3207
3208         struct rect src = { 0 }; /* viewport in composition space*/
3209         struct rect dst = { 0 }; /* stream addressable area */
3210
3211         /* no mode. nothing to be done */
3212         if (!mode)
3213                 return;
3214
3215         /* Full screen scaling by default */
3216         src.width = mode->hdisplay;
3217         src.height = mode->vdisplay;
3218         dst.width = stream->timing.h_addressable;
3219         dst.height = stream->timing.v_addressable;
3220
3221         if (dm_state) {
3222                 rmx_type = dm_state->scaling;
3223                 if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
3224                         if (src.width * dst.height <
3225                                         src.height * dst.width) {
3226                                 /* height needs less upscaling/more downscaling */
3227                                 dst.width = src.width *
3228                                                 dst.height / src.height;
3229                         } else {
3230                                 /* width needs less upscaling/more downscaling */
3231                                 dst.height = src.height *
3232                                                 dst.width / src.width;
3233                         }
3234                 } else if (rmx_type == RMX_CENTER) {
3235                         dst = src;
3236                 }
3237
3238                 dst.x = (stream->timing.h_addressable - dst.width) / 2;
3239                 dst.y = (stream->timing.v_addressable - dst.height) / 2;
3240
3241                 if (dm_state->underscan_enable) {
3242                         dst.x += dm_state->underscan_hborder / 2;
3243                         dst.y += dm_state->underscan_vborder / 2;
3244                         dst.width -= dm_state->underscan_hborder;
3245                         dst.height -= dm_state->underscan_vborder;
3246                 }
3247         }
3248
3249         stream->src = src;
3250         stream->dst = dst;
3251
3252         DRM_DEBUG_DRIVER("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
3253                         dst.x, dst.y, dst.width, dst.height);
3254
3255 }
3256
3257 static enum dc_color_depth
3258 convert_color_depth_from_display_info(const struct drm_connector *connector,
3259                                       const struct drm_connector_state *state)
3260 {
3261         uint8_t bpc = (uint8_t)connector->display_info.bpc;
3262
3263         /* Assume 8 bpc by default if no bpc is specified. */
3264         bpc = bpc ? bpc : 8;
3265
3266         if (!state)
3267                 state = connector->state;
3268
3269         if (state) {
3270                 /*
3271                  * Cap display bpc based on the user requested value.
3272                  *
3273                  * The value for state->max_bpc may not correctly updated
3274                  * depending on when the connector gets added to the state
3275                  * or if this was called outside of atomic check, so it
3276                  * can't be used directly.
3277                  */
3278                 bpc = min(bpc, state->max_requested_bpc);
3279
3280                 /* Round down to the nearest even number. */
3281                 bpc = bpc - (bpc & 1);
3282         }
3283
3284         switch (bpc) {
3285         case 0:
3286                 /*
3287                  * Temporary Work around, DRM doesn't parse color depth for
3288                  * EDID revision before 1.4
3289                  * TODO: Fix edid parsing
3290                  */
3291                 return COLOR_DEPTH_888;
3292         case 6:
3293                 return COLOR_DEPTH_666;
3294         case 8:
3295                 return COLOR_DEPTH_888;
3296         case 10:
3297                 return COLOR_DEPTH_101010;
3298         case 12:
3299                 return COLOR_DEPTH_121212;
3300         case 14:
3301                 return COLOR_DEPTH_141414;
3302         case 16:
3303                 return COLOR_DEPTH_161616;
3304         default:
3305                 return COLOR_DEPTH_UNDEFINED;
3306         }
3307 }
3308
3309 static enum dc_aspect_ratio
3310 get_aspect_ratio(const struct drm_display_mode *mode_in)
3311 {
3312         /* 1-1 mapping, since both enums follow the HDMI spec. */
3313         return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
3314 }
3315
3316 static enum dc_color_space
3317 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing)
3318 {
3319         enum dc_color_space color_space = COLOR_SPACE_SRGB;
3320
3321         switch (dc_crtc_timing->pixel_encoding) {
3322         case PIXEL_ENCODING_YCBCR422:
3323         case PIXEL_ENCODING_YCBCR444:
3324         case PIXEL_ENCODING_YCBCR420:
3325         {
3326                 /*
3327                  * 27030khz is the separation point between HDTV and SDTV
3328                  * according to HDMI spec, we use YCbCr709 and YCbCr601
3329                  * respectively
3330                  */
3331                 if (dc_crtc_timing->pix_clk_100hz > 270300) {
3332                         if (dc_crtc_timing->flags.Y_ONLY)
3333                                 color_space =
3334                                         COLOR_SPACE_YCBCR709_LIMITED;
3335                         else
3336                                 color_space = COLOR_SPACE_YCBCR709;
3337                 } else {
3338                         if (dc_crtc_timing->flags.Y_ONLY)
3339                                 color_space =
3340                                         COLOR_SPACE_YCBCR601_LIMITED;
3341                         else
3342                                 color_space = COLOR_SPACE_YCBCR601;
3343                 }
3344
3345         }
3346         break;
3347         case PIXEL_ENCODING_RGB:
3348                 color_space = COLOR_SPACE_SRGB;
3349                 break;
3350
3351         default:
3352                 WARN_ON(1);
3353                 break;
3354         }
3355
3356         return color_space;
3357 }
3358
3359 static void reduce_mode_colour_depth(struct dc_crtc_timing *timing_out)
3360 {
3361         if (timing_out->display_color_depth <= COLOR_DEPTH_888)
3362                 return;
3363
3364         timing_out->display_color_depth--;
3365 }
3366
3367 static void adjust_colour_depth_from_display_info(struct dc_crtc_timing *timing_out,
3368                                                 const struct drm_display_info *info)
3369 {
3370         int normalized_clk;
3371         if (timing_out->display_color_depth <= COLOR_DEPTH_888)
3372                 return;
3373         do {
3374                 normalized_clk = timing_out->pix_clk_100hz / 10;
3375                 /* YCbCr 4:2:0 requires additional adjustment of 1/2 */
3376                 if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
3377                         normalized_clk /= 2;
3378                 /* Adjusting pix clock following on HDMI spec based on colour depth */
3379                 switch (timing_out->display_color_depth) {
3380                 case COLOR_DEPTH_101010:
3381                         normalized_clk = (normalized_clk * 30) / 24;
3382                         break;
3383                 case COLOR_DEPTH_121212:
3384                         normalized_clk = (normalized_clk * 36) / 24;
3385                         break;
3386                 case COLOR_DEPTH_161616:
3387                         normalized_clk = (normalized_clk * 48) / 24;
3388                         break;
3389                 default:
3390                         return;
3391                 }
3392                 if (normalized_clk <= info->max_tmds_clock)
3393                         return;
3394                 reduce_mode_colour_depth(timing_out);
3395
3396         } while (timing_out->display_color_depth > COLOR_DEPTH_888);
3397
3398 }
3399
3400 static void fill_stream_properties_from_drm_display_mode(
3401         struct dc_stream_state *stream,
3402         const struct drm_display_mode *mode_in,
3403         const struct drm_connector *connector,
3404         const struct drm_connector_state *connector_state,
3405         const struct dc_stream_state *old_stream)
3406 {
3407         struct dc_crtc_timing *timing_out = &stream->timing;
3408         const struct drm_display_info *info = &connector->display_info;
3409         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3410         struct hdmi_vendor_infoframe hv_frame;
3411         struct hdmi_avi_infoframe avi_frame;
3412
3413         memset(&hv_frame, 0, sizeof(hv_frame));
3414         memset(&avi_frame, 0, sizeof(avi_frame));
3415
3416         timing_out->h_border_left = 0;
3417         timing_out->h_border_right = 0;
3418         timing_out->v_border_top = 0;
3419         timing_out->v_border_bottom = 0;
3420         /* TODO: un-hardcode */
3421         if (drm_mode_is_420_only(info, mode_in)
3422                         && stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
3423                 timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
3424         else if (drm_mode_is_420_also(info, mode_in)
3425                         && aconnector->force_yuv420_output)
3426                 timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
3427         else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCRCB444)
3428                         && stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
3429                 timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
3430         else
3431                 timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
3432
3433         timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
3434         timing_out->display_color_depth = convert_color_depth_from_display_info(
3435                 connector, connector_state);
3436         timing_out->scan_type = SCANNING_TYPE_NODATA;
3437         timing_out->hdmi_vic = 0;
3438
3439         if(old_stream) {
3440                 timing_out->vic = old_stream->timing.vic;
3441                 timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
3442                 timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
3443         } else {
3444                 timing_out->vic = drm_match_cea_mode(mode_in);
3445                 if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
3446                         timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
3447                 if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
3448                         timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
3449         }
3450
3451         if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
3452                 drm_hdmi_avi_infoframe_from_display_mode(&avi_frame, (struct drm_connector *)connector, mode_in);
3453                 timing_out->vic = avi_frame.video_code;
3454                 drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame, (struct drm_connector *)connector, mode_in);
3455                 timing_out->hdmi_vic = hv_frame.vic;
3456         }
3457
3458         timing_out->h_addressable = mode_in->crtc_hdisplay;
3459         timing_out->h_total = mode_in->crtc_htotal;
3460         timing_out->h_sync_width =
3461                 mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
3462         timing_out->h_front_porch =
3463                 mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
3464         timing_out->v_total = mode_in->crtc_vtotal;
3465         timing_out->v_addressable = mode_in->crtc_vdisplay;
3466         timing_out->v_front_porch =
3467                 mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
3468         timing_out->v_sync_width =
3469                 mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
3470         timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
3471         timing_out->aspect_ratio = get_aspect_ratio(mode_in);
3472
3473         stream->output_color_space = get_output_color_space(timing_out);
3474
3475         stream->out_transfer_func->type = TF_TYPE_PREDEFINED;
3476         stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
3477         if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
3478                 adjust_colour_depth_from_display_info(timing_out, info);
3479 }
3480
3481 static void fill_audio_info(struct audio_info *audio_info,
3482                             const struct drm_connector *drm_connector,
3483                             const struct dc_sink *dc_sink)
3484 {
3485         int i = 0;
3486         int cea_revision = 0;
3487         const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
3488
3489         audio_info->manufacture_id = edid_caps->manufacturer_id;
3490         audio_info->product_id = edid_caps->product_id;
3491
3492         cea_revision = drm_connector->display_info.cea_rev;
3493
3494         strscpy(audio_info->display_name,
3495                 edid_caps->display_name,
3496                 AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
3497
3498         if (cea_revision >= 3) {
3499                 audio_info->mode_count = edid_caps->audio_mode_count;
3500
3501                 for (i = 0; i < audio_info->mode_count; ++i) {
3502                         audio_info->modes[i].format_code =
3503                                         (enum audio_format_code)
3504                                         (edid_caps->audio_modes[i].format_code);
3505                         audio_info->modes[i].channel_count =
3506                                         edid_caps->audio_modes[i].channel_count;
3507                         audio_info->modes[i].sample_rates.all =
3508                                         edid_caps->audio_modes[i].sample_rate;
3509                         audio_info->modes[i].sample_size =
3510                                         edid_caps->audio_modes[i].sample_size;
3511                 }
3512         }
3513
3514         audio_info->flags.all = edid_caps->speaker_flags;
3515
3516         /* TODO: We only check for the progressive mode, check for interlace mode too */
3517         if (drm_connector->latency_present[0]) {
3518                 audio_info->video_latency = drm_connector->video_latency[0];
3519                 audio_info->audio_latency = drm_connector->audio_latency[0];
3520         }
3521
3522         /* TODO: For DP, video and audio latency should be calculated from DPCD caps */
3523
3524 }
3525
3526 static void
3527 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
3528                                       struct drm_display_mode *dst_mode)
3529 {
3530         dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
3531         dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
3532         dst_mode->crtc_clock = src_mode->crtc_clock;
3533         dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
3534         dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
3535         dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
3536         dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
3537         dst_mode->crtc_htotal = src_mode->crtc_htotal;
3538         dst_mode->crtc_hskew = src_mode->crtc_hskew;
3539         dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
3540         dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
3541         dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
3542         dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
3543         dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
3544 }
3545
3546 static void
3547 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
3548                                         const struct drm_display_mode *native_mode,
3549                                         bool scale_enabled)
3550 {
3551         if (scale_enabled) {
3552                 copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
3553         } else if (native_mode->clock == drm_mode->clock &&
3554                         native_mode->htotal == drm_mode->htotal &&
3555                         native_mode->vtotal == drm_mode->vtotal) {
3556                 copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
3557         } else {
3558                 /* no scaling nor amdgpu inserted, no need to patch */
3559         }
3560 }
3561
3562 static struct dc_sink *
3563 create_fake_sink(struct amdgpu_dm_connector *aconnector)
3564 {
3565         struct dc_sink_init_data sink_init_data = { 0 };
3566         struct dc_sink *sink = NULL;
3567         sink_init_data.link = aconnector->dc_link;
3568         sink_init_data.sink_signal = aconnector->dc_link->connector_signal;
3569
3570         sink = dc_sink_create(&sink_init_data);
3571         if (!sink) {
3572                 DRM_ERROR("Failed to create sink!\n");
3573                 return NULL;
3574         }
3575         sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
3576
3577         return sink;
3578 }
3579
3580 static void set_multisync_trigger_params(
3581                 struct dc_stream_state *stream)
3582 {
3583         if (stream->triggered_crtc_reset.enabled) {
3584                 stream->triggered_crtc_reset.event = CRTC_EVENT_VSYNC_RISING;
3585                 stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_LINE;
3586         }
3587 }
3588
3589 static void set_master_stream(struct dc_stream_state *stream_set[],
3590                               int stream_count)
3591 {
3592         int j, highest_rfr = 0, master_stream = 0;
3593
3594         for (j = 0;  j < stream_count; j++) {
3595                 if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
3596                         int refresh_rate = 0;
3597
3598                         refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
3599                                 (stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
3600                         if (refresh_rate > highest_rfr) {
3601                                 highest_rfr = refresh_rate;
3602                                 master_stream = j;
3603                         }
3604                 }
3605         }
3606         for (j = 0;  j < stream_count; j++) {
3607                 if (stream_set[j])
3608                         stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
3609         }
3610 }
3611
3612 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
3613 {
3614         int i = 0;
3615
3616         if (context->stream_count < 2)
3617                 return;
3618         for (i = 0; i < context->stream_count ; i++) {
3619                 if (!context->streams[i])
3620                         continue;
3621                 /*
3622                  * TODO: add a function to read AMD VSDB bits and set
3623                  * crtc_sync_master.multi_sync_enabled flag
3624                  * For now it's set to false
3625                  */
3626                 set_multisync_trigger_params(context->streams[i]);
3627         }
3628         set_master_stream(context->streams, context->stream_count);
3629 }
3630
3631 static struct dc_stream_state *
3632 create_stream_for_sink(struct amdgpu_dm_connector *aconnector,
3633                        const struct drm_display_mode *drm_mode,
3634                        const struct dm_connector_state *dm_state,
3635                        const struct dc_stream_state *old_stream)
3636 {
3637         struct drm_display_mode *preferred_mode = NULL;
3638         struct drm_connector *drm_connector;
3639         const struct drm_connector_state *con_state =
3640                 dm_state ? &dm_state->base : NULL;
3641         struct dc_stream_state *stream = NULL;
3642         struct drm_display_mode mode = *drm_mode;
3643         bool native_mode_found = false;
3644         bool scale = dm_state ? (dm_state->scaling != RMX_OFF) : false;
3645         int mode_refresh;
3646         int preferred_refresh = 0;
3647 #ifdef CONFIG_DRM_AMD_DC_DSC_SUPPORT
3648         struct dsc_dec_dpcd_caps dsc_caps;
3649         uint32_t link_bandwidth_kbps;
3650 #endif
3651
3652         struct dc_sink *sink = NULL;
3653         if (aconnector == NULL) {
3654                 DRM_ERROR("aconnector is NULL!\n");
3655                 return stream;
3656         }
3657
3658         drm_connector = &aconnector->base;
3659
3660         if (!aconnector->dc_sink) {
3661                 sink = create_fake_sink(aconnector);
3662                 if (!sink)
3663                         return stream;
3664         } else {
3665                 sink = aconnector->dc_sink;
3666                 dc_sink_retain(sink);
3667         }
3668
3669         stream = dc_create_stream_for_sink(sink);
3670
3671         if (stream == NULL) {
3672                 DRM_ERROR("Failed to create stream for sink!\n");
3673                 goto finish;
3674         }
3675
3676         stream->dm_stream_context = aconnector;
3677
3678         stream->timing.flags.LTE_340MCSC_SCRAMBLE =
3679                 drm_connector->display_info.hdmi.scdc.scrambling.low_rates;
3680
3681         list_for_each_entry(preferred_mode, &aconnector->base.modes, head) {
3682                 /* Search for preferred mode */
3683                 if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
3684                         native_mode_found = true;
3685                         break;
3686                 }
3687         }
3688         if (!native_mode_found)
3689                 preferred_mode = list_first_entry_or_null(
3690                                 &aconnector->base.modes,
3691                                 struct drm_display_mode,
3692                                 head);
3693
3694         mode_refresh = drm_mode_vrefresh(&mode);
3695
3696         if (preferred_mode == NULL) {
3697                 /*
3698                  * This may not be an error, the use case is when we have no
3699                  * usermode calls to reset and set mode upon hotplug. In this
3700                  * case, we call set mode ourselves to restore the previous mode
3701                  * and the modelist may not be filled in in time.
3702                  */
3703                 DRM_DEBUG_DRIVER("No preferred mode found\n");
3704         } else {
3705                 decide_crtc_timing_for_drm_display_mode(
3706                                 &mode, preferred_mode,
3707                                 dm_state ? (dm_state->scaling != RMX_OFF) : false);
3708                 preferred_refresh = drm_mode_vrefresh(preferred_mode);
3709         }
3710
3711         if (!dm_state)
3712                 drm_mode_set_crtcinfo(&mode, 0);
3713
3714         /*
3715         * If scaling is enabled and refresh rate didn't change
3716         * we copy the vic and polarities of the old timings
3717         */
3718         if (!scale || mode_refresh != preferred_refresh)
3719                 fill_stream_properties_from_drm_display_mode(stream,
3720                         &mode, &aconnector->base, con_state, NULL);
3721         else
3722                 fill_stream_properties_from_drm_display_mode(stream,
3723                         &mode, &aconnector->base, con_state, old_stream);
3724
3725 #ifdef CONFIG_DRM_AMD_DC_DSC_SUPPORT
3726         stream->timing.flags.DSC = 0;
3727
3728         if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
3729                 dc_dsc_parse_dsc_dpcd(aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
3730                                       aconnector->dc_link->dpcd_caps.dsc_caps.dsc_ext_caps.raw,
3731                                       &dsc_caps);
3732                 link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
3733                                                              dc_link_get_link_cap(aconnector->dc_link));
3734
3735                 if (dsc_caps.is_dsc_supported)
3736                         if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
3737                                                   &dsc_caps,
3738                                                   aconnector->dc_link->ctx->dc->debug.dsc_min_slice_height_override,
3739                                                   link_bandwidth_kbps,
3740                                                   &stream->timing,
3741                                                   &stream->timing.dsc_cfg))
3742                                 stream->timing.flags.DSC = 1;
3743         }
3744 #endif
3745
3746         update_stream_scaling_settings(&mode, dm_state, stream);
3747
3748         fill_audio_info(
3749                 &stream->audio_info,
3750                 drm_connector,
3751                 sink);
3752
3753         update_stream_signal(stream, sink);
3754
3755         if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
3756                 mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket, false, false);
3757         if (stream->link->psr_feature_enabled)  {
3758                 struct dc  *core_dc = stream->link->ctx->dc;
3759
3760                 if (dc_is_dmcu_initialized(core_dc)) {
3761                         struct dmcu *dmcu = core_dc->res_pool->dmcu;
3762
3763                         stream->psr_version = dmcu->dmcu_version.psr_version;
3764                         mod_build_vsc_infopacket(stream, &stream->vsc_infopacket);
3765                 }
3766         }
3767 finish:
3768         dc_sink_release(sink);
3769
3770         return stream;
3771 }
3772
3773 static void amdgpu_dm_crtc_destroy(struct drm_crtc *crtc)
3774 {
3775         drm_crtc_cleanup(crtc);
3776         kfree(crtc);
3777 }
3778
3779 static void dm_crtc_destroy_state(struct drm_crtc *crtc,
3780                                   struct drm_crtc_state *state)
3781 {
3782         struct dm_crtc_state *cur = to_dm_crtc_state(state);
3783
3784         /* TODO Destroy dc_stream objects are stream object is flattened */
3785         if (cur->stream)
3786                 dc_stream_release(cur->stream);
3787
3788
3789         __drm_atomic_helper_crtc_destroy_state(state);
3790
3791
3792         kfree(state);
3793 }
3794
3795 static void dm_crtc_reset_state(struct drm_crtc *crtc)
3796 {
3797         struct dm_crtc_state *state;
3798
3799         if (crtc->state)
3800                 dm_crtc_destroy_state(crtc, crtc->state);
3801
3802         state = kzalloc(sizeof(*state), GFP_KERNEL);
3803         if (WARN_ON(!state))
3804                 return;
3805
3806         crtc->state = &state->base;
3807         crtc->state->crtc = crtc;
3808
3809 }
3810
3811 static struct drm_crtc_state *
3812 dm_crtc_duplicate_state(struct drm_crtc *crtc)
3813 {
3814         struct dm_crtc_state *state, *cur;
3815
3816         cur = to_dm_crtc_state(crtc->state);
3817
3818         if (WARN_ON(!crtc->state))
3819                 return NULL;
3820
3821         state = kzalloc(sizeof(*state), GFP_KERNEL);
3822         if (!state)
3823                 return NULL;
3824
3825         __drm_atomic_helper_crtc_duplicate_state(crtc, &state->base);
3826
3827         if (cur->stream) {
3828                 state->stream = cur->stream;
3829                 dc_stream_retain(state->stream);
3830         }
3831
3832         state->active_planes = cur->active_planes;
3833         state->interrupts_enabled = cur->interrupts_enabled;
3834         state->vrr_params = cur->vrr_params;
3835         state->vrr_infopacket = cur->vrr_infopacket;
3836         state->abm_level = cur->abm_level;
3837         state->vrr_supported = cur->vrr_supported;
3838         state->freesync_config = cur->freesync_config;
3839         state->crc_src = cur->crc_src;
3840         state->cm_has_degamma = cur->cm_has_degamma;
3841         state->cm_is_degamma_srgb = cur->cm_is_degamma_srgb;
3842
3843         /* TODO Duplicate dc_stream after objects are stream object is flattened */
3844
3845         return &state->base;
3846 }
3847
3848 static inline int dm_set_vupdate_irq(struct drm_crtc *crtc, bool enable)
3849 {
3850         enum dc_irq_source irq_source;
3851         struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
3852         struct amdgpu_device *adev = crtc->dev->dev_private;
3853         int rc;
3854
3855         irq_source = IRQ_TYPE_VUPDATE + acrtc->otg_inst;
3856
3857         rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3858
3859         DRM_DEBUG_DRIVER("crtc %d - vupdate irq %sabling: r=%d\n",
3860                          acrtc->crtc_id, enable ? "en" : "dis", rc);
3861         return rc;
3862 }
3863
3864 static inline int dm_set_vblank(struct drm_crtc *crtc, bool enable)
3865 {
3866         enum dc_irq_source irq_source;
3867         struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
3868         struct amdgpu_device *adev = crtc->dev->dev_private;
3869         struct dm_crtc_state *acrtc_state = to_dm_crtc_state(crtc->state);
3870         int rc = 0;
3871
3872         if (enable) {
3873                 /* vblank irq on -> Only need vupdate irq in vrr mode */
3874                 if (amdgpu_dm_vrr_active(acrtc_state))
3875                         rc = dm_set_vupdate_irq(crtc, true);
3876         } else {
3877                 /* vblank irq off -> vupdate irq off */
3878                 rc = dm_set_vupdate_irq(crtc, false);
3879         }
3880
3881         if (rc)
3882                 return rc;
3883
3884         irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3885         return dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3886 }
3887
3888 static int dm_enable_vblank(struct drm_crtc *crtc)
3889 {
3890         return dm_set_vblank(crtc, true);
3891 }
3892
3893 static void dm_disable_vblank(struct drm_crtc *crtc)
3894 {
3895         dm_set_vblank(crtc, false);
3896 }
3897
3898 /* Implemented only the options currently availible for the driver */
3899 static const struct drm_crtc_funcs amdgpu_dm_crtc_funcs = {
3900         .reset = dm_crtc_reset_state,
3901         .destroy = amdgpu_dm_crtc_destroy,
3902         .gamma_set = drm_atomic_helper_legacy_gamma_set,
3903         .set_config = drm_atomic_helper_set_config,
3904         .page_flip = drm_atomic_helper_page_flip,
3905         .atomic_duplicate_state = dm_crtc_duplicate_state,
3906         .atomic_destroy_state = dm_crtc_destroy_state,
3907         .set_crc_source = amdgpu_dm_crtc_set_crc_source,
3908         .verify_crc_source = amdgpu_dm_crtc_verify_crc_source,
3909         .get_crc_sources = amdgpu_dm_crtc_get_crc_sources,
3910         .enable_vblank = dm_enable_vblank,
3911         .disable_vblank = dm_disable_vblank,
3912 };
3913
3914 static enum drm_connector_status
3915 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
3916 {
3917         bool connected;
3918         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3919
3920         /*
3921          * Notes:
3922          * 1. This interface is NOT called in context of HPD irq.
3923          * 2. This interface *is called* in context of user-mode ioctl. Which
3924          * makes it a bad place for *any* MST-related activity.
3925          */
3926
3927         if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
3928             !aconnector->fake_enable)
3929                 connected = (aconnector->dc_sink != NULL);
3930         else
3931                 connected = (aconnector->base.force == DRM_FORCE_ON);
3932
3933         return (connected ? connector_status_connected :
3934                         connector_status_disconnected);
3935 }
3936
3937 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
3938                                             struct drm_connector_state *connector_state,
3939                                             struct drm_property *property,
3940                                             uint64_t val)
3941 {
3942         struct drm_device *dev = connector->dev;
3943         struct amdgpu_device *adev = dev->dev_private;
3944         struct dm_connector_state *dm_old_state =
3945                 to_dm_connector_state(connector->state);
3946         struct dm_connector_state *dm_new_state =
3947                 to_dm_connector_state(connector_state);
3948
3949         int ret = -EINVAL;
3950
3951         if (property == dev->mode_config.scaling_mode_property) {
3952                 enum amdgpu_rmx_type rmx_type;
3953
3954                 switch (val) {
3955                 case DRM_MODE_SCALE_CENTER:
3956                         rmx_type = RMX_CENTER;
3957                         break;
3958                 case DRM_MODE_SCALE_ASPECT:
3959                         rmx_type = RMX_ASPECT;
3960                         break;
3961                 case DRM_MODE_SCALE_FULLSCREEN:
3962                         rmx_type = RMX_FULL;
3963                         break;
3964                 case DRM_MODE_SCALE_NONE:
3965                 default:
3966                         rmx_type = RMX_OFF;
3967                         break;
3968                 }
3969
3970                 if (dm_old_state->scaling == rmx_type)
3971                         return 0;
3972
3973                 dm_new_state->scaling = rmx_type;
3974                 ret = 0;
3975         } else if (property == adev->mode_info.underscan_hborder_property) {
3976                 dm_new_state->underscan_hborder = val;
3977                 ret = 0;
3978         } else if (property == adev->mode_info.underscan_vborder_property) {
3979                 dm_new_state->underscan_vborder = val;
3980                 ret = 0;
3981         } else if (property == adev->mode_info.underscan_property) {
3982                 dm_new_state->underscan_enable = val;
3983                 ret = 0;
3984         } else if (property == adev->mode_info.abm_level_property) {
3985                 dm_new_state->abm_level = val;
3986                 ret = 0;
3987         }
3988
3989         return ret;
3990 }
3991
3992 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
3993                                             const struct drm_connector_state *state,
3994                                             struct drm_property *property,
3995                                             uint64_t *val)
3996 {
3997         struct drm_device *dev = connector->dev;
3998         struct amdgpu_device *adev = dev->dev_private;
3999         struct dm_connector_state *dm_state =
4000                 to_dm_connector_state(state);
4001         int ret = -EINVAL;
4002
4003         if (property == dev->mode_config.scaling_mode_property) {
4004                 switch (dm_state->scaling) {
4005                 case RMX_CENTER:
4006                         *val = DRM_MODE_SCALE_CENTER;
4007                         break;
4008                 case RMX_ASPECT:
4009                         *val = DRM_MODE_SCALE_ASPECT;
4010                         break;
4011                 case RMX_FULL:
4012                         *val = DRM_MODE_SCALE_FULLSCREEN;
4013                         break;
4014                 case RMX_OFF:
4015                 default:
4016                         *val = DRM_MODE_SCALE_NONE;
4017                         break;
4018                 }
4019                 ret = 0;
4020         } else if (property == adev->mode_info.underscan_hborder_property) {
4021                 *val = dm_state->underscan_hborder;
4022                 ret = 0;
4023         } else if (property == adev->mode_info.underscan_vborder_property) {
4024                 *val = dm_state->underscan_vborder;
4025                 ret = 0;
4026         } else if (property == adev->mode_info.underscan_property) {
4027                 *val = dm_state->underscan_enable;
4028                 ret = 0;
4029         } else if (property == adev->mode_info.abm_level_property) {
4030                 *val = dm_state->abm_level;
4031                 ret = 0;
4032         }
4033
4034         return ret;
4035 }
4036
4037 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
4038 {
4039         struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
4040
4041         drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
4042 }
4043
4044 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
4045 {
4046         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
4047         const struct dc_link *link = aconnector->dc_link;
4048         struct amdgpu_device *adev = connector->dev->dev_private;
4049         struct amdgpu_display_manager *dm = &adev->dm;
4050
4051 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
4052         defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
4053
4054         if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
4055             link->type != dc_connection_none &&
4056             dm->backlight_dev) {
4057                 backlight_device_unregister(dm->backlight_dev);
4058                 dm->backlight_dev = NULL;
4059         }
4060 #endif
4061
4062         if (aconnector->dc_em_sink)
4063                 dc_sink_release(aconnector->dc_em_sink);
4064         aconnector->dc_em_sink = NULL;
4065         if (aconnector->dc_sink)
4066                 dc_sink_release(aconnector->dc_sink);
4067         aconnector->dc_sink = NULL;
4068
4069         drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
4070         drm_connector_unregister(connector);
4071         drm_connector_cleanup(connector);
4072         if (aconnector->i2c) {
4073                 i2c_del_adapter(&aconnector->i2c->base);
4074                 kfree(aconnector->i2c);
4075         }
4076
4077         kfree(connector);
4078 }
4079
4080 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
4081 {
4082         struct dm_connector_state *state =
4083                 to_dm_connector_state(connector->state);
4084
4085         if (connector->state)
4086                 __drm_atomic_helper_connector_destroy_state(connector->state);
4087
4088         kfree(state);
4089
4090         state = kzalloc(sizeof(*state), GFP_KERNEL);
4091
4092         if (state) {
4093                 state->scaling = RMX_OFF;
4094                 state->underscan_enable = false;
4095                 state->underscan_hborder = 0;
4096                 state->underscan_vborder = 0;
4097                 state->base.max_requested_bpc = 8;
4098
4099                 if (connector->connector_type == DRM_MODE_CONNECTOR_eDP)
4100                         state->abm_level = amdgpu_dm_abm_level;
4101
4102                 __drm_atomic_helper_connector_reset(connector, &state->base);
4103         }
4104 }
4105
4106 struct drm_connector_state *
4107 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
4108 {
4109         struct dm_connector_state *state =
4110                 to_dm_connector_state(connector->state);
4111
4112         struct dm_connector_state *new_state =
4113                         kmemdup(state, sizeof(*state), GFP_KERNEL);
4114
4115         if (!new_state)
4116                 return NULL;
4117
4118         __drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
4119
4120         new_state->freesync_capable = state->freesync_capable;
4121         new_state->abm_level = state->abm_level;
4122         new_state->scaling = state->scaling;
4123         new_state->underscan_enable = state->underscan_enable;
4124         new_state->underscan_hborder = state->underscan_hborder;
4125         new_state->underscan_vborder = state->underscan_vborder;
4126
4127         return &new_state->base;
4128 }
4129
4130 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
4131         .reset = amdgpu_dm_connector_funcs_reset,
4132         .detect = amdgpu_dm_connector_detect,
4133         .fill_modes = drm_helper_probe_single_connector_modes,
4134         .destroy = amdgpu_dm_connector_destroy,
4135         .atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
4136         .atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
4137         .atomic_set_property = amdgpu_dm_connector_atomic_set_property,
4138         .atomic_get_property = amdgpu_dm_connector_atomic_get_property,
4139         .early_unregister = amdgpu_dm_connector_unregister
4140 };
4141
4142 static int get_modes(struct drm_connector *connector)
4143 {
4144         return amdgpu_dm_connector_get_modes(connector);
4145 }
4146
4147 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
4148 {
4149         struct dc_sink_init_data init_params = {
4150                         .link = aconnector->dc_link,
4151                         .sink_signal = SIGNAL_TYPE_VIRTUAL
4152         };
4153         struct edid *edid;
4154
4155         if (!aconnector->base.edid_blob_ptr) {
4156                 DRM_ERROR("No EDID firmware found on connector: %s ,forcing to OFF!\n",
4157                                 aconnector->base.name);
4158
4159                 aconnector->base.force = DRM_FORCE_OFF;
4160                 aconnector->base.override_edid = false;
4161                 return;
4162         }
4163
4164         edid = (struct edid *) aconnector->base.edid_blob_ptr->data;
4165
4166         aconnector->edid = edid;
4167
4168         aconnector->dc_em_sink = dc_link_add_remote_sink(
4169                 aconnector->dc_link,
4170                 (uint8_t *)edid,
4171                 (edid->extensions + 1) * EDID_LENGTH,
4172                 &init_params);
4173
4174         if (aconnector->base.force == DRM_FORCE_ON) {
4175                 aconnector->dc_sink = aconnector->dc_link->local_sink ?
4176                 aconnector->dc_link->local_sink :
4177                 aconnector->dc_em_sink;
4178                 dc_sink_retain(aconnector->dc_sink);
4179         }
4180 }
4181
4182 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
4183 {
4184         struct dc_link *link = (struct dc_link *)aconnector->dc_link;
4185
4186         /*
4187          * In case of headless boot with force on for DP managed connector
4188          * Those settings have to be != 0 to get initial modeset
4189          */
4190         if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
4191                 link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
4192                 link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
4193         }
4194
4195
4196         aconnector->base.override_edid = true;
4197         create_eml_sink(aconnector);
4198 }
4199
4200 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
4201                                    struct drm_display_mode *mode)
4202 {
4203         int result = MODE_ERROR;
4204         struct dc_sink *dc_sink;
4205         struct amdgpu_device *adev = connector->dev->dev_private;
4206         /* TODO: Unhardcode stream count */
4207         struct dc_stream_state *stream;
4208         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
4209         enum dc_status dc_result = DC_OK;
4210
4211         if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
4212                         (mode->flags & DRM_MODE_FLAG_DBLSCAN))
4213                 return result;
4214
4215         /*
4216          * Only run this the first time mode_valid is called to initilialize
4217          * EDID mgmt
4218          */
4219         if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
4220                 !aconnector->dc_em_sink)
4221                 handle_edid_mgmt(aconnector);
4222
4223         dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
4224
4225         if (dc_sink == NULL) {
4226                 DRM_ERROR("dc_sink is NULL!\n");
4227                 goto fail;
4228         }
4229
4230         stream = create_stream_for_sink(aconnector, mode, NULL, NULL);
4231         if (stream == NULL) {
4232                 DRM_ERROR("Failed to create stream for sink!\n");
4233                 goto fail;
4234         }
4235
4236         dc_result = dc_validate_stream(adev->dm.dc, stream);
4237
4238         if (dc_result == DC_OK)
4239                 result = MODE_OK;
4240         else
4241                 DRM_DEBUG_KMS("Mode %dx%d (clk %d) failed DC validation with error %d\n",
4242                               mode->hdisplay,
4243                               mode->vdisplay,
4244                               mode->clock,
4245                               dc_result);
4246
4247         dc_stream_release(stream);
4248
4249 fail:
4250         /* TODO: error handling*/
4251         return result;
4252 }
4253
4254 static int fill_hdr_info_packet(const struct drm_connector_state *state,
4255                                 struct dc_info_packet *out)
4256 {
4257         struct hdmi_drm_infoframe frame;
4258         unsigned char buf[30]; /* 26 + 4 */
4259         ssize_t len;
4260         int ret, i;
4261
4262         memset(out, 0, sizeof(*out));
4263
4264         if (!state->hdr_output_metadata)
4265                 return 0;
4266
4267         ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
4268         if (ret)
4269                 return ret;
4270
4271         len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
4272         if (len < 0)
4273                 return (int)len;
4274
4275         /* Static metadata is a fixed 26 bytes + 4 byte header. */
4276         if (len != 30)
4277                 return -EINVAL;
4278
4279         /* Prepare the infopacket for DC. */
4280         switch (state->connector->connector_type) {
4281         case DRM_MODE_CONNECTOR_HDMIA:
4282                 out->hb0 = 0x87; /* type */
4283                 out->hb1 = 0x01; /* version */
4284                 out->hb2 = 0x1A; /* length */
4285                 out->sb[0] = buf[3]; /* checksum */
4286                 i = 1;
4287                 break;
4288
4289         case DRM_MODE_CONNECTOR_DisplayPort:
4290         case DRM_MODE_CONNECTOR_eDP:
4291                 out->hb0 = 0x00; /* sdp id, zero */
4292                 out->hb1 = 0x87; /* type */
4293                 out->hb2 = 0x1D; /* payload len - 1 */
4294                 out->hb3 = (0x13 << 2); /* sdp version */
4295                 out->sb[0] = 0x01; /* version */
4296                 out->sb[1] = 0x1A; /* length */
4297                 i = 2;
4298                 break;
4299
4300         default:
4301                 return -EINVAL;
4302         }
4303
4304         memcpy(&out->sb[i], &buf[4], 26);
4305         out->valid = true;
4306
4307         print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
4308                        sizeof(out->sb), false);
4309
4310         return 0;
4311 }
4312
4313 static bool
4314 is_hdr_metadata_different(const struct drm_connector_state *old_state,
4315                           const struct drm_connector_state *new_state)
4316 {
4317         struct drm_property_blob *old_blob = old_state->hdr_output_metadata;
4318         struct drm_property_blob *new_blob = new_state->hdr_output_metadata;
4319
4320         if (old_blob != new_blob) {
4321                 if (old_blob && new_blob &&
4322                     old_blob->length == new_blob->length)
4323                         return memcmp(old_blob->data, new_blob->data,
4324                                       old_blob->length);
4325
4326                 return true;
4327         }
4328
4329         return false;
4330 }
4331
4332 static int
4333 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
4334                                  struct drm_atomic_state *state)
4335 {
4336         struct drm_connector_state *new_con_state =
4337                 drm_atomic_get_new_connector_state(state, conn);
4338         struct drm_connector_state *old_con_state =
4339                 drm_atomic_get_old_connector_state(state, conn);
4340         struct drm_crtc *crtc = new_con_state->crtc;
4341         struct drm_crtc_state *new_crtc_state;
4342         int ret;
4343
4344         if (!crtc)
4345                 return 0;
4346
4347         if (is_hdr_metadata_different(old_con_state, new_con_state)) {
4348                 struct dc_info_packet hdr_infopacket;
4349
4350                 ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
4351                 if (ret)
4352                         return ret;
4353
4354                 new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
4355                 if (IS_ERR(new_crtc_state))
4356                         return PTR_ERR(new_crtc_state);
4357
4358                 /*
4359                  * DC considers the stream backends changed if the
4360                  * static metadata changes. Forcing the modeset also
4361                  * gives a simple way for userspace to switch from
4362                  * 8bpc to 10bpc when setting the metadata to enter
4363                  * or exit HDR.
4364                  *
4365                  * Changing the static metadata after it's been
4366                  * set is permissible, however. So only force a
4367                  * modeset if we're entering or exiting HDR.
4368                  */
4369                 new_crtc_state->mode_changed =
4370                         !old_con_state->hdr_output_metadata ||
4371                         !new_con_state->hdr_output_metadata;
4372         }
4373
4374         return 0;
4375 }
4376
4377 static const struct drm_connector_helper_funcs
4378 amdgpu_dm_connector_helper_funcs = {
4379         /*
4380          * If hotplugging a second bigger display in FB Con mode, bigger resolution
4381          * modes will be filtered by drm_mode_validate_size(), and those modes
4382          * are missing after user start lightdm. So we need to renew modes list.
4383          * in get_modes call back, not just return the modes count
4384          */
4385         .get_modes = get_modes,
4386         .mode_valid = amdgpu_dm_connector_mode_valid,
4387         .atomic_check = amdgpu_dm_connector_atomic_check,
4388 };
4389
4390 static void dm_crtc_helper_disable(struct drm_crtc *crtc)
4391 {
4392 }
4393
4394 static bool does_crtc_have_active_cursor(struct drm_crtc_state *new_crtc_state)
4395 {
4396         struct drm_device *dev = new_crtc_state->crtc->dev;
4397         struct drm_plane *plane;
4398
4399         drm_for_each_plane_mask(plane, dev, new_crtc_state->plane_mask) {
4400                 if (plane->type == DRM_PLANE_TYPE_CURSOR)
4401                         return true;
4402         }
4403
4404         return false;
4405 }
4406
4407 static int count_crtc_active_planes(struct drm_crtc_state *new_crtc_state)
4408 {
4409         struct drm_atomic_state *state = new_crtc_state->state;
4410         struct drm_plane *plane;
4411         int num_active = 0;
4412
4413         drm_for_each_plane_mask(plane, state->dev, new_crtc_state->plane_mask) {
4414                 struct drm_plane_state *new_plane_state;
4415
4416                 /* Cursor planes are "fake". */
4417                 if (plane->type == DRM_PLANE_TYPE_CURSOR)
4418                         continue;
4419
4420                 new_plane_state = drm_atomic_get_new_plane_state(state, plane);
4421
4422                 if (!new_plane_state) {
4423                         /*
4424                          * The plane is enable on the CRTC and hasn't changed
4425                          * state. This means that it previously passed
4426                          * validation and is therefore enabled.
4427                          */
4428                         num_active += 1;
4429                         continue;
4430                 }
4431
4432                 /* We need a framebuffer to be considered enabled. */
4433                 num_active += (new_plane_state->fb != NULL);
4434         }
4435
4436         return num_active;
4437 }
4438
4439 /*
4440  * Sets whether interrupts should be enabled on a specific CRTC.
4441  * We require that the stream be enabled and that there exist active
4442  * DC planes on the stream.
4443  */
4444 static void
4445 dm_update_crtc_interrupt_state(struct drm_crtc *crtc,
4446                                struct drm_crtc_state *new_crtc_state)
4447 {
4448         struct dm_crtc_state *dm_new_crtc_state =
4449                 to_dm_crtc_state(new_crtc_state);
4450
4451         dm_new_crtc_state->active_planes = 0;
4452         dm_new_crtc_state->interrupts_enabled = false;
4453
4454         if (!dm_new_crtc_state->stream)
4455                 return;
4456
4457         dm_new_crtc_state->active_planes =
4458                 count_crtc_active_planes(new_crtc_state);
4459
4460         dm_new_crtc_state->interrupts_enabled =
4461                 dm_new_crtc_state->active_planes > 0;
4462 }
4463
4464 static int dm_crtc_helper_atomic_check(struct drm_crtc *crtc,
4465                                        struct drm_crtc_state *state)
4466 {
4467         struct amdgpu_device *adev = crtc->dev->dev_private;
4468         struct dc *dc = adev->dm.dc;
4469         struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(state);
4470         int ret = -EINVAL;
4471
4472         /*
4473          * Update interrupt state for the CRTC. This needs to happen whenever
4474          * the CRTC has changed or whenever any of its planes have changed.
4475          * Atomic check satisfies both of these requirements since the CRTC
4476          * is added to the state by DRM during drm_atomic_helper_check_planes.
4477          */
4478         dm_update_crtc_interrupt_state(crtc, state);
4479
4480         if (unlikely(!dm_crtc_state->stream &&
4481                      modeset_required(state, NULL, dm_crtc_state->stream))) {
4482                 WARN_ON(1);
4483                 return ret;
4484         }
4485
4486         /* In some use cases, like reset, no stream is attached */
4487         if (!dm_crtc_state->stream)
4488                 return 0;
4489
4490         /*
4491          * We want at least one hardware plane enabled to use
4492          * the stream with a cursor enabled.
4493          */
4494         if (state->enable && state->active &&
4495             does_crtc_have_active_cursor(state) &&
4496             dm_crtc_state->active_planes == 0)
4497                 return -EINVAL;
4498
4499         if (dc_validate_stream(dc, dm_crtc_state->stream) == DC_OK)
4500                 return 0;
4501
4502         return ret;
4503 }
4504
4505 static bool dm_crtc_helper_mode_fixup(struct drm_crtc *crtc,
4506                                       const struct drm_display_mode *mode,
4507                                       struct drm_display_mode *adjusted_mode)
4508 {
4509         return true;
4510 }
4511
4512 static const struct drm_crtc_helper_funcs amdgpu_dm_crtc_helper_funcs = {
4513         .disable = dm_crtc_helper_disable,
4514         .atomic_check = dm_crtc_helper_atomic_check,
4515         .mode_fixup = dm_crtc_helper_mode_fixup
4516 };
4517
4518 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
4519 {
4520
4521 }
4522
4523 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
4524                                           struct drm_crtc_state *crtc_state,
4525                                           struct drm_connector_state *conn_state)
4526 {
4527         return 0;
4528 }
4529
4530 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
4531         .disable = dm_encoder_helper_disable,
4532         .atomic_check = dm_encoder_helper_atomic_check
4533 };
4534
4535 static void dm_drm_plane_reset(struct drm_plane *plane)
4536 {
4537         struct dm_plane_state *amdgpu_state = NULL;
4538
4539         if (plane->state)
4540                 plane->funcs->atomic_destroy_state(plane, plane->state);
4541
4542         amdgpu_state = kzalloc(sizeof(*amdgpu_state), GFP_KERNEL);
4543         WARN_ON(amdgpu_state == NULL);
4544
4545         if (amdgpu_state)
4546                 __drm_atomic_helper_plane_reset(plane, &amdgpu_state->base);
4547 }
4548
4549 static struct drm_plane_state *
4550 dm_drm_plane_duplicate_state(struct drm_plane *plane)
4551 {
4552         struct dm_plane_state *dm_plane_state, *old_dm_plane_state;
4553
4554         old_dm_plane_state = to_dm_plane_state(plane->state);
4555         dm_plane_state = kzalloc(sizeof(*dm_plane_state), GFP_KERNEL);
4556         if (!dm_plane_state)
4557                 return NULL;
4558
4559         __drm_atomic_helper_plane_duplicate_state(plane, &dm_plane_state->base);
4560
4561         if (old_dm_plane_state->dc_state) {
4562                 dm_plane_state->dc_state = old_dm_plane_state->dc_state;
4563                 dc_plane_state_retain(dm_plane_state->dc_state);
4564         }
4565
4566         return &dm_plane_state->base;
4567 }
4568
4569 void dm_drm_plane_destroy_state(struct drm_plane *plane,
4570                                 struct drm_plane_state *state)
4571 {
4572         struct dm_plane_state *dm_plane_state = to_dm_plane_state(state);
4573
4574         if (dm_plane_state->dc_state)
4575                 dc_plane_state_release(dm_plane_state->dc_state);
4576
4577         drm_atomic_helper_plane_destroy_state(plane, state);
4578 }
4579
4580 static const struct drm_plane_funcs dm_plane_funcs = {
4581         .update_plane   = drm_atomic_helper_update_plane,
4582         .disable_plane  = drm_atomic_helper_disable_plane,
4583         .destroy        = drm_primary_helper_destroy,
4584         .reset = dm_drm_plane_reset,
4585         .atomic_duplicate_state = dm_drm_plane_duplicate_state,
4586         .atomic_destroy_state = dm_drm_plane_destroy_state,
4587 };
4588
4589 static int dm_plane_helper_prepare_fb(struct drm_plane *plane,
4590                                       struct drm_plane_state *new_state)
4591 {
4592         struct amdgpu_framebuffer *afb;
4593         struct drm_gem_object *obj;
4594         struct amdgpu_device *adev;
4595         struct amdgpu_bo *rbo;
4596         struct dm_plane_state *dm_plane_state_new, *dm_plane_state_old;
4597         struct list_head list;
4598         struct ttm_validate_buffer tv;
4599         struct ww_acquire_ctx ticket;
4600         uint64_t tiling_flags;
4601         uint32_t domain;
4602         int r;
4603
4604         dm_plane_state_old = to_dm_plane_state(plane->state);
4605         dm_plane_state_new = to_dm_plane_state(new_state);
4606
4607         if (!new_state->fb) {
4608                 DRM_DEBUG_DRIVER("No FB bound\n");
4609                 return 0;
4610         }
4611
4612         afb = to_amdgpu_framebuffer(new_state->fb);
4613         obj = new_state->fb->obj[0];
4614         rbo = gem_to_amdgpu_bo(obj);
4615         adev = amdgpu_ttm_adev(rbo->tbo.bdev);
4616         INIT_LIST_HEAD(&list);
4617
4618         tv.bo = &rbo->tbo;
4619         tv.num_shared = 1;
4620         list_add(&tv.head, &list);
4621
4622         r = ttm_eu_reserve_buffers(&ticket, &list, false, NULL);
4623         if (r) {
4624                 dev_err(adev->dev, "fail to reserve bo (%d)\n", r);
4625                 return r;
4626         }
4627
4628         if (plane->type != DRM_PLANE_TYPE_CURSOR)
4629                 domain = amdgpu_display_supported_domains(adev, rbo->flags);
4630         else
4631                 domain = AMDGPU_GEM_DOMAIN_VRAM;
4632
4633         r = amdgpu_bo_pin(rbo, domain);
4634         if (unlikely(r != 0)) {
4635                 if (r != -ERESTARTSYS)
4636                         DRM_ERROR("Failed to pin framebuffer with error %d\n", r);
4637                 ttm_eu_backoff_reservation(&ticket, &list);
4638                 return r;
4639         }
4640
4641         r = amdgpu_ttm_alloc_gart(&rbo->tbo);
4642         if (unlikely(r != 0)) {
4643                 amdgpu_bo_unpin(rbo);
4644                 ttm_eu_backoff_reservation(&ticket, &list);
4645                 DRM_ERROR("%p bind failed\n", rbo);
4646                 return r;
4647         }
4648
4649         amdgpu_bo_get_tiling_flags(rbo, &tiling_flags);
4650
4651         ttm_eu_backoff_reservation(&ticket, &list);
4652
4653         afb->address = amdgpu_bo_gpu_offset(rbo);
4654
4655         amdgpu_bo_ref(rbo);
4656
4657         if (dm_plane_state_new->dc_state &&
4658                         dm_plane_state_old->dc_state != dm_plane_state_new->dc_state) {
4659                 struct dc_plane_state *plane_state = dm_plane_state_new->dc_state;
4660
4661                 fill_plane_buffer_attributes(
4662                         adev, afb, plane_state->format, plane_state->rotation,
4663                         tiling_flags, &plane_state->tiling_info,
4664                         &plane_state->plane_size, &plane_state->dcc,
4665                         &plane_state->address);
4666         }
4667
4668         return 0;
4669 }
4670
4671 static void dm_plane_helper_cleanup_fb(struct drm_plane *plane,
4672                                        struct drm_plane_state *old_state)
4673 {
4674         struct amdgpu_bo *rbo;
4675         int r;
4676
4677         if (!old_state->fb)
4678                 return;
4679
4680         rbo = gem_to_amdgpu_bo(old_state->fb->obj[0]);
4681         r = amdgpu_bo_reserve(rbo, false);
4682         if (unlikely(r)) {
4683                 DRM_ERROR("failed to reserve rbo before unpin\n");
4684                 return;
4685         }
4686
4687         amdgpu_bo_unpin(rbo);
4688         amdgpu_bo_unreserve(rbo);
4689         amdgpu_bo_unref(&rbo);
4690 }
4691
4692 static int dm_plane_atomic_check(struct drm_plane *plane,
4693                                  struct drm_plane_state *state)
4694 {
4695         struct amdgpu_device *adev = plane->dev->dev_private;
4696         struct dc *dc = adev->dm.dc;
4697         struct dm_plane_state *dm_plane_state;
4698         struct dc_scaling_info scaling_info;
4699         int ret;
4700
4701         dm_plane_state = to_dm_plane_state(state);
4702
4703         if (!dm_plane_state->dc_state)
4704                 return 0;
4705
4706         ret = fill_dc_scaling_info(state, &scaling_info);
4707         if (ret)
4708                 return ret;
4709
4710         if (dc_validate_plane(dc, dm_plane_state->dc_state) == DC_OK)
4711                 return 0;
4712
4713         return -EINVAL;
4714 }
4715
4716 static int dm_plane_atomic_async_check(struct drm_plane *plane,
4717                                        struct drm_plane_state *new_plane_state)
4718 {
4719         /* Only support async updates on cursor planes. */
4720         if (plane->type != DRM_PLANE_TYPE_CURSOR)
4721                 return -EINVAL;
4722
4723         return 0;
4724 }
4725
4726 static void dm_plane_atomic_async_update(struct drm_plane *plane,
4727                                          struct drm_plane_state *new_state)
4728 {
4729         struct drm_plane_state *old_state =
4730                 drm_atomic_get_old_plane_state(new_state->state, plane);
4731
4732         swap(plane->state->fb, new_state->fb);
4733
4734         plane->state->src_x = new_state->src_x;
4735         plane->state->src_y = new_state->src_y;
4736         plane->state->src_w = new_state->src_w;
4737         plane->state->src_h = new_state->src_h;
4738         plane->state->crtc_x = new_state->crtc_x;
4739         plane->state->crtc_y = new_state->crtc_y;
4740         plane->state->crtc_w = new_state->crtc_w;
4741         plane->state->crtc_h = new_state->crtc_h;
4742
4743         handle_cursor_update(plane, old_state);
4744 }
4745
4746 static const struct drm_plane_helper_funcs dm_plane_helper_funcs = {
4747         .prepare_fb = dm_plane_helper_prepare_fb,
4748         .cleanup_fb = dm_plane_helper_cleanup_fb,
4749         .atomic_check = dm_plane_atomic_check,
4750         .atomic_async_check = dm_plane_atomic_async_check,
4751         .atomic_async_update = dm_plane_atomic_async_update
4752 };
4753
4754 /*
4755  * TODO: these are currently initialized to rgb formats only.
4756  * For future use cases we should either initialize them dynamically based on
4757  * plane capabilities, or initialize this array to all formats, so internal drm
4758  * check will succeed, and let DC implement proper check
4759  */
4760 static const uint32_t rgb_formats[] = {
4761         DRM_FORMAT_XRGB8888,
4762         DRM_FORMAT_ARGB8888,
4763         DRM_FORMAT_RGBA8888,
4764         DRM_FORMAT_XRGB2101010,
4765         DRM_FORMAT_XBGR2101010,
4766         DRM_FORMAT_ARGB2101010,
4767         DRM_FORMAT_ABGR2101010,
4768         DRM_FORMAT_XBGR8888,
4769         DRM_FORMAT_ABGR8888,
4770         DRM_FORMAT_RGB565,
4771 };
4772
4773 static const uint32_t overlay_formats[] = {
4774         DRM_FORMAT_XRGB8888,
4775         DRM_FORMAT_ARGB8888,
4776         DRM_FORMAT_RGBA8888,
4777         DRM_FORMAT_XBGR8888,
4778         DRM_FORMAT_ABGR8888,
4779         DRM_FORMAT_RGB565
4780 };
4781
4782 static const u32 cursor_formats[] = {
4783         DRM_FORMAT_ARGB8888
4784 };
4785
4786 static int get_plane_formats(const struct drm_plane *plane,
4787                              const struct dc_plane_cap *plane_cap,
4788                              uint32_t *formats, int max_formats)
4789 {
4790         int i, num_formats = 0;
4791
4792         /*
4793          * TODO: Query support for each group of formats directly from
4794          * DC plane caps. This will require adding more formats to the
4795          * caps list.
4796          */
4797
4798         switch (plane->type) {
4799         case DRM_PLANE_TYPE_PRIMARY:
4800                 for (i = 0; i < ARRAY_SIZE(rgb_formats); ++i) {
4801                         if (num_formats >= max_formats)
4802                                 break;
4803
4804                         formats[num_formats++] = rgb_formats[i];
4805                 }
4806
4807                 if (plane_cap && plane_cap->pixel_format_support.nv12)
4808                         formats[num_formats++] = DRM_FORMAT_NV12;
4809                 break;
4810
4811         case DRM_PLANE_TYPE_OVERLAY:
4812                 for (i = 0; i < ARRAY_SIZE(overlay_formats); ++i) {
4813                         if (num_formats >= max_formats)
4814                                 break;
4815
4816                         formats[num_formats++] = overlay_formats[i];
4817                 }
4818                 break;
4819
4820         case DRM_PLANE_TYPE_CURSOR:
4821                 for (i = 0; i < ARRAY_SIZE(cursor_formats); ++i) {
4822                         if (num_formats >= max_formats)
4823                                 break;
4824
4825                         formats[num_formats++] = cursor_formats[i];
4826                 }
4827                 break;
4828         }
4829
4830         return num_formats;
4831 }
4832
4833 static int amdgpu_dm_plane_init(struct amdgpu_display_manager *dm,
4834                                 struct drm_plane *plane,
4835                                 unsigned long possible_crtcs,
4836                                 const struct dc_plane_cap *plane_cap)
4837 {
4838         uint32_t formats[32];
4839         int num_formats;
4840         int res = -EPERM;
4841
4842         num_formats = get_plane_formats(plane, plane_cap, formats,
4843                                         ARRAY_SIZE(formats));
4844
4845         res = drm_universal_plane_init(dm->adev->ddev, plane, possible_crtcs,
4846                                        &dm_plane_funcs, formats, num_formats,
4847                                        NULL, plane->type, NULL);
4848         if (res)
4849                 return res;
4850
4851         if (plane->type == DRM_PLANE_TYPE_OVERLAY &&
4852             plane_cap && plane_cap->per_pixel_alpha) {
4853                 unsigned int blend_caps = BIT(DRM_MODE_BLEND_PIXEL_NONE) |
4854                                           BIT(DRM_MODE_BLEND_PREMULTI);
4855
4856                 drm_plane_create_alpha_property(plane);
4857                 drm_plane_create_blend_mode_property(plane, blend_caps);
4858         }
4859
4860         if (plane->type == DRM_PLANE_TYPE_PRIMARY &&
4861             plane_cap && plane_cap->pixel_format_support.nv12) {
4862                 /* This only affects YUV formats. */
4863                 drm_plane_create_color_properties(
4864                         plane,
4865                         BIT(DRM_COLOR_YCBCR_BT601) |
4866                         BIT(DRM_COLOR_YCBCR_BT709),
4867                         BIT(DRM_COLOR_YCBCR_LIMITED_RANGE) |
4868                         BIT(DRM_COLOR_YCBCR_FULL_RANGE),
4869                         DRM_COLOR_YCBCR_BT709, DRM_COLOR_YCBCR_LIMITED_RANGE);
4870         }
4871
4872         drm_plane_helper_add(plane, &dm_plane_helper_funcs);
4873
4874         /* Create (reset) the plane state */
4875         if (plane->funcs->reset)
4876                 plane->funcs->reset(plane);
4877
4878         return 0;
4879 }
4880
4881 static int amdgpu_dm_crtc_init(struct amdgpu_display_manager *dm,
4882                                struct drm_plane *plane,
4883                                uint32_t crtc_index)
4884 {
4885         struct amdgpu_crtc *acrtc = NULL;
4886         struct drm_plane *cursor_plane;
4887
4888         int res = -ENOMEM;
4889
4890         cursor_plane = kzalloc(sizeof(*cursor_plane), GFP_KERNEL);
4891         if (!cursor_plane)
4892                 goto fail;
4893
4894         cursor_plane->type = DRM_PLANE_TYPE_CURSOR;
4895         res = amdgpu_dm_plane_init(dm, cursor_plane, 0, NULL);
4896
4897         acrtc = kzalloc(sizeof(struct amdgpu_crtc), GFP_KERNEL);
4898         if (!acrtc)
4899                 goto fail;
4900
4901         res = drm_crtc_init_with_planes(
4902                         dm->ddev,
4903                         &acrtc->base,
4904                         plane,
4905                         cursor_plane,
4906                         &amdgpu_dm_crtc_funcs, NULL);
4907
4908         if (res)
4909                 goto fail;
4910
4911         drm_crtc_helper_add(&acrtc->base, &amdgpu_dm_crtc_helper_funcs);
4912
4913         /* Create (reset) the plane state */
4914         if (acrtc->base.funcs->reset)
4915                 acrtc->base.funcs->reset(&acrtc->base);
4916
4917         acrtc->max_cursor_width = dm->adev->dm.dc->caps.max_cursor_size;
4918         acrtc->max_cursor_height = dm->adev->dm.dc->caps.max_cursor_size;
4919
4920         acrtc->crtc_id = crtc_index;
4921         acrtc->base.enabled = false;
4922         acrtc->otg_inst = -1;
4923
4924         dm->adev->mode_info.crtcs[crtc_index] = acrtc;
4925         drm_crtc_enable_color_mgmt(&acrtc->base, MAX_COLOR_LUT_ENTRIES,
4926                                    true, MAX_COLOR_LUT_ENTRIES);
4927         drm_mode_crtc_set_gamma_size(&acrtc->base, MAX_COLOR_LEGACY_LUT_ENTRIES);
4928
4929         return 0;
4930
4931 fail:
4932         kfree(acrtc);
4933         kfree(cursor_plane);
4934         return res;
4935 }
4936
4937
4938 static int to_drm_connector_type(enum signal_type st)
4939 {
4940         switch (st) {
4941         case SIGNAL_TYPE_HDMI_TYPE_A:
4942                 return DRM_MODE_CONNECTOR_HDMIA;
4943         case SIGNAL_TYPE_EDP:
4944                 return DRM_MODE_CONNECTOR_eDP;
4945         case SIGNAL_TYPE_LVDS:
4946                 return DRM_MODE_CONNECTOR_LVDS;
4947         case SIGNAL_TYPE_RGB:
4948                 return DRM_MODE_CONNECTOR_VGA;
4949         case SIGNAL_TYPE_DISPLAY_PORT:
4950         case SIGNAL_TYPE_DISPLAY_PORT_MST:
4951                 return DRM_MODE_CONNECTOR_DisplayPort;
4952         case SIGNAL_TYPE_DVI_DUAL_LINK:
4953         case SIGNAL_TYPE_DVI_SINGLE_LINK:
4954                 return DRM_MODE_CONNECTOR_DVID;
4955         case SIGNAL_TYPE_VIRTUAL:
4956                 return DRM_MODE_CONNECTOR_VIRTUAL;
4957
4958         default:
4959                 return DRM_MODE_CONNECTOR_Unknown;
4960         }
4961 }
4962
4963 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
4964 {
4965         struct drm_encoder *encoder;
4966
4967         /* There is only one encoder per connector */
4968         drm_connector_for_each_possible_encoder(connector, encoder)
4969                 return encoder;
4970
4971         return NULL;
4972 }
4973
4974 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
4975 {
4976         struct drm_encoder *encoder;
4977         struct amdgpu_encoder *amdgpu_encoder;
4978
4979         encoder = amdgpu_dm_connector_to_encoder(connector);
4980
4981         if (encoder == NULL)
4982                 return;
4983
4984         amdgpu_encoder = to_amdgpu_encoder(encoder);
4985
4986         amdgpu_encoder->native_mode.clock = 0;
4987
4988         if (!list_empty(&connector->probed_modes)) {
4989                 struct drm_display_mode *preferred_mode = NULL;
4990
4991                 list_for_each_entry(preferred_mode,
4992                                     &connector->probed_modes,
4993                                     head) {
4994                         if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
4995                                 amdgpu_encoder->native_mode = *preferred_mode;
4996
4997                         break;
4998                 }
4999
5000         }
5001 }
5002
5003 static struct drm_display_mode *
5004 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
5005                              char *name,
5006                              int hdisplay, int vdisplay)
5007 {
5008         struct drm_device *dev = encoder->dev;
5009         struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
5010         struct drm_display_mode *mode = NULL;
5011         struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
5012
5013         mode = drm_mode_duplicate(dev, native_mode);
5014
5015         if (mode == NULL)
5016                 return NULL;
5017
5018         mode->hdisplay = hdisplay;
5019         mode->vdisplay = vdisplay;
5020         mode->type &= ~DRM_MODE_TYPE_PREFERRED;
5021         strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
5022
5023         return mode;
5024
5025 }
5026
5027 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
5028                                                  struct drm_connector *connector)
5029 {
5030         struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
5031         struct drm_display_mode *mode = NULL;
5032         struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
5033         struct amdgpu_dm_connector *amdgpu_dm_connector =
5034                                 to_amdgpu_dm_connector(connector);
5035         int i;
5036         int n;
5037         struct mode_size {
5038                 char name[DRM_DISPLAY_MODE_LEN];
5039                 int w;
5040                 int h;
5041         } common_modes[] = {
5042                 {  "640x480",  640,  480},
5043                 {  "800x600",  800,  600},
5044                 { "1024x768", 1024,  768},
5045                 { "1280x720", 1280,  720},
5046                 { "1280x800", 1280,  800},
5047                 {"1280x1024", 1280, 1024},
5048                 { "1440x900", 1440,  900},
5049                 {"1680x1050", 1680, 1050},
5050                 {"1600x1200", 1600, 1200},
5051                 {"1920x1080", 1920, 1080},
5052                 {"1920x1200", 1920, 1200}
5053         };
5054
5055         n = ARRAY_SIZE(common_modes);
5056
5057         for (i = 0; i < n; i++) {
5058                 struct drm_display_mode *curmode = NULL;
5059                 bool mode_existed = false;
5060
5061                 if (common_modes[i].w > native_mode->hdisplay ||
5062                     common_modes[i].h > native_mode->vdisplay ||
5063                    (common_modes[i].w == native_mode->hdisplay &&
5064                     common_modes[i].h == native_mode->vdisplay))
5065                         continue;
5066
5067                 list_for_each_entry(curmode, &connector->probed_modes, head) {
5068                         if (common_modes[i].w == curmode->hdisplay &&
5069                             common_modes[i].h == curmode->vdisplay) {
5070                                 mode_existed = true;
5071                                 break;
5072                         }
5073                 }
5074
5075                 if (mode_existed)
5076                         continue;
5077
5078                 mode = amdgpu_dm_create_common_mode(encoder,
5079                                 common_modes[i].name, common_modes[i].w,
5080                                 common_modes[i].h);
5081                 drm_mode_probed_add(connector, mode);
5082                 amdgpu_dm_connector->num_modes++;
5083         }
5084 }
5085
5086 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
5087                                               struct edid *edid)
5088 {
5089         struct amdgpu_dm_connector *amdgpu_dm_connector =
5090                         to_amdgpu_dm_connector(connector);
5091
5092         if (edid) {
5093                 /* empty probed_modes */
5094                 INIT_LIST_HEAD(&connector->probed_modes);
5095                 amdgpu_dm_connector->num_modes =
5096                                 drm_add_edid_modes(connector, edid);
5097
5098                 /* sorting the probed modes before calling function
5099                  * amdgpu_dm_get_native_mode() since EDID can have
5100                  * more than one preferred mode. The modes that are
5101                  * later in the probed mode list could be of higher
5102                  * and preferred resolution. For example, 3840x2160
5103                  * resolution in base EDID preferred timing and 4096x2160
5104                  * preferred resolution in DID extension block later.
5105                  */
5106                 drm_mode_sort(&connector->probed_modes);
5107                 amdgpu_dm_get_native_mode(connector);
5108         } else {
5109                 amdgpu_dm_connector->num_modes = 0;
5110         }
5111 }
5112
5113 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
5114 {
5115         struct amdgpu_dm_connector *amdgpu_dm_connector =
5116                         to_amdgpu_dm_connector(connector);
5117         struct drm_encoder *encoder;
5118         struct edid *edid = amdgpu_dm_connector->edid;
5119
5120         encoder = amdgpu_dm_connector_to_encoder(connector);
5121
5122         if (!edid || !drm_edid_is_valid(edid)) {
5123                 amdgpu_dm_connector->num_modes =
5124                                 drm_add_modes_noedid(connector, 640, 480);
5125         } else {
5126                 amdgpu_dm_connector_ddc_get_modes(connector, edid);
5127                 amdgpu_dm_connector_add_common_modes(encoder, connector);
5128         }
5129         amdgpu_dm_fbc_init(connector);
5130
5131         return amdgpu_dm_connector->num_modes;
5132 }
5133
5134 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
5135                                      struct amdgpu_dm_connector *aconnector,
5136                                      int connector_type,
5137                                      struct dc_link *link,
5138                                      int link_index)
5139 {
5140         struct amdgpu_device *adev = dm->ddev->dev_private;
5141
5142         /*
5143          * Some of the properties below require access to state, like bpc.
5144          * Allocate some default initial connector state with our reset helper.
5145          */
5146         if (aconnector->base.funcs->reset)
5147                 aconnector->base.funcs->reset(&aconnector->base);
5148
5149         aconnector->connector_id = link_index;
5150         aconnector->dc_link = link;
5151         aconnector->base.interlace_allowed = false;
5152         aconnector->base.doublescan_allowed = false;
5153         aconnector->base.stereo_allowed = false;
5154         aconnector->base.dpms = DRM_MODE_DPMS_OFF;
5155         aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
5156         aconnector->audio_inst = -1;
5157         mutex_init(&aconnector->hpd_lock);
5158
5159         /*
5160          * configure support HPD hot plug connector_>polled default value is 0
5161          * which means HPD hot plug not supported
5162          */
5163         switch (connector_type) {
5164         case DRM_MODE_CONNECTOR_HDMIA:
5165                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
5166                 aconnector->base.ycbcr_420_allowed =
5167                         link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
5168                 break;
5169         case DRM_MODE_CONNECTOR_DisplayPort:
5170                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
5171                 aconnector->base.ycbcr_420_allowed =
5172                         link->link_enc->features.dp_ycbcr420_supported ? true : false;
5173                 break;
5174         case DRM_MODE_CONNECTOR_DVID:
5175                 aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
5176                 break;
5177         default:
5178                 break;
5179         }
5180
5181         drm_object_attach_property(&aconnector->base.base,
5182                                 dm->ddev->mode_config.scaling_mode_property,
5183                                 DRM_MODE_SCALE_NONE);
5184
5185         drm_object_attach_property(&aconnector->base.base,
5186                                 adev->mode_info.underscan_property,
5187                                 UNDERSCAN_OFF);
5188         drm_object_attach_property(&aconnector->base.base,
5189                                 adev->mode_info.underscan_hborder_property,
5190                                 0);
5191         drm_object_attach_property(&aconnector->base.base,
5192                                 adev->mode_info.underscan_vborder_property,
5193                                 0);
5194
5195         drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
5196
5197         /* This defaults to the max in the range, but we want 8bpc. */
5198         aconnector->base.state->max_bpc = 8;
5199         aconnector->base.state->max_requested_bpc = 8;
5200
5201         if (connector_type == DRM_MODE_CONNECTOR_eDP &&
5202             dc_is_dmcu_initialized(adev->dm.dc)) {
5203                 drm_object_attach_property(&aconnector->base.base,
5204                                 adev->mode_info.abm_level_property, 0);
5205         }
5206
5207         if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
5208             connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
5209             connector_type == DRM_MODE_CONNECTOR_eDP) {
5210                 drm_object_attach_property(
5211                         &aconnector->base.base,
5212                         dm->ddev->mode_config.hdr_output_metadata_property, 0);
5213
5214                 drm_connector_attach_vrr_capable_property(
5215                         &aconnector->base);
5216 #ifdef CONFIG_DRM_AMD_DC_HDCP
5217                 if (adev->asic_type >= CHIP_RAVEN)
5218                         drm_connector_attach_content_protection_property(&aconnector->base, false);
5219 #endif
5220         }
5221 }
5222
5223 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
5224                               struct i2c_msg *msgs, int num)
5225 {
5226         struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
5227         struct ddc_service *ddc_service = i2c->ddc_service;
5228         struct i2c_command cmd;
5229         int i;
5230         int result = -EIO;
5231
5232         cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
5233
5234         if (!cmd.payloads)
5235                 return result;
5236
5237         cmd.number_of_payloads = num;
5238         cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
5239         cmd.speed = 100;
5240
5241         for (i = 0; i < num; i++) {
5242                 cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
5243                 cmd.payloads[i].address = msgs[i].addr;
5244                 cmd.payloads[i].length = msgs[i].len;
5245                 cmd.payloads[i].data = msgs[i].buf;
5246         }
5247
5248         if (dc_submit_i2c(
5249                         ddc_service->ctx->dc,
5250                         ddc_service->ddc_pin->hw_info.ddc_channel,
5251                         &cmd))
5252                 result = num;
5253
5254         kfree(cmd.payloads);
5255         return result;
5256 }
5257
5258 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
5259 {
5260         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
5261 }
5262
5263 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
5264         .master_xfer = amdgpu_dm_i2c_xfer,
5265         .functionality = amdgpu_dm_i2c_func,
5266 };
5267
5268 static struct amdgpu_i2c_adapter *
5269 create_i2c(struct ddc_service *ddc_service,
5270            int link_index,
5271            int *res)
5272 {
5273         struct amdgpu_device *adev = ddc_service->ctx->driver_context;
5274         struct amdgpu_i2c_adapter *i2c;
5275
5276         i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
5277         if (!i2c)
5278                 return NULL;
5279         i2c->base.owner = THIS_MODULE;
5280         i2c->base.class = I2C_CLASS_DDC;
5281         i2c->base.dev.parent = &adev->pdev->dev;
5282         i2c->base.algo = &amdgpu_dm_i2c_algo;
5283         snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
5284         i2c_set_adapdata(&i2c->base, i2c);
5285         i2c->ddc_service = ddc_service;
5286         i2c->ddc_service->ddc_pin->hw_info.ddc_channel = link_index;
5287
5288         return i2c;
5289 }
5290
5291
5292 /*
5293  * Note: this function assumes that dc_link_detect() was called for the
5294  * dc_link which will be represented by this aconnector.
5295  */
5296 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
5297                                     struct amdgpu_dm_connector *aconnector,
5298                                     uint32_t link_index,
5299                                     struct amdgpu_encoder *aencoder)
5300 {
5301         int res = 0;
5302         int connector_type;
5303         struct dc *dc = dm->dc;
5304         struct dc_link *link = dc_get_link_at_index(dc, link_index);
5305         struct amdgpu_i2c_adapter *i2c;
5306
5307         link->priv = aconnector;
5308
5309         DRM_DEBUG_DRIVER("%s()\n", __func__);
5310
5311         i2c = create_i2c(link->ddc, link->link_index, &res);
5312         if (!i2c) {
5313                 DRM_ERROR("Failed to create i2c adapter data\n");
5314                 return -ENOMEM;
5315         }
5316
5317         aconnector->i2c = i2c;
5318         res = i2c_add_adapter(&i2c->base);
5319
5320         if (res) {
5321                 DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
5322                 goto out_free;
5323         }
5324
5325         connector_type = to_drm_connector_type(link->connector_signal);
5326
5327         res = drm_connector_init(
5328                         dm->ddev,
5329                         &aconnector->base,
5330                         &amdgpu_dm_connector_funcs,
5331                         connector_type);
5332
5333         if (res) {
5334                 DRM_ERROR("connector_init failed\n");
5335                 aconnector->connector_id = -1;
5336                 goto out_free;
5337         }
5338
5339         drm_connector_helper_add(
5340                         &aconnector->base,
5341                         &amdgpu_dm_connector_helper_funcs);
5342
5343         amdgpu_dm_connector_init_helper(
5344                 dm,
5345                 aconnector,
5346                 connector_type,
5347                 link,
5348                 link_index);
5349
5350         drm_connector_attach_encoder(
5351                 &aconnector->base, &aencoder->base);
5352
5353         drm_connector_register(&aconnector->base);
5354 #if defined(CONFIG_DEBUG_FS)
5355         connector_debugfs_init(aconnector);
5356         aconnector->debugfs_dpcd_address = 0;
5357         aconnector->debugfs_dpcd_size = 0;
5358 #endif
5359
5360         if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
5361                 || connector_type == DRM_MODE_CONNECTOR_eDP)
5362                 amdgpu_dm_initialize_dp_connector(dm, aconnector);
5363
5364 out_free:
5365         if (res) {
5366                 kfree(i2c);
5367                 aconnector->i2c = NULL;
5368         }
5369         return res;
5370 }
5371
5372 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
5373 {
5374         switch (adev->mode_info.num_crtc) {
5375         case 1:
5376                 return 0x1;
5377         case 2:
5378                 return 0x3;
5379         case 3:
5380                 return 0x7;
5381         case 4:
5382                 return 0xf;
5383         case 5:
5384                 return 0x1f;
5385         case 6:
5386         default:
5387                 return 0x3f;
5388         }
5389 }
5390
5391 static int amdgpu_dm_encoder_init(struct drm_device *dev,
5392                                   struct amdgpu_encoder *aencoder,
5393                                   uint32_t link_index)
5394 {
5395         struct amdgpu_device *adev = dev->dev_private;
5396
5397         int res = drm_encoder_init(dev,
5398                                    &aencoder->base,
5399                                    &amdgpu_dm_encoder_funcs,
5400                                    DRM_MODE_ENCODER_TMDS,
5401                                    NULL);
5402
5403         aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
5404
5405         if (!res)
5406                 aencoder->encoder_id = link_index;
5407         else
5408                 aencoder->encoder_id = -1;
5409
5410         drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
5411
5412         return res;
5413 }
5414
5415 static void manage_dm_interrupts(struct amdgpu_device *adev,
5416                                  struct amdgpu_crtc *acrtc,
5417                                  bool enable)
5418 {
5419         /*
5420          * this is not correct translation but will work as soon as VBLANK
5421          * constant is the same as PFLIP
5422          */
5423         int irq_type =
5424                 amdgpu_display_crtc_idx_to_irq_type(
5425                         adev,
5426                         acrtc->crtc_id);
5427
5428         if (enable) {
5429                 drm_crtc_vblank_on(&acrtc->base);
5430                 amdgpu_irq_get(
5431                         adev,
5432                         &adev->pageflip_irq,
5433                         irq_type);
5434         } else {
5435
5436                 amdgpu_irq_put(
5437                         adev,
5438                         &adev->pageflip_irq,
5439                         irq_type);
5440                 drm_crtc_vblank_off(&acrtc->base);
5441         }
5442 }
5443
5444 static bool
5445 is_scaling_state_different(const struct dm_connector_state *dm_state,
5446                            const struct dm_connector_state *old_dm_state)
5447 {
5448         if (dm_state->scaling != old_dm_state->scaling)
5449                 return true;
5450         if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
5451                 if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
5452                         return true;
5453         } else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
5454                 if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
5455                         return true;
5456         } else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
5457                    dm_state->underscan_vborder != old_dm_state->underscan_vborder)
5458                 return true;
5459         return false;
5460 }
5461
5462 #ifdef CONFIG_DRM_AMD_DC_HDCP
5463 static bool is_content_protection_different(struct drm_connector_state *state,
5464                                             const struct drm_connector_state *old_state,
5465                                             const struct drm_connector *connector, struct hdcp_workqueue *hdcp_w)
5466 {
5467         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5468
5469         /* CP is being re enabled, ignore this */
5470         if (old_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
5471             state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
5472                 state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
5473                 return false;
5474         }
5475
5476         /* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED */
5477         if (old_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
5478             state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
5479                 state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
5480
5481         /* Check if something is connected/enabled, otherwise we start hdcp but nothing is connected/enabled
5482          * hot-plug, headless s3, dpms
5483          */
5484         if (state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED && connector->dpms == DRM_MODE_DPMS_ON &&
5485             aconnector->dc_sink != NULL)
5486                 return true;
5487
5488         if (old_state->content_protection == state->content_protection)
5489                 return false;
5490
5491         if (state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED)
5492                 return true;
5493
5494         return false;
5495 }
5496
5497 static void update_content_protection(struct drm_connector_state *state, const struct drm_connector *connector,
5498                                       struct hdcp_workqueue *hdcp_w)
5499 {
5500         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5501
5502         if (state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
5503                 hdcp_add_display(hdcp_w, aconnector->dc_link->link_index, aconnector);
5504         else if (state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED)
5505                 hdcp_remove_display(hdcp_w, aconnector->dc_link->link_index, aconnector->base.index);
5506
5507 }
5508 #endif
5509 static void remove_stream(struct amdgpu_device *adev,
5510                           struct amdgpu_crtc *acrtc,
5511                           struct dc_stream_state *stream)
5512 {
5513         /* this is the update mode case */
5514
5515         acrtc->otg_inst = -1;
5516         acrtc->enabled = false;
5517 }
5518
5519 static int get_cursor_position(struct drm_plane *plane, struct drm_crtc *crtc,
5520                                struct dc_cursor_position *position)
5521 {
5522         struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
5523         int x, y;
5524         int xorigin = 0, yorigin = 0;
5525
5526         position->enable = false;
5527         position->x = 0;
5528         position->y = 0;
5529
5530         if (!crtc || !plane->state->fb)
5531                 return 0;
5532
5533         if ((plane->state->crtc_w > amdgpu_crtc->max_cursor_width) ||
5534             (plane->state->crtc_h > amdgpu_crtc->max_cursor_height)) {
5535                 DRM_ERROR("%s: bad cursor width or height %d x %d\n",
5536                           __func__,
5537                           plane->state->crtc_w,
5538                           plane->state->crtc_h);
5539                 return -EINVAL;
5540         }
5541
5542         x = plane->state->crtc_x;
5543         y = plane->state->crtc_y;
5544
5545         if (x <= -amdgpu_crtc->max_cursor_width ||
5546             y <= -amdgpu_crtc->max_cursor_height)
5547                 return 0;
5548
5549         if (crtc->primary->state) {
5550                 /* avivo cursor are offset into the total surface */
5551                 x += crtc->primary->state->src_x >> 16;
5552                 y += crtc->primary->state->src_y >> 16;
5553         }
5554
5555         if (x < 0) {
5556                 xorigin = min(-x, amdgpu_crtc->max_cursor_width - 1);
5557                 x = 0;
5558         }
5559         if (y < 0) {
5560                 yorigin = min(-y, amdgpu_crtc->max_cursor_height - 1);
5561                 y = 0;
5562         }
5563         position->enable = true;
5564         position->x = x;
5565         position->y = y;
5566         position->x_hotspot = xorigin;
5567         position->y_hotspot = yorigin;
5568
5569         return 0;
5570 }
5571
5572 static void handle_cursor_update(struct drm_plane *plane,
5573                                  struct drm_plane_state *old_plane_state)
5574 {
5575         struct amdgpu_device *adev = plane->dev->dev_private;
5576         struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
5577         struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
5578         struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
5579         struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
5580         uint64_t address = afb ? afb->address : 0;
5581         struct dc_cursor_position position;
5582         struct dc_cursor_attributes attributes;
5583         int ret;
5584
5585         if (!plane->state->fb && !old_plane_state->fb)
5586                 return;
5587
5588         DRM_DEBUG_DRIVER("%s: crtc_id=%d with size %d to %d\n",
5589                          __func__,
5590                          amdgpu_crtc->crtc_id,
5591                          plane->state->crtc_w,
5592                          plane->state->crtc_h);
5593
5594         ret = get_cursor_position(plane, crtc, &position);
5595         if (ret)
5596                 return;
5597
5598         if (!position.enable) {
5599                 /* turn off cursor */
5600                 if (crtc_state && crtc_state->stream) {
5601                         mutex_lock(&adev->dm.dc_lock);
5602                         dc_stream_set_cursor_position(crtc_state->stream,
5603                                                       &position);
5604                         mutex_unlock(&adev->dm.dc_lock);
5605                 }
5606                 return;
5607         }
5608
5609         amdgpu_crtc->cursor_width = plane->state->crtc_w;
5610         amdgpu_crtc->cursor_height = plane->state->crtc_h;
5611
5612         memset(&attributes, 0, sizeof(attributes));
5613         attributes.address.high_part = upper_32_bits(address);
5614         attributes.address.low_part  = lower_32_bits(address);
5615         attributes.width             = plane->state->crtc_w;
5616         attributes.height            = plane->state->crtc_h;
5617         attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
5618         attributes.rotation_angle    = 0;
5619         attributes.attribute_flags.value = 0;
5620
5621         attributes.pitch = attributes.width;
5622
5623         if (crtc_state->stream) {
5624                 mutex_lock(&adev->dm.dc_lock);
5625                 if (!dc_stream_set_cursor_attributes(crtc_state->stream,
5626                                                          &attributes))
5627                         DRM_ERROR("DC failed to set cursor attributes\n");
5628
5629                 if (!dc_stream_set_cursor_position(crtc_state->stream,
5630                                                    &position))
5631                         DRM_ERROR("DC failed to set cursor position\n");
5632                 mutex_unlock(&adev->dm.dc_lock);
5633         }
5634 }
5635
5636 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
5637 {
5638
5639         assert_spin_locked(&acrtc->base.dev->event_lock);
5640         WARN_ON(acrtc->event);
5641
5642         acrtc->event = acrtc->base.state->event;
5643
5644         /* Set the flip status */
5645         acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
5646
5647         /* Mark this event as consumed */
5648         acrtc->base.state->event = NULL;
5649
5650         DRM_DEBUG_DRIVER("crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
5651                                                  acrtc->crtc_id);
5652 }
5653
5654 static void update_freesync_state_on_stream(
5655         struct amdgpu_display_manager *dm,
5656         struct dm_crtc_state *new_crtc_state,
5657         struct dc_stream_state *new_stream,
5658         struct dc_plane_state *surface,
5659         u32 flip_timestamp_in_us)
5660 {
5661         struct mod_vrr_params vrr_params;
5662         struct dc_info_packet vrr_infopacket = {0};
5663         struct amdgpu_device *adev = dm->adev;
5664         unsigned long flags;
5665
5666         if (!new_stream)
5667                 return;
5668
5669         /*
5670          * TODO: Determine why min/max totals and vrefresh can be 0 here.
5671          * For now it's sufficient to just guard against these conditions.
5672          */
5673
5674         if (!new_stream->timing.h_total || !new_stream->timing.v_total)
5675                 return;
5676
5677         spin_lock_irqsave(&adev->ddev->event_lock, flags);
5678         vrr_params = new_crtc_state->vrr_params;
5679
5680         if (surface) {
5681                 mod_freesync_handle_preflip(
5682                         dm->freesync_module,
5683                         surface,
5684                         new_stream,
5685                         flip_timestamp_in_us,
5686                         &vrr_params);
5687
5688                 if (adev->family < AMDGPU_FAMILY_AI &&
5689                     amdgpu_dm_vrr_active(new_crtc_state)) {
5690                         mod_freesync_handle_v_update(dm->freesync_module,
5691                                                      new_stream, &vrr_params);
5692
5693                         /* Need to call this before the frame ends. */
5694                         dc_stream_adjust_vmin_vmax(dm->dc,
5695                                                    new_crtc_state->stream,
5696                                                    &vrr_params.adjust);
5697                 }
5698         }
5699
5700         mod_freesync_build_vrr_infopacket(
5701                 dm->freesync_module,
5702                 new_stream,
5703                 &vrr_params,
5704                 PACKET_TYPE_VRR,
5705                 TRANSFER_FUNC_UNKNOWN,
5706                 &vrr_infopacket);
5707
5708         new_crtc_state->freesync_timing_changed |=
5709                 (memcmp(&new_crtc_state->vrr_params.adjust,
5710                         &vrr_params.adjust,
5711                         sizeof(vrr_params.adjust)) != 0);
5712
5713         new_crtc_state->freesync_vrr_info_changed |=
5714                 (memcmp(&new_crtc_state->vrr_infopacket,
5715                         &vrr_infopacket,
5716                         sizeof(vrr_infopacket)) != 0);
5717
5718         new_crtc_state->vrr_params = vrr_params;
5719         new_crtc_state->vrr_infopacket = vrr_infopacket;
5720
5721         new_stream->adjust = new_crtc_state->vrr_params.adjust;
5722         new_stream->vrr_infopacket = vrr_infopacket;
5723
5724         if (new_crtc_state->freesync_vrr_info_changed)
5725                 DRM_DEBUG_KMS("VRR packet update: crtc=%u enabled=%d state=%d",
5726                               new_crtc_state->base.crtc->base.id,
5727                               (int)new_crtc_state->base.vrr_enabled,
5728                               (int)vrr_params.state);
5729
5730         spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
5731 }
5732
5733 static void pre_update_freesync_state_on_stream(
5734         struct amdgpu_display_manager *dm,
5735         struct dm_crtc_state *new_crtc_state)
5736 {
5737         struct dc_stream_state *new_stream = new_crtc_state->stream;
5738         struct mod_vrr_params vrr_params;
5739         struct mod_freesync_config config = new_crtc_state->freesync_config;
5740         struct amdgpu_device *adev = dm->adev;
5741         unsigned long flags;
5742
5743         if (!new_stream)
5744                 return;
5745
5746         /*
5747          * TODO: Determine why min/max totals and vrefresh can be 0 here.
5748          * For now it's sufficient to just guard against these conditions.
5749          */
5750         if (!new_stream->timing.h_total || !new_stream->timing.v_total)
5751                 return;
5752
5753         spin_lock_irqsave(&adev->ddev->event_lock, flags);
5754         vrr_params = new_crtc_state->vrr_params;
5755
5756         if (new_crtc_state->vrr_supported &&
5757             config.min_refresh_in_uhz &&
5758             config.max_refresh_in_uhz) {
5759                 config.state = new_crtc_state->base.vrr_enabled ?
5760                         VRR_STATE_ACTIVE_VARIABLE :
5761                         VRR_STATE_INACTIVE;
5762         } else {
5763                 config.state = VRR_STATE_UNSUPPORTED;
5764         }
5765
5766         mod_freesync_build_vrr_params(dm->freesync_module,
5767                                       new_stream,
5768                                       &config, &vrr_params);
5769
5770         new_crtc_state->freesync_timing_changed |=
5771                 (memcmp(&new_crtc_state->vrr_params.adjust,
5772                         &vrr_params.adjust,
5773                         sizeof(vrr_params.adjust)) != 0);
5774
5775         new_crtc_state->vrr_params = vrr_params;
5776         spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
5777 }
5778
5779 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
5780                                             struct dm_crtc_state *new_state)
5781 {
5782         bool old_vrr_active = amdgpu_dm_vrr_active(old_state);
5783         bool new_vrr_active = amdgpu_dm_vrr_active(new_state);
5784
5785         if (!old_vrr_active && new_vrr_active) {
5786                 /* Transition VRR inactive -> active:
5787                  * While VRR is active, we must not disable vblank irq, as a
5788                  * reenable after disable would compute bogus vblank/pflip
5789                  * timestamps if it likely happened inside display front-porch.
5790                  *
5791                  * We also need vupdate irq for the actual core vblank handling
5792                  * at end of vblank.
5793                  */
5794                 dm_set_vupdate_irq(new_state->base.crtc, true);
5795                 drm_crtc_vblank_get(new_state->base.crtc);
5796                 DRM_DEBUG_DRIVER("%s: crtc=%u VRR off->on: Get vblank ref\n",
5797                                  __func__, new_state->base.crtc->base.id);
5798         } else if (old_vrr_active && !new_vrr_active) {
5799                 /* Transition VRR active -> inactive:
5800                  * Allow vblank irq disable again for fixed refresh rate.
5801                  */
5802                 dm_set_vupdate_irq(new_state->base.crtc, false);
5803                 drm_crtc_vblank_put(new_state->base.crtc);
5804                 DRM_DEBUG_DRIVER("%s: crtc=%u VRR on->off: Drop vblank ref\n",
5805                                  __func__, new_state->base.crtc->base.id);
5806         }
5807 }
5808
5809 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
5810 {
5811         struct drm_plane *plane;
5812         struct drm_plane_state *old_plane_state, *new_plane_state;
5813         int i;
5814
5815         /*
5816          * TODO: Make this per-stream so we don't issue redundant updates for
5817          * commits with multiple streams.
5818          */
5819         for_each_oldnew_plane_in_state(state, plane, old_plane_state,
5820                                        new_plane_state, i)
5821                 if (plane->type == DRM_PLANE_TYPE_CURSOR)
5822                         handle_cursor_update(plane, old_plane_state);
5823 }
5824
5825 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
5826                                     struct dc_state *dc_state,
5827                                     struct drm_device *dev,
5828                                     struct amdgpu_display_manager *dm,
5829                                     struct drm_crtc *pcrtc,
5830                                     bool wait_for_vblank)
5831 {
5832         uint32_t i;
5833         uint64_t timestamp_ns;
5834         struct drm_plane *plane;
5835         struct drm_plane_state *old_plane_state, *new_plane_state;
5836         struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
5837         struct drm_crtc_state *new_pcrtc_state =
5838                         drm_atomic_get_new_crtc_state(state, pcrtc);
5839         struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
5840         struct dm_crtc_state *dm_old_crtc_state =
5841                         to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
5842         int planes_count = 0, vpos, hpos;
5843         long r;
5844         unsigned long flags;
5845         struct amdgpu_bo *abo;
5846         uint64_t tiling_flags;
5847         uint32_t target_vblank, last_flip_vblank;
5848         bool vrr_active = amdgpu_dm_vrr_active(acrtc_state);
5849         bool pflip_present = false;
5850         bool swizzle = true;
5851         struct {
5852                 struct dc_surface_update surface_updates[MAX_SURFACES];
5853                 struct dc_plane_info plane_infos[MAX_SURFACES];
5854                 struct dc_scaling_info scaling_infos[MAX_SURFACES];
5855                 struct dc_flip_addrs flip_addrs[MAX_SURFACES];
5856                 struct dc_stream_update stream_update;
5857         } *bundle;
5858
5859         bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
5860
5861         if (!bundle) {
5862                 dm_error("Failed to allocate update bundle\n");
5863                 goto cleanup;
5864         }
5865
5866         /*
5867          * Disable the cursor first if we're disabling all the planes.
5868          * It'll remain on the screen after the planes are re-enabled
5869          * if we don't.
5870          */
5871         if (acrtc_state->active_planes == 0)
5872                 amdgpu_dm_commit_cursors(state);
5873
5874         /* update planes when needed */
5875         for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
5876                 struct drm_crtc *crtc = new_plane_state->crtc;
5877                 struct drm_crtc_state *new_crtc_state;
5878                 struct drm_framebuffer *fb = new_plane_state->fb;
5879                 bool plane_needs_flip;
5880                 struct dc_plane_state *dc_plane;
5881                 struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
5882
5883                 /* Cursor plane is handled after stream updates */
5884                 if (plane->type == DRM_PLANE_TYPE_CURSOR)
5885                         continue;
5886
5887                 if (!fb || !crtc || pcrtc != crtc)
5888                         continue;
5889
5890                 new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
5891                 if (!new_crtc_state->active)
5892                         continue;
5893
5894                 dc_plane = dm_new_plane_state->dc_state;
5895
5896                 if (dc_plane && !dc_plane->tiling_info.gfx9.swizzle)
5897                         swizzle = false;
5898
5899                 bundle->surface_updates[planes_count].surface = dc_plane;
5900                 if (new_pcrtc_state->color_mgmt_changed) {
5901                         bundle->surface_updates[planes_count].gamma = dc_plane->gamma_correction;
5902                         bundle->surface_updates[planes_count].in_transfer_func = dc_plane->in_transfer_func;
5903                 }
5904
5905                 fill_dc_scaling_info(new_plane_state,
5906                                      &bundle->scaling_infos[planes_count]);
5907
5908                 bundle->surface_updates[planes_count].scaling_info =
5909                         &bundle->scaling_infos[planes_count];
5910
5911                 plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
5912
5913                 pflip_present = pflip_present || plane_needs_flip;
5914
5915                 if (!plane_needs_flip) {
5916                         planes_count += 1;
5917                         continue;
5918                 }
5919
5920                 abo = gem_to_amdgpu_bo(fb->obj[0]);
5921
5922                 /*
5923                  * Wait for all fences on this FB. Do limited wait to avoid
5924                  * deadlock during GPU reset when this fence will not signal
5925                  * but we hold reservation lock for the BO.
5926                  */
5927                 r = dma_resv_wait_timeout_rcu(abo->tbo.base.resv, true,
5928                                                         false,
5929                                                         msecs_to_jiffies(5000));
5930                 if (unlikely(r <= 0))
5931                         DRM_ERROR("Waiting for fences timed out!");
5932
5933                 /*
5934                  * TODO This might fail and hence better not used, wait
5935                  * explicitly on fences instead
5936                  * and in general should be called for
5937                  * blocking commit to as per framework helpers
5938                  */
5939                 r = amdgpu_bo_reserve(abo, true);
5940                 if (unlikely(r != 0))
5941                         DRM_ERROR("failed to reserve buffer before flip\n");
5942
5943                 amdgpu_bo_get_tiling_flags(abo, &tiling_flags);
5944
5945                 amdgpu_bo_unreserve(abo);
5946
5947                 fill_dc_plane_info_and_addr(
5948                         dm->adev, new_plane_state, tiling_flags,
5949                         &bundle->plane_infos[planes_count],
5950                         &bundle->flip_addrs[planes_count].address);
5951
5952                 bundle->surface_updates[planes_count].plane_info =
5953                         &bundle->plane_infos[planes_count];
5954
5955                 /*
5956                  * Only allow immediate flips for fast updates that don't
5957                  * change FB pitch, DCC state, rotation or mirroing.
5958                  */
5959                 bundle->flip_addrs[planes_count].flip_immediate =
5960                         crtc->state->async_flip &&
5961                         acrtc_state->update_type == UPDATE_TYPE_FAST;
5962
5963                 timestamp_ns = ktime_get_ns();
5964                 bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
5965                 bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
5966                 bundle->surface_updates[planes_count].surface = dc_plane;
5967
5968                 if (!bundle->surface_updates[planes_count].surface) {
5969                         DRM_ERROR("No surface for CRTC: id=%d\n",
5970                                         acrtc_attach->crtc_id);
5971                         continue;
5972                 }
5973
5974                 if (plane == pcrtc->primary)
5975                         update_freesync_state_on_stream(
5976                                 dm,
5977                                 acrtc_state,
5978                                 acrtc_state->stream,
5979                                 dc_plane,
5980                                 bundle->flip_addrs[planes_count].flip_timestamp_in_us);
5981
5982                 DRM_DEBUG_DRIVER("%s Flipping to hi: 0x%x, low: 0x%x\n",
5983                                  __func__,
5984                                  bundle->flip_addrs[planes_count].address.grph.addr.high_part,
5985                                  bundle->flip_addrs[planes_count].address.grph.addr.low_part);
5986
5987                 planes_count += 1;
5988
5989         }
5990
5991         if (pflip_present) {
5992                 if (!vrr_active) {
5993                         /* Use old throttling in non-vrr fixed refresh rate mode
5994                          * to keep flip scheduling based on target vblank counts
5995                          * working in a backwards compatible way, e.g., for
5996                          * clients using the GLX_OML_sync_control extension or
5997                          * DRI3/Present extension with defined target_msc.
5998                          */
5999                         last_flip_vblank = amdgpu_get_vblank_counter_kms(dm->ddev, acrtc_attach->crtc_id);
6000                 }
6001                 else {
6002                         /* For variable refresh rate mode only:
6003                          * Get vblank of last completed flip to avoid > 1 vrr
6004                          * flips per video frame by use of throttling, but allow
6005                          * flip programming anywhere in the possibly large
6006                          * variable vrr vblank interval for fine-grained flip
6007                          * timing control and more opportunity to avoid stutter
6008                          * on late submission of flips.
6009                          */
6010                         spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
6011                         last_flip_vblank = acrtc_attach->last_flip_vblank;
6012                         spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
6013                 }
6014
6015                 target_vblank = last_flip_vblank + wait_for_vblank;
6016
6017                 /*
6018                  * Wait until we're out of the vertical blank period before the one
6019                  * targeted by the flip
6020                  */
6021                 while ((acrtc_attach->enabled &&
6022                         (amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
6023                                                             0, &vpos, &hpos, NULL,
6024                                                             NULL, &pcrtc->hwmode)
6025                          & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
6026                         (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
6027                         (int)(target_vblank -
6028                           amdgpu_get_vblank_counter_kms(dm->ddev, acrtc_attach->crtc_id)) > 0)) {
6029                         usleep_range(1000, 1100);
6030                 }
6031
6032                 if (acrtc_attach->base.state->event) {
6033                         drm_crtc_vblank_get(pcrtc);
6034
6035                         spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
6036
6037                         WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
6038                         prepare_flip_isr(acrtc_attach);
6039
6040                         spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
6041                 }
6042
6043                 if (acrtc_state->stream) {
6044                         if (acrtc_state->freesync_vrr_info_changed)
6045                                 bundle->stream_update.vrr_infopacket =
6046                                         &acrtc_state->stream->vrr_infopacket;
6047                 }
6048         }
6049
6050         /* Update the planes if changed or disable if we don't have any. */
6051         if ((planes_count || acrtc_state->active_planes == 0) &&
6052                 acrtc_state->stream) {
6053                 bundle->stream_update.stream = acrtc_state->stream;
6054                 if (new_pcrtc_state->mode_changed) {
6055                         bundle->stream_update.src = acrtc_state->stream->src;
6056                         bundle->stream_update.dst = acrtc_state->stream->dst;
6057                 }
6058
6059                 if (new_pcrtc_state->color_mgmt_changed) {
6060                         /*
6061                          * TODO: This isn't fully correct since we've actually
6062                          * already modified the stream in place.
6063                          */
6064                         bundle->stream_update.gamut_remap =
6065                                 &acrtc_state->stream->gamut_remap_matrix;
6066                         bundle->stream_update.output_csc_transform =
6067                                 &acrtc_state->stream->csc_color_matrix;
6068                         bundle->stream_update.out_transfer_func =
6069                                 acrtc_state->stream->out_transfer_func;
6070                 }
6071
6072                 acrtc_state->stream->abm_level = acrtc_state->abm_level;
6073                 if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
6074                         bundle->stream_update.abm_level = &acrtc_state->abm_level;
6075
6076                 /*
6077                  * If FreeSync state on the stream has changed then we need to
6078                  * re-adjust the min/max bounds now that DC doesn't handle this
6079                  * as part of commit.
6080                  */
6081                 if (amdgpu_dm_vrr_active(dm_old_crtc_state) !=
6082                     amdgpu_dm_vrr_active(acrtc_state)) {
6083                         spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
6084                         dc_stream_adjust_vmin_vmax(
6085                                 dm->dc, acrtc_state->stream,
6086                                 &acrtc_state->vrr_params.adjust);
6087                         spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
6088                 }
6089                 mutex_lock(&dm->dc_lock);
6090                 if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
6091                                 acrtc_state->stream->link->psr_allow_active)
6092                         amdgpu_dm_psr_disable(acrtc_state->stream);
6093
6094                 dc_commit_updates_for_stream(dm->dc,
6095                                                      bundle->surface_updates,
6096                                                      planes_count,
6097                                                      acrtc_state->stream,
6098                                                      &bundle->stream_update,
6099                                                      dc_state);
6100
6101                 if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
6102                                                 acrtc_state->stream->psr_version &&
6103                                                 !acrtc_state->stream->link->psr_feature_enabled)
6104                         amdgpu_dm_link_setup_psr(acrtc_state->stream);
6105                 else if ((acrtc_state->update_type == UPDATE_TYPE_FAST) &&
6106                                                 acrtc_state->stream->link->psr_feature_enabled &&
6107                                                 !acrtc_state->stream->link->psr_allow_active &&
6108                                                 swizzle) {
6109                         amdgpu_dm_psr_enable(acrtc_state->stream);
6110                 }
6111
6112                 mutex_unlock(&dm->dc_lock);
6113         }
6114
6115         /*
6116          * Update cursor state *after* programming all the planes.
6117          * This avoids redundant programming in the case where we're going
6118          * to be disabling a single plane - those pipes are being disabled.
6119          */
6120         if (acrtc_state->active_planes)
6121                 amdgpu_dm_commit_cursors(state);
6122
6123 cleanup:
6124         kfree(bundle);
6125 }
6126
6127 static void amdgpu_dm_commit_audio(struct drm_device *dev,
6128                                    struct drm_atomic_state *state)
6129 {
6130         struct amdgpu_device *adev = dev->dev_private;
6131         struct amdgpu_dm_connector *aconnector;
6132         struct drm_connector *connector;
6133         struct drm_connector_state *old_con_state, *new_con_state;
6134         struct drm_crtc_state *new_crtc_state;
6135         struct dm_crtc_state *new_dm_crtc_state;
6136         const struct dc_stream_status *status;
6137         int i, inst;
6138
6139         /* Notify device removals. */
6140         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
6141                 if (old_con_state->crtc != new_con_state->crtc) {
6142                         /* CRTC changes require notification. */
6143                         goto notify;
6144                 }
6145
6146                 if (!new_con_state->crtc)
6147                         continue;
6148
6149                 new_crtc_state = drm_atomic_get_new_crtc_state(
6150                         state, new_con_state->crtc);
6151
6152                 if (!new_crtc_state)
6153                         continue;
6154
6155                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
6156                         continue;
6157
6158         notify:
6159                 aconnector = to_amdgpu_dm_connector(connector);
6160
6161                 mutex_lock(&adev->dm.audio_lock);
6162                 inst = aconnector->audio_inst;
6163                 aconnector->audio_inst = -1;
6164                 mutex_unlock(&adev->dm.audio_lock);
6165
6166                 amdgpu_dm_audio_eld_notify(adev, inst);
6167         }
6168
6169         /* Notify audio device additions. */
6170         for_each_new_connector_in_state(state, connector, new_con_state, i) {
6171                 if (!new_con_state->crtc)
6172                         continue;
6173
6174                 new_crtc_state = drm_atomic_get_new_crtc_state(
6175                         state, new_con_state->crtc);
6176
6177                 if (!new_crtc_state)
6178                         continue;
6179
6180                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
6181                         continue;
6182
6183                 new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
6184                 if (!new_dm_crtc_state->stream)
6185                         continue;
6186
6187                 status = dc_stream_get_status(new_dm_crtc_state->stream);
6188                 if (!status)
6189                         continue;
6190
6191                 aconnector = to_amdgpu_dm_connector(connector);
6192
6193                 mutex_lock(&adev->dm.audio_lock);
6194                 inst = status->audio_inst;
6195                 aconnector->audio_inst = inst;
6196                 mutex_unlock(&adev->dm.audio_lock);
6197
6198                 amdgpu_dm_audio_eld_notify(adev, inst);
6199         }
6200 }
6201
6202 /*
6203  * Enable interrupts on CRTCs that are newly active, undergone
6204  * a modeset, or have active planes again.
6205  *
6206  * Done in two passes, based on the for_modeset flag:
6207  * Pass 1: For CRTCs going through modeset
6208  * Pass 2: For CRTCs going from 0 to n active planes
6209  *
6210  * Interrupts can only be enabled after the planes are programmed,
6211  * so this requires a two-pass approach since we don't want to
6212  * just defer the interrupts until after commit planes every time.
6213  */
6214 static void amdgpu_dm_enable_crtc_interrupts(struct drm_device *dev,
6215                                              struct drm_atomic_state *state,
6216                                              bool for_modeset)
6217 {
6218         struct amdgpu_device *adev = dev->dev_private;
6219         struct drm_crtc *crtc;
6220         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
6221         int i;
6222 #ifdef CONFIG_DEBUG_FS
6223         enum amdgpu_dm_pipe_crc_source source;
6224 #endif
6225
6226         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
6227                                       new_crtc_state, i) {
6228                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
6229                 struct dm_crtc_state *dm_new_crtc_state =
6230                         to_dm_crtc_state(new_crtc_state);
6231                 struct dm_crtc_state *dm_old_crtc_state =
6232                         to_dm_crtc_state(old_crtc_state);
6233                 bool modeset = drm_atomic_crtc_needs_modeset(new_crtc_state);
6234                 bool run_pass;
6235
6236                 run_pass = (for_modeset && modeset) ||
6237                            (!for_modeset && !modeset &&
6238                             !dm_old_crtc_state->interrupts_enabled);
6239
6240                 if (!run_pass)
6241                         continue;
6242
6243                 if (!dm_new_crtc_state->interrupts_enabled)
6244                         continue;
6245
6246                 manage_dm_interrupts(adev, acrtc, true);
6247
6248 #ifdef CONFIG_DEBUG_FS
6249                 /* The stream has changed so CRC capture needs to re-enabled. */
6250                 source = dm_new_crtc_state->crc_src;
6251                 if (amdgpu_dm_is_valid_crc_source(source)) {
6252                         amdgpu_dm_crtc_configure_crc_source(
6253                                 crtc, dm_new_crtc_state,
6254                                 dm_new_crtc_state->crc_src);
6255                 }
6256 #endif
6257         }
6258 }
6259
6260 /*
6261  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
6262  * @crtc_state: the DRM CRTC state
6263  * @stream_state: the DC stream state.
6264  *
6265  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
6266  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
6267  */
6268 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
6269                                                 struct dc_stream_state *stream_state)
6270 {
6271         stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
6272 }
6273
6274 static int amdgpu_dm_atomic_commit(struct drm_device *dev,
6275                                    struct drm_atomic_state *state,
6276                                    bool nonblock)
6277 {
6278         struct drm_crtc *crtc;
6279         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
6280         struct amdgpu_device *adev = dev->dev_private;
6281         int i;
6282
6283         /*
6284          * We evade vblank and pflip interrupts on CRTCs that are undergoing
6285          * a modeset, being disabled, or have no active planes.
6286          *
6287          * It's done in atomic commit rather than commit tail for now since
6288          * some of these interrupt handlers access the current CRTC state and
6289          * potentially the stream pointer itself.
6290          *
6291          * Since the atomic state is swapped within atomic commit and not within
6292          * commit tail this would leave to new state (that hasn't been committed yet)
6293          * being accesssed from within the handlers.
6294          *
6295          * TODO: Fix this so we can do this in commit tail and not have to block
6296          * in atomic check.
6297          */
6298         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6299                 struct dm_crtc_state *dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6300                 struct dm_crtc_state *dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6301                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
6302
6303                 if (dm_old_crtc_state->interrupts_enabled &&
6304                     (!dm_new_crtc_state->interrupts_enabled ||
6305                      drm_atomic_crtc_needs_modeset(new_crtc_state)))
6306                         manage_dm_interrupts(adev, acrtc, false);
6307         }
6308         /*
6309          * Add check here for SoC's that support hardware cursor plane, to
6310          * unset legacy_cursor_update
6311          */
6312
6313         return drm_atomic_helper_commit(dev, state, nonblock);
6314
6315         /*TODO Handle EINTR, reenable IRQ*/
6316 }
6317
6318 /**
6319  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
6320  * @state: The atomic state to commit
6321  *
6322  * This will tell DC to commit the constructed DC state from atomic_check,
6323  * programming the hardware. Any failures here implies a hardware failure, since
6324  * atomic check should have filtered anything non-kosher.
6325  */
6326 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
6327 {
6328         struct drm_device *dev = state->dev;
6329         struct amdgpu_device *adev = dev->dev_private;
6330         struct amdgpu_display_manager *dm = &adev->dm;
6331         struct dm_atomic_state *dm_state;
6332         struct dc_state *dc_state = NULL, *dc_state_temp = NULL;
6333         uint32_t i, j;
6334         struct drm_crtc *crtc;
6335         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
6336         unsigned long flags;
6337         bool wait_for_vblank = true;
6338         struct drm_connector *connector;
6339         struct drm_connector_state *old_con_state, *new_con_state;
6340         struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
6341         int crtc_disable_count = 0;
6342
6343         drm_atomic_helper_update_legacy_modeset_state(dev, state);
6344
6345         dm_state = dm_atomic_get_new_state(state);
6346         if (dm_state && dm_state->context) {
6347                 dc_state = dm_state->context;
6348         } else {
6349                 /* No state changes, retain current state. */
6350                 dc_state_temp = dc_create_state(dm->dc);
6351                 ASSERT(dc_state_temp);
6352                 dc_state = dc_state_temp;
6353                 dc_resource_state_copy_construct_current(dm->dc, dc_state);
6354         }
6355
6356         /* update changed items */
6357         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6358                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
6359
6360                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6361                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6362
6363                 DRM_DEBUG_DRIVER(
6364                         "amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
6365                         "planes_changed:%d, mode_changed:%d,active_changed:%d,"
6366                         "connectors_changed:%d\n",
6367                         acrtc->crtc_id,
6368                         new_crtc_state->enable,
6369                         new_crtc_state->active,
6370                         new_crtc_state->planes_changed,
6371                         new_crtc_state->mode_changed,
6372                         new_crtc_state->active_changed,
6373                         new_crtc_state->connectors_changed);
6374
6375                 /* Copy all transient state flags into dc state */
6376                 if (dm_new_crtc_state->stream) {
6377                         amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
6378                                                             dm_new_crtc_state->stream);
6379                 }
6380
6381                 /* handles headless hotplug case, updating new_state and
6382                  * aconnector as needed
6383                  */
6384
6385                 if (modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
6386
6387                         DRM_DEBUG_DRIVER("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
6388
6389                         if (!dm_new_crtc_state->stream) {
6390                                 /*
6391                                  * this could happen because of issues with
6392                                  * userspace notifications delivery.
6393                                  * In this case userspace tries to set mode on
6394                                  * display which is disconnected in fact.
6395                                  * dc_sink is NULL in this case on aconnector.
6396                                  * We expect reset mode will come soon.
6397                                  *
6398                                  * This can also happen when unplug is done
6399                                  * during resume sequence ended
6400                                  *
6401                                  * In this case, we want to pretend we still
6402                                  * have a sink to keep the pipe running so that
6403                                  * hw state is consistent with the sw state
6404                                  */
6405                                 DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
6406                                                 __func__, acrtc->base.base.id);
6407                                 continue;
6408                         }
6409
6410                         if (dm_old_crtc_state->stream)
6411                                 remove_stream(adev, acrtc, dm_old_crtc_state->stream);
6412
6413                         pm_runtime_get_noresume(dev->dev);
6414
6415                         acrtc->enabled = true;
6416                         acrtc->hw_mode = new_crtc_state->mode;
6417                         crtc->hwmode = new_crtc_state->mode;
6418                 } else if (modereset_required(new_crtc_state)) {
6419                         DRM_DEBUG_DRIVER("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
6420                         /* i.e. reset mode */
6421                         if (dm_old_crtc_state->stream) {
6422                                 if (dm_old_crtc_state->stream->link->psr_allow_active)
6423                                         amdgpu_dm_psr_disable(dm_old_crtc_state->stream);
6424
6425                                 remove_stream(adev, acrtc, dm_old_crtc_state->stream);
6426                         }
6427                 }
6428         } /* for_each_crtc_in_state() */
6429
6430         if (dc_state) {
6431                 dm_enable_per_frame_crtc_master_sync(dc_state);
6432                 mutex_lock(&dm->dc_lock);
6433                 WARN_ON(!dc_commit_state(dm->dc, dc_state));
6434                 mutex_unlock(&dm->dc_lock);
6435         }
6436
6437         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
6438                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
6439
6440                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6441
6442                 if (dm_new_crtc_state->stream != NULL) {
6443                         const struct dc_stream_status *status =
6444                                         dc_stream_get_status(dm_new_crtc_state->stream);
6445
6446                         if (!status)
6447                                 status = dc_stream_get_status_from_state(dc_state,
6448                                                                          dm_new_crtc_state->stream);
6449
6450                         if (!status)
6451                                 DC_ERR("got no status for stream %p on acrtc%p\n", dm_new_crtc_state->stream, acrtc);
6452                         else
6453                                 acrtc->otg_inst = status->primary_otg_inst;
6454                 }
6455         }
6456 #ifdef CONFIG_DRM_AMD_DC_HDCP
6457         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
6458                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
6459                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
6460                 struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6461
6462                 new_crtc_state = NULL;
6463
6464                 if (acrtc)
6465                         new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
6466
6467                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6468
6469                 if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
6470                     connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
6471                         hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
6472                         new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
6473                         continue;
6474                 }
6475
6476                 if (is_content_protection_different(new_con_state, old_con_state, connector, adev->dm.hdcp_workqueue))
6477                         update_content_protection(new_con_state, connector, adev->dm.hdcp_workqueue);
6478         }
6479 #endif
6480
6481         /* Handle connector state changes */
6482         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
6483                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
6484                 struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
6485                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
6486                 struct dc_surface_update dummy_updates[MAX_SURFACES];
6487                 struct dc_stream_update stream_update;
6488                 struct dc_info_packet hdr_packet;
6489                 struct dc_stream_status *status = NULL;
6490                 bool abm_changed, hdr_changed, scaling_changed;
6491
6492                 memset(&dummy_updates, 0, sizeof(dummy_updates));
6493                 memset(&stream_update, 0, sizeof(stream_update));
6494
6495                 if (acrtc) {
6496                         new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
6497                         old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
6498                 }
6499
6500                 /* Skip any modesets/resets */
6501                 if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
6502                         continue;
6503
6504                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6505                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6506
6507                 scaling_changed = is_scaling_state_different(dm_new_con_state,
6508                                                              dm_old_con_state);
6509
6510                 abm_changed = dm_new_crtc_state->abm_level !=
6511                               dm_old_crtc_state->abm_level;
6512
6513                 hdr_changed =
6514                         is_hdr_metadata_different(old_con_state, new_con_state);
6515
6516                 if (!scaling_changed && !abm_changed && !hdr_changed)
6517                         continue;
6518
6519                 stream_update.stream = dm_new_crtc_state->stream;
6520                 if (scaling_changed) {
6521                         update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
6522                                         dm_new_con_state, dm_new_crtc_state->stream);
6523
6524                         stream_update.src = dm_new_crtc_state->stream->src;
6525                         stream_update.dst = dm_new_crtc_state->stream->dst;
6526                 }
6527
6528                 if (abm_changed) {
6529                         dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
6530
6531                         stream_update.abm_level = &dm_new_crtc_state->abm_level;
6532                 }
6533
6534                 if (hdr_changed) {
6535                         fill_hdr_info_packet(new_con_state, &hdr_packet);
6536                         stream_update.hdr_static_metadata = &hdr_packet;
6537                 }
6538
6539                 status = dc_stream_get_status(dm_new_crtc_state->stream);
6540                 WARN_ON(!status);
6541                 WARN_ON(!status->plane_count);
6542
6543                 /*
6544                  * TODO: DC refuses to perform stream updates without a dc_surface_update.
6545                  * Here we create an empty update on each plane.
6546                  * To fix this, DC should permit updating only stream properties.
6547                  */
6548                 for (j = 0; j < status->plane_count; j++)
6549                         dummy_updates[j].surface = status->plane_states[0];
6550
6551
6552                 mutex_lock(&dm->dc_lock);
6553                 dc_commit_updates_for_stream(dm->dc,
6554                                                      dummy_updates,
6555                                                      status->plane_count,
6556                                                      dm_new_crtc_state->stream,
6557                                                      &stream_update,
6558                                                      dc_state);
6559                 mutex_unlock(&dm->dc_lock);
6560         }
6561
6562         /* Count number of newly disabled CRTCs for dropping PM refs later. */
6563         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
6564                                       new_crtc_state, i) {
6565                 if (old_crtc_state->active && !new_crtc_state->active)
6566                         crtc_disable_count++;
6567
6568                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6569                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6570
6571                 /* Update freesync active state. */
6572                 pre_update_freesync_state_on_stream(dm, dm_new_crtc_state);
6573
6574                 /* Handle vrr on->off / off->on transitions */
6575                 amdgpu_dm_handle_vrr_transition(dm_old_crtc_state,
6576                                                 dm_new_crtc_state);
6577         }
6578
6579         /* Enable interrupts for CRTCs going through a modeset. */
6580         amdgpu_dm_enable_crtc_interrupts(dev, state, true);
6581
6582         for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
6583                 if (new_crtc_state->async_flip)
6584                         wait_for_vblank = false;
6585
6586         /* update planes when needed per crtc*/
6587         for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
6588                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6589
6590                 if (dm_new_crtc_state->stream)
6591                         amdgpu_dm_commit_planes(state, dc_state, dev,
6592                                                 dm, crtc, wait_for_vblank);
6593         }
6594
6595         /* Enable interrupts for CRTCs going from 0 to n active planes. */
6596         amdgpu_dm_enable_crtc_interrupts(dev, state, false);
6597
6598         /* Update audio instances for each connector. */
6599         amdgpu_dm_commit_audio(dev, state);
6600
6601         /*
6602          * send vblank event on all events not handled in flip and
6603          * mark consumed event for drm_atomic_helper_commit_hw_done
6604          */
6605         spin_lock_irqsave(&adev->ddev->event_lock, flags);
6606         for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
6607
6608                 if (new_crtc_state->event)
6609                         drm_send_event_locked(dev, &new_crtc_state->event->base);
6610
6611                 new_crtc_state->event = NULL;
6612         }
6613         spin_unlock_irqrestore(&adev->ddev->event_lock, flags);
6614
6615         /* Signal HW programming completion */
6616         drm_atomic_helper_commit_hw_done(state);
6617
6618         if (wait_for_vblank)
6619                 drm_atomic_helper_wait_for_flip_done(dev, state);
6620
6621         drm_atomic_helper_cleanup_planes(dev, state);
6622
6623         /*
6624          * Finally, drop a runtime PM reference for each newly disabled CRTC,
6625          * so we can put the GPU into runtime suspend if we're not driving any
6626          * displays anymore
6627          */
6628         for (i = 0; i < crtc_disable_count; i++)
6629                 pm_runtime_put_autosuspend(dev->dev);
6630         pm_runtime_mark_last_busy(dev->dev);
6631
6632         if (dc_state_temp)
6633                 dc_release_state(dc_state_temp);
6634 }
6635
6636
6637 static int dm_force_atomic_commit(struct drm_connector *connector)
6638 {
6639         int ret = 0;
6640         struct drm_device *ddev = connector->dev;
6641         struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
6642         struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
6643         struct drm_plane *plane = disconnected_acrtc->base.primary;
6644         struct drm_connector_state *conn_state;
6645         struct drm_crtc_state *crtc_state;
6646         struct drm_plane_state *plane_state;
6647
6648         if (!state)
6649                 return -ENOMEM;
6650
6651         state->acquire_ctx = ddev->mode_config.acquire_ctx;
6652
6653         /* Construct an atomic state to restore previous display setting */
6654
6655         /*
6656          * Attach connectors to drm_atomic_state
6657          */
6658         conn_state = drm_atomic_get_connector_state(state, connector);
6659
6660         ret = PTR_ERR_OR_ZERO(conn_state);
6661         if (ret)
6662                 goto err;
6663
6664         /* Attach crtc to drm_atomic_state*/
6665         crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
6666
6667         ret = PTR_ERR_OR_ZERO(crtc_state);
6668         if (ret)
6669                 goto err;
6670
6671         /* force a restore */
6672         crtc_state->mode_changed = true;
6673
6674         /* Attach plane to drm_atomic_state */
6675         plane_state = drm_atomic_get_plane_state(state, plane);
6676
6677         ret = PTR_ERR_OR_ZERO(plane_state);
6678         if (ret)
6679                 goto err;
6680
6681
6682         /* Call commit internally with the state we just constructed */
6683         ret = drm_atomic_commit(state);
6684         if (!ret)
6685                 return 0;
6686
6687 err:
6688         DRM_ERROR("Restoring old state failed with %i\n", ret);
6689         drm_atomic_state_put(state);
6690
6691         return ret;
6692 }
6693
6694 /*
6695  * This function handles all cases when set mode does not come upon hotplug.
6696  * This includes when a display is unplugged then plugged back into the
6697  * same port and when running without usermode desktop manager supprot
6698  */
6699 void dm_restore_drm_connector_state(struct drm_device *dev,
6700                                     struct drm_connector *connector)
6701 {
6702         struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6703         struct amdgpu_crtc *disconnected_acrtc;
6704         struct dm_crtc_state *acrtc_state;
6705
6706         if (!aconnector->dc_sink || !connector->state || !connector->encoder)
6707                 return;
6708
6709         disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
6710         if (!disconnected_acrtc)
6711                 return;
6712
6713         acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
6714         if (!acrtc_state->stream)
6715                 return;
6716
6717         /*
6718          * If the previous sink is not released and different from the current,
6719          * we deduce we are in a state where we can not rely on usermode call
6720          * to turn on the display, so we do it here
6721          */
6722         if (acrtc_state->stream->sink != aconnector->dc_sink)
6723                 dm_force_atomic_commit(&aconnector->base);
6724 }
6725
6726 /*
6727  * Grabs all modesetting locks to serialize against any blocking commits,
6728  * Waits for completion of all non blocking commits.
6729  */
6730 static int do_aquire_global_lock(struct drm_device *dev,
6731                                  struct drm_atomic_state *state)
6732 {
6733         struct drm_crtc *crtc;
6734         struct drm_crtc_commit *commit;
6735         long ret;
6736
6737         /*
6738          * Adding all modeset locks to aquire_ctx will
6739          * ensure that when the framework release it the
6740          * extra locks we are locking here will get released to
6741          */
6742         ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
6743         if (ret)
6744                 return ret;
6745
6746         list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
6747                 spin_lock(&crtc->commit_lock);
6748                 commit = list_first_entry_or_null(&crtc->commit_list,
6749                                 struct drm_crtc_commit, commit_entry);
6750                 if (commit)
6751                         drm_crtc_commit_get(commit);
6752                 spin_unlock(&crtc->commit_lock);
6753
6754                 if (!commit)
6755                         continue;
6756
6757                 /*
6758                  * Make sure all pending HW programming completed and
6759                  * page flips done
6760                  */
6761                 ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
6762
6763                 if (ret > 0)
6764                         ret = wait_for_completion_interruptible_timeout(
6765                                         &commit->flip_done, 10*HZ);
6766
6767                 if (ret == 0)
6768                         DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done "
6769                                   "timed out\n", crtc->base.id, crtc->name);
6770
6771                 drm_crtc_commit_put(commit);
6772         }
6773
6774         return ret < 0 ? ret : 0;
6775 }
6776
6777 static void get_freesync_config_for_crtc(
6778         struct dm_crtc_state *new_crtc_state,
6779         struct dm_connector_state *new_con_state)
6780 {
6781         struct mod_freesync_config config = {0};
6782         struct amdgpu_dm_connector *aconnector =
6783                         to_amdgpu_dm_connector(new_con_state->base.connector);
6784         struct drm_display_mode *mode = &new_crtc_state->base.mode;
6785         int vrefresh = drm_mode_vrefresh(mode);
6786
6787         new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
6788                                         vrefresh >= aconnector->min_vfreq &&
6789                                         vrefresh <= aconnector->max_vfreq;
6790
6791         if (new_crtc_state->vrr_supported) {
6792                 new_crtc_state->stream->ignore_msa_timing_param = true;
6793                 config.state = new_crtc_state->base.vrr_enabled ?
6794                                 VRR_STATE_ACTIVE_VARIABLE :
6795                                 VRR_STATE_INACTIVE;
6796                 config.min_refresh_in_uhz =
6797                                 aconnector->min_vfreq * 1000000;
6798                 config.max_refresh_in_uhz =
6799                                 aconnector->max_vfreq * 1000000;
6800                 config.vsif_supported = true;
6801                 config.btr = true;
6802         }
6803
6804         new_crtc_state->freesync_config = config;
6805 }
6806
6807 static void reset_freesync_config_for_crtc(
6808         struct dm_crtc_state *new_crtc_state)
6809 {
6810         new_crtc_state->vrr_supported = false;
6811
6812         memset(&new_crtc_state->vrr_params, 0,
6813                sizeof(new_crtc_state->vrr_params));
6814         memset(&new_crtc_state->vrr_infopacket, 0,
6815                sizeof(new_crtc_state->vrr_infopacket));
6816 }
6817
6818 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
6819                                 struct drm_atomic_state *state,
6820                                 struct drm_crtc *crtc,
6821                                 struct drm_crtc_state *old_crtc_state,
6822                                 struct drm_crtc_state *new_crtc_state,
6823                                 bool enable,
6824                                 bool *lock_and_validation_needed)
6825 {
6826         struct dm_atomic_state *dm_state = NULL;
6827         struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
6828         struct dc_stream_state *new_stream;
6829         int ret = 0;
6830
6831         /*
6832          * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
6833          * update changed items
6834          */
6835         struct amdgpu_crtc *acrtc = NULL;
6836         struct amdgpu_dm_connector *aconnector = NULL;
6837         struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
6838         struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
6839
6840         new_stream = NULL;
6841
6842         dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6843         dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6844         acrtc = to_amdgpu_crtc(crtc);
6845         aconnector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
6846
6847         /* TODO This hack should go away */
6848         if (aconnector && enable) {
6849                 /* Make sure fake sink is created in plug-in scenario */
6850                 drm_new_conn_state = drm_atomic_get_new_connector_state(state,
6851                                                             &aconnector->base);
6852                 drm_old_conn_state = drm_atomic_get_old_connector_state(state,
6853                                                             &aconnector->base);
6854
6855                 if (IS_ERR(drm_new_conn_state)) {
6856                         ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
6857                         goto fail;
6858                 }
6859
6860                 dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
6861                 dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
6862
6863                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
6864                         goto skip_modeset;
6865
6866                 new_stream = create_stream_for_sink(aconnector,
6867                                                      &new_crtc_state->mode,
6868                                                     dm_new_conn_state,
6869                                                     dm_old_crtc_state->stream);
6870
6871                 /*
6872                  * we can have no stream on ACTION_SET if a display
6873                  * was disconnected during S3, in this case it is not an
6874                  * error, the OS will be updated after detection, and
6875                  * will do the right thing on next atomic commit
6876                  */
6877
6878                 if (!new_stream) {
6879                         DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
6880                                         __func__, acrtc->base.base.id);
6881                         ret = -ENOMEM;
6882                         goto fail;
6883                 }
6884
6885                 dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
6886
6887                 ret = fill_hdr_info_packet(drm_new_conn_state,
6888                                            &new_stream->hdr_static_metadata);
6889                 if (ret)
6890                         goto fail;
6891
6892                 /*
6893                  * If we already removed the old stream from the context
6894                  * (and set the new stream to NULL) then we can't reuse
6895                  * the old stream even if the stream and scaling are unchanged.
6896                  * We'll hit the BUG_ON and black screen.
6897                  *
6898                  * TODO: Refactor this function to allow this check to work
6899                  * in all conditions.
6900                  */
6901                 if (dm_new_crtc_state->stream &&
6902                     dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
6903                     dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
6904                         new_crtc_state->mode_changed = false;
6905                         DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
6906                                          new_crtc_state->mode_changed);
6907                 }
6908         }
6909
6910         /* mode_changed flag may get updated above, need to check again */
6911         if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
6912                 goto skip_modeset;
6913
6914         DRM_DEBUG_DRIVER(
6915                 "amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
6916                 "planes_changed:%d, mode_changed:%d,active_changed:%d,"
6917                 "connectors_changed:%d\n",
6918                 acrtc->crtc_id,
6919                 new_crtc_state->enable,
6920                 new_crtc_state->active,
6921                 new_crtc_state->planes_changed,
6922                 new_crtc_state->mode_changed,
6923                 new_crtc_state->active_changed,
6924                 new_crtc_state->connectors_changed);
6925
6926         /* Remove stream for any changed/disabled CRTC */
6927         if (!enable) {
6928
6929                 if (!dm_old_crtc_state->stream)
6930                         goto skip_modeset;
6931
6932                 ret = dm_atomic_get_state(state, &dm_state);
6933                 if (ret)
6934                         goto fail;
6935
6936                 DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
6937                                 crtc->base.id);
6938
6939                 /* i.e. reset mode */
6940                 if (dc_remove_stream_from_ctx(
6941                                 dm->dc,
6942                                 dm_state->context,
6943                                 dm_old_crtc_state->stream) != DC_OK) {
6944                         ret = -EINVAL;
6945                         goto fail;
6946                 }
6947
6948                 dc_stream_release(dm_old_crtc_state->stream);
6949                 dm_new_crtc_state->stream = NULL;
6950
6951                 reset_freesync_config_for_crtc(dm_new_crtc_state);
6952
6953                 *lock_and_validation_needed = true;
6954
6955         } else {/* Add stream for any updated/enabled CRTC */
6956                 /*
6957                  * Quick fix to prevent NULL pointer on new_stream when
6958                  * added MST connectors not found in existing crtc_state in the chained mode
6959                  * TODO: need to dig out the root cause of that
6960                  */
6961                 if (!aconnector || (!aconnector->dc_sink && aconnector->mst_port))
6962                         goto skip_modeset;
6963
6964                 if (modereset_required(new_crtc_state))
6965                         goto skip_modeset;
6966
6967                 if (modeset_required(new_crtc_state, new_stream,
6968                                      dm_old_crtc_state->stream)) {
6969
6970                         WARN_ON(dm_new_crtc_state->stream);
6971
6972                         ret = dm_atomic_get_state(state, &dm_state);
6973                         if (ret)
6974                                 goto fail;
6975
6976                         dm_new_crtc_state->stream = new_stream;
6977
6978                         dc_stream_retain(new_stream);
6979
6980                         DRM_DEBUG_DRIVER("Enabling DRM crtc: %d\n",
6981                                                 crtc->base.id);
6982
6983                         if (dc_add_stream_to_ctx(
6984                                         dm->dc,
6985                                         dm_state->context,
6986                                         dm_new_crtc_state->stream) != DC_OK) {
6987                                 ret = -EINVAL;
6988                                 goto fail;
6989                         }
6990
6991                         *lock_and_validation_needed = true;
6992                 }
6993         }
6994
6995 skip_modeset:
6996         /* Release extra reference */
6997         if (new_stream)
6998                  dc_stream_release(new_stream);
6999
7000         /*
7001          * We want to do dc stream updates that do not require a
7002          * full modeset below.
7003          */
7004         if (!(enable && aconnector && new_crtc_state->enable &&
7005               new_crtc_state->active))
7006                 return 0;
7007         /*
7008          * Given above conditions, the dc state cannot be NULL because:
7009          * 1. We're in the process of enabling CRTCs (just been added
7010          *    to the dc context, or already is on the context)
7011          * 2. Has a valid connector attached, and
7012          * 3. Is currently active and enabled.
7013          * => The dc stream state currently exists.
7014          */
7015         BUG_ON(dm_new_crtc_state->stream == NULL);
7016
7017         /* Scaling or underscan settings */
7018         if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state))
7019                 update_stream_scaling_settings(
7020                         &new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
7021
7022         /* ABM settings */
7023         dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
7024
7025         /*
7026          * Color management settings. We also update color properties
7027          * when a modeset is needed, to ensure it gets reprogrammed.
7028          */
7029         if (dm_new_crtc_state->base.color_mgmt_changed ||
7030             drm_atomic_crtc_needs_modeset(new_crtc_state)) {
7031                 ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
7032                 if (ret)
7033                         goto fail;
7034         }
7035
7036         /* Update Freesync settings. */
7037         get_freesync_config_for_crtc(dm_new_crtc_state,
7038                                      dm_new_conn_state);
7039
7040         return ret;
7041
7042 fail:
7043         if (new_stream)
7044                 dc_stream_release(new_stream);
7045         return ret;
7046 }
7047
7048 static bool should_reset_plane(struct drm_atomic_state *state,
7049                                struct drm_plane *plane,
7050                                struct drm_plane_state *old_plane_state,
7051                                struct drm_plane_state *new_plane_state)
7052 {
7053         struct drm_plane *other;
7054         struct drm_plane_state *old_other_state, *new_other_state;
7055         struct drm_crtc_state *new_crtc_state;
7056         int i;
7057
7058         /*
7059          * TODO: Remove this hack once the checks below are sufficient
7060          * enough to determine when we need to reset all the planes on
7061          * the stream.
7062          */
7063         if (state->allow_modeset)
7064                 return true;
7065
7066         /* Exit early if we know that we're adding or removing the plane. */
7067         if (old_plane_state->crtc != new_plane_state->crtc)
7068                 return true;
7069
7070         /* old crtc == new_crtc == NULL, plane not in context. */
7071         if (!new_plane_state->crtc)
7072                 return false;
7073
7074         new_crtc_state =
7075                 drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
7076
7077         if (!new_crtc_state)
7078                 return true;
7079
7080         /* CRTC Degamma changes currently require us to recreate planes. */
7081         if (new_crtc_state->color_mgmt_changed)
7082                 return true;
7083
7084         if (drm_atomic_crtc_needs_modeset(new_crtc_state))
7085                 return true;
7086
7087         /*
7088          * If there are any new primary or overlay planes being added or
7089          * removed then the z-order can potentially change. To ensure
7090          * correct z-order and pipe acquisition the current DC architecture
7091          * requires us to remove and recreate all existing planes.
7092          *
7093          * TODO: Come up with a more elegant solution for this.
7094          */
7095         for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
7096                 if (other->type == DRM_PLANE_TYPE_CURSOR)
7097                         continue;
7098
7099                 if (old_other_state->crtc != new_plane_state->crtc &&
7100                     new_other_state->crtc != new_plane_state->crtc)
7101                         continue;
7102
7103                 if (old_other_state->crtc != new_other_state->crtc)
7104                         return true;
7105
7106                 /* TODO: Remove this once we can handle fast format changes. */
7107                 if (old_other_state->fb && new_other_state->fb &&
7108                     old_other_state->fb->format != new_other_state->fb->format)
7109                         return true;
7110         }
7111
7112         return false;
7113 }
7114
7115 static int dm_update_plane_state(struct dc *dc,
7116                                  struct drm_atomic_state *state,
7117                                  struct drm_plane *plane,
7118                                  struct drm_plane_state *old_plane_state,
7119                                  struct drm_plane_state *new_plane_state,
7120                                  bool enable,
7121                                  bool *lock_and_validation_needed)
7122 {
7123
7124         struct dm_atomic_state *dm_state = NULL;
7125         struct drm_crtc *new_plane_crtc, *old_plane_crtc;
7126         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
7127         struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
7128         struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
7129         bool needs_reset;
7130         int ret = 0;
7131
7132
7133         new_plane_crtc = new_plane_state->crtc;
7134         old_plane_crtc = old_plane_state->crtc;
7135         dm_new_plane_state = to_dm_plane_state(new_plane_state);
7136         dm_old_plane_state = to_dm_plane_state(old_plane_state);
7137
7138         /*TODO Implement atomic check for cursor plane */
7139         if (plane->type == DRM_PLANE_TYPE_CURSOR)
7140                 return 0;
7141
7142         needs_reset = should_reset_plane(state, plane, old_plane_state,
7143                                          new_plane_state);
7144
7145         /* Remove any changed/removed planes */
7146         if (!enable) {
7147                 if (!needs_reset)
7148                         return 0;
7149
7150                 if (!old_plane_crtc)
7151                         return 0;
7152
7153                 old_crtc_state = drm_atomic_get_old_crtc_state(
7154                                 state, old_plane_crtc);
7155                 dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
7156
7157                 if (!dm_old_crtc_state->stream)
7158                         return 0;
7159
7160                 DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
7161                                 plane->base.id, old_plane_crtc->base.id);
7162
7163                 ret = dm_atomic_get_state(state, &dm_state);
7164                 if (ret)
7165                         return ret;
7166
7167                 if (!dc_remove_plane_from_context(
7168                                 dc,
7169                                 dm_old_crtc_state->stream,
7170                                 dm_old_plane_state->dc_state,
7171                                 dm_state->context)) {
7172
7173                         ret = EINVAL;
7174                         return ret;
7175                 }
7176
7177
7178                 dc_plane_state_release(dm_old_plane_state->dc_state);
7179                 dm_new_plane_state->dc_state = NULL;
7180
7181                 *lock_and_validation_needed = true;
7182
7183         } else { /* Add new planes */
7184                 struct dc_plane_state *dc_new_plane_state;
7185
7186                 if (drm_atomic_plane_disabling(plane->state, new_plane_state))
7187                         return 0;
7188
7189                 if (!new_plane_crtc)
7190                         return 0;
7191
7192                 new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
7193                 dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
7194
7195                 if (!dm_new_crtc_state->stream)
7196                         return 0;
7197
7198                 if (!needs_reset)
7199                         return 0;
7200
7201                 WARN_ON(dm_new_plane_state->dc_state);
7202
7203                 dc_new_plane_state = dc_create_plane_state(dc);
7204                 if (!dc_new_plane_state)
7205                         return -ENOMEM;
7206
7207                 DRM_DEBUG_DRIVER("Enabling DRM plane: %d on DRM crtc %d\n",
7208                                 plane->base.id, new_plane_crtc->base.id);
7209
7210                 ret = fill_dc_plane_attributes(
7211                         new_plane_crtc->dev->dev_private,
7212                         dc_new_plane_state,
7213                         new_plane_state,
7214                         new_crtc_state);
7215                 if (ret) {
7216                         dc_plane_state_release(dc_new_plane_state);
7217                         return ret;
7218                 }
7219
7220                 ret = dm_atomic_get_state(state, &dm_state);
7221                 if (ret) {
7222                         dc_plane_state_release(dc_new_plane_state);
7223                         return ret;
7224                 }
7225
7226                 /*
7227                  * Any atomic check errors that occur after this will
7228                  * not need a release. The plane state will be attached
7229                  * to the stream, and therefore part of the atomic
7230                  * state. It'll be released when the atomic state is
7231                  * cleaned.
7232                  */
7233                 if (!dc_add_plane_to_context(
7234                                 dc,
7235                                 dm_new_crtc_state->stream,
7236                                 dc_new_plane_state,
7237                                 dm_state->context)) {
7238
7239                         dc_plane_state_release(dc_new_plane_state);
7240                         return -EINVAL;
7241                 }
7242
7243                 dm_new_plane_state->dc_state = dc_new_plane_state;
7244
7245                 /* Tell DC to do a full surface update every time there
7246                  * is a plane change. Inefficient, but works for now.
7247                  */
7248                 dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
7249
7250                 *lock_and_validation_needed = true;
7251         }
7252
7253
7254         return ret;
7255 }
7256
7257 static int
7258 dm_determine_update_type_for_commit(struct amdgpu_display_manager *dm,
7259                                     struct drm_atomic_state *state,
7260                                     enum surface_update_type *out_type)
7261 {
7262         struct dc *dc = dm->dc;
7263         struct dm_atomic_state *dm_state = NULL, *old_dm_state = NULL;
7264         int i, j, num_plane, ret = 0;
7265         struct drm_plane_state *old_plane_state, *new_plane_state;
7266         struct dm_plane_state *new_dm_plane_state, *old_dm_plane_state;
7267         struct drm_crtc *new_plane_crtc, *old_plane_crtc;
7268         struct drm_plane *plane;
7269
7270         struct drm_crtc *crtc;
7271         struct drm_crtc_state *new_crtc_state, *old_crtc_state;
7272         struct dm_crtc_state *new_dm_crtc_state, *old_dm_crtc_state;
7273         struct dc_stream_status *status = NULL;
7274
7275         struct dc_surface_update *updates;
7276         enum surface_update_type update_type = UPDATE_TYPE_FAST;
7277
7278         updates = kcalloc(MAX_SURFACES, sizeof(*updates), GFP_KERNEL);
7279
7280         if (!updates) {
7281                 DRM_ERROR("Failed to allocate plane updates\n");
7282                 /* Set type to FULL to avoid crashing in DC*/
7283                 update_type = UPDATE_TYPE_FULL;
7284                 goto cleanup;
7285         }
7286
7287         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
7288                 struct dc_scaling_info scaling_info;
7289                 struct dc_stream_update stream_update;
7290
7291                 memset(&stream_update, 0, sizeof(stream_update));
7292
7293                 new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
7294                 old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
7295                 num_plane = 0;
7296
7297                 if (new_dm_crtc_state->stream != old_dm_crtc_state->stream) {
7298                         update_type = UPDATE_TYPE_FULL;
7299                         goto cleanup;
7300                 }
7301
7302                 if (!new_dm_crtc_state->stream)
7303                         continue;
7304
7305                 for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, j) {
7306                         const struct amdgpu_framebuffer *amdgpu_fb =
7307                                 to_amdgpu_framebuffer(new_plane_state->fb);
7308                         struct dc_plane_info plane_info;
7309                         struct dc_flip_addrs flip_addr;
7310                         uint64_t tiling_flags;
7311
7312                         new_plane_crtc = new_plane_state->crtc;
7313                         old_plane_crtc = old_plane_state->crtc;
7314                         new_dm_plane_state = to_dm_plane_state(new_plane_state);
7315                         old_dm_plane_state = to_dm_plane_state(old_plane_state);
7316
7317                         if (plane->type == DRM_PLANE_TYPE_CURSOR)
7318                                 continue;
7319
7320                         if (new_dm_plane_state->dc_state != old_dm_plane_state->dc_state) {
7321                                 update_type = UPDATE_TYPE_FULL;
7322                                 goto cleanup;
7323                         }
7324
7325                         if (crtc != new_plane_crtc)
7326                                 continue;
7327
7328                         updates[num_plane].surface = new_dm_plane_state->dc_state;
7329
7330                         if (new_crtc_state->mode_changed) {
7331                                 stream_update.dst = new_dm_crtc_state->stream->dst;
7332                                 stream_update.src = new_dm_crtc_state->stream->src;
7333                         }
7334
7335                         if (new_crtc_state->color_mgmt_changed) {
7336                                 updates[num_plane].gamma =
7337                                                 new_dm_plane_state->dc_state->gamma_correction;
7338                                 updates[num_plane].in_transfer_func =
7339                                                 new_dm_plane_state->dc_state->in_transfer_func;
7340                                 stream_update.gamut_remap =
7341                                                 &new_dm_crtc_state->stream->gamut_remap_matrix;
7342                                 stream_update.output_csc_transform =
7343                                                 &new_dm_crtc_state->stream->csc_color_matrix;
7344                                 stream_update.out_transfer_func =
7345                                                 new_dm_crtc_state->stream->out_transfer_func;
7346                         }
7347
7348                         ret = fill_dc_scaling_info(new_plane_state,
7349                                                    &scaling_info);
7350                         if (ret)
7351                                 goto cleanup;
7352
7353                         updates[num_plane].scaling_info = &scaling_info;
7354
7355                         if (amdgpu_fb) {
7356                                 ret = get_fb_info(amdgpu_fb, &tiling_flags);
7357                                 if (ret)
7358                                         goto cleanup;
7359
7360                                 memset(&flip_addr, 0, sizeof(flip_addr));
7361
7362                                 ret = fill_dc_plane_info_and_addr(
7363                                         dm->adev, new_plane_state, tiling_flags,
7364                                         &plane_info,
7365                                         &flip_addr.address);
7366                                 if (ret)
7367                                         goto cleanup;
7368
7369                                 updates[num_plane].plane_info = &plane_info;
7370                                 updates[num_plane].flip_addr = &flip_addr;
7371                         }
7372
7373                         num_plane++;
7374                 }
7375
7376                 if (num_plane == 0)
7377                         continue;
7378
7379                 ret = dm_atomic_get_state(state, &dm_state);
7380                 if (ret)
7381                         goto cleanup;
7382
7383                 old_dm_state = dm_atomic_get_old_state(state);
7384                 if (!old_dm_state) {
7385                         ret = -EINVAL;
7386                         goto cleanup;
7387                 }
7388
7389                 status = dc_stream_get_status_from_state(old_dm_state->context,
7390                                                          new_dm_crtc_state->stream);
7391                 stream_update.stream = new_dm_crtc_state->stream;
7392                 /*
7393                  * TODO: DC modifies the surface during this call so we need
7394                  * to lock here - find a way to do this without locking.
7395                  */
7396                 mutex_lock(&dm->dc_lock);
7397                 update_type = dc_check_update_surfaces_for_stream(dc, updates, num_plane,
7398                                                                   &stream_update, status);
7399                 mutex_unlock(&dm->dc_lock);
7400
7401                 if (update_type > UPDATE_TYPE_MED) {
7402                         update_type = UPDATE_TYPE_FULL;
7403                         goto cleanup;
7404                 }
7405         }
7406
7407 cleanup:
7408         kfree(updates);
7409
7410         *out_type = update_type;
7411         return ret;
7412 }
7413
7414 /**
7415  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
7416  * @dev: The DRM device
7417  * @state: The atomic state to commit
7418  *
7419  * Validate that the given atomic state is programmable by DC into hardware.
7420  * This involves constructing a &struct dc_state reflecting the new hardware
7421  * state we wish to commit, then querying DC to see if it is programmable. It's
7422  * important not to modify the existing DC state. Otherwise, atomic_check
7423  * may unexpectedly commit hardware changes.
7424  *
7425  * When validating the DC state, it's important that the right locks are
7426  * acquired. For full updates case which removes/adds/updates streams on one
7427  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
7428  * that any such full update commit will wait for completion of any outstanding
7429  * flip using DRMs synchronization events. See
7430  * dm_determine_update_type_for_commit()
7431  *
7432  * Note that DM adds the affected connectors for all CRTCs in state, when that
7433  * might not seem necessary. This is because DC stream creation requires the
7434  * DC sink, which is tied to the DRM connector state. Cleaning this up should
7435  * be possible but non-trivial - a possible TODO item.
7436  *
7437  * Return: -Error code if validation failed.
7438  */
7439 static int amdgpu_dm_atomic_check(struct drm_device *dev,
7440                                   struct drm_atomic_state *state)
7441 {
7442         struct amdgpu_device *adev = dev->dev_private;
7443         struct dm_atomic_state *dm_state = NULL;
7444         struct dc *dc = adev->dm.dc;
7445         struct drm_connector *connector;
7446         struct drm_connector_state *old_con_state, *new_con_state;
7447         struct drm_crtc *crtc;
7448         struct drm_crtc_state *old_crtc_state, *new_crtc_state;
7449         struct drm_plane *plane;
7450         struct drm_plane_state *old_plane_state, *new_plane_state;
7451         enum surface_update_type update_type = UPDATE_TYPE_FAST;
7452         enum surface_update_type overall_update_type = UPDATE_TYPE_FAST;
7453
7454         int ret, i;
7455
7456         /*
7457          * This bool will be set for true for any modeset/reset
7458          * or plane update which implies non fast surface update.
7459          */
7460         bool lock_and_validation_needed = false;
7461
7462         ret = drm_atomic_helper_check_modeset(dev, state);
7463         if (ret)
7464                 goto fail;
7465
7466         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
7467                 if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
7468                     !new_crtc_state->color_mgmt_changed &&
7469                     old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled)
7470                         continue;
7471
7472                 if (!new_crtc_state->enable)
7473                         continue;
7474
7475                 ret = drm_atomic_add_affected_connectors(state, crtc);
7476                 if (ret)
7477                         return ret;
7478
7479                 ret = drm_atomic_add_affected_planes(state, crtc);
7480                 if (ret)
7481                         goto fail;
7482         }
7483
7484         /*
7485          * Add all primary and overlay planes on the CRTC to the state
7486          * whenever a plane is enabled to maintain correct z-ordering
7487          * and to enable fast surface updates.
7488          */
7489         drm_for_each_crtc(crtc, dev) {
7490                 bool modified = false;
7491
7492                 for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
7493                         if (plane->type == DRM_PLANE_TYPE_CURSOR)
7494                                 continue;
7495
7496                         if (new_plane_state->crtc == crtc ||
7497                             old_plane_state->crtc == crtc) {
7498                                 modified = true;
7499                                 break;
7500                         }
7501                 }
7502
7503                 if (!modified)
7504                         continue;
7505
7506                 drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
7507                         if (plane->type == DRM_PLANE_TYPE_CURSOR)
7508                                 continue;
7509
7510                         new_plane_state =
7511                                 drm_atomic_get_plane_state(state, plane);
7512
7513                         if (IS_ERR(new_plane_state)) {
7514                                 ret = PTR_ERR(new_plane_state);
7515                                 goto fail;
7516                         }
7517                 }
7518         }
7519
7520         /* Remove exiting planes if they are modified */
7521         for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
7522                 ret = dm_update_plane_state(dc, state, plane,
7523                                             old_plane_state,
7524                                             new_plane_state,
7525                                             false,
7526                                             &lock_and_validation_needed);
7527                 if (ret)
7528                         goto fail;
7529         }
7530
7531         /* Disable all crtcs which require disable */
7532         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
7533                 ret = dm_update_crtc_state(&adev->dm, state, crtc,
7534                                            old_crtc_state,
7535                                            new_crtc_state,
7536                                            false,
7537                                            &lock_and_validation_needed);
7538                 if (ret)
7539                         goto fail;
7540         }
7541
7542         /* Enable all crtcs which require enable */
7543         for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
7544                 ret = dm_update_crtc_state(&adev->dm, state, crtc,
7545                                            old_crtc_state,
7546                                            new_crtc_state,
7547                                            true,
7548                                            &lock_and_validation_needed);
7549                 if (ret)
7550                         goto fail;
7551         }
7552
7553         /* Add new/modified planes */
7554         for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
7555                 ret = dm_update_plane_state(dc, state, plane,
7556                                             old_plane_state,
7557                                             new_plane_state,
7558                                             true,
7559                                             &lock_and_validation_needed);
7560                 if (ret)
7561                         goto fail;
7562         }
7563
7564         /* Run this here since we want to validate the streams we created */
7565         ret = drm_atomic_helper_check_planes(dev, state);
7566         if (ret)
7567                 goto fail;
7568
7569         if (state->legacy_cursor_update) {
7570                 /*
7571                  * This is a fast cursor update coming from the plane update
7572                  * helper, check if it can be done asynchronously for better
7573                  * performance.
7574                  */
7575                 state->async_update =
7576                         !drm_atomic_helper_async_check(dev, state);
7577
7578                 /*
7579                  * Skip the remaining global validation if this is an async
7580                  * update. Cursor updates can be done without affecting
7581                  * state or bandwidth calcs and this avoids the performance
7582                  * penalty of locking the private state object and
7583                  * allocating a new dc_state.
7584                  */
7585                 if (state->async_update)
7586                         return 0;
7587         }
7588
7589         /* Check scaling and underscan changes*/
7590         /* TODO Removed scaling changes validation due to inability to commit
7591          * new stream into context w\o causing full reset. Need to
7592          * decide how to handle.
7593          */
7594         for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
7595                 struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
7596                 struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
7597                 struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
7598
7599                 /* Skip any modesets/resets */
7600                 if (!acrtc || drm_atomic_crtc_needs_modeset(
7601                                 drm_atomic_get_new_crtc_state(state, &acrtc->base)))
7602                         continue;
7603
7604                 /* Skip any thing not scale or underscan changes */
7605                 if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
7606                         continue;
7607
7608                 overall_update_type = UPDATE_TYPE_FULL;
7609                 lock_and_validation_needed = true;
7610         }
7611
7612         ret = dm_determine_update_type_for_commit(&adev->dm, state, &update_type);
7613         if (ret)
7614                 goto fail;
7615
7616         if (overall_update_type < update_type)
7617                 overall_update_type = update_type;
7618
7619         /*
7620          * lock_and_validation_needed was an old way to determine if we need to set
7621          * the global lock. Leaving it in to check if we broke any corner cases
7622          * lock_and_validation_needed true = UPDATE_TYPE_FULL or UPDATE_TYPE_MED
7623          * lock_and_validation_needed false = UPDATE_TYPE_FAST
7624          */
7625         if (lock_and_validation_needed && overall_update_type <= UPDATE_TYPE_FAST)
7626                 WARN(1, "Global lock should be Set, overall_update_type should be UPDATE_TYPE_MED or UPDATE_TYPE_FULL");
7627
7628         if (overall_update_type > UPDATE_TYPE_FAST) {
7629                 ret = dm_atomic_get_state(state, &dm_state);
7630                 if (ret)
7631                         goto fail;
7632
7633                 ret = do_aquire_global_lock(dev, state);
7634                 if (ret)
7635                         goto fail;
7636
7637                 if (dc_validate_global_state(dc, dm_state->context, false) != DC_OK) {
7638                         ret = -EINVAL;
7639                         goto fail;
7640                 }
7641         } else {
7642                 /*
7643                  * The commit is a fast update. Fast updates shouldn't change
7644                  * the DC context, affect global validation, and can have their
7645                  * commit work done in parallel with other commits not touching
7646                  * the same resource. If we have a new DC context as part of
7647                  * the DM atomic state from validation we need to free it and
7648                  * retain the existing one instead.
7649                  */
7650                 struct dm_atomic_state *new_dm_state, *old_dm_state;
7651
7652                 new_dm_state = dm_atomic_get_new_state(state);
7653                 old_dm_state = dm_atomic_get_old_state(state);
7654
7655                 if (new_dm_state && old_dm_state) {
7656                         if (new_dm_state->context)
7657                                 dc_release_state(new_dm_state->context);
7658
7659                         new_dm_state->context = old_dm_state->context;
7660
7661                         if (old_dm_state->context)
7662                                 dc_retain_state(old_dm_state->context);
7663                 }
7664         }
7665
7666         /* Store the overall update type for use later in atomic check. */
7667         for_each_new_crtc_in_state (state, crtc, new_crtc_state, i) {
7668                 struct dm_crtc_state *dm_new_crtc_state =
7669                         to_dm_crtc_state(new_crtc_state);
7670
7671                 dm_new_crtc_state->update_type = (int)overall_update_type;
7672         }
7673
7674         /* Must be success */
7675         WARN_ON(ret);
7676         return ret;
7677
7678 fail:
7679         if (ret == -EDEADLK)
7680                 DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
7681         else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
7682                 DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
7683         else
7684                 DRM_DEBUG_DRIVER("Atomic check failed with err: %d \n", ret);
7685
7686         return ret;
7687 }
7688
7689 static bool is_dp_capable_without_timing_msa(struct dc *dc,
7690                                              struct amdgpu_dm_connector *amdgpu_dm_connector)
7691 {
7692         uint8_t dpcd_data;
7693         bool capable = false;
7694
7695         if (amdgpu_dm_connector->dc_link &&
7696                 dm_helpers_dp_read_dpcd(
7697                                 NULL,
7698                                 amdgpu_dm_connector->dc_link,
7699                                 DP_DOWN_STREAM_PORT_COUNT,
7700                                 &dpcd_data,
7701                                 sizeof(dpcd_data))) {
7702                 capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
7703         }
7704
7705         return capable;
7706 }
7707 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
7708                                         struct edid *edid)
7709 {
7710         int i;
7711         bool edid_check_required;
7712         struct detailed_timing *timing;
7713         struct detailed_non_pixel *data;
7714         struct detailed_data_monitor_range *range;
7715         struct amdgpu_dm_connector *amdgpu_dm_connector =
7716                         to_amdgpu_dm_connector(connector);
7717         struct dm_connector_state *dm_con_state = NULL;
7718
7719         struct drm_device *dev = connector->dev;
7720         struct amdgpu_device *adev = dev->dev_private;
7721         bool freesync_capable = false;
7722
7723         if (!connector->state) {
7724                 DRM_ERROR("%s - Connector has no state", __func__);
7725                 goto update;
7726         }
7727
7728         if (!edid) {
7729                 dm_con_state = to_dm_connector_state(connector->state);
7730
7731                 amdgpu_dm_connector->min_vfreq = 0;
7732                 amdgpu_dm_connector->max_vfreq = 0;
7733                 amdgpu_dm_connector->pixel_clock_mhz = 0;
7734
7735                 goto update;
7736         }
7737
7738         dm_con_state = to_dm_connector_state(connector->state);
7739
7740         edid_check_required = false;
7741         if (!amdgpu_dm_connector->dc_sink) {
7742                 DRM_ERROR("dc_sink NULL, could not add free_sync module.\n");
7743                 goto update;
7744         }
7745         if (!adev->dm.freesync_module)
7746                 goto update;
7747         /*
7748          * if edid non zero restrict freesync only for dp and edp
7749          */
7750         if (edid) {
7751                 if (amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
7752                         || amdgpu_dm_connector->dc_sink->sink_signal == SIGNAL_TYPE_EDP) {
7753                         edid_check_required = is_dp_capable_without_timing_msa(
7754                                                 adev->dm.dc,
7755                                                 amdgpu_dm_connector);
7756                 }
7757         }
7758         if (edid_check_required == true && (edid->version > 1 ||
7759            (edid->version == 1 && edid->revision > 1))) {
7760                 for (i = 0; i < 4; i++) {
7761
7762                         timing  = &edid->detailed_timings[i];
7763                         data    = &timing->data.other_data;
7764                         range   = &data->data.range;
7765                         /*
7766                          * Check if monitor has continuous frequency mode
7767                          */
7768                         if (data->type != EDID_DETAIL_MONITOR_RANGE)
7769                                 continue;
7770                         /*
7771                          * Check for flag range limits only. If flag == 1 then
7772                          * no additional timing information provided.
7773                          * Default GTF, GTF Secondary curve and CVT are not
7774                          * supported
7775                          */
7776                         if (range->flags != 1)
7777                                 continue;
7778
7779                         amdgpu_dm_connector->min_vfreq = range->min_vfreq;
7780                         amdgpu_dm_connector->max_vfreq = range->max_vfreq;
7781                         amdgpu_dm_connector->pixel_clock_mhz =
7782                                 range->pixel_clock_mhz * 10;
7783                         break;
7784                 }
7785
7786                 if (amdgpu_dm_connector->max_vfreq -
7787                     amdgpu_dm_connector->min_vfreq > 10) {
7788
7789                         freesync_capable = true;
7790                 }
7791         }
7792
7793 update:
7794         if (dm_con_state)
7795                 dm_con_state->freesync_capable = freesync_capable;
7796
7797         if (connector->vrr_capable_property)
7798                 drm_connector_set_vrr_capable_property(connector,
7799                                                        freesync_capable);
7800 }
7801
7802 static void amdgpu_dm_set_psr_caps(struct dc_link *link)
7803 {
7804         uint8_t dpcd_data[EDP_PSR_RECEIVER_CAP_SIZE];
7805
7806         if (!(link->connector_signal & SIGNAL_TYPE_EDP))
7807                 return;
7808         if (link->type == dc_connection_none)
7809                 return;
7810         if (dm_helpers_dp_read_dpcd(NULL, link, DP_PSR_SUPPORT,
7811                                         dpcd_data, sizeof(dpcd_data))) {
7812                 link->psr_feature_enabled = dpcd_data[0] ? true:false;
7813                 DRM_INFO("PSR support:%d\n", link->psr_feature_enabled);
7814         }
7815 }
7816
7817 /*
7818  * amdgpu_dm_link_setup_psr() - configure psr link
7819  * @stream: stream state
7820  *
7821  * Return: true if success
7822  */
7823 static bool amdgpu_dm_link_setup_psr(struct dc_stream_state *stream)
7824 {
7825         struct dc_link *link = NULL;
7826         struct psr_config psr_config = {0};
7827         struct psr_context psr_context = {0};
7828         struct dc *dc = NULL;
7829         bool ret = false;
7830
7831         if (stream == NULL)
7832                 return false;
7833
7834         link = stream->link;
7835         dc = link->ctx->dc;
7836
7837         psr_config.psr_version = dc->res_pool->dmcu->dmcu_version.psr_version;
7838
7839         if (psr_config.psr_version > 0) {
7840                 psr_config.psr_exit_link_training_required = 0x1;
7841                 psr_config.psr_frame_capture_indication_req = 0;
7842                 psr_config.psr_rfb_setup_time = 0x37;
7843                 psr_config.psr_sdp_transmit_line_num_deadline = 0x20;
7844                 psr_config.allow_smu_optimizations = 0x0;
7845
7846                 ret = dc_link_setup_psr(link, stream, &psr_config, &psr_context);
7847
7848         }
7849         DRM_DEBUG_DRIVER("PSR link: %d\n",      link->psr_feature_enabled);
7850
7851         return ret;
7852 }
7853
7854 /*
7855  * amdgpu_dm_psr_enable() - enable psr f/w
7856  * @stream: stream state
7857  *
7858  * Return: true if success
7859  */
7860 bool amdgpu_dm_psr_enable(struct dc_stream_state *stream)
7861 {
7862         struct dc_link *link = stream->link;
7863         struct dc_static_screen_events triggers = {0};
7864
7865         DRM_DEBUG_DRIVER("Enabling psr...\n");
7866
7867         triggers.cursor_update = true;
7868         triggers.overlay_update = true;
7869         triggers.surface_update = true;
7870
7871         dc_stream_set_static_screen_events(link->ctx->dc,
7872                                            &stream, 1,
7873                                            &triggers);
7874
7875         return dc_link_set_psr_allow_active(link, true, false);
7876 }
7877
7878 /*
7879  * amdgpu_dm_psr_disable() - disable psr f/w
7880  * @stream:  stream state
7881  *
7882  * Return: true if success
7883  */
7884 static bool amdgpu_dm_psr_disable(struct dc_stream_state *stream)
7885 {
7886
7887         DRM_DEBUG_DRIVER("Disabling psr...\n");
7888
7889         return dc_link_set_psr_allow_active(stream->link, false, true);
7890 }