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