OSDN Git Service

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