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