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