xref: /openbsd-src/sys/dev/pci/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision 3374c67d44f9b75b98444cbf63020f777792342e)
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_link_dp.h"
32 #include "link_enc_cfg.h"
33 #include "dc/inc/core_types.h"
34 #include "dal_asic_id.h"
35 #include "dmub/dmub_srv.h"
36 #include "dc/inc/hw/dmcu.h"
37 #include "dc/inc/hw/abm.h"
38 #include "dc/dc_dmub_srv.h"
39 #include "dc/dc_edid_parser.h"
40 #include "dc/dc_stat.h"
41 #include "amdgpu_dm_trace.h"
42 
43 #include "vid.h"
44 #include "amdgpu.h"
45 #include "amdgpu_display.h"
46 #include "amdgpu_ucode.h"
47 #include "atom.h"
48 #include "amdgpu_dm.h"
49 #include "amdgpu_dm_plane.h"
50 #include "amdgpu_dm_crtc.h"
51 #ifdef CONFIG_DRM_AMD_DC_HDCP
52 #include "amdgpu_dm_hdcp.h"
53 #include <drm/display/drm_hdcp_helper.h>
54 #endif
55 #include "amdgpu_pm.h"
56 #include "amdgpu_atombios.h"
57 
58 #include "amd_shared.h"
59 #include "amdgpu_dm_irq.h"
60 #include "dm_helpers.h"
61 #include "amdgpu_dm_mst_types.h"
62 #if defined(CONFIG_DEBUG_FS)
63 #include "amdgpu_dm_debugfs.h"
64 #endif
65 #include "amdgpu_dm_psr.h"
66 
67 #include "ivsrcid/ivsrcid_vislands30.h"
68 
69 #include "i2caux_interface.h"
70 #include <linux/module.h>
71 #include <linux/moduleparam.h>
72 #include <linux/types.h>
73 #include <linux/pm_runtime.h>
74 #include <linux/pci.h>
75 #include <linux/firmware.h>
76 #include <linux/component.h>
77 #include <linux/dmi.h>
78 
79 #include <drm/display/drm_dp_mst_helper.h>
80 #include <drm/display/drm_hdmi_helper.h>
81 #include <drm/drm_atomic.h>
82 #include <drm/drm_atomic_uapi.h>
83 #include <drm/drm_atomic_helper.h>
84 #include <drm/drm_blend.h>
85 #include <drm/drm_fb_helper.h>
86 #include <drm/drm_fourcc.h>
87 #include <drm/drm_edid.h>
88 #include <drm/drm_vblank.h>
89 #include <drm/drm_audio_component.h>
90 #include <drm/drm_gem_atomic_helper.h>
91 #include <drm/drm_plane_helper.h>
92 
93 #include <acpi/video.h>
94 
95 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
96 
97 #include "dcn/dcn_1_0_offset.h"
98 #include "dcn/dcn_1_0_sh_mask.h"
99 #include "soc15_hw_ip.h"
100 #include "soc15_common.h"
101 #include "vega10_ip_offset.h"
102 
103 #include "gc/gc_11_0_0_offset.h"
104 #include "gc/gc_11_0_0_sh_mask.h"
105 
106 #include "modules/inc/mod_freesync.h"
107 #include "modules/power/power_helpers.h"
108 #include "modules/inc/mod_info_packet.h"
109 
110 #define FIRMWARE_RENOIR_DMUB "amdgpu/renoir_dmcub.bin"
111 MODULE_FIRMWARE(FIRMWARE_RENOIR_DMUB);
112 #define FIRMWARE_SIENNA_CICHLID_DMUB "amdgpu/sienna_cichlid_dmcub.bin"
113 MODULE_FIRMWARE(FIRMWARE_SIENNA_CICHLID_DMUB);
114 #define FIRMWARE_NAVY_FLOUNDER_DMUB "amdgpu/navy_flounder_dmcub.bin"
115 MODULE_FIRMWARE(FIRMWARE_NAVY_FLOUNDER_DMUB);
116 #define FIRMWARE_GREEN_SARDINE_DMUB "amdgpu/green_sardine_dmcub.bin"
117 MODULE_FIRMWARE(FIRMWARE_GREEN_SARDINE_DMUB);
118 #define FIRMWARE_VANGOGH_DMUB "amdgpu/vangogh_dmcub.bin"
119 MODULE_FIRMWARE(FIRMWARE_VANGOGH_DMUB);
120 #define FIRMWARE_DIMGREY_CAVEFISH_DMUB "amdgpu/dimgrey_cavefish_dmcub.bin"
121 MODULE_FIRMWARE(FIRMWARE_DIMGREY_CAVEFISH_DMUB);
122 #define FIRMWARE_BEIGE_GOBY_DMUB "amdgpu/beige_goby_dmcub.bin"
123 MODULE_FIRMWARE(FIRMWARE_BEIGE_GOBY_DMUB);
124 #define FIRMWARE_YELLOW_CARP_DMUB "amdgpu/yellow_carp_dmcub.bin"
125 MODULE_FIRMWARE(FIRMWARE_YELLOW_CARP_DMUB);
126 #define FIRMWARE_DCN_314_DMUB "amdgpu/dcn_3_1_4_dmcub.bin"
127 MODULE_FIRMWARE(FIRMWARE_DCN_314_DMUB);
128 #define FIRMWARE_DCN_315_DMUB "amdgpu/dcn_3_1_5_dmcub.bin"
129 MODULE_FIRMWARE(FIRMWARE_DCN_315_DMUB);
130 #define FIRMWARE_DCN316_DMUB "amdgpu/dcn_3_1_6_dmcub.bin"
131 MODULE_FIRMWARE(FIRMWARE_DCN316_DMUB);
132 
133 #define FIRMWARE_DCN_V3_2_0_DMCUB "amdgpu/dcn_3_2_0_dmcub.bin"
134 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_0_DMCUB);
135 #define FIRMWARE_DCN_V3_2_1_DMCUB "amdgpu/dcn_3_2_1_dmcub.bin"
136 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_1_DMCUB);
137 
138 #define FIRMWARE_RAVEN_DMCU		"amdgpu/raven_dmcu.bin"
139 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
140 
141 #define FIRMWARE_NAVI12_DMCU            "amdgpu/navi12_dmcu.bin"
142 MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
143 
144 /* Number of bytes in PSP header for firmware. */
145 #define PSP_HEADER_BYTES 0x100
146 
147 /* Number of bytes in PSP footer for firmware. */
148 #define PSP_FOOTER_BYTES 0x100
149 
150 /*
151  * DMUB Async to Sync Mechanism Status
152  */
153 #define DMUB_ASYNC_TO_SYNC_ACCESS_FAIL 1
154 #define DMUB_ASYNC_TO_SYNC_ACCESS_TIMEOUT 2
155 #define DMUB_ASYNC_TO_SYNC_ACCESS_SUCCESS 3
156 #define DMUB_ASYNC_TO_SYNC_ACCESS_INVALID 4
157 
158 /**
159  * DOC: overview
160  *
161  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
162  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
163  * requests into DC requests, and DC responses into DRM responses.
164  *
165  * The root control structure is &struct amdgpu_display_manager.
166  */
167 
168 /* basic init/fini API */
169 static int amdgpu_dm_init(struct amdgpu_device *adev);
170 static void amdgpu_dm_fini(struct amdgpu_device *adev);
171 static bool is_freesync_video_mode(const struct drm_display_mode *mode, struct amdgpu_dm_connector *aconnector);
172 
173 static enum drm_mode_subconnector get_subconnector_type(struct dc_link *link)
174 {
175 	switch (link->dpcd_caps.dongle_type) {
176 	case DISPLAY_DONGLE_NONE:
177 		return DRM_MODE_SUBCONNECTOR_Native;
178 	case DISPLAY_DONGLE_DP_VGA_CONVERTER:
179 		return DRM_MODE_SUBCONNECTOR_VGA;
180 	case DISPLAY_DONGLE_DP_DVI_CONVERTER:
181 	case DISPLAY_DONGLE_DP_DVI_DONGLE:
182 		return DRM_MODE_SUBCONNECTOR_DVID;
183 	case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
184 	case DISPLAY_DONGLE_DP_HDMI_DONGLE:
185 		return DRM_MODE_SUBCONNECTOR_HDMIA;
186 	case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
187 	default:
188 		return DRM_MODE_SUBCONNECTOR_Unknown;
189 	}
190 }
191 
192 static void update_subconnector_property(struct amdgpu_dm_connector *aconnector)
193 {
194 	struct dc_link *link = aconnector->dc_link;
195 	struct drm_connector *connector = &aconnector->base;
196 	enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
197 
198 	if (connector->connector_type != DRM_MODE_CONNECTOR_DisplayPort)
199 		return;
200 
201 	if (aconnector->dc_sink)
202 		subconnector = get_subconnector_type(link);
203 
204 	drm_object_property_set_value(&connector->base,
205 			connector->dev->mode_config.dp_subconnector_property,
206 			subconnector);
207 }
208 
209 /*
210  * initializes drm_device display related structures, based on the information
211  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
212  * drm_encoder, drm_mode_config
213  *
214  * Returns 0 on success
215  */
216 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
217 /* removes and deallocates the drm structures, created by the above function */
218 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
219 
220 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
221 				    struct amdgpu_dm_connector *amdgpu_dm_connector,
222 				    uint32_t link_index,
223 				    struct amdgpu_encoder *amdgpu_encoder);
224 static int amdgpu_dm_encoder_init(struct drm_device *dev,
225 				  struct amdgpu_encoder *aencoder,
226 				  uint32_t link_index);
227 
228 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
229 
230 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
231 
232 static int amdgpu_dm_atomic_check(struct drm_device *dev,
233 				  struct drm_atomic_state *state);
234 
235 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector);
236 static void handle_hpd_rx_irq(void *param);
237 
238 static bool
239 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
240 				 struct drm_crtc_state *new_crtc_state);
241 /*
242  * dm_vblank_get_counter
243  *
244  * @brief
245  * Get counter for number of vertical blanks
246  *
247  * @param
248  * struct amdgpu_device *adev - [in] desired amdgpu device
249  * int disp_idx - [in] which CRTC to get the counter from
250  *
251  * @return
252  * Counter for vertical blanks
253  */
254 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
255 {
256 	if (crtc >= adev->mode_info.num_crtc)
257 		return 0;
258 	else {
259 		struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
260 
261 		if (acrtc->dm_irq_params.stream == NULL) {
262 			DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
263 				  crtc);
264 			return 0;
265 		}
266 
267 		return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
268 	}
269 }
270 
271 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
272 				  u32 *vbl, u32 *position)
273 {
274 	uint32_t v_blank_start, v_blank_end, h_position, v_position;
275 
276 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
277 		return -EINVAL;
278 	else {
279 		struct amdgpu_crtc *acrtc = adev->mode_info.crtcs[crtc];
280 
281 		if (acrtc->dm_irq_params.stream ==  NULL) {
282 			DRM_ERROR("dc_stream_state is NULL for crtc '%d'!\n",
283 				  crtc);
284 			return 0;
285 		}
286 
287 		/*
288 		 * TODO rework base driver to use values directly.
289 		 * for now parse it back into reg-format
290 		 */
291 		dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
292 					 &v_blank_start,
293 					 &v_blank_end,
294 					 &h_position,
295 					 &v_position);
296 
297 		*position = v_position | (h_position << 16);
298 		*vbl = v_blank_start | (v_blank_end << 16);
299 	}
300 
301 	return 0;
302 }
303 
304 static bool dm_is_idle(void *handle)
305 {
306 	/* XXX todo */
307 	return true;
308 }
309 
310 static int dm_wait_for_idle(void *handle)
311 {
312 	/* XXX todo */
313 	return 0;
314 }
315 
316 static bool dm_check_soft_reset(void *handle)
317 {
318 	return false;
319 }
320 
321 static int dm_soft_reset(void *handle)
322 {
323 	/* XXX todo */
324 	return 0;
325 }
326 
327 static struct amdgpu_crtc *
328 get_crtc_by_otg_inst(struct amdgpu_device *adev,
329 		     int otg_inst)
330 {
331 	struct drm_device *dev = adev_to_drm(adev);
332 	struct drm_crtc *crtc;
333 	struct amdgpu_crtc *amdgpu_crtc;
334 
335 	if (WARN_ON(otg_inst == -1))
336 		return adev->mode_info.crtcs[0];
337 
338 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
339 		amdgpu_crtc = to_amdgpu_crtc(crtc);
340 
341 		if (amdgpu_crtc->otg_inst == otg_inst)
342 			return amdgpu_crtc;
343 	}
344 
345 	return NULL;
346 }
347 
348 static inline bool is_dc_timing_adjust_needed(struct dm_crtc_state *old_state,
349 					      struct dm_crtc_state *new_state)
350 {
351 	if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
352 		return true;
353 	else if (amdgpu_dm_vrr_active(old_state) != amdgpu_dm_vrr_active(new_state))
354 		return true;
355 	else
356 		return false;
357 }
358 
359 /**
360  * dm_pflip_high_irq() - Handle pageflip interrupt
361  * @interrupt_params: ignored
362  *
363  * Handles the pageflip interrupt by notifying all interested parties
364  * that the pageflip has been completed.
365  */
366 static void dm_pflip_high_irq(void *interrupt_params)
367 {
368 	struct amdgpu_crtc *amdgpu_crtc;
369 	struct common_irq_params *irq_params = interrupt_params;
370 	struct amdgpu_device *adev = irq_params->adev;
371 	unsigned long flags;
372 	struct drm_pending_vblank_event *e;
373 	uint32_t vpos, hpos, v_blank_start, v_blank_end;
374 	bool vrr_active;
375 
376 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
377 
378 	/* IRQ could occur when in initial stage */
379 	/* TODO work and BO cleanup */
380 	if (amdgpu_crtc == NULL) {
381 		DC_LOG_PFLIP("CRTC is null, returning.\n");
382 		return;
383 	}
384 
385 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
386 
387 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED){
388 		DC_LOG_PFLIP("amdgpu_crtc->pflip_status = %d !=AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p] \n",
389 						 amdgpu_crtc->pflip_status,
390 						 AMDGPU_FLIP_SUBMITTED,
391 						 amdgpu_crtc->crtc_id,
392 						 amdgpu_crtc);
393 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
394 		return;
395 	}
396 
397 	/* page flip completed. */
398 	e = amdgpu_crtc->event;
399 	amdgpu_crtc->event = NULL;
400 
401 	WARN_ON(!e);
402 
403 	vrr_active = amdgpu_dm_vrr_active_irq(amdgpu_crtc);
404 
405 	/* Fixed refresh rate, or VRR scanout position outside front-porch? */
406 	if (!vrr_active ||
407 	    !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
408 				      &v_blank_end, &hpos, &vpos) ||
409 	    (vpos < v_blank_start)) {
410 		/* Update to correct count and vblank timestamp if racing with
411 		 * vblank irq. This also updates to the correct vblank timestamp
412 		 * even in VRR mode, as scanout is past the front-porch atm.
413 		 */
414 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
415 
416 		/* Wake up userspace by sending the pageflip event with proper
417 		 * count and timestamp of vblank of flip completion.
418 		 */
419 		if (e) {
420 			drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
421 
422 			/* Event sent, so done with vblank for this flip */
423 			drm_crtc_vblank_put(&amdgpu_crtc->base);
424 		}
425 	} else if (e) {
426 		/* VRR active and inside front-porch: vblank count and
427 		 * timestamp for pageflip event will only be up to date after
428 		 * drm_crtc_handle_vblank() has been executed from late vblank
429 		 * irq handler after start of back-porch (vline 0). We queue the
430 		 * pageflip event for send-out by drm_crtc_handle_vblank() with
431 		 * updated timestamp and count, once it runs after us.
432 		 *
433 		 * We need to open-code this instead of using the helper
434 		 * drm_crtc_arm_vblank_event(), as that helper would
435 		 * call drm_crtc_accurate_vblank_count(), which we must
436 		 * not call in VRR mode while we are in front-porch!
437 		 */
438 
439 		/* sequence will be replaced by real count during send-out. */
440 		e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
441 		e->pipe = amdgpu_crtc->crtc_id;
442 
443 		list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
444 		e = NULL;
445 	}
446 
447 	/* Keep track of vblank of this flip for flip throttling. We use the
448 	 * cooked hw counter, as that one incremented at start of this vblank
449 	 * of pageflip completion, so last_flip_vblank is the forbidden count
450 	 * for queueing new pageflips if vsync + VRR is enabled.
451 	 */
452 	amdgpu_crtc->dm_irq_params.last_flip_vblank =
453 		amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
454 
455 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
456 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
457 
458 	DC_LOG_PFLIP("crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
459 		     amdgpu_crtc->crtc_id, amdgpu_crtc,
460 		     vrr_active, (int) !e);
461 }
462 
463 static void dm_vupdate_high_irq(void *interrupt_params)
464 {
465 	struct common_irq_params *irq_params = interrupt_params;
466 	struct amdgpu_device *adev = irq_params->adev;
467 	struct amdgpu_crtc *acrtc;
468 	struct drm_device *drm_dev;
469 	struct drm_vblank_crtc *vblank;
470 	ktime_t frame_duration_ns, previous_timestamp;
471 	unsigned long flags;
472 	int vrr_active;
473 
474 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
475 
476 	if (acrtc) {
477 		vrr_active = amdgpu_dm_vrr_active_irq(acrtc);
478 		drm_dev = acrtc->base.dev;
479 		vblank = &drm_dev->vblank[acrtc->base.index];
480 		previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
481 		frame_duration_ns = vblank->time - previous_timestamp;
482 
483 		if (frame_duration_ns > 0) {
484 			trace_amdgpu_refresh_rate_track(acrtc->base.index,
485 						frame_duration_ns,
486 						ktime_divns(NSEC_PER_SEC, frame_duration_ns));
487 			atomic64_set(&irq_params->previous_timestamp, vblank->time);
488 		}
489 
490 		DC_LOG_VBLANK("crtc:%d, vupdate-vrr:%d\n",
491 			      acrtc->crtc_id,
492 			      vrr_active);
493 
494 		/* Core vblank handling is done here after end of front-porch in
495 		 * vrr mode, as vblank timestamping will give valid results
496 		 * while now done after front-porch. This will also deliver
497 		 * page-flip completion events that have been queued to us
498 		 * if a pageflip happened inside front-porch.
499 		 */
500 		if (vrr_active) {
501 			dm_crtc_handle_vblank(acrtc);
502 
503 			/* BTR processing for pre-DCE12 ASICs */
504 			if (acrtc->dm_irq_params.stream &&
505 			    adev->family < AMDGPU_FAMILY_AI) {
506 				spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
507 				mod_freesync_handle_v_update(
508 				    adev->dm.freesync_module,
509 				    acrtc->dm_irq_params.stream,
510 				    &acrtc->dm_irq_params.vrr_params);
511 
512 				dc_stream_adjust_vmin_vmax(
513 				    adev->dm.dc,
514 				    acrtc->dm_irq_params.stream,
515 				    &acrtc->dm_irq_params.vrr_params.adjust);
516 				spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
517 			}
518 		}
519 	}
520 }
521 
522 /**
523  * dm_crtc_high_irq() - Handles CRTC interrupt
524  * @interrupt_params: used for determining the CRTC instance
525  *
526  * Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
527  * event handler.
528  */
529 static void dm_crtc_high_irq(void *interrupt_params)
530 {
531 	struct common_irq_params *irq_params = interrupt_params;
532 	struct amdgpu_device *adev = irq_params->adev;
533 	struct amdgpu_crtc *acrtc;
534 	unsigned long flags;
535 	int vrr_active;
536 
537 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
538 	if (!acrtc)
539 		return;
540 
541 	vrr_active = amdgpu_dm_vrr_active_irq(acrtc);
542 
543 	DC_LOG_VBLANK("crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
544 		      vrr_active, acrtc->dm_irq_params.active_planes);
545 
546 	/**
547 	 * Core vblank handling at start of front-porch is only possible
548 	 * in non-vrr mode, as only there vblank timestamping will give
549 	 * valid results while done in front-porch. Otherwise defer it
550 	 * to dm_vupdate_high_irq after end of front-porch.
551 	 */
552 	if (!vrr_active)
553 		dm_crtc_handle_vblank(acrtc);
554 
555 	/**
556 	 * Following stuff must happen at start of vblank, for crc
557 	 * computation and below-the-range btr support in vrr mode.
558 	 */
559 	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
560 
561 	/* BTR updates need to happen before VUPDATE on Vega and above. */
562 	if (adev->family < AMDGPU_FAMILY_AI)
563 		return;
564 
565 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
566 
567 	if (acrtc->dm_irq_params.stream &&
568 	    acrtc->dm_irq_params.vrr_params.supported &&
569 	    acrtc->dm_irq_params.freesync_config.state ==
570 		    VRR_STATE_ACTIVE_VARIABLE) {
571 		mod_freesync_handle_v_update(adev->dm.freesync_module,
572 					     acrtc->dm_irq_params.stream,
573 					     &acrtc->dm_irq_params.vrr_params);
574 
575 		dc_stream_adjust_vmin_vmax(adev->dm.dc, acrtc->dm_irq_params.stream,
576 					   &acrtc->dm_irq_params.vrr_params.adjust);
577 	}
578 
579 	/*
580 	 * If there aren't any active_planes then DCH HUBP may be clock-gated.
581 	 * In that case, pageflip completion interrupts won't fire and pageflip
582 	 * completion events won't get delivered. Prevent this by sending
583 	 * pending pageflip events from here if a flip is still pending.
584 	 *
585 	 * If any planes are enabled, use dm_pflip_high_irq() instead, to
586 	 * avoid race conditions between flip programming and completion,
587 	 * which could cause too early flip completion events.
588 	 */
589 	if (adev->family >= AMDGPU_FAMILY_RV &&
590 	    acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
591 	    acrtc->dm_irq_params.active_planes == 0) {
592 		if (acrtc->event) {
593 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
594 			acrtc->event = NULL;
595 			drm_crtc_vblank_put(&acrtc->base);
596 		}
597 		acrtc->pflip_status = AMDGPU_FLIP_NONE;
598 	}
599 
600 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
601 }
602 
603 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
604 /**
605  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
606  * DCN generation ASICs
607  * @interrupt_params: interrupt parameters
608  *
609  * Used to set crc window/read out crc value at vertical line 0 position
610  */
611 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
612 {
613 	struct common_irq_params *irq_params = interrupt_params;
614 	struct amdgpu_device *adev = irq_params->adev;
615 	struct amdgpu_crtc *acrtc;
616 
617 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
618 
619 	if (!acrtc)
620 		return;
621 
622 	amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
623 }
624 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
625 
626 /**
627  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
628  * @adev: amdgpu_device pointer
629  * @notify: dmub notification structure
630  *
631  * Dmub AUX or SET_CONFIG command completion processing callback
632  * Copies dmub notification to DM which is to be read by AUX command.
633  * issuing thread and also signals the event to wake up the thread.
634  */
635 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
636 					struct dmub_notification *notify)
637 {
638 	if (adev->dm.dmub_notify)
639 		memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
640 	if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
641 		complete(&adev->dm.dmub_aux_transfer_done);
642 }
643 
644 /**
645  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
646  * @adev: amdgpu_device pointer
647  * @notify: dmub notification structure
648  *
649  * Dmub Hpd interrupt processing callback. Gets displayindex through the
650  * ink index and calls helper to do the processing.
651  */
652 static void dmub_hpd_callback(struct amdgpu_device *adev,
653 			      struct dmub_notification *notify)
654 {
655 	struct amdgpu_dm_connector *aconnector;
656 	struct amdgpu_dm_connector *hpd_aconnector = NULL;
657 	struct drm_connector *connector;
658 	struct drm_connector_list_iter iter;
659 	struct dc_link *link;
660 	uint8_t link_index = 0;
661 	struct drm_device *dev;
662 
663 	if (adev == NULL)
664 		return;
665 
666 	if (notify == NULL) {
667 		DRM_ERROR("DMUB HPD callback notification was NULL");
668 		return;
669 	}
670 
671 	if (notify->link_index > adev->dm.dc->link_count) {
672 		DRM_ERROR("DMUB HPD index (%u)is abnormal", notify->link_index);
673 		return;
674 	}
675 
676 	link_index = notify->link_index;
677 	link = adev->dm.dc->links[link_index];
678 	dev = adev->dm.ddev;
679 
680 	drm_connector_list_iter_begin(dev, &iter);
681 	drm_for_each_connector_iter(connector, &iter) {
682 		aconnector = to_amdgpu_dm_connector(connector);
683 		if (link && aconnector->dc_link == link) {
684 			DRM_INFO("DMUB HPD callback: link_index=%u\n", link_index);
685 			hpd_aconnector = aconnector;
686 			break;
687 		}
688 	}
689 	drm_connector_list_iter_end(&iter);
690 
691 	if (hpd_aconnector) {
692 		if (notify->type == DMUB_NOTIFICATION_HPD)
693 			handle_hpd_irq_helper(hpd_aconnector);
694 		else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
695 			handle_hpd_rx_irq(hpd_aconnector);
696 	}
697 }
698 
699 /**
700  * register_dmub_notify_callback - Sets callback for DMUB notify
701  * @adev: amdgpu_device pointer
702  * @type: Type of dmub notification
703  * @callback: Dmub interrupt callback function
704  * @dmub_int_thread_offload: offload indicator
705  *
706  * API to register a dmub callback handler for a dmub notification
707  * Also sets indicator whether callback processing to be offloaded.
708  * to dmub interrupt handling thread
709  * Return: true if successfully registered, false if there is existing registration
710  */
711 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
712 					  enum dmub_notification_type type,
713 					  dmub_notify_interrupt_callback_t callback,
714 					  bool dmub_int_thread_offload)
715 {
716 	if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
717 		adev->dm.dmub_callback[type] = callback;
718 		adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
719 	} else
720 		return false;
721 
722 	return true;
723 }
724 
725 static void dm_handle_hpd_work(struct work_struct *work)
726 {
727 	struct dmub_hpd_work *dmub_hpd_wrk;
728 
729 	dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
730 
731 	if (!dmub_hpd_wrk->dmub_notify) {
732 		DRM_ERROR("dmub_hpd_wrk dmub_notify is NULL");
733 		return;
734 	}
735 
736 	if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
737 		dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
738 		dmub_hpd_wrk->dmub_notify);
739 	}
740 
741 	kfree(dmub_hpd_wrk->dmub_notify);
742 	kfree(dmub_hpd_wrk);
743 
744 }
745 
746 #define DMUB_TRACE_MAX_READ 64
747 /**
748  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
749  * @interrupt_params: used for determining the Outbox instance
750  *
751  * Handles the Outbox Interrupt
752  * event handler.
753  */
754 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
755 {
756 	struct dmub_notification notify;
757 	struct common_irq_params *irq_params = interrupt_params;
758 	struct amdgpu_device *adev = irq_params->adev;
759 	struct amdgpu_display_manager *dm = &adev->dm;
760 	struct dmcub_trace_buf_entry entry = { 0 };
761 	uint32_t count = 0;
762 	struct dmub_hpd_work *dmub_hpd_wrk;
763 	struct dc_link *plink = NULL;
764 
765 	if (dc_enable_dmub_notifications(adev->dm.dc) &&
766 		irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
767 
768 		do {
769 			dc_stat_get_dmub_notification(adev->dm.dc, &notify);
770 			if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
771 				DRM_ERROR("DM: notify type %d invalid!", notify.type);
772 				continue;
773 			}
774 			if (!dm->dmub_callback[notify.type]) {
775 				DRM_DEBUG_DRIVER("DMUB notification skipped, no handler: type=%d\n", notify.type);
776 				continue;
777 			}
778 			if (dm->dmub_thread_offload[notify.type] == true) {
779 				dmub_hpd_wrk = kzalloc(sizeof(*dmub_hpd_wrk), GFP_ATOMIC);
780 				if (!dmub_hpd_wrk) {
781 					DRM_ERROR("Failed to allocate dmub_hpd_wrk");
782 					return;
783 				}
784 				dmub_hpd_wrk->dmub_notify = kzalloc(sizeof(struct dmub_notification), GFP_ATOMIC);
785 				if (!dmub_hpd_wrk->dmub_notify) {
786 					kfree(dmub_hpd_wrk);
787 					DRM_ERROR("Failed to allocate dmub_hpd_wrk->dmub_notify");
788 					return;
789 				}
790 				INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
791 				if (dmub_hpd_wrk->dmub_notify)
792 					memcpy(dmub_hpd_wrk->dmub_notify, &notify, sizeof(struct dmub_notification));
793 				dmub_hpd_wrk->adev = adev;
794 				if (notify.type == DMUB_NOTIFICATION_HPD) {
795 					plink = adev->dm.dc->links[notify.link_index];
796 					if (plink) {
797 						plink->hpd_status =
798 							notify.hpd_status == DP_HPD_PLUG;
799 					}
800 				}
801 				queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
802 			} else {
803 				dm->dmub_callback[notify.type](adev, &notify);
804 			}
805 		} while (notify.pending_notification);
806 	}
807 
808 
809 	do {
810 		if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
811 			trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
812 							entry.param0, entry.param1);
813 
814 			DRM_DEBUG_DRIVER("trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
815 				 entry.trace_code, entry.tick_count, entry.param0, entry.param1);
816 		} else
817 			break;
818 
819 		count++;
820 
821 	} while (count <= DMUB_TRACE_MAX_READ);
822 
823 	if (count > DMUB_TRACE_MAX_READ)
824 		DRM_DEBUG_DRIVER("Warning : count > DMUB_TRACE_MAX_READ");
825 }
826 
827 static int dm_set_clockgating_state(void *handle,
828 		  enum amd_clockgating_state state)
829 {
830 	return 0;
831 }
832 
833 static int dm_set_powergating_state(void *handle,
834 		  enum amd_powergating_state state)
835 {
836 	return 0;
837 }
838 
839 /* Prototypes of private functions */
840 static int dm_early_init(void* handle);
841 
842 /* Allocate memory for FBC compressed data  */
843 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
844 {
845 	struct drm_device *dev = connector->dev;
846 	struct amdgpu_device *adev = drm_to_adev(dev);
847 	struct dm_compressor_info *compressor = &adev->dm.compressor;
848 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
849 	struct drm_display_mode *mode;
850 	unsigned long max_size = 0;
851 
852 	if (adev->dm.dc->fbc_compressor == NULL)
853 		return;
854 
855 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
856 		return;
857 
858 	if (compressor->bo_ptr)
859 		return;
860 
861 
862 	list_for_each_entry(mode, &connector->modes, head) {
863 		if (max_size < mode->htotal * mode->vtotal)
864 			max_size = mode->htotal * mode->vtotal;
865 	}
866 
867 	if (max_size) {
868 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
869 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
870 			    &compressor->gpu_addr, &compressor->cpu_addr);
871 
872 		if (r)
873 			DRM_ERROR("DM: Failed to initialize FBC\n");
874 		else {
875 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
876 			DRM_INFO("DM: FBC alloc %lu\n", max_size*4);
877 		}
878 
879 	}
880 
881 }
882 
883 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
884 					  int pipe, bool *enabled,
885 					  unsigned char *buf, int max_bytes)
886 {
887 	struct drm_device *dev = dev_get_drvdata(kdev);
888 	struct amdgpu_device *adev = drm_to_adev(dev);
889 	struct drm_connector *connector;
890 	struct drm_connector_list_iter conn_iter;
891 	struct amdgpu_dm_connector *aconnector;
892 	int ret = 0;
893 
894 	*enabled = false;
895 
896 	mutex_lock(&adev->dm.audio_lock);
897 
898 	drm_connector_list_iter_begin(dev, &conn_iter);
899 	drm_for_each_connector_iter(connector, &conn_iter) {
900 		aconnector = to_amdgpu_dm_connector(connector);
901 		if (aconnector->audio_inst != port)
902 			continue;
903 
904 		*enabled = true;
905 		ret = drm_eld_size(connector->eld);
906 		memcpy(buf, connector->eld, min(max_bytes, ret));
907 
908 		break;
909 	}
910 	drm_connector_list_iter_end(&conn_iter);
911 
912 	mutex_unlock(&adev->dm.audio_lock);
913 
914 	DRM_DEBUG_KMS("Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
915 
916 	return ret;
917 }
918 
919 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
920 	.get_eld = amdgpu_dm_audio_component_get_eld,
921 };
922 
923 static int amdgpu_dm_audio_component_bind(struct device *kdev,
924 				       struct device *hda_kdev, void *data)
925 {
926 	struct drm_device *dev = dev_get_drvdata(kdev);
927 	struct amdgpu_device *adev = drm_to_adev(dev);
928 	struct drm_audio_component *acomp = data;
929 
930 	acomp->ops = &amdgpu_dm_audio_component_ops;
931 	acomp->dev = kdev;
932 	adev->dm.audio_component = acomp;
933 
934 	return 0;
935 }
936 
937 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
938 					  struct device *hda_kdev, void *data)
939 {
940 	struct drm_device *dev = dev_get_drvdata(kdev);
941 	struct amdgpu_device *adev = drm_to_adev(dev);
942 	struct drm_audio_component *acomp = data;
943 
944 	acomp->ops = NULL;
945 	acomp->dev = NULL;
946 	adev->dm.audio_component = NULL;
947 }
948 
949 #ifdef notyet
950 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
951 	.bind	= amdgpu_dm_audio_component_bind,
952 	.unbind	= amdgpu_dm_audio_component_unbind,
953 };
954 #endif
955 
956 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
957 {
958 	int i, ret;
959 
960 	if (!amdgpu_audio)
961 		return 0;
962 
963 	adev->mode_info.audio.enabled = true;
964 
965 	adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
966 
967 	for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
968 		adev->mode_info.audio.pin[i].channels = -1;
969 		adev->mode_info.audio.pin[i].rate = -1;
970 		adev->mode_info.audio.pin[i].bits_per_sample = -1;
971 		adev->mode_info.audio.pin[i].status_bits = 0;
972 		adev->mode_info.audio.pin[i].category_code = 0;
973 		adev->mode_info.audio.pin[i].connected = false;
974 		adev->mode_info.audio.pin[i].id =
975 			adev->dm.dc->res_pool->audios[i]->inst;
976 		adev->mode_info.audio.pin[i].offset = 0;
977 	}
978 
979 	ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
980 	if (ret < 0)
981 		return ret;
982 
983 	adev->dm.audio_registered = true;
984 
985 	return 0;
986 }
987 
988 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
989 {
990 	if (!amdgpu_audio)
991 		return;
992 
993 	if (!adev->mode_info.audio.enabled)
994 		return;
995 
996 	if (adev->dm.audio_registered) {
997 		component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
998 		adev->dm.audio_registered = false;
999 	}
1000 
1001 	/* TODO: Disable audio? */
1002 
1003 	adev->mode_info.audio.enabled = false;
1004 }
1005 
1006 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
1007 {
1008 	struct drm_audio_component *acomp = adev->dm.audio_component;
1009 
1010 	if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
1011 		DRM_DEBUG_KMS("Notify ELD: %d\n", pin);
1012 
1013 		acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1014 						 pin, -1);
1015 	}
1016 }
1017 
1018 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1019 {
1020 	const struct dmcub_firmware_header_v1_0 *hdr;
1021 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1022 	struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1023 	const struct firmware *dmub_fw = adev->dm.dmub_fw;
1024 	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1025 	struct abm *abm = adev->dm.dc->res_pool->abm;
1026 	struct dmub_srv_hw_params hw_params;
1027 	enum dmub_status status;
1028 	const unsigned char *fw_inst_const, *fw_bss_data;
1029 	uint32_t i, fw_inst_const_size, fw_bss_data_size;
1030 	bool has_hw_support;
1031 
1032 	if (!dmub_srv)
1033 		/* DMUB isn't supported on the ASIC. */
1034 		return 0;
1035 
1036 	if (!fb_info) {
1037 		DRM_ERROR("No framebuffer info for DMUB service.\n");
1038 		return -EINVAL;
1039 	}
1040 
1041 	if (!dmub_fw) {
1042 		/* Firmware required for DMUB support. */
1043 		DRM_ERROR("No firmware provided for DMUB.\n");
1044 		return -EINVAL;
1045 	}
1046 
1047 	status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1048 	if (status != DMUB_STATUS_OK) {
1049 		DRM_ERROR("Error checking HW support for DMUB: %d\n", status);
1050 		return -EINVAL;
1051 	}
1052 
1053 	if (!has_hw_support) {
1054 		DRM_INFO("DMUB unsupported on ASIC\n");
1055 		return 0;
1056 	}
1057 
1058 	/* Reset DMCUB if it was previously running - before we overwrite its memory. */
1059 	status = dmub_srv_hw_reset(dmub_srv);
1060 	if (status != DMUB_STATUS_OK)
1061 		DRM_WARN("Error resetting DMUB HW: %d\n", status);
1062 
1063 	hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1064 
1065 	fw_inst_const = dmub_fw->data +
1066 			le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1067 			PSP_HEADER_BYTES;
1068 
1069 	fw_bss_data = dmub_fw->data +
1070 		      le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1071 		      le32_to_cpu(hdr->inst_const_bytes);
1072 
1073 	/* Copy firmware and bios info into FB memory. */
1074 	fw_inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
1075 			     PSP_HEADER_BYTES - PSP_FOOTER_BYTES;
1076 
1077 	fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1078 
1079 	/* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1080 	 * amdgpu_ucode_init_single_fw will load dmub firmware
1081 	 * fw_inst_const part to cw0; otherwise, the firmware back door load
1082 	 * will be done by dm_dmub_hw_init
1083 	 */
1084 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1085 		memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1086 				fw_inst_const_size);
1087 	}
1088 
1089 	if (fw_bss_data_size)
1090 		memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1091 		       fw_bss_data, fw_bss_data_size);
1092 
1093 	/* Copy firmware bios info into FB memory. */
1094 	memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1095 	       adev->bios_size);
1096 
1097 	/* Reset regions that need to be reset. */
1098 	memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1099 	fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1100 
1101 	memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1102 	       fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1103 
1104 	memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1105 	       fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1106 
1107 	/* Initialize hardware. */
1108 	memset(&hw_params, 0, sizeof(hw_params));
1109 	hw_params.fb_base = adev->gmc.fb_start;
1110 	hw_params.fb_offset = adev->gmc.aper_base;
1111 
1112 	/* backdoor load firmware and trigger dmub running */
1113 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1114 		hw_params.load_inst_const = true;
1115 
1116 	if (dmcu)
1117 		hw_params.psp_version = dmcu->psp_version;
1118 
1119 	for (i = 0; i < fb_info->num_fb; ++i)
1120 		hw_params.fb[i] = &fb_info->fb[i];
1121 
1122 	switch (adev->ip_versions[DCE_HWIP][0]) {
1123 	case IP_VERSION(3, 1, 3):
1124 	case IP_VERSION(3, 1, 4):
1125 		hw_params.dpia_supported = true;
1126 		hw_params.disable_dpia = adev->dm.dc->debug.dpia_debug.bits.disable_dpia;
1127 		break;
1128 	default:
1129 		break;
1130 	}
1131 
1132 	status = dmub_srv_hw_init(dmub_srv, &hw_params);
1133 	if (status != DMUB_STATUS_OK) {
1134 		DRM_ERROR("Error initializing DMUB HW: %d\n", status);
1135 		return -EINVAL;
1136 	}
1137 
1138 	/* Wait for firmware load to finish. */
1139 	status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1140 	if (status != DMUB_STATUS_OK)
1141 		DRM_WARN("Wait for DMUB auto-load failed: %d\n", status);
1142 
1143 	/* Init DMCU and ABM if available. */
1144 	if (dmcu && abm) {
1145 		dmcu->funcs->dmcu_init(dmcu);
1146 		abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1147 	}
1148 
1149 	if (!adev->dm.dc->ctx->dmub_srv)
1150 		adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1151 	if (!adev->dm.dc->ctx->dmub_srv) {
1152 		DRM_ERROR("Couldn't allocate DC DMUB server!\n");
1153 		return -ENOMEM;
1154 	}
1155 
1156 	DRM_INFO("DMUB hardware initialized: version=0x%08X\n",
1157 		 adev->dm.dmcub_fw_version);
1158 
1159 	return 0;
1160 }
1161 
1162 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1163 {
1164 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1165 	enum dmub_status status;
1166 	bool init;
1167 
1168 	if (!dmub_srv) {
1169 		/* DMUB isn't supported on the ASIC. */
1170 		return;
1171 	}
1172 
1173 	status = dmub_srv_is_hw_init(dmub_srv, &init);
1174 	if (status != DMUB_STATUS_OK)
1175 		DRM_WARN("DMUB hardware init check failed: %d\n", status);
1176 
1177 	if (status == DMUB_STATUS_OK && init) {
1178 		/* Wait for firmware load to finish. */
1179 		status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1180 		if (status != DMUB_STATUS_OK)
1181 			DRM_WARN("Wait for DMUB auto-load failed: %d\n", status);
1182 	} else {
1183 		/* Perform the full hardware initialization. */
1184 		dm_dmub_hw_init(adev);
1185 	}
1186 }
1187 
1188 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1189 {
1190 	uint64_t pt_base;
1191 	uint32_t logical_addr_low;
1192 	uint32_t logical_addr_high;
1193 	uint32_t agp_base, agp_bot, agp_top;
1194 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1195 
1196 	memset(pa_config, 0, sizeof(*pa_config));
1197 
1198 	logical_addr_low  = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1199 	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1200 
1201 	if (adev->apu_flags & AMD_APU_IS_RAVEN2)
1202 		/*
1203 		 * Raven2 has a HW issue that it is unable to use the vram which
1204 		 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1205 		 * workaround that increase system aperture high address (add 1)
1206 		 * to get rid of the VM fault and hardware hang.
1207 		 */
1208 		logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1209 	else
1210 		logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1211 
1212 	agp_base = 0;
1213 	agp_bot = adev->gmc.agp_start >> 24;
1214 	agp_top = adev->gmc.agp_end >> 24;
1215 
1216 
1217 	page_table_start.high_part = (u32)(adev->gmc.gart_start >> 44) & 0xF;
1218 	page_table_start.low_part = (u32)(adev->gmc.gart_start >> 12);
1219 	page_table_end.high_part = (u32)(adev->gmc.gart_end >> 44) & 0xF;
1220 	page_table_end.low_part = (u32)(adev->gmc.gart_end >> 12);
1221 	page_table_base.high_part = upper_32_bits(pt_base) & 0xF;
1222 	page_table_base.low_part = lower_32_bits(pt_base);
1223 
1224 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1225 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1226 
1227 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24 ;
1228 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1229 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1230 
1231 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1232 	pa_config->system_aperture.fb_offset = adev->gmc.aper_base;
1233 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1234 
1235 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1236 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1237 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1238 
1239 	pa_config->is_hvm_enabled = 0;
1240 
1241 }
1242 
1243 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1244 {
1245 	struct hpd_rx_irq_offload_work *offload_work;
1246 	struct amdgpu_dm_connector *aconnector;
1247 	struct dc_link *dc_link;
1248 	struct amdgpu_device *adev;
1249 	enum dc_connection_type new_connection_type = dc_connection_none;
1250 	unsigned long flags;
1251 
1252 	offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1253 	aconnector = offload_work->offload_wq->aconnector;
1254 
1255 	if (!aconnector) {
1256 		DRM_ERROR("Can't retrieve aconnector in hpd_rx_irq_offload_work");
1257 		goto skip;
1258 	}
1259 
1260 	adev = drm_to_adev(aconnector->base.dev);
1261 	dc_link = aconnector->dc_link;
1262 
1263 	mutex_lock(&aconnector->hpd_lock);
1264 	if (!dc_link_detect_sink(dc_link, &new_connection_type))
1265 		DRM_ERROR("KMS: Failed to detect connector\n");
1266 	mutex_unlock(&aconnector->hpd_lock);
1267 
1268 	if (new_connection_type == dc_connection_none)
1269 		goto skip;
1270 
1271 	if (amdgpu_in_reset(adev))
1272 		goto skip;
1273 
1274 	mutex_lock(&adev->dm.dc_lock);
1275 	if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST)
1276 		dc_link_dp_handle_automated_test(dc_link);
1277 	else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1278 			hpd_rx_irq_check_link_loss_status(dc_link, &offload_work->data) &&
1279 			dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1280 		dc_link_dp_handle_link_loss(dc_link);
1281 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1282 		offload_work->offload_wq->is_handling_link_loss = false;
1283 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1284 	}
1285 	mutex_unlock(&adev->dm.dc_lock);
1286 
1287 skip:
1288 	kfree(offload_work);
1289 
1290 }
1291 
1292 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct dc *dc)
1293 {
1294 	int max_caps = dc->caps.max_links;
1295 	int i = 0;
1296 	struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1297 
1298 	hpd_rx_offload_wq = kcalloc(max_caps, sizeof(*hpd_rx_offload_wq), GFP_KERNEL);
1299 
1300 	if (!hpd_rx_offload_wq)
1301 		return NULL;
1302 
1303 
1304 	for (i = 0; i < max_caps; i++) {
1305 		hpd_rx_offload_wq[i].wq =
1306 				    create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1307 
1308 		if (hpd_rx_offload_wq[i].wq == NULL) {
1309 			DRM_ERROR("create amdgpu_dm_hpd_rx_offload_wq fail!");
1310 			goto out_err;
1311 		}
1312 
1313 		mtx_init(&hpd_rx_offload_wq[i].offload_lock, IPL_TTY);
1314 	}
1315 
1316 	return hpd_rx_offload_wq;
1317 
1318 out_err:
1319 	for (i = 0; i < max_caps; i++) {
1320 		if (hpd_rx_offload_wq[i].wq)
1321 			destroy_workqueue(hpd_rx_offload_wq[i].wq);
1322 	}
1323 	kfree(hpd_rx_offload_wq);
1324 	return NULL;
1325 }
1326 
1327 struct amdgpu_stutter_quirk {
1328 	u16 chip_vendor;
1329 	u16 chip_device;
1330 	u16 subsys_vendor;
1331 	u16 subsys_device;
1332 	u8 revision;
1333 };
1334 
1335 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1336 	/* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1337 	{ 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1338 	{ 0, 0, 0, 0, 0 },
1339 };
1340 
1341 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1342 {
1343 	const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1344 
1345 	while (p && p->chip_device != 0) {
1346 		if (pdev->vendor == p->chip_vendor &&
1347 		    pdev->device == p->chip_device &&
1348 		    pdev->subsystem_vendor == p->subsys_vendor &&
1349 		    pdev->subsystem_device == p->subsys_device &&
1350 		    pdev->revision == p->revision) {
1351 			return true;
1352 		}
1353 		++p;
1354 	}
1355 	return false;
1356 }
1357 
1358 static const struct dmi_system_id hpd_disconnect_quirk_table[] = {
1359 	{
1360 		.matches = {
1361 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1362 			DMI_MATCH(DMI_PRODUCT_NAME, "Precision 3660"),
1363 		},
1364 	},
1365 	{
1366 		.matches = {
1367 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1368 			DMI_MATCH(DMI_PRODUCT_NAME, "Precision 3260"),
1369 		},
1370 	},
1371 	{
1372 		.matches = {
1373 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1374 			DMI_MATCH(DMI_PRODUCT_NAME, "Precision 3460"),
1375 		},
1376 	},
1377 	{
1378 		.matches = {
1379 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1380 			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Tower Plus 7010"),
1381 		},
1382 	},
1383 	{
1384 		.matches = {
1385 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1386 			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Tower 7010"),
1387 		},
1388 	},
1389 	{
1390 		.matches = {
1391 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1392 			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex SFF Plus 7010"),
1393 		},
1394 	},
1395 	{
1396 		.matches = {
1397 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1398 			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex SFF 7010"),
1399 		},
1400 	},
1401 	{
1402 		.matches = {
1403 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1404 			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Micro Plus 7010"),
1405 		},
1406 	},
1407 	{
1408 		.matches = {
1409 			DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
1410 			DMI_MATCH(DMI_PRODUCT_NAME, "OptiPlex Micro 7010"),
1411 		},
1412 	},
1413 	{}
1414 	/* TODO: refactor this from a fixed table to a dynamic option */
1415 };
1416 
1417 static void retrieve_dmi_info(struct amdgpu_display_manager *dm)
1418 {
1419 	const struct dmi_system_id *dmi_id;
1420 
1421 	dm->aux_hpd_discon_quirk = false;
1422 
1423 	dmi_id = dmi_first_match(hpd_disconnect_quirk_table);
1424 	if (dmi_id) {
1425 		dm->aux_hpd_discon_quirk = true;
1426 		DRM_INFO("aux_hpd_discon_quirk attached\n");
1427 	}
1428 }
1429 
1430 static int amdgpu_dm_init(struct amdgpu_device *adev)
1431 {
1432 	struct dc_init_data init_data;
1433 #ifdef CONFIG_DRM_AMD_DC_HDCP
1434 	struct dc_callback_init init_params;
1435 #endif
1436 	int r;
1437 
1438 	adev->dm.ddev = adev_to_drm(adev);
1439 	adev->dm.adev = adev;
1440 
1441 	/* Zero all the fields */
1442 	memset(&init_data, 0, sizeof(init_data));
1443 #ifdef CONFIG_DRM_AMD_DC_HDCP
1444 	memset(&init_params, 0, sizeof(init_params));
1445 #endif
1446 
1447 	rw_init(&adev->dm.dc_lock, "dmdc");
1448 	rw_init(&adev->dm.audio_lock, "dmaud");
1449 	mtx_init(&adev->dm.vblank_lock, IPL_TTY);
1450 
1451 	if(amdgpu_dm_irq_init(adev)) {
1452 		DRM_ERROR("amdgpu: failed to initialize DM IRQ support.\n");
1453 		goto error;
1454 	}
1455 
1456 	init_data.asic_id.chip_family = adev->family;
1457 
1458 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
1459 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
1460 	init_data.asic_id.chip_id = adev->pdev->device;
1461 
1462 	init_data.asic_id.vram_width = adev->gmc.vram_width;
1463 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
1464 	init_data.asic_id.atombios_base_address =
1465 		adev->mode_info.atom_context->bios;
1466 
1467 	init_data.driver = adev;
1468 
1469 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
1470 
1471 	if (!adev->dm.cgs_device) {
1472 		DRM_ERROR("amdgpu: failed to create cgs device.\n");
1473 		goto error;
1474 	}
1475 
1476 	init_data.cgs_device = adev->dm.cgs_device;
1477 
1478 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
1479 
1480 	switch (adev->ip_versions[DCE_HWIP][0]) {
1481 	case IP_VERSION(2, 1, 0):
1482 		switch (adev->dm.dmcub_fw_version) {
1483 		case 0: /* development */
1484 		case 0x1: /* linux-firmware.git hash 6d9f399 */
1485 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
1486 			init_data.flags.disable_dmcu = false;
1487 			break;
1488 		default:
1489 			init_data.flags.disable_dmcu = true;
1490 		}
1491 		break;
1492 	case IP_VERSION(2, 0, 3):
1493 		init_data.flags.disable_dmcu = true;
1494 		break;
1495 	default:
1496 		break;
1497 	}
1498 
1499 	switch (adev->asic_type) {
1500 	case CHIP_CARRIZO:
1501 	case CHIP_STONEY:
1502 		init_data.flags.gpu_vm_support = true;
1503 		break;
1504 	default:
1505 		switch (adev->ip_versions[DCE_HWIP][0]) {
1506 		case IP_VERSION(1, 0, 0):
1507 		case IP_VERSION(1, 0, 1):
1508 			/* enable S/G on PCO and RV2 */
1509 			if ((adev->apu_flags & AMD_APU_IS_RAVEN2) ||
1510 			    (adev->apu_flags & AMD_APU_IS_PICASSO))
1511 				init_data.flags.gpu_vm_support = true;
1512 			break;
1513 		case IP_VERSION(2, 1, 0):
1514 		case IP_VERSION(3, 0, 1):
1515 		case IP_VERSION(3, 1, 2):
1516 		case IP_VERSION(3, 1, 3):
1517 		case IP_VERSION(3, 1, 5):
1518 		case IP_VERSION(3, 1, 6):
1519 			init_data.flags.gpu_vm_support = true;
1520 			break;
1521 		default:
1522 			break;
1523 		}
1524 		break;
1525 	}
1526 
1527 	if (init_data.flags.gpu_vm_support)
1528 		adev->mode_info.gpu_vm_support = true;
1529 
1530 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
1531 		init_data.flags.fbc_support = true;
1532 
1533 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
1534 		init_data.flags.multi_mon_pp_mclk_switch = true;
1535 
1536 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
1537 		init_data.flags.disable_fractional_pwm = true;
1538 
1539 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
1540 		init_data.flags.edp_no_power_sequencing = true;
1541 
1542 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
1543 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
1544 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
1545 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
1546 
1547 	init_data.flags.seamless_boot_edp_requested = false;
1548 
1549 	if (check_seamless_boot_capability(adev)) {
1550 		init_data.flags.seamless_boot_edp_requested = true;
1551 		init_data.flags.allow_seamless_boot_optimization = true;
1552 		DRM_INFO("Seamless boot condition check passed\n");
1553 	}
1554 
1555 	init_data.flags.enable_mipi_converter_optimization = true;
1556 
1557 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
1558 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
1559 
1560 	INIT_LIST_HEAD(&adev->dm.da_list);
1561 
1562 	retrieve_dmi_info(&adev->dm);
1563 
1564 	/* Display Core create. */
1565 	adev->dm.dc = dc_create(&init_data);
1566 
1567 	if (adev->dm.dc) {
1568 		DRM_INFO("Display Core initialized with v%s!\n", DC_VER);
1569 	} else {
1570 		DRM_INFO("Display Core failed to initialize with v%s!\n", DC_VER);
1571 		goto error;
1572 	}
1573 
1574 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
1575 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
1576 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
1577 	}
1578 
1579 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
1580 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
1581 	if (dm_should_disable_stutter(adev->pdev))
1582 		adev->dm.dc->debug.disable_stutter = true;
1583 
1584 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
1585 		adev->dm.dc->debug.disable_stutter = true;
1586 
1587 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC) {
1588 		adev->dm.dc->debug.disable_dsc = true;
1589 	}
1590 
1591 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
1592 		adev->dm.dc->debug.disable_clock_gate = true;
1593 
1594 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
1595 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
1596 
1597 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
1598 
1599 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
1600 	adev->dm.dc->debug.ignore_cable_id = true;
1601 
1602 	r = dm_dmub_hw_init(adev);
1603 	if (r) {
1604 		DRM_ERROR("DMUB interface failed to initialize: status=%d\n", r);
1605 		goto error;
1606 	}
1607 
1608 	dc_hardware_init(adev->dm.dc);
1609 
1610 	adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev->dm.dc);
1611 	if (!adev->dm.hpd_rx_offload_wq) {
1612 		DRM_ERROR("amdgpu: failed to create hpd rx offload workqueue.\n");
1613 		goto error;
1614 	}
1615 
1616 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
1617 		struct dc_phy_addr_space_config pa_config;
1618 
1619 		mmhub_read_system_context(adev, &pa_config);
1620 
1621 		// Call the DC init_memory func
1622 		dc_setup_system_context(adev->dm.dc, &pa_config);
1623 	}
1624 
1625 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
1626 	if (!adev->dm.freesync_module) {
1627 		DRM_ERROR(
1628 		"amdgpu: failed to initialize freesync_module.\n");
1629 	} else
1630 		DRM_DEBUG_DRIVER("amdgpu: freesync_module init done %p.\n",
1631 				adev->dm.freesync_module);
1632 
1633 	amdgpu_dm_init_color_mod();
1634 
1635 	if (adev->dm.dc->caps.max_links > 0) {
1636 		adev->dm.vblank_control_workqueue =
1637 			create_singlethread_workqueue("dm_vblank_control_workqueue");
1638 		if (!adev->dm.vblank_control_workqueue)
1639 			DRM_ERROR("amdgpu: failed to initialize vblank_workqueue.\n");
1640 	}
1641 
1642 #ifdef CONFIG_DRM_AMD_DC_HDCP
1643 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
1644 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
1645 
1646 		if (!adev->dm.hdcp_workqueue)
1647 			DRM_ERROR("amdgpu: failed to initialize hdcp_workqueue.\n");
1648 		else
1649 			DRM_DEBUG_DRIVER("amdgpu: hdcp_workqueue init done %p.\n", adev->dm.hdcp_workqueue);
1650 
1651 		dc_init_callbacks(adev->dm.dc, &init_params);
1652 	}
1653 #endif
1654 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
1655 	adev->dm.crc_rd_wrk = amdgpu_dm_crtc_secure_display_create_work();
1656 #endif
1657 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
1658 		init_completion(&adev->dm.dmub_aux_transfer_done);
1659 		adev->dm.dmub_notify = kzalloc(sizeof(struct dmub_notification), GFP_KERNEL);
1660 		if (!adev->dm.dmub_notify) {
1661 			DRM_INFO("amdgpu: fail to allocate adev->dm.dmub_notify");
1662 			goto error;
1663 		}
1664 
1665 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
1666 		if (!adev->dm.delayed_hpd_wq) {
1667 			DRM_ERROR("amdgpu: failed to create hpd offload workqueue.\n");
1668 			goto error;
1669 		}
1670 
1671 		amdgpu_dm_outbox_init(adev);
1672 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
1673 			dmub_aux_setconfig_callback, false)) {
1674 			DRM_ERROR("amdgpu: fail to register dmub aux callback");
1675 			goto error;
1676 		}
1677 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD, dmub_hpd_callback, true)) {
1678 			DRM_ERROR("amdgpu: fail to register dmub hpd callback");
1679 			goto error;
1680 		}
1681 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ, dmub_hpd_callback, true)) {
1682 			DRM_ERROR("amdgpu: fail to register dmub hpd callback");
1683 			goto error;
1684 		}
1685 	}
1686 
1687 	/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
1688 	 * It is expected that DMUB will resend any pending notifications at this point, for
1689 	 * example HPD from DPIA.
1690 	 */
1691 	if (dc_is_dmub_outbox_supported(adev->dm.dc))
1692 		dc_enable_dmub_outbox(adev->dm.dc);
1693 
1694 	if (amdgpu_dm_initialize_drm_device(adev)) {
1695 		DRM_ERROR(
1696 		"amdgpu: failed to initialize sw for display support.\n");
1697 		goto error;
1698 	}
1699 
1700 	/* create fake encoders for MST */
1701 	dm_dp_create_fake_mst_encoders(adev);
1702 
1703 	/* TODO: Add_display_info? */
1704 
1705 	/* TODO use dynamic cursor width */
1706 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
1707 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
1708 
1709 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
1710 		DRM_ERROR(
1711 		"amdgpu: failed to initialize sw for display support.\n");
1712 		goto error;
1713 	}
1714 
1715 
1716 	DRM_DEBUG_DRIVER("KMS initialized.\n");
1717 
1718 	return 0;
1719 error:
1720 	amdgpu_dm_fini(adev);
1721 
1722 	return -EINVAL;
1723 }
1724 
1725 static int amdgpu_dm_early_fini(void *handle)
1726 {
1727 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
1728 
1729 	amdgpu_dm_audio_fini(adev);
1730 
1731 	return 0;
1732 }
1733 
1734 static void amdgpu_dm_fini(struct amdgpu_device *adev)
1735 {
1736 	int i;
1737 
1738 	if (adev->dm.vblank_control_workqueue) {
1739 		destroy_workqueue(adev->dm.vblank_control_workqueue);
1740 		adev->dm.vblank_control_workqueue = NULL;
1741 	}
1742 
1743 	for (i = 0; i < adev->dm.display_indexes_num; i++) {
1744 		drm_encoder_cleanup(&adev->dm.mst_encoders[i].base);
1745 	}
1746 
1747 	amdgpu_dm_destroy_drm_device(&adev->dm);
1748 
1749 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
1750 	if (adev->dm.crc_rd_wrk) {
1751 		flush_work(&adev->dm.crc_rd_wrk->notify_ta_work);
1752 		kfree(adev->dm.crc_rd_wrk);
1753 		adev->dm.crc_rd_wrk = NULL;
1754 	}
1755 #endif
1756 #ifdef CONFIG_DRM_AMD_DC_HDCP
1757 	if (adev->dm.hdcp_workqueue) {
1758 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
1759 		adev->dm.hdcp_workqueue = NULL;
1760 	}
1761 
1762 	if (adev->dm.dc)
1763 		dc_deinit_callbacks(adev->dm.dc);
1764 #endif
1765 
1766 	dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
1767 
1768 	if (dc_enable_dmub_notifications(adev->dm.dc)) {
1769 		kfree(adev->dm.dmub_notify);
1770 		adev->dm.dmub_notify = NULL;
1771 		destroy_workqueue(adev->dm.delayed_hpd_wq);
1772 		adev->dm.delayed_hpd_wq = NULL;
1773 	}
1774 
1775 	if (adev->dm.dmub_bo)
1776 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
1777 				      &adev->dm.dmub_bo_gpu_addr,
1778 				      &adev->dm.dmub_bo_cpu_addr);
1779 
1780 	if (adev->dm.hpd_rx_offload_wq) {
1781 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
1782 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
1783 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
1784 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
1785 			}
1786 		}
1787 
1788 		kfree(adev->dm.hpd_rx_offload_wq);
1789 		adev->dm.hpd_rx_offload_wq = NULL;
1790 	}
1791 
1792 	/* DC Destroy TODO: Replace destroy DAL */
1793 	if (adev->dm.dc)
1794 		dc_destroy(&adev->dm.dc);
1795 	/*
1796 	 * TODO: pageflip, vlank interrupt
1797 	 *
1798 	 * amdgpu_dm_irq_fini(adev);
1799 	 */
1800 
1801 	if (adev->dm.cgs_device) {
1802 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
1803 		adev->dm.cgs_device = NULL;
1804 	}
1805 	if (adev->dm.freesync_module) {
1806 		mod_freesync_destroy(adev->dm.freesync_module);
1807 		adev->dm.freesync_module = NULL;
1808 	}
1809 
1810 	mutex_destroy(&adev->dm.audio_lock);
1811 	mutex_destroy(&adev->dm.dc_lock);
1812 
1813 	return;
1814 }
1815 
1816 static int load_dmcu_fw(struct amdgpu_device *adev)
1817 {
1818 	const char *fw_name_dmcu = NULL;
1819 	int r;
1820 	const struct dmcu_firmware_header_v1_0 *hdr;
1821 
1822 	switch(adev->asic_type) {
1823 #if defined(CONFIG_DRM_AMD_DC_SI)
1824 	case CHIP_TAHITI:
1825 	case CHIP_PITCAIRN:
1826 	case CHIP_VERDE:
1827 	case CHIP_OLAND:
1828 #endif
1829 	case CHIP_BONAIRE:
1830 	case CHIP_HAWAII:
1831 	case CHIP_KAVERI:
1832 	case CHIP_KABINI:
1833 	case CHIP_MULLINS:
1834 	case CHIP_TONGA:
1835 	case CHIP_FIJI:
1836 	case CHIP_CARRIZO:
1837 	case CHIP_STONEY:
1838 	case CHIP_POLARIS11:
1839 	case CHIP_POLARIS10:
1840 	case CHIP_POLARIS12:
1841 	case CHIP_VEGAM:
1842 	case CHIP_VEGA10:
1843 	case CHIP_VEGA12:
1844 	case CHIP_VEGA20:
1845 		return 0;
1846 	case CHIP_NAVI12:
1847 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
1848 		break;
1849 	case CHIP_RAVEN:
1850 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
1851 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
1852 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
1853 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
1854 		else
1855 			return 0;
1856 		break;
1857 	default:
1858 		switch (adev->ip_versions[DCE_HWIP][0]) {
1859 		case IP_VERSION(2, 0, 2):
1860 		case IP_VERSION(2, 0, 3):
1861 		case IP_VERSION(2, 0, 0):
1862 		case IP_VERSION(2, 1, 0):
1863 		case IP_VERSION(3, 0, 0):
1864 		case IP_VERSION(3, 0, 2):
1865 		case IP_VERSION(3, 0, 3):
1866 		case IP_VERSION(3, 0, 1):
1867 		case IP_VERSION(3, 1, 2):
1868 		case IP_VERSION(3, 1, 3):
1869 		case IP_VERSION(3, 1, 4):
1870 		case IP_VERSION(3, 1, 5):
1871 		case IP_VERSION(3, 1, 6):
1872 		case IP_VERSION(3, 2, 0):
1873 		case IP_VERSION(3, 2, 1):
1874 			return 0;
1875 		default:
1876 			break;
1877 		}
1878 		DRM_ERROR("Unsupported ASIC type: 0x%X\n", adev->asic_type);
1879 		return -EINVAL;
1880 	}
1881 
1882 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1883 		DRM_DEBUG_KMS("dm: DMCU firmware not supported on direct or SMU loading\n");
1884 		return 0;
1885 	}
1886 
1887 	r = request_firmware_direct(&adev->dm.fw_dmcu, fw_name_dmcu, adev->dev);
1888 	if (r == -ENOENT) {
1889 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
1890 		DRM_DEBUG_KMS("dm: DMCU firmware not found\n");
1891 		adev->dm.fw_dmcu = NULL;
1892 		return 0;
1893 	}
1894 	if (r) {
1895 		dev_err(adev->dev, "amdgpu_dm: Can't load firmware \"%s\"\n",
1896 			fw_name_dmcu);
1897 		return r;
1898 	}
1899 
1900 	r = amdgpu_ucode_validate(adev->dm.fw_dmcu);
1901 	if (r) {
1902 		dev_err(adev->dev, "amdgpu_dm: Can't validate firmware \"%s\"\n",
1903 			fw_name_dmcu);
1904 		release_firmware(adev->dm.fw_dmcu);
1905 		adev->dm.fw_dmcu = NULL;
1906 		return r;
1907 	}
1908 
1909 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
1910 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
1911 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
1912 	adev->firmware.fw_size +=
1913 		roundup2(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
1914 
1915 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
1916 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
1917 	adev->firmware.fw_size +=
1918 		roundup2(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
1919 
1920 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
1921 
1922 	DRM_DEBUG_KMS("PSP loading DMCU firmware\n");
1923 
1924 	return 0;
1925 }
1926 
1927 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
1928 {
1929 	struct amdgpu_device *adev = ctx;
1930 
1931 	return dm_read_reg(adev->dm.dc->ctx, address);
1932 }
1933 
1934 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
1935 				     uint32_t value)
1936 {
1937 	struct amdgpu_device *adev = ctx;
1938 
1939 	return dm_write_reg(adev->dm.dc->ctx, address, value);
1940 }
1941 
1942 static int dm_dmub_sw_init(struct amdgpu_device *adev)
1943 {
1944 	struct dmub_srv_create_params create_params;
1945 	struct dmub_srv_region_params region_params;
1946 	struct dmub_srv_region_info region_info;
1947 	struct dmub_srv_fb_params fb_params;
1948 	struct dmub_srv_fb_info *fb_info;
1949 	struct dmub_srv *dmub_srv;
1950 	const struct dmcub_firmware_header_v1_0 *hdr;
1951 	const char *fw_name_dmub;
1952 	enum dmub_asic dmub_asic;
1953 	enum dmub_status status;
1954 	int r;
1955 
1956 	switch (adev->ip_versions[DCE_HWIP][0]) {
1957 	case IP_VERSION(2, 1, 0):
1958 		dmub_asic = DMUB_ASIC_DCN21;
1959 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
1960 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
1961 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
1962 		break;
1963 	case IP_VERSION(3, 0, 0):
1964 		if (adev->ip_versions[GC_HWIP][0] == IP_VERSION(10, 3, 0)) {
1965 			dmub_asic = DMUB_ASIC_DCN30;
1966 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
1967 		} else {
1968 			dmub_asic = DMUB_ASIC_DCN30;
1969 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
1970 		}
1971 		break;
1972 	case IP_VERSION(3, 0, 1):
1973 		dmub_asic = DMUB_ASIC_DCN301;
1974 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
1975 		break;
1976 	case IP_VERSION(3, 0, 2):
1977 		dmub_asic = DMUB_ASIC_DCN302;
1978 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
1979 		break;
1980 	case IP_VERSION(3, 0, 3):
1981 		dmub_asic = DMUB_ASIC_DCN303;
1982 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
1983 		break;
1984 	case IP_VERSION(3, 1, 2):
1985 	case IP_VERSION(3, 1, 3):
1986 		dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
1987 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
1988 		break;
1989 	case IP_VERSION(3, 1, 4):
1990 		dmub_asic = DMUB_ASIC_DCN314;
1991 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
1992 		break;
1993 	case IP_VERSION(3, 1, 5):
1994 		dmub_asic = DMUB_ASIC_DCN315;
1995 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
1996 		break;
1997 	case IP_VERSION(3, 1, 6):
1998 		dmub_asic = DMUB_ASIC_DCN316;
1999 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
2000 		break;
2001 	case IP_VERSION(3, 2, 0):
2002 		dmub_asic = DMUB_ASIC_DCN32;
2003 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
2004 		break;
2005 	case IP_VERSION(3, 2, 1):
2006 		dmub_asic = DMUB_ASIC_DCN321;
2007 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
2008 		break;
2009 	default:
2010 		/* ASIC doesn't support DMUB. */
2011 		return 0;
2012 	}
2013 
2014 	r = request_firmware_direct(&adev->dm.dmub_fw, fw_name_dmub, adev->dev);
2015 	if (r) {
2016 		DRM_ERROR("DMUB firmware loading failed: %d\n", r);
2017 		return 0;
2018 	}
2019 
2020 	r = amdgpu_ucode_validate(adev->dm.dmub_fw);
2021 	if (r) {
2022 		DRM_ERROR("Couldn't validate DMUB firmware: %d\n", r);
2023 		return 0;
2024 	}
2025 
2026 	hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
2027 	adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
2028 
2029 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
2030 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
2031 			AMDGPU_UCODE_ID_DMCUB;
2032 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
2033 			adev->dm.dmub_fw;
2034 		adev->firmware.fw_size +=
2035 			roundup2(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
2036 
2037 		DRM_INFO("Loading DMUB firmware via PSP: version=0x%08X\n",
2038 			 adev->dm.dmcub_fw_version);
2039 	}
2040 
2041 
2042 	adev->dm.dmub_srv = kzalloc(sizeof(*adev->dm.dmub_srv), GFP_KERNEL);
2043 	dmub_srv = adev->dm.dmub_srv;
2044 
2045 	if (!dmub_srv) {
2046 		DRM_ERROR("Failed to allocate DMUB service!\n");
2047 		return -ENOMEM;
2048 	}
2049 
2050 	memset(&create_params, 0, sizeof(create_params));
2051 	create_params.user_ctx = adev;
2052 	create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2053 	create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2054 	create_params.asic = dmub_asic;
2055 
2056 	/* Create the DMUB service. */
2057 	status = dmub_srv_create(dmub_srv, &create_params);
2058 	if (status != DMUB_STATUS_OK) {
2059 		DRM_ERROR("Error creating DMUB service: %d\n", status);
2060 		return -EINVAL;
2061 	}
2062 
2063 	/* Calculate the size of all the regions for the DMUB service. */
2064 	memset(&region_params, 0, sizeof(region_params));
2065 
2066 	region_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2067 					PSP_HEADER_BYTES - PSP_FOOTER_BYTES;
2068 	region_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2069 	region_params.vbios_size = adev->bios_size;
2070 	region_params.fw_bss_data = region_params.bss_data_size ?
2071 		adev->dm.dmub_fw->data +
2072 		le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2073 		le32_to_cpu(hdr->inst_const_bytes) : NULL;
2074 	region_params.fw_inst_const =
2075 		adev->dm.dmub_fw->data +
2076 		le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2077 		PSP_HEADER_BYTES;
2078 
2079 	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2080 					   &region_info);
2081 
2082 	if (status != DMUB_STATUS_OK) {
2083 		DRM_ERROR("Error calculating DMUB region info: %d\n", status);
2084 		return -EINVAL;
2085 	}
2086 
2087 	/*
2088 	 * Allocate a framebuffer based on the total size of all the regions.
2089 	 * TODO: Move this into GART.
2090 	 */
2091 	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2092 				    AMDGPU_GEM_DOMAIN_VRAM, &adev->dm.dmub_bo,
2093 				    &adev->dm.dmub_bo_gpu_addr,
2094 				    &adev->dm.dmub_bo_cpu_addr);
2095 	if (r)
2096 		return r;
2097 
2098 	/* Rebase the regions on the framebuffer address. */
2099 	memset(&fb_params, 0, sizeof(fb_params));
2100 	fb_params.cpu_addr = adev->dm.dmub_bo_cpu_addr;
2101 	fb_params.gpu_addr = adev->dm.dmub_bo_gpu_addr;
2102 	fb_params.region_info = &region_info;
2103 
2104 	adev->dm.dmub_fb_info =
2105 		kzalloc(sizeof(*adev->dm.dmub_fb_info), GFP_KERNEL);
2106 	fb_info = adev->dm.dmub_fb_info;
2107 
2108 	if (!fb_info) {
2109 		DRM_ERROR(
2110 			"Failed to allocate framebuffer info for DMUB service!\n");
2111 		return -ENOMEM;
2112 	}
2113 
2114 	status = dmub_srv_calc_fb_info(dmub_srv, &fb_params, fb_info);
2115 	if (status != DMUB_STATUS_OK) {
2116 		DRM_ERROR("Error calculating DMUB FB info: %d\n", status);
2117 		return -EINVAL;
2118 	}
2119 
2120 	return 0;
2121 }
2122 
2123 static int dm_sw_init(void *handle)
2124 {
2125 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2126 	int r;
2127 
2128 	r = dm_dmub_sw_init(adev);
2129 	if (r)
2130 		return r;
2131 
2132 	return load_dmcu_fw(adev);
2133 }
2134 
2135 static int dm_sw_fini(void *handle)
2136 {
2137 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2138 
2139 	kfree(adev->dm.dmub_fb_info);
2140 	adev->dm.dmub_fb_info = NULL;
2141 
2142 	if (adev->dm.dmub_srv) {
2143 		dmub_srv_destroy(adev->dm.dmub_srv);
2144 		adev->dm.dmub_srv = NULL;
2145 	}
2146 
2147 	release_firmware(adev->dm.dmub_fw);
2148 	adev->dm.dmub_fw = NULL;
2149 
2150 	release_firmware(adev->dm.fw_dmcu);
2151 	adev->dm.fw_dmcu = NULL;
2152 
2153 	return 0;
2154 }
2155 
2156 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2157 {
2158 	struct amdgpu_dm_connector *aconnector;
2159 	struct drm_connector *connector;
2160 	struct drm_connector_list_iter iter;
2161 	int ret = 0;
2162 
2163 	drm_connector_list_iter_begin(dev, &iter);
2164 	drm_for_each_connector_iter(connector, &iter) {
2165 		aconnector = to_amdgpu_dm_connector(connector);
2166 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
2167 		    aconnector->mst_mgr.aux) {
2168 			DRM_DEBUG_DRIVER("DM_MST: starting TM on aconnector: %p [id: %d]\n",
2169 					 aconnector,
2170 					 aconnector->base.base.id);
2171 
2172 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2173 			if (ret < 0) {
2174 				DRM_ERROR("DM_MST: Failed to start MST\n");
2175 				aconnector->dc_link->type =
2176 					dc_connection_single;
2177 				break;
2178 			}
2179 		}
2180 	}
2181 	drm_connector_list_iter_end(&iter);
2182 
2183 	return ret;
2184 }
2185 
2186 static int dm_late_init(void *handle)
2187 {
2188 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2189 
2190 	struct dmcu_iram_parameters params;
2191 	unsigned int linear_lut[16];
2192 	int i;
2193 	struct dmcu *dmcu = NULL;
2194 
2195 	dmcu = adev->dm.dc->res_pool->dmcu;
2196 
2197 	for (i = 0; i < 16; i++)
2198 		linear_lut[i] = 0xFFFF * i / 15;
2199 
2200 	params.set = 0;
2201 	params.backlight_ramping_override = false;
2202 	params.backlight_ramping_start = 0xCCCC;
2203 	params.backlight_ramping_reduction = 0xCCCCCCCC;
2204 	params.backlight_lut_array_size = 16;
2205 	params.backlight_lut_array = linear_lut;
2206 
2207 	/* Min backlight level after ABM reduction,  Don't allow below 1%
2208 	 * 0xFFFF x 0.01 = 0x28F
2209 	 */
2210 	params.min_abm_backlight = 0x28F;
2211 	/* In the case where abm is implemented on dmcub,
2212 	* dmcu object will be null.
2213 	* ABM 2.4 and up are implemented on dmcub.
2214 	*/
2215 	if (dmcu) {
2216 		if (!dmcu_load_iram(dmcu, params))
2217 			return -EINVAL;
2218 	} else if (adev->dm.dc->ctx->dmub_srv) {
2219 		struct dc_link *edp_links[MAX_NUM_EDP];
2220 		int edp_num;
2221 
2222 		get_edp_links(adev->dm.dc, edp_links, &edp_num);
2223 		for (i = 0; i < edp_num; i++) {
2224 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
2225 				return -EINVAL;
2226 		}
2227 	}
2228 
2229 	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
2230 }
2231 
2232 static void s3_handle_mst(struct drm_device *dev, bool suspend)
2233 {
2234 	struct amdgpu_dm_connector *aconnector;
2235 	struct drm_connector *connector;
2236 	struct drm_connector_list_iter iter;
2237 	struct drm_dp_mst_topology_mgr *mgr;
2238 	int ret;
2239 	bool need_hotplug = false;
2240 
2241 	drm_connector_list_iter_begin(dev, &iter);
2242 	drm_for_each_connector_iter(connector, &iter) {
2243 		aconnector = to_amdgpu_dm_connector(connector);
2244 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
2245 		    aconnector->mst_port)
2246 			continue;
2247 
2248 		mgr = &aconnector->mst_mgr;
2249 
2250 		if (suspend) {
2251 			drm_dp_mst_topology_mgr_suspend(mgr);
2252 		} else {
2253 			ret = drm_dp_mst_topology_mgr_resume(mgr, true);
2254 			if (ret < 0) {
2255 				dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2256 					aconnector->dc_link);
2257 				need_hotplug = true;
2258 			}
2259 		}
2260 	}
2261 	drm_connector_list_iter_end(&iter);
2262 
2263 	if (need_hotplug)
2264 		drm_kms_helper_hotplug_event(dev);
2265 }
2266 
2267 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
2268 {
2269 	int ret = 0;
2270 
2271 	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
2272 	 * on window driver dc implementation.
2273 	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
2274 	 * should be passed to smu during boot up and resume from s3.
2275 	 * boot up: dc calculate dcn watermark clock settings within dc_create,
2276 	 * dcn20_resource_construct
2277 	 * then call pplib functions below to pass the settings to smu:
2278 	 * smu_set_watermarks_for_clock_ranges
2279 	 * smu_set_watermarks_table
2280 	 * navi10_set_watermarks_table
2281 	 * smu_write_watermarks_table
2282 	 *
2283 	 * For Renoir, clock settings of dcn watermark are also fixed values.
2284 	 * dc has implemented different flow for window driver:
2285 	 * dc_hardware_init / dc_set_power_state
2286 	 * dcn10_init_hw
2287 	 * notify_wm_ranges
2288 	 * set_wm_ranges
2289 	 * -- Linux
2290 	 * smu_set_watermarks_for_clock_ranges
2291 	 * renoir_set_watermarks_table
2292 	 * smu_write_watermarks_table
2293 	 *
2294 	 * For Linux,
2295 	 * dc_hardware_init -> amdgpu_dm_init
2296 	 * dc_set_power_state --> dm_resume
2297 	 *
2298 	 * therefore, this function apply to navi10/12/14 but not Renoir
2299 	 * *
2300 	 */
2301 	switch (adev->ip_versions[DCE_HWIP][0]) {
2302 	case IP_VERSION(2, 0, 2):
2303 	case IP_VERSION(2, 0, 0):
2304 		break;
2305 	default:
2306 		return 0;
2307 	}
2308 
2309 	ret = amdgpu_dpm_write_watermarks_table(adev);
2310 	if (ret) {
2311 		DRM_ERROR("Failed to update WMTABLE!\n");
2312 		return ret;
2313 	}
2314 
2315 	return 0;
2316 }
2317 
2318 /**
2319  * dm_hw_init() - Initialize DC device
2320  * @handle: The base driver device containing the amdgpu_dm device.
2321  *
2322  * Initialize the &struct amdgpu_display_manager device. This involves calling
2323  * the initializers of each DM component, then populating the struct with them.
2324  *
2325  * Although the function implies hardware initialization, both hardware and
2326  * software are initialized here. Splitting them out to their relevant init
2327  * hooks is a future TODO item.
2328  *
2329  * Some notable things that are initialized here:
2330  *
2331  * - Display Core, both software and hardware
2332  * - DC modules that we need (freesync and color management)
2333  * - DRM software states
2334  * - Interrupt sources and handlers
2335  * - Vblank support
2336  * - Debug FS entries, if enabled
2337  */
2338 static int dm_hw_init(void *handle)
2339 {
2340 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2341 	/* Create DAL display manager */
2342 	amdgpu_dm_init(adev);
2343 	amdgpu_dm_hpd_init(adev);
2344 
2345 	return 0;
2346 }
2347 
2348 /**
2349  * dm_hw_fini() - Teardown DC device
2350  * @handle: The base driver device containing the amdgpu_dm device.
2351  *
2352  * Teardown components within &struct amdgpu_display_manager that require
2353  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
2354  * were loaded. Also flush IRQ workqueues and disable them.
2355  */
2356 static int dm_hw_fini(void *handle)
2357 {
2358 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
2359 
2360 	amdgpu_dm_hpd_fini(adev);
2361 
2362 	amdgpu_dm_irq_fini(adev);
2363 	amdgpu_dm_fini(adev);
2364 	return 0;
2365 }
2366 
2367 
2368 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
2369 				 struct dc_state *state, bool enable)
2370 {
2371 	enum dc_irq_source irq_source;
2372 	struct amdgpu_crtc *acrtc;
2373 	int rc = -EBUSY;
2374 	int i = 0;
2375 
2376 	for (i = 0; i < state->stream_count; i++) {
2377 		acrtc = get_crtc_by_otg_inst(
2378 				adev, state->stream_status[i].primary_otg_inst);
2379 
2380 		if (acrtc && state->stream_status[i].plane_count != 0) {
2381 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
2382 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
2383 			DRM_DEBUG_VBL("crtc %d - vupdate irq %sabling: r=%d\n",
2384 				      acrtc->crtc_id, enable ? "en" : "dis", rc);
2385 			if (rc)
2386 				DRM_WARN("Failed to %s pflip interrupts\n",
2387 					 enable ? "enable" : "disable");
2388 
2389 			if (enable) {
2390 				rc = dm_enable_vblank(&acrtc->base);
2391 				if (rc)
2392 					DRM_WARN("Failed to enable vblank interrupts\n");
2393 			} else {
2394 				dm_disable_vblank(&acrtc->base);
2395 			}
2396 
2397 		}
2398 	}
2399 
2400 }
2401 
2402 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
2403 {
2404 	struct dc_state *context = NULL;
2405 	enum dc_status res = DC_ERROR_UNEXPECTED;
2406 	int i;
2407 	struct dc_stream_state *del_streams[MAX_PIPES];
2408 	int del_streams_count = 0;
2409 
2410 	memset(del_streams, 0, sizeof(del_streams));
2411 
2412 	context = dc_create_state(dc);
2413 	if (context == NULL)
2414 		goto context_alloc_fail;
2415 
2416 	dc_resource_state_copy_construct_current(dc, context);
2417 
2418 	/* First remove from context all streams */
2419 	for (i = 0; i < context->stream_count; i++) {
2420 		struct dc_stream_state *stream = context->streams[i];
2421 
2422 		del_streams[del_streams_count++] = stream;
2423 	}
2424 
2425 	/* Remove all planes for removed streams and then remove the streams */
2426 	for (i = 0; i < del_streams_count; i++) {
2427 		if (!dc_rem_all_planes_for_stream(dc, del_streams[i], context)) {
2428 			res = DC_FAIL_DETACH_SURFACES;
2429 			goto fail;
2430 		}
2431 
2432 		res = dc_remove_stream_from_ctx(dc, context, del_streams[i]);
2433 		if (res != DC_OK)
2434 			goto fail;
2435 	}
2436 
2437 	res = dc_commit_state(dc, context);
2438 
2439 fail:
2440 	dc_release_state(context);
2441 
2442 context_alloc_fail:
2443 	return res;
2444 }
2445 
2446 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
2447 {
2448 	int i;
2449 
2450 	if (dm->hpd_rx_offload_wq) {
2451 		for (i = 0; i < dm->dc->caps.max_links; i++)
2452 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
2453 	}
2454 }
2455 
2456 static int dm_suspend(void *handle)
2457 {
2458 	struct amdgpu_device *adev = handle;
2459 	struct amdgpu_display_manager *dm = &adev->dm;
2460 	int ret = 0;
2461 
2462 	if (amdgpu_in_reset(adev)) {
2463 		mutex_lock(&dm->dc_lock);
2464 
2465 		dc_allow_idle_optimizations(adev->dm.dc, false);
2466 
2467 		dm->cached_dc_state = dc_copy_state(dm->dc->current_state);
2468 
2469 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
2470 
2471 		amdgpu_dm_commit_zero_streams(dm->dc);
2472 
2473 		amdgpu_dm_irq_suspend(adev);
2474 
2475 		hpd_rx_irq_work_suspend(dm);
2476 
2477 		return ret;
2478 	}
2479 
2480 	WARN_ON(adev->dm.cached_state);
2481 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
2482 
2483 	s3_handle_mst(adev_to_drm(adev), true);
2484 
2485 	amdgpu_dm_irq_suspend(adev);
2486 
2487 	hpd_rx_irq_work_suspend(dm);
2488 
2489 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
2490 
2491 	return 0;
2492 }
2493 
2494 struct amdgpu_dm_connector *
2495 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
2496 					     struct drm_crtc *crtc)
2497 {
2498 	uint32_t i;
2499 	struct drm_connector_state *new_con_state;
2500 	struct drm_connector *connector;
2501 	struct drm_crtc *crtc_from_state;
2502 
2503 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
2504 		crtc_from_state = new_con_state->crtc;
2505 
2506 		if (crtc_from_state == crtc)
2507 			return to_amdgpu_dm_connector(connector);
2508 	}
2509 
2510 	return NULL;
2511 }
2512 
2513 static void emulated_link_detect(struct dc_link *link)
2514 {
2515 	struct dc_sink_init_data sink_init_data = { 0 };
2516 	struct display_sink_capability sink_caps = { 0 };
2517 	enum dc_edid_status edid_status;
2518 	struct dc_context *dc_ctx = link->ctx;
2519 	struct dc_sink *sink = NULL;
2520 	struct dc_sink *prev_sink = NULL;
2521 
2522 	link->type = dc_connection_none;
2523 	prev_sink = link->local_sink;
2524 
2525 	if (prev_sink)
2526 		dc_sink_release(prev_sink);
2527 
2528 	switch (link->connector_signal) {
2529 	case SIGNAL_TYPE_HDMI_TYPE_A: {
2530 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
2531 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
2532 		break;
2533 	}
2534 
2535 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
2536 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
2537 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
2538 		break;
2539 	}
2540 
2541 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
2542 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
2543 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
2544 		break;
2545 	}
2546 
2547 	case SIGNAL_TYPE_LVDS: {
2548 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
2549 		sink_caps.signal = SIGNAL_TYPE_LVDS;
2550 		break;
2551 	}
2552 
2553 	case SIGNAL_TYPE_EDP: {
2554 		sink_caps.transaction_type =
2555 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
2556 		sink_caps.signal = SIGNAL_TYPE_EDP;
2557 		break;
2558 	}
2559 
2560 	case SIGNAL_TYPE_DISPLAY_PORT: {
2561 		sink_caps.transaction_type =
2562 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
2563 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
2564 		break;
2565 	}
2566 
2567 	default:
2568 		DC_ERROR("Invalid connector type! signal:%d\n",
2569 			link->connector_signal);
2570 		return;
2571 	}
2572 
2573 	sink_init_data.link = link;
2574 	sink_init_data.sink_signal = sink_caps.signal;
2575 
2576 	sink = dc_sink_create(&sink_init_data);
2577 	if (!sink) {
2578 		DC_ERROR("Failed to create sink!\n");
2579 		return;
2580 	}
2581 
2582 	/* dc_sink_create returns a new reference */
2583 	link->local_sink = sink;
2584 
2585 	edid_status = dm_helpers_read_local_edid(
2586 			link->ctx,
2587 			link,
2588 			sink);
2589 
2590 	if (edid_status != EDID_OK)
2591 		DC_ERROR("Failed to read EDID");
2592 
2593 }
2594 
2595 static void dm_gpureset_commit_state(struct dc_state *dc_state,
2596 				     struct amdgpu_display_manager *dm)
2597 {
2598 	struct {
2599 		struct dc_surface_update surface_updates[MAX_SURFACES];
2600 		struct dc_plane_info plane_infos[MAX_SURFACES];
2601 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
2602 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
2603 		struct dc_stream_update stream_update;
2604 	} * bundle;
2605 	int k, m;
2606 
2607 	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
2608 
2609 	if (!bundle) {
2610 		dm_error("Failed to allocate update bundle\n");
2611 		goto cleanup;
2612 	}
2613 
2614 	for (k = 0; k < dc_state->stream_count; k++) {
2615 		bundle->stream_update.stream = dc_state->streams[k];
2616 
2617 		for (m = 0; m < dc_state->stream_status->plane_count; m++) {
2618 			bundle->surface_updates[m].surface =
2619 				dc_state->stream_status->plane_states[m];
2620 			bundle->surface_updates[m].surface->force_full_update =
2621 				true;
2622 		}
2623 		dc_commit_updates_for_stream(
2624 			dm->dc, bundle->surface_updates,
2625 			dc_state->stream_status->plane_count,
2626 			dc_state->streams[k], &bundle->stream_update, dc_state);
2627 	}
2628 
2629 cleanup:
2630 	kfree(bundle);
2631 
2632 	return;
2633 }
2634 
2635 static int dm_resume(void *handle)
2636 {
2637 	struct amdgpu_device *adev = handle;
2638 	struct drm_device *ddev = adev_to_drm(adev);
2639 	struct amdgpu_display_manager *dm = &adev->dm;
2640 	struct amdgpu_dm_connector *aconnector;
2641 	struct drm_connector *connector;
2642 	struct drm_connector_list_iter iter;
2643 	struct drm_crtc *crtc;
2644 	struct drm_crtc_state *new_crtc_state;
2645 	struct dm_crtc_state *dm_new_crtc_state;
2646 	struct drm_plane *plane;
2647 	struct drm_plane_state *new_plane_state;
2648 	struct dm_plane_state *dm_new_plane_state;
2649 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
2650 	enum dc_connection_type new_connection_type = dc_connection_none;
2651 	struct dc_state *dc_state;
2652 	int i, r, j;
2653 
2654 	if (amdgpu_in_reset(adev)) {
2655 		dc_state = dm->cached_dc_state;
2656 
2657 		/*
2658 		 * The dc->current_state is backed up into dm->cached_dc_state
2659 		 * before we commit 0 streams.
2660 		 *
2661 		 * DC will clear link encoder assignments on the real state
2662 		 * but the changes won't propagate over to the copy we made
2663 		 * before the 0 streams commit.
2664 		 *
2665 		 * DC expects that link encoder assignments are *not* valid
2666 		 * when committing a state, so as a workaround we can copy
2667 		 * off of the current state.
2668 		 *
2669 		 * We lose the previous assignments, but we had already
2670 		 * commit 0 streams anyway.
2671 		 */
2672 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
2673 
2674 		r = dm_dmub_hw_init(adev);
2675 		if (r)
2676 			DRM_ERROR("DMUB interface failed to initialize: status=%d\n", r);
2677 
2678 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
2679 		dc_resume(dm->dc);
2680 
2681 		amdgpu_dm_irq_resume_early(adev);
2682 
2683 		for (i = 0; i < dc_state->stream_count; i++) {
2684 			dc_state->streams[i]->mode_changed = true;
2685 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
2686 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
2687 					= 0xffffffff;
2688 			}
2689 		}
2690 
2691 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2692 			amdgpu_dm_outbox_init(adev);
2693 			dc_enable_dmub_outbox(adev->dm.dc);
2694 		}
2695 
2696 		WARN_ON(!dc_commit_state(dm->dc, dc_state));
2697 
2698 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
2699 
2700 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
2701 
2702 		dc_release_state(dm->cached_dc_state);
2703 		dm->cached_dc_state = NULL;
2704 
2705 		amdgpu_dm_irq_resume_late(adev);
2706 
2707 		mutex_unlock(&dm->dc_lock);
2708 
2709 		return 0;
2710 	}
2711 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
2712 	dc_release_state(dm_state->context);
2713 	dm_state->context = dc_create_state(dm->dc);
2714 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
2715 	dc_resource_state_construct(dm->dc, dm_state->context);
2716 
2717 	/* Before powering on DC we need to re-initialize DMUB. */
2718 	dm_dmub_hw_resume(adev);
2719 
2720 	/* Re-enable outbox interrupts for DPIA. */
2721 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2722 		amdgpu_dm_outbox_init(adev);
2723 		dc_enable_dmub_outbox(adev->dm.dc);
2724 	}
2725 
2726 	/* power on hardware */
2727 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
2728 
2729 	/* program HPD filter */
2730 	dc_resume(dm->dc);
2731 
2732 	/*
2733 	 * early enable HPD Rx IRQ, should be done before set mode as short
2734 	 * pulse interrupts are used for MST
2735 	 */
2736 	amdgpu_dm_irq_resume_early(adev);
2737 
2738 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
2739 	s3_handle_mst(ddev, false);
2740 
2741 	/* Do detection*/
2742 	drm_connector_list_iter_begin(ddev, &iter);
2743 	drm_for_each_connector_iter(connector, &iter) {
2744 		aconnector = to_amdgpu_dm_connector(connector);
2745 
2746 		/*
2747 		 * this is the case when traversing through already created
2748 		 * MST connectors, should be skipped
2749 		 */
2750 		if (aconnector->dc_link &&
2751 		    aconnector->dc_link->type == dc_connection_mst_branch)
2752 			continue;
2753 
2754 		mutex_lock(&aconnector->hpd_lock);
2755 		if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
2756 			DRM_ERROR("KMS: Failed to detect connector\n");
2757 
2758 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
2759 			emulated_link_detect(aconnector->dc_link);
2760 		} else {
2761 			mutex_lock(&dm->dc_lock);
2762 			dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
2763 			mutex_unlock(&dm->dc_lock);
2764 		}
2765 
2766 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
2767 			aconnector->fake_enable = false;
2768 
2769 		if (aconnector->dc_sink)
2770 			dc_sink_release(aconnector->dc_sink);
2771 		aconnector->dc_sink = NULL;
2772 		amdgpu_dm_update_connector_after_detect(aconnector);
2773 		mutex_unlock(&aconnector->hpd_lock);
2774 	}
2775 	drm_connector_list_iter_end(&iter);
2776 
2777 	/* Force mode set in atomic commit */
2778 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i)
2779 		new_crtc_state->active_changed = true;
2780 
2781 	/*
2782 	 * atomic_check is expected to create the dc states. We need to release
2783 	 * them here, since they were duplicated as part of the suspend
2784 	 * procedure.
2785 	 */
2786 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
2787 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
2788 		if (dm_new_crtc_state->stream) {
2789 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
2790 			dc_stream_release(dm_new_crtc_state->stream);
2791 			dm_new_crtc_state->stream = NULL;
2792 		}
2793 	}
2794 
2795 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
2796 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
2797 		if (dm_new_plane_state->dc_state) {
2798 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
2799 			dc_plane_state_release(dm_new_plane_state->dc_state);
2800 			dm_new_plane_state->dc_state = NULL;
2801 		}
2802 	}
2803 
2804 	drm_atomic_helper_resume(ddev, dm->cached_state);
2805 
2806 	dm->cached_state = NULL;
2807 
2808 	amdgpu_dm_irq_resume_late(adev);
2809 
2810 	amdgpu_dm_smu_write_watermarks_table(adev);
2811 
2812 	return 0;
2813 }
2814 
2815 /**
2816  * DOC: DM Lifecycle
2817  *
2818  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
2819  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
2820  * the base driver's device list to be initialized and torn down accordingly.
2821  *
2822  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
2823  */
2824 
2825 static const struct amd_ip_funcs amdgpu_dm_funcs = {
2826 	.name = "dm",
2827 	.early_init = dm_early_init,
2828 	.late_init = dm_late_init,
2829 	.sw_init = dm_sw_init,
2830 	.sw_fini = dm_sw_fini,
2831 	.early_fini = amdgpu_dm_early_fini,
2832 	.hw_init = dm_hw_init,
2833 	.hw_fini = dm_hw_fini,
2834 	.suspend = dm_suspend,
2835 	.resume = dm_resume,
2836 	.is_idle = dm_is_idle,
2837 	.wait_for_idle = dm_wait_for_idle,
2838 	.check_soft_reset = dm_check_soft_reset,
2839 	.soft_reset = dm_soft_reset,
2840 	.set_clockgating_state = dm_set_clockgating_state,
2841 	.set_powergating_state = dm_set_powergating_state,
2842 };
2843 
2844 const struct amdgpu_ip_block_version dm_ip_block =
2845 {
2846 	.type = AMD_IP_BLOCK_TYPE_DCE,
2847 	.major = 1,
2848 	.minor = 0,
2849 	.rev = 0,
2850 	.funcs = &amdgpu_dm_funcs,
2851 };
2852 
2853 
2854 /**
2855  * DOC: atomic
2856  *
2857  * *WIP*
2858  */
2859 
2860 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
2861 	.fb_create = amdgpu_display_user_framebuffer_create,
2862 	.get_format_info = amd_get_format_info,
2863 	.output_poll_changed = drm_fb_helper_output_poll_changed,
2864 	.atomic_check = amdgpu_dm_atomic_check,
2865 	.atomic_commit = drm_atomic_helper_commit,
2866 };
2867 
2868 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
2869 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
2870 	.atomic_commit_setup = drm_dp_mst_atomic_setup_commit,
2871 };
2872 
2873 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
2874 {
2875 	struct amdgpu_dm_backlight_caps *caps;
2876 	struct amdgpu_display_manager *dm;
2877 	struct drm_connector *conn_base;
2878 	struct amdgpu_device *adev;
2879 	struct dc_link *link = NULL;
2880 	struct drm_luminance_range_info *luminance_range;
2881 	int i;
2882 
2883 	if (!aconnector || !aconnector->dc_link)
2884 		return;
2885 
2886 	link = aconnector->dc_link;
2887 	if (link->connector_signal != SIGNAL_TYPE_EDP)
2888 		return;
2889 
2890 	conn_base = &aconnector->base;
2891 	adev = drm_to_adev(conn_base->dev);
2892 	dm = &adev->dm;
2893 	for (i = 0; i < dm->num_of_edps; i++) {
2894 		if (link == dm->backlight_link[i])
2895 			break;
2896 	}
2897 	if (i >= dm->num_of_edps)
2898 		return;
2899 	caps = &dm->backlight_caps[i];
2900 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
2901 	caps->aux_support = false;
2902 
2903 	if (caps->ext_caps->bits.oled == 1 /*||
2904 	    caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
2905 	    caps->ext_caps->bits.hdr_aux_backlight_control == 1*/)
2906 		caps->aux_support = true;
2907 
2908 	if (amdgpu_backlight == 0)
2909 		caps->aux_support = false;
2910 	else if (amdgpu_backlight == 1)
2911 		caps->aux_support = true;
2912 
2913 	luminance_range = &conn_base->display_info.luminance_range;
2914 	caps->aux_min_input_signal = luminance_range->min_luminance;
2915 	caps->aux_max_input_signal = luminance_range->max_luminance;
2916 }
2917 
2918 void amdgpu_dm_update_connector_after_detect(
2919 		struct amdgpu_dm_connector *aconnector)
2920 {
2921 	struct drm_connector *connector = &aconnector->base;
2922 	struct drm_device *dev = connector->dev;
2923 	struct dc_sink *sink;
2924 
2925 	/* MST handled by drm_mst framework */
2926 	if (aconnector->mst_mgr.mst_state == true)
2927 		return;
2928 
2929 	sink = aconnector->dc_link->local_sink;
2930 	if (sink)
2931 		dc_sink_retain(sink);
2932 
2933 	/*
2934 	 * Edid mgmt connector gets first update only in mode_valid hook and then
2935 	 * the connector sink is set to either fake or physical sink depends on link status.
2936 	 * Skip if already done during boot.
2937 	 */
2938 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
2939 			&& aconnector->dc_em_sink) {
2940 
2941 		/*
2942 		 * For S3 resume with headless use eml_sink to fake stream
2943 		 * because on resume connector->sink is set to NULL
2944 		 */
2945 		mutex_lock(&dev->mode_config.mutex);
2946 
2947 		if (sink) {
2948 			if (aconnector->dc_sink) {
2949 				amdgpu_dm_update_freesync_caps(connector, NULL);
2950 				/*
2951 				 * retain and release below are used to
2952 				 * bump up refcount for sink because the link doesn't point
2953 				 * to it anymore after disconnect, so on next crtc to connector
2954 				 * reshuffle by UMD we will get into unwanted dc_sink release
2955 				 */
2956 				dc_sink_release(aconnector->dc_sink);
2957 			}
2958 			aconnector->dc_sink = sink;
2959 			dc_sink_retain(aconnector->dc_sink);
2960 			amdgpu_dm_update_freesync_caps(connector,
2961 					aconnector->edid);
2962 		} else {
2963 			amdgpu_dm_update_freesync_caps(connector, NULL);
2964 			if (!aconnector->dc_sink) {
2965 				aconnector->dc_sink = aconnector->dc_em_sink;
2966 				dc_sink_retain(aconnector->dc_sink);
2967 			}
2968 		}
2969 
2970 		mutex_unlock(&dev->mode_config.mutex);
2971 
2972 		if (sink)
2973 			dc_sink_release(sink);
2974 		return;
2975 	}
2976 
2977 	/*
2978 	 * TODO: temporary guard to look for proper fix
2979 	 * if this sink is MST sink, we should not do anything
2980 	 */
2981 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
2982 		dc_sink_release(sink);
2983 		return;
2984 	}
2985 
2986 	if (aconnector->dc_sink == sink) {
2987 		/*
2988 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
2989 		 * Do nothing!!
2990 		 */
2991 		DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: dc_sink didn't change.\n",
2992 				aconnector->connector_id);
2993 		if (sink)
2994 			dc_sink_release(sink);
2995 		return;
2996 	}
2997 
2998 	DRM_DEBUG_DRIVER("DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
2999 		aconnector->connector_id, aconnector->dc_sink, sink);
3000 
3001 	mutex_lock(&dev->mode_config.mutex);
3002 
3003 	/*
3004 	 * 1. Update status of the drm connector
3005 	 * 2. Send an event and let userspace tell us what to do
3006 	 */
3007 	if (sink) {
3008 		/*
3009 		 * TODO: check if we still need the S3 mode update workaround.
3010 		 * If yes, put it here.
3011 		 */
3012 		if (aconnector->dc_sink) {
3013 			amdgpu_dm_update_freesync_caps(connector, NULL);
3014 			dc_sink_release(aconnector->dc_sink);
3015 		}
3016 
3017 		aconnector->dc_sink = sink;
3018 		dc_sink_retain(aconnector->dc_sink);
3019 		if (sink->dc_edid.length == 0) {
3020 			aconnector->edid = NULL;
3021 			if (aconnector->dc_link->aux_mode) {
3022 				drm_dp_cec_unset_edid(
3023 					&aconnector->dm_dp_aux.aux);
3024 			}
3025 		} else {
3026 			aconnector->edid =
3027 				(struct edid *)sink->dc_edid.raw_edid;
3028 
3029 			if (aconnector->dc_link->aux_mode)
3030 				drm_dp_cec_set_edid(&aconnector->dm_dp_aux.aux,
3031 						    aconnector->edid);
3032 		}
3033 
3034 		drm_connector_update_edid_property(connector, aconnector->edid);
3035 		amdgpu_dm_update_freesync_caps(connector, aconnector->edid);
3036 		update_connector_ext_caps(aconnector);
3037 	} else {
3038 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
3039 		amdgpu_dm_update_freesync_caps(connector, NULL);
3040 		drm_connector_update_edid_property(connector, NULL);
3041 		aconnector->num_modes = 0;
3042 		dc_sink_release(aconnector->dc_sink);
3043 		aconnector->dc_sink = NULL;
3044 		aconnector->edid = NULL;
3045 #ifdef CONFIG_DRM_AMD_DC_HDCP
3046 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
3047 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
3048 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
3049 #endif
3050 	}
3051 
3052 	mutex_unlock(&dev->mode_config.mutex);
3053 
3054 	update_subconnector_property(aconnector);
3055 
3056 	if (sink)
3057 		dc_sink_release(sink);
3058 }
3059 
3060 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
3061 {
3062 	struct drm_connector *connector = &aconnector->base;
3063 	struct drm_device *dev = connector->dev;
3064 	enum dc_connection_type new_connection_type = dc_connection_none;
3065 	struct amdgpu_device *adev = drm_to_adev(dev);
3066 #ifdef CONFIG_DRM_AMD_DC_HDCP
3067 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
3068 #endif
3069 	bool ret = false;
3070 
3071 	if (adev->dm.disable_hpd_irq)
3072 		return;
3073 
3074 	/*
3075 	 * In case of failure or MST no need to update connector status or notify the OS
3076 	 * since (for MST case) MST does this in its own context.
3077 	 */
3078 	mutex_lock(&aconnector->hpd_lock);
3079 
3080 #ifdef CONFIG_DRM_AMD_DC_HDCP
3081 	if (adev->dm.hdcp_workqueue) {
3082 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
3083 		dm_con_state->update_hdcp = true;
3084 	}
3085 #endif
3086 	if (aconnector->fake_enable)
3087 		aconnector->fake_enable = false;
3088 
3089 	if (!dc_link_detect_sink(aconnector->dc_link, &new_connection_type))
3090 		DRM_ERROR("KMS: Failed to detect connector\n");
3091 
3092 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
3093 		emulated_link_detect(aconnector->dc_link);
3094 
3095 		drm_modeset_lock_all(dev);
3096 		dm_restore_drm_connector_state(dev, connector);
3097 		drm_modeset_unlock_all(dev);
3098 
3099 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
3100 			drm_kms_helper_connector_hotplug_event(connector);
3101 	} else {
3102 		mutex_lock(&adev->dm.dc_lock);
3103 		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
3104 		mutex_unlock(&adev->dm.dc_lock);
3105 		if (ret) {
3106 			amdgpu_dm_update_connector_after_detect(aconnector);
3107 
3108 			drm_modeset_lock_all(dev);
3109 			dm_restore_drm_connector_state(dev, connector);
3110 			drm_modeset_unlock_all(dev);
3111 
3112 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
3113 				drm_kms_helper_connector_hotplug_event(connector);
3114 		}
3115 	}
3116 	mutex_unlock(&aconnector->hpd_lock);
3117 
3118 }
3119 
3120 static void handle_hpd_irq(void *param)
3121 {
3122 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
3123 
3124 	handle_hpd_irq_helper(aconnector);
3125 
3126 }
3127 
3128 static void dm_handle_mst_sideband_msg(struct amdgpu_dm_connector *aconnector)
3129 {
3130 	uint8_t esi[DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI] = { 0 };
3131 	uint8_t dret;
3132 	bool new_irq_handled = false;
3133 	int dpcd_addr;
3134 	int dpcd_bytes_to_read;
3135 
3136 	const int max_process_count = 30;
3137 	int process_count = 0;
3138 
3139 	const struct dc_link_status *link_status = dc_link_get_status(aconnector->dc_link);
3140 
3141 	if (link_status->dpcd_caps->dpcd_rev.raw < 0x12) {
3142 		dpcd_bytes_to_read = DP_LANE0_1_STATUS - DP_SINK_COUNT;
3143 		/* DPCD 0x200 - 0x201 for downstream IRQ */
3144 		dpcd_addr = DP_SINK_COUNT;
3145 	} else {
3146 		dpcd_bytes_to_read = DP_PSR_ERROR_STATUS - DP_SINK_COUNT_ESI;
3147 		/* DPCD 0x2002 - 0x2005 for downstream IRQ */
3148 		dpcd_addr = DP_SINK_COUNT_ESI;
3149 	}
3150 
3151 	dret = drm_dp_dpcd_read(
3152 		&aconnector->dm_dp_aux.aux,
3153 		dpcd_addr,
3154 		esi,
3155 		dpcd_bytes_to_read);
3156 
3157 	while (dret == dpcd_bytes_to_read &&
3158 		process_count < max_process_count) {
3159 		uint8_t retry;
3160 		dret = 0;
3161 
3162 		process_count++;
3163 
3164 		DRM_DEBUG_DRIVER("ESI %02x %02x %02x\n", esi[0], esi[1], esi[2]);
3165 		/* handle HPD short pulse irq */
3166 		if (aconnector->mst_mgr.mst_state)
3167 			drm_dp_mst_hpd_irq(
3168 				&aconnector->mst_mgr,
3169 				esi,
3170 				&new_irq_handled);
3171 
3172 		if (new_irq_handled) {
3173 			/* ACK at DPCD to notify down stream */
3174 			const int ack_dpcd_bytes_to_write =
3175 				dpcd_bytes_to_read - 1;
3176 
3177 			for (retry = 0; retry < 3; retry++) {
3178 				uint8_t wret;
3179 
3180 				wret = drm_dp_dpcd_write(
3181 					&aconnector->dm_dp_aux.aux,
3182 					dpcd_addr + 1,
3183 					&esi[1],
3184 					ack_dpcd_bytes_to_write);
3185 				if (wret == ack_dpcd_bytes_to_write)
3186 					break;
3187 			}
3188 
3189 			/* check if there is new irq to be handled */
3190 			dret = drm_dp_dpcd_read(
3191 				&aconnector->dm_dp_aux.aux,
3192 				dpcd_addr,
3193 				esi,
3194 				dpcd_bytes_to_read);
3195 
3196 			new_irq_handled = false;
3197 		} else {
3198 			break;
3199 		}
3200 	}
3201 
3202 	if (process_count == max_process_count)
3203 		DRM_DEBUG_DRIVER("Loop exceeded max iterations\n");
3204 }
3205 
3206 static void schedule_hpd_rx_offload_work(struct hpd_rx_irq_offload_work_queue *offload_wq,
3207 							union hpd_irq_data hpd_irq_data)
3208 {
3209 	struct hpd_rx_irq_offload_work *offload_work =
3210 				kzalloc(sizeof(*offload_work), GFP_KERNEL);
3211 
3212 	if (!offload_work) {
3213 		DRM_ERROR("Failed to allocate hpd_rx_irq_offload_work.\n");
3214 		return;
3215 	}
3216 
3217 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
3218 	offload_work->data = hpd_irq_data;
3219 	offload_work->offload_wq = offload_wq;
3220 
3221 	queue_work(offload_wq->wq, &offload_work->work);
3222 	DRM_DEBUG_KMS("queue work to handle hpd_rx offload work");
3223 }
3224 
3225 static void handle_hpd_rx_irq(void *param)
3226 {
3227 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
3228 	struct drm_connector *connector = &aconnector->base;
3229 	struct drm_device *dev = connector->dev;
3230 	struct dc_link *dc_link = aconnector->dc_link;
3231 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
3232 	bool result = false;
3233 	enum dc_connection_type new_connection_type = dc_connection_none;
3234 	struct amdgpu_device *adev = drm_to_adev(dev);
3235 	union hpd_irq_data hpd_irq_data;
3236 	bool link_loss = false;
3237 	bool has_left_work = false;
3238 	int idx = aconnector->base.index;
3239 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
3240 
3241 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
3242 
3243 	if (adev->dm.disable_hpd_irq)
3244 		return;
3245 
3246 	/*
3247 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
3248 	 * conflict, after implement i2c helper, this mutex should be
3249 	 * retired.
3250 	 */
3251 	mutex_lock(&aconnector->hpd_lock);
3252 
3253 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
3254 						&link_loss, true, &has_left_work);
3255 
3256 	if (!has_left_work)
3257 		goto out;
3258 
3259 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
3260 		schedule_hpd_rx_offload_work(offload_wq, hpd_irq_data);
3261 		goto out;
3262 	}
3263 
3264 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
3265 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
3266 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
3267 			dm_handle_mst_sideband_msg(aconnector);
3268 			goto out;
3269 		}
3270 
3271 		if (link_loss) {
3272 			bool skip = false;
3273 
3274 			spin_lock(&offload_wq->offload_lock);
3275 			skip = offload_wq->is_handling_link_loss;
3276 
3277 			if (!skip)
3278 				offload_wq->is_handling_link_loss = true;
3279 
3280 			spin_unlock(&offload_wq->offload_lock);
3281 
3282 			if (!skip)
3283 				schedule_hpd_rx_offload_work(offload_wq, hpd_irq_data);
3284 
3285 			goto out;
3286 		}
3287 	}
3288 
3289 out:
3290 	if (result && !is_mst_root_connector) {
3291 		/* Downstream Port status changed. */
3292 		if (!dc_link_detect_sink(dc_link, &new_connection_type))
3293 			DRM_ERROR("KMS: Failed to detect connector\n");
3294 
3295 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3296 			emulated_link_detect(dc_link);
3297 
3298 			if (aconnector->fake_enable)
3299 				aconnector->fake_enable = false;
3300 
3301 			amdgpu_dm_update_connector_after_detect(aconnector);
3302 
3303 
3304 			drm_modeset_lock_all(dev);
3305 			dm_restore_drm_connector_state(dev, connector);
3306 			drm_modeset_unlock_all(dev);
3307 
3308 			drm_kms_helper_connector_hotplug_event(connector);
3309 		} else {
3310 			bool ret = false;
3311 
3312 			mutex_lock(&adev->dm.dc_lock);
3313 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
3314 			mutex_unlock(&adev->dm.dc_lock);
3315 
3316 			if (ret) {
3317 				if (aconnector->fake_enable)
3318 					aconnector->fake_enable = false;
3319 
3320 				amdgpu_dm_update_connector_after_detect(aconnector);
3321 
3322 				drm_modeset_lock_all(dev);
3323 				dm_restore_drm_connector_state(dev, connector);
3324 				drm_modeset_unlock_all(dev);
3325 
3326 				drm_kms_helper_connector_hotplug_event(connector);
3327 			}
3328 		}
3329 	}
3330 #ifdef CONFIG_DRM_AMD_DC_HDCP
3331 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
3332 		if (adev->dm.hdcp_workqueue)
3333 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
3334 	}
3335 #endif
3336 
3337 	if (dc_link->type != dc_connection_mst_branch)
3338 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
3339 
3340 	mutex_unlock(&aconnector->hpd_lock);
3341 }
3342 
3343 static void register_hpd_handlers(struct amdgpu_device *adev)
3344 {
3345 	struct drm_device *dev = adev_to_drm(adev);
3346 	struct drm_connector *connector;
3347 	struct amdgpu_dm_connector *aconnector;
3348 	const struct dc_link *dc_link;
3349 	struct dc_interrupt_params int_params = {0};
3350 
3351 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3352 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3353 
3354 	list_for_each_entry(connector,
3355 			&dev->mode_config.connector_list, head)	{
3356 
3357 		aconnector = to_amdgpu_dm_connector(connector);
3358 		dc_link = aconnector->dc_link;
3359 
3360 		if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd) {
3361 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
3362 			int_params.irq_source = dc_link->irq_source_hpd;
3363 
3364 			amdgpu_dm_irq_register_interrupt(adev, &int_params,
3365 					handle_hpd_irq,
3366 					(void *) aconnector);
3367 		}
3368 
3369 		if (DC_IRQ_SOURCE_INVALID != dc_link->irq_source_hpd_rx) {
3370 
3371 			/* Also register for DP short pulse (hpd_rx). */
3372 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
3373 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
3374 
3375 			amdgpu_dm_irq_register_interrupt(adev, &int_params,
3376 					handle_hpd_rx_irq,
3377 					(void *) aconnector);
3378 
3379 			if (adev->dm.hpd_rx_offload_wq)
3380 				adev->dm.hpd_rx_offload_wq[connector->index].aconnector =
3381 					aconnector;
3382 		}
3383 	}
3384 }
3385 
3386 #if defined(CONFIG_DRM_AMD_DC_SI)
3387 /* Register IRQ sources and initialize IRQ callbacks */
3388 static int dce60_register_irq_handlers(struct amdgpu_device *adev)
3389 {
3390 	struct dc *dc = adev->dm.dc;
3391 	struct common_irq_params *c_irq_params;
3392 	struct dc_interrupt_params int_params = {0};
3393 	int r;
3394 	int i;
3395 	unsigned client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
3396 
3397 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3398 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3399 
3400 	/*
3401 	 * Actions of amdgpu_irq_add_id():
3402 	 * 1. Register a set() function with base driver.
3403 	 *    Base driver will call set() function to enable/disable an
3404 	 *    interrupt in DC hardware.
3405 	 * 2. Register amdgpu_dm_irq_handler().
3406 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
3407 	 *    coming from DC hardware.
3408 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
3409 	 *    for acknowledging and handling. */
3410 
3411 	/* Use VBLANK interrupt */
3412 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
3413 		r = amdgpu_irq_add_id(adev, client_id, i+1 , &adev->crtc_irq);
3414 		if (r) {
3415 			DRM_ERROR("Failed to add crtc irq id!\n");
3416 			return r;
3417 		}
3418 
3419 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3420 		int_params.irq_source =
3421 			dc_interrupt_to_irq_source(dc, i+1 , 0);
3422 
3423 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
3424 
3425 		c_irq_params->adev = adev;
3426 		c_irq_params->irq_src = int_params.irq_source;
3427 
3428 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3429 				dm_crtc_high_irq, c_irq_params);
3430 	}
3431 
3432 	/* Use GRPH_PFLIP interrupt */
3433 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
3434 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
3435 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
3436 		if (r) {
3437 			DRM_ERROR("Failed to add page flip irq id!\n");
3438 			return r;
3439 		}
3440 
3441 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3442 		int_params.irq_source =
3443 			dc_interrupt_to_irq_source(dc, i, 0);
3444 
3445 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
3446 
3447 		c_irq_params->adev = adev;
3448 		c_irq_params->irq_src = int_params.irq_source;
3449 
3450 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3451 				dm_pflip_high_irq, c_irq_params);
3452 
3453 	}
3454 
3455 	/* HPD */
3456 	r = amdgpu_irq_add_id(adev, client_id,
3457 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
3458 	if (r) {
3459 		DRM_ERROR("Failed to add hpd irq id!\n");
3460 		return r;
3461 	}
3462 
3463 	register_hpd_handlers(adev);
3464 
3465 	return 0;
3466 }
3467 #endif
3468 
3469 /* Register IRQ sources and initialize IRQ callbacks */
3470 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
3471 {
3472 	struct dc *dc = adev->dm.dc;
3473 	struct common_irq_params *c_irq_params;
3474 	struct dc_interrupt_params int_params = {0};
3475 	int r;
3476 	int i;
3477 	unsigned client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
3478 
3479 	if (adev->family >= AMDGPU_FAMILY_AI)
3480 		client_id = SOC15_IH_CLIENTID_DCE;
3481 
3482 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3483 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3484 
3485 	/*
3486 	 * Actions of amdgpu_irq_add_id():
3487 	 * 1. Register a set() function with base driver.
3488 	 *    Base driver will call set() function to enable/disable an
3489 	 *    interrupt in DC hardware.
3490 	 * 2. Register amdgpu_dm_irq_handler().
3491 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
3492 	 *    coming from DC hardware.
3493 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
3494 	 *    for acknowledging and handling. */
3495 
3496 	/* Use VBLANK interrupt */
3497 	for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
3498 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
3499 		if (r) {
3500 			DRM_ERROR("Failed to add crtc irq id!\n");
3501 			return r;
3502 		}
3503 
3504 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3505 		int_params.irq_source =
3506 			dc_interrupt_to_irq_source(dc, i, 0);
3507 
3508 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
3509 
3510 		c_irq_params->adev = adev;
3511 		c_irq_params->irq_src = int_params.irq_source;
3512 
3513 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3514 				dm_crtc_high_irq, c_irq_params);
3515 	}
3516 
3517 	/* Use VUPDATE interrupt */
3518 	for (i = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT; i <= VISLANDS30_IV_SRCID_D6_V_UPDATE_INT; i += 2) {
3519 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->vupdate_irq);
3520 		if (r) {
3521 			DRM_ERROR("Failed to add vupdate irq id!\n");
3522 			return r;
3523 		}
3524 
3525 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3526 		int_params.irq_source =
3527 			dc_interrupt_to_irq_source(dc, i, 0);
3528 
3529 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
3530 
3531 		c_irq_params->adev = adev;
3532 		c_irq_params->irq_src = int_params.irq_source;
3533 
3534 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3535 				dm_vupdate_high_irq, c_irq_params);
3536 	}
3537 
3538 	/* Use GRPH_PFLIP interrupt */
3539 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
3540 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
3541 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
3542 		if (r) {
3543 			DRM_ERROR("Failed to add page flip irq id!\n");
3544 			return r;
3545 		}
3546 
3547 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3548 		int_params.irq_source =
3549 			dc_interrupt_to_irq_source(dc, i, 0);
3550 
3551 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
3552 
3553 		c_irq_params->adev = adev;
3554 		c_irq_params->irq_src = int_params.irq_source;
3555 
3556 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3557 				dm_pflip_high_irq, c_irq_params);
3558 
3559 	}
3560 
3561 	/* HPD */
3562 	r = amdgpu_irq_add_id(adev, client_id,
3563 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
3564 	if (r) {
3565 		DRM_ERROR("Failed to add hpd irq id!\n");
3566 		return r;
3567 	}
3568 
3569 	register_hpd_handlers(adev);
3570 
3571 	return 0;
3572 }
3573 
3574 /* Register IRQ sources and initialize IRQ callbacks */
3575 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
3576 {
3577 	struct dc *dc = adev->dm.dc;
3578 	struct common_irq_params *c_irq_params;
3579 	struct dc_interrupt_params int_params = {0};
3580 	int r;
3581 	int i;
3582 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
3583 	static const unsigned int vrtl_int_srcid[] = {
3584 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
3585 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
3586 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
3587 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
3588 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
3589 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
3590 	};
3591 #endif
3592 
3593 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3594 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3595 
3596 	/*
3597 	 * Actions of amdgpu_irq_add_id():
3598 	 * 1. Register a set() function with base driver.
3599 	 *    Base driver will call set() function to enable/disable an
3600 	 *    interrupt in DC hardware.
3601 	 * 2. Register amdgpu_dm_irq_handler().
3602 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
3603 	 *    coming from DC hardware.
3604 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
3605 	 *    for acknowledging and handling.
3606 	 */
3607 
3608 	/* Use VSTARTUP interrupt */
3609 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
3610 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
3611 			i++) {
3612 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
3613 
3614 		if (r) {
3615 			DRM_ERROR("Failed to add crtc irq id!\n");
3616 			return r;
3617 		}
3618 
3619 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3620 		int_params.irq_source =
3621 			dc_interrupt_to_irq_source(dc, i, 0);
3622 
3623 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
3624 
3625 		c_irq_params->adev = adev;
3626 		c_irq_params->irq_src = int_params.irq_source;
3627 
3628 		amdgpu_dm_irq_register_interrupt(
3629 			adev, &int_params, dm_crtc_high_irq, c_irq_params);
3630 	}
3631 
3632 	/* Use otg vertical line interrupt */
3633 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
3634 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
3635 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
3636 				vrtl_int_srcid[i], &adev->vline0_irq);
3637 
3638 		if (r) {
3639 			DRM_ERROR("Failed to add vline0 irq id!\n");
3640 			return r;
3641 		}
3642 
3643 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3644 		int_params.irq_source =
3645 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
3646 
3647 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID) {
3648 			DRM_ERROR("Failed to register vline0 irq %d!\n", vrtl_int_srcid[i]);
3649 			break;
3650 		}
3651 
3652 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
3653 					- DC_IRQ_SOURCE_DC1_VLINE0];
3654 
3655 		c_irq_params->adev = adev;
3656 		c_irq_params->irq_src = int_params.irq_source;
3657 
3658 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3659 				dm_dcn_vertical_interrupt0_high_irq, c_irq_params);
3660 	}
3661 #endif
3662 
3663 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
3664 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
3665 	 * to trigger at end of each vblank, regardless of state of the lock,
3666 	 * matching DCE behaviour.
3667 	 */
3668 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
3669 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
3670 	     i++) {
3671 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
3672 
3673 		if (r) {
3674 			DRM_ERROR("Failed to add vupdate irq id!\n");
3675 			return r;
3676 		}
3677 
3678 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3679 		int_params.irq_source =
3680 			dc_interrupt_to_irq_source(dc, i, 0);
3681 
3682 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
3683 
3684 		c_irq_params->adev = adev;
3685 		c_irq_params->irq_src = int_params.irq_source;
3686 
3687 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3688 				dm_vupdate_high_irq, c_irq_params);
3689 	}
3690 
3691 	/* Use GRPH_PFLIP interrupt */
3692 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
3693 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
3694 			i++) {
3695 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
3696 		if (r) {
3697 			DRM_ERROR("Failed to add page flip irq id!\n");
3698 			return r;
3699 		}
3700 
3701 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
3702 		int_params.irq_source =
3703 			dc_interrupt_to_irq_source(dc, i, 0);
3704 
3705 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
3706 
3707 		c_irq_params->adev = adev;
3708 		c_irq_params->irq_src = int_params.irq_source;
3709 
3710 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3711 				dm_pflip_high_irq, c_irq_params);
3712 
3713 	}
3714 
3715 	/* HPD */
3716 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
3717 			&adev->hpd_irq);
3718 	if (r) {
3719 		DRM_ERROR("Failed to add hpd irq id!\n");
3720 		return r;
3721 	}
3722 
3723 	register_hpd_handlers(adev);
3724 
3725 	return 0;
3726 }
3727 /* Register Outbox IRQ sources and initialize IRQ callbacks */
3728 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
3729 {
3730 	struct dc *dc = adev->dm.dc;
3731 	struct common_irq_params *c_irq_params;
3732 	struct dc_interrupt_params int_params = {0};
3733 	int r, i;
3734 
3735 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
3736 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
3737 
3738 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
3739 			&adev->dmub_outbox_irq);
3740 	if (r) {
3741 		DRM_ERROR("Failed to add outbox irq id!\n");
3742 		return r;
3743 	}
3744 
3745 	if (dc->ctx->dmub_srv) {
3746 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
3747 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
3748 		int_params.irq_source =
3749 		dc_interrupt_to_irq_source(dc, i, 0);
3750 
3751 		c_irq_params = &adev->dm.dmub_outbox_params[0];
3752 
3753 		c_irq_params->adev = adev;
3754 		c_irq_params->irq_src = int_params.irq_source;
3755 
3756 		amdgpu_dm_irq_register_interrupt(adev, &int_params,
3757 				dm_dmub_outbox1_low_irq, c_irq_params);
3758 	}
3759 
3760 	return 0;
3761 }
3762 
3763 /*
3764  * Acquires the lock for the atomic state object and returns
3765  * the new atomic state.
3766  *
3767  * This should only be called during atomic check.
3768  */
3769 int dm_atomic_get_state(struct drm_atomic_state *state,
3770 			struct dm_atomic_state **dm_state)
3771 {
3772 	struct drm_device *dev = state->dev;
3773 	struct amdgpu_device *adev = drm_to_adev(dev);
3774 	struct amdgpu_display_manager *dm = &adev->dm;
3775 	struct drm_private_state *priv_state;
3776 
3777 	if (*dm_state)
3778 		return 0;
3779 
3780 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
3781 	if (IS_ERR(priv_state))
3782 		return PTR_ERR(priv_state);
3783 
3784 	*dm_state = to_dm_atomic_state(priv_state);
3785 
3786 	return 0;
3787 }
3788 
3789 static struct dm_atomic_state *
3790 dm_atomic_get_new_state(struct drm_atomic_state *state)
3791 {
3792 	struct drm_device *dev = state->dev;
3793 	struct amdgpu_device *adev = drm_to_adev(dev);
3794 	struct amdgpu_display_manager *dm = &adev->dm;
3795 	struct drm_private_obj *obj;
3796 	struct drm_private_state *new_obj_state;
3797 	int i;
3798 
3799 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
3800 		if (obj->funcs == dm->atomic_obj.funcs)
3801 			return to_dm_atomic_state(new_obj_state);
3802 	}
3803 
3804 	return NULL;
3805 }
3806 
3807 static struct drm_private_state *
3808 dm_atomic_duplicate_state(struct drm_private_obj *obj)
3809 {
3810 	struct dm_atomic_state *old_state, *new_state;
3811 
3812 	new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
3813 	if (!new_state)
3814 		return NULL;
3815 
3816 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
3817 
3818 	old_state = to_dm_atomic_state(obj->state);
3819 
3820 	if (old_state && old_state->context)
3821 		new_state->context = dc_copy_state(old_state->context);
3822 
3823 	if (!new_state->context) {
3824 		kfree(new_state);
3825 		return NULL;
3826 	}
3827 
3828 	return &new_state->base;
3829 }
3830 
3831 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
3832 				    struct drm_private_state *state)
3833 {
3834 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
3835 
3836 	if (dm_state && dm_state->context)
3837 		dc_release_state(dm_state->context);
3838 
3839 	kfree(dm_state);
3840 }
3841 
3842 static struct drm_private_state_funcs dm_atomic_state_funcs = {
3843 	.atomic_duplicate_state = dm_atomic_duplicate_state,
3844 	.atomic_destroy_state = dm_atomic_destroy_state,
3845 };
3846 
3847 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
3848 {
3849 	struct dm_atomic_state *state;
3850 	int r;
3851 
3852 	adev->mode_info.mode_config_initialized = true;
3853 
3854 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
3855 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
3856 
3857 	adev_to_drm(adev)->mode_config.max_width = 16384;
3858 	adev_to_drm(adev)->mode_config.max_height = 16384;
3859 
3860 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
3861 	if (adev->asic_type == CHIP_HAWAII)
3862 		/* disable prefer shadow for now due to hibernation issues */
3863 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
3864 	else
3865 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
3866 	/* indicates support for immediate flip */
3867 	adev_to_drm(adev)->mode_config.async_page_flip = true;
3868 
3869 	adev_to_drm(adev)->mode_config.fb_base = adev->gmc.aper_base;
3870 
3871 	state = kzalloc(sizeof(*state), GFP_KERNEL);
3872 	if (!state)
3873 		return -ENOMEM;
3874 
3875 	state->context = dc_create_state(adev->dm.dc);
3876 	if (!state->context) {
3877 		kfree(state);
3878 		return -ENOMEM;
3879 	}
3880 
3881 	dc_resource_state_copy_construct_current(adev->dm.dc, state->context);
3882 
3883 	drm_atomic_private_obj_init(adev_to_drm(adev),
3884 				    &adev->dm.atomic_obj,
3885 				    &state->base,
3886 				    &dm_atomic_state_funcs);
3887 
3888 	r = amdgpu_display_modeset_create_props(adev);
3889 	if (r) {
3890 		dc_release_state(state->context);
3891 		kfree(state);
3892 		return r;
3893 	}
3894 
3895 	r = amdgpu_dm_audio_init(adev);
3896 	if (r) {
3897 		dc_release_state(state->context);
3898 		kfree(state);
3899 		return r;
3900 	}
3901 
3902 	return 0;
3903 }
3904 
3905 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
3906 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
3907 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
3908 
3909 static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
3910 					    int bl_idx)
3911 {
3912 #if defined(CONFIG_ACPI)
3913 	struct amdgpu_dm_backlight_caps caps;
3914 
3915 	memset(&caps, 0, sizeof(caps));
3916 
3917 	if (dm->backlight_caps[bl_idx].caps_valid)
3918 		return;
3919 
3920 	amdgpu_acpi_get_backlight_caps(&caps);
3921 	if (caps.caps_valid) {
3922 		dm->backlight_caps[bl_idx].caps_valid = true;
3923 		if (caps.aux_support)
3924 			return;
3925 		dm->backlight_caps[bl_idx].min_input_signal = caps.min_input_signal;
3926 		dm->backlight_caps[bl_idx].max_input_signal = caps.max_input_signal;
3927 	} else {
3928 		dm->backlight_caps[bl_idx].min_input_signal =
3929 				AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
3930 		dm->backlight_caps[bl_idx].max_input_signal =
3931 				AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
3932 	}
3933 #else
3934 	if (dm->backlight_caps[bl_idx].aux_support)
3935 		return;
3936 
3937 	dm->backlight_caps[bl_idx].min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
3938 	dm->backlight_caps[bl_idx].max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
3939 #endif
3940 }
3941 
3942 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
3943 				unsigned *min, unsigned *max)
3944 {
3945 	if (!caps)
3946 		return 0;
3947 
3948 	if (caps->aux_support) {
3949 		// Firmware limits are in nits, DC API wants millinits.
3950 		*max = 1000 * caps->aux_max_input_signal;
3951 		*min = 1000 * caps->aux_min_input_signal;
3952 	} else {
3953 		// Firmware limits are 8-bit, PWM control is 16-bit.
3954 		*max = 0x101 * caps->max_input_signal;
3955 		*min = 0x101 * caps->min_input_signal;
3956 	}
3957 	return 1;
3958 }
3959 
3960 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
3961 					uint32_t brightness)
3962 {
3963 	unsigned min, max;
3964 
3965 	if (!get_brightness_range(caps, &min, &max))
3966 		return brightness;
3967 
3968 	// Rescale 0..255 to min..max
3969 	return min + DIV_ROUND_CLOSEST((max - min) * brightness,
3970 				       AMDGPU_MAX_BL_LEVEL);
3971 }
3972 
3973 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
3974 				      uint32_t brightness)
3975 {
3976 	unsigned min, max;
3977 
3978 	if (!get_brightness_range(caps, &min, &max))
3979 		return brightness;
3980 
3981 	if (brightness < min)
3982 		return 0;
3983 	// Rescale min..max to 0..255
3984 	return DIV_ROUND_CLOSEST(AMDGPU_MAX_BL_LEVEL * (brightness - min),
3985 				 max - min);
3986 }
3987 
3988 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
3989 					 int bl_idx,
3990 					 u32 user_brightness)
3991 {
3992 	struct amdgpu_dm_backlight_caps caps;
3993 	struct dc_link *link;
3994 	u32 brightness;
3995 	bool rc;
3996 
3997 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
3998 	caps = dm->backlight_caps[bl_idx];
3999 
4000 	dm->brightness[bl_idx] = user_brightness;
4001 	/* update scratch register */
4002 	if (bl_idx == 0)
4003 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
4004 	brightness = convert_brightness_from_user(&caps, dm->brightness[bl_idx]);
4005 	link = (struct dc_link *)dm->backlight_link[bl_idx];
4006 
4007 	/* Change brightness based on AUX property */
4008 	if (caps.aux_support) {
4009 		rc = dc_link_set_backlight_level_nits(link, true, brightness,
4010 						      AUX_BL_DEFAULT_TRANSITION_TIME_MS);
4011 		if (!rc)
4012 			DRM_DEBUG("DM: Failed to update backlight via AUX on eDP[%d]\n", bl_idx);
4013 	} else {
4014 		rc = dc_link_set_backlight_level(link, brightness, 0);
4015 		if (!rc)
4016 			DRM_DEBUG("DM: Failed to update backlight on eDP[%d]\n", bl_idx);
4017 	}
4018 
4019 	if (rc)
4020 		dm->actual_brightness[bl_idx] = user_brightness;
4021 }
4022 
4023 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
4024 {
4025 	struct amdgpu_display_manager *dm = bl_get_data(bd);
4026 	int i;
4027 
4028 	for (i = 0; i < dm->num_of_edps; i++) {
4029 		if (bd == dm->backlight_dev[i])
4030 			break;
4031 	}
4032 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
4033 		i = 0;
4034 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
4035 
4036 	return 0;
4037 }
4038 
4039 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
4040 					 int bl_idx)
4041 {
4042 	struct amdgpu_dm_backlight_caps caps;
4043 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
4044 
4045 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
4046 	caps = dm->backlight_caps[bl_idx];
4047 
4048 	if (caps.aux_support) {
4049 		u32 avg, peak;
4050 		bool rc;
4051 
4052 		rc = dc_link_get_backlight_level_nits(link, &avg, &peak);
4053 		if (!rc)
4054 			return dm->brightness[bl_idx];
4055 		return convert_brightness_to_user(&caps, avg);
4056 	} else {
4057 		int ret = dc_link_get_backlight_level(link);
4058 
4059 		if (ret == DC_ERROR_UNEXPECTED)
4060 			return dm->brightness[bl_idx];
4061 		return convert_brightness_to_user(&caps, ret);
4062 	}
4063 }
4064 
4065 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
4066 {
4067 	struct amdgpu_display_manager *dm = bl_get_data(bd);
4068 	int i;
4069 
4070 	for (i = 0; i < dm->num_of_edps; i++) {
4071 		if (bd == dm->backlight_dev[i])
4072 			break;
4073 	}
4074 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
4075 		i = 0;
4076 	return amdgpu_dm_backlight_get_level(dm, i);
4077 }
4078 
4079 static const struct backlight_ops amdgpu_dm_backlight_ops = {
4080 	.options = BL_CORE_SUSPENDRESUME,
4081 	.get_brightness = amdgpu_dm_backlight_get_brightness,
4082 	.update_status	= amdgpu_dm_backlight_update_status,
4083 };
4084 
4085 static void
4086 amdgpu_dm_register_backlight_device(struct amdgpu_display_manager *dm)
4087 {
4088 	char bl_name[16];
4089 	struct backlight_properties props = { 0 };
4090 
4091 	amdgpu_dm_update_backlight_caps(dm, dm->num_of_edps);
4092 	dm->brightness[dm->num_of_edps] = AMDGPU_MAX_BL_LEVEL;
4093 
4094 	if (!acpi_video_backlight_use_native()) {
4095 		drm_info(adev_to_drm(dm->adev), "Skipping amdgpu DM backlight registration\n");
4096 		/* Try registering an ACPI video backlight device instead. */
4097 		acpi_video_register_backlight();
4098 		return;
4099 	}
4100 
4101 	props.max_brightness = AMDGPU_MAX_BL_LEVEL;
4102 	props.brightness = AMDGPU_MAX_BL_LEVEL;
4103 	props.type = BACKLIGHT_RAW;
4104 
4105 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
4106 		 adev_to_drm(dm->adev)->primary->index + dm->num_of_edps);
4107 
4108 	dm->backlight_dev[dm->num_of_edps] = backlight_device_register(bl_name,
4109 								       adev_to_drm(dm->adev)->dev,
4110 								       dm,
4111 								       &amdgpu_dm_backlight_ops,
4112 								       &props);
4113 
4114 	if (IS_ERR(dm->backlight_dev[dm->num_of_edps]))
4115 		DRM_ERROR("DM: Backlight registration failed!\n");
4116 	else
4117 		DRM_DEBUG_DRIVER("DM: Registered Backlight device: %s\n", bl_name);
4118 }
4119 
4120 static int initialize_plane(struct amdgpu_display_manager *dm,
4121 			    struct amdgpu_mode_info *mode_info, int plane_id,
4122 			    enum drm_plane_type plane_type,
4123 			    const struct dc_plane_cap *plane_cap)
4124 {
4125 	struct drm_plane *plane;
4126 	unsigned long possible_crtcs;
4127 	int ret = 0;
4128 
4129 	plane = kzalloc(sizeof(struct drm_plane), GFP_KERNEL);
4130 	if (!plane) {
4131 		DRM_ERROR("KMS: Failed to allocate plane\n");
4132 		return -ENOMEM;
4133 	}
4134 	plane->type = plane_type;
4135 
4136 	/*
4137 	 * HACK: IGT tests expect that the primary plane for a CRTC
4138 	 * can only have one possible CRTC. Only expose support for
4139 	 * any CRTC if they're not going to be used as a primary plane
4140 	 * for a CRTC - like overlay or underlay planes.
4141 	 */
4142 	possible_crtcs = 1 << plane_id;
4143 	if (plane_id >= dm->dc->caps.max_streams)
4144 		possible_crtcs = 0xff;
4145 
4146 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
4147 
4148 	if (ret) {
4149 		DRM_ERROR("KMS: Failed to initialize plane\n");
4150 		kfree(plane);
4151 		return ret;
4152 	}
4153 
4154 	if (mode_info)
4155 		mode_info->planes[plane_id] = plane;
4156 
4157 	return ret;
4158 }
4159 
4160 
4161 static void register_backlight_device(struct amdgpu_display_manager *dm,
4162 				      struct dc_link *link)
4163 {
4164 	if ((link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) &&
4165 	    link->type != dc_connection_none) {
4166 		/*
4167 		 * Event if registration failed, we should continue with
4168 		 * DM initialization because not having a backlight control
4169 		 * is better then a black screen.
4170 		 */
4171 		if (!dm->backlight_dev[dm->num_of_edps])
4172 			amdgpu_dm_register_backlight_device(dm);
4173 
4174 		if (dm->backlight_dev[dm->num_of_edps]) {
4175 			dm->backlight_link[dm->num_of_edps] = link;
4176 			dm->num_of_edps++;
4177 		}
4178 	}
4179 }
4180 
4181 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
4182 
4183 /*
4184  * In this architecture, the association
4185  * connector -> encoder -> crtc
4186  * id not really requried. The crtc and connector will hold the
4187  * display_index as an abstraction to use with DAL component
4188  *
4189  * Returns 0 on success
4190  */
4191 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
4192 {
4193 	struct amdgpu_display_manager *dm = &adev->dm;
4194 	int32_t i;
4195 	struct amdgpu_dm_connector *aconnector = NULL;
4196 	struct amdgpu_encoder *aencoder = NULL;
4197 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
4198 	uint32_t link_cnt;
4199 	int32_t primary_planes;
4200 	enum dc_connection_type new_connection_type = dc_connection_none;
4201 	const struct dc_plane_cap *plane;
4202 	bool psr_feature_enabled = false;
4203 
4204 	dm->display_indexes_num = dm->dc->caps.max_streams;
4205 	/* Update the actual used number of crtc */
4206 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
4207 
4208 	link_cnt = dm->dc->caps.max_links;
4209 	if (amdgpu_dm_mode_config_init(dm->adev)) {
4210 		DRM_ERROR("DM: Failed to initialize mode config\n");
4211 		return -EINVAL;
4212 	}
4213 
4214 	/* There is one primary plane per CRTC */
4215 	primary_planes = dm->dc->caps.max_streams;
4216 	ASSERT(primary_planes <= AMDGPU_MAX_PLANES);
4217 
4218 	/*
4219 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
4220 	 * Order is reversed to match iteration order in atomic check.
4221 	 */
4222 	for (i = (primary_planes - 1); i >= 0; i--) {
4223 		plane = &dm->dc->caps.planes[i];
4224 
4225 		if (initialize_plane(dm, mode_info, i,
4226 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
4227 			DRM_ERROR("KMS: Failed to initialize primary plane\n");
4228 			goto fail;
4229 		}
4230 	}
4231 
4232 	/*
4233 	 * Initialize overlay planes, index starting after primary planes.
4234 	 * These planes have a higher DRM index than the primary planes since
4235 	 * they should be considered as having a higher z-order.
4236 	 * Order is reversed to match iteration order in atomic check.
4237 	 *
4238 	 * Only support DCN for now, and only expose one so we don't encourage
4239 	 * userspace to use up all the pipes.
4240 	 */
4241 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
4242 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
4243 
4244 		/* Do not create overlay if MPO disabled */
4245 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
4246 			break;
4247 
4248 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
4249 			continue;
4250 
4251 		if (!plane->blends_with_above || !plane->blends_with_below)
4252 			continue;
4253 
4254 		if (!plane->pixel_format_support.argb8888)
4255 			continue;
4256 
4257 		if (initialize_plane(dm, NULL, primary_planes + i,
4258 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
4259 			DRM_ERROR("KMS: Failed to initialize overlay plane\n");
4260 			goto fail;
4261 		}
4262 
4263 		/* Only create one overlay plane. */
4264 		break;
4265 	}
4266 
4267 	for (i = 0; i < dm->dc->caps.max_streams; i++)
4268 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
4269 			DRM_ERROR("KMS: Failed to initialize crtc\n");
4270 			goto fail;
4271 		}
4272 
4273 	/* Use Outbox interrupt */
4274 	switch (adev->ip_versions[DCE_HWIP][0]) {
4275 	case IP_VERSION(3, 0, 0):
4276 	case IP_VERSION(3, 1, 2):
4277 	case IP_VERSION(3, 1, 3):
4278 	case IP_VERSION(3, 1, 4):
4279 	case IP_VERSION(3, 1, 5):
4280 	case IP_VERSION(3, 1, 6):
4281 	case IP_VERSION(3, 2, 0):
4282 	case IP_VERSION(3, 2, 1):
4283 	case IP_VERSION(2, 1, 0):
4284 		if (register_outbox_irq_handlers(dm->adev)) {
4285 			DRM_ERROR("DM: Failed to initialize IRQ\n");
4286 			goto fail;
4287 		}
4288 		break;
4289 	default:
4290 		DRM_DEBUG_KMS("Unsupported DCN IP version for outbox: 0x%X\n",
4291 			      adev->ip_versions[DCE_HWIP][0]);
4292 	}
4293 
4294 	/* Determine whether to enable PSR support by default. */
4295 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
4296 		switch (adev->ip_versions[DCE_HWIP][0]) {
4297 		case IP_VERSION(3, 1, 2):
4298 		case IP_VERSION(3, 1, 3):
4299 		case IP_VERSION(3, 1, 4):
4300 		case IP_VERSION(3, 1, 5):
4301 		case IP_VERSION(3, 1, 6):
4302 		case IP_VERSION(3, 2, 0):
4303 		case IP_VERSION(3, 2, 1):
4304 			psr_feature_enabled = true;
4305 			break;
4306 		default:
4307 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
4308 			break;
4309 		}
4310 	}
4311 
4312 	/* loops over all connectors on the board */
4313 	for (i = 0; i < link_cnt; i++) {
4314 		struct dc_link *link = NULL;
4315 
4316 		if (i > AMDGPU_DM_MAX_DISPLAY_INDEX) {
4317 			DRM_ERROR(
4318 				"KMS: Cannot support more than %d display indexes\n",
4319 					AMDGPU_DM_MAX_DISPLAY_INDEX);
4320 			continue;
4321 		}
4322 
4323 		aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
4324 		if (!aconnector)
4325 			goto fail;
4326 
4327 		aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
4328 		if (!aencoder)
4329 			goto fail;
4330 
4331 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
4332 			DRM_ERROR("KMS: Failed to initialize encoder\n");
4333 			goto fail;
4334 		}
4335 
4336 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
4337 			DRM_ERROR("KMS: Failed to initialize connector\n");
4338 			goto fail;
4339 		}
4340 
4341 		link = dc_get_link_at_index(dm->dc, i);
4342 
4343 		if (!dc_link_detect_sink(link, &new_connection_type))
4344 			DRM_ERROR("KMS: Failed to detect connector\n");
4345 
4346 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4347 			emulated_link_detect(link);
4348 			amdgpu_dm_update_connector_after_detect(aconnector);
4349 		} else {
4350 			bool ret = false;
4351 
4352 			mutex_lock(&dm->dc_lock);
4353 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
4354 			mutex_unlock(&dm->dc_lock);
4355 
4356 			if (ret) {
4357 				amdgpu_dm_update_connector_after_detect(aconnector);
4358 				register_backlight_device(dm, link);
4359 
4360 				if (dm->num_of_edps)
4361 					update_connector_ext_caps(aconnector);
4362 
4363 				if (psr_feature_enabled)
4364 					amdgpu_dm_set_psr_caps(link);
4365 
4366 				/* TODO: Fix vblank control helpers to delay PSR entry to allow this when
4367 				 * PSR is also supported.
4368 				 */
4369 				if (link->psr_settings.psr_feature_enabled)
4370 					adev_to_drm(adev)->vblank_disable_immediate = false;
4371 			}
4372 		}
4373 		amdgpu_set_panel_orientation(&aconnector->base);
4374 	}
4375 
4376 	/* Software is initialized. Now we can register interrupt handlers. */
4377 	switch (adev->asic_type) {
4378 #if defined(CONFIG_DRM_AMD_DC_SI)
4379 	case CHIP_TAHITI:
4380 	case CHIP_PITCAIRN:
4381 	case CHIP_VERDE:
4382 	case CHIP_OLAND:
4383 		if (dce60_register_irq_handlers(dm->adev)) {
4384 			DRM_ERROR("DM: Failed to initialize IRQ\n");
4385 			goto fail;
4386 		}
4387 		break;
4388 #endif
4389 	case CHIP_BONAIRE:
4390 	case CHIP_HAWAII:
4391 	case CHIP_KAVERI:
4392 	case CHIP_KABINI:
4393 	case CHIP_MULLINS:
4394 	case CHIP_TONGA:
4395 	case CHIP_FIJI:
4396 	case CHIP_CARRIZO:
4397 	case CHIP_STONEY:
4398 	case CHIP_POLARIS11:
4399 	case CHIP_POLARIS10:
4400 	case CHIP_POLARIS12:
4401 	case CHIP_VEGAM:
4402 	case CHIP_VEGA10:
4403 	case CHIP_VEGA12:
4404 	case CHIP_VEGA20:
4405 		if (dce110_register_irq_handlers(dm->adev)) {
4406 			DRM_ERROR("DM: Failed to initialize IRQ\n");
4407 			goto fail;
4408 		}
4409 		break;
4410 	default:
4411 		switch (adev->ip_versions[DCE_HWIP][0]) {
4412 		case IP_VERSION(1, 0, 0):
4413 		case IP_VERSION(1, 0, 1):
4414 		case IP_VERSION(2, 0, 2):
4415 		case IP_VERSION(2, 0, 3):
4416 		case IP_VERSION(2, 0, 0):
4417 		case IP_VERSION(2, 1, 0):
4418 		case IP_VERSION(3, 0, 0):
4419 		case IP_VERSION(3, 0, 2):
4420 		case IP_VERSION(3, 0, 3):
4421 		case IP_VERSION(3, 0, 1):
4422 		case IP_VERSION(3, 1, 2):
4423 		case IP_VERSION(3, 1, 3):
4424 		case IP_VERSION(3, 1, 4):
4425 		case IP_VERSION(3, 1, 5):
4426 		case IP_VERSION(3, 1, 6):
4427 		case IP_VERSION(3, 2, 0):
4428 		case IP_VERSION(3, 2, 1):
4429 			if (dcn10_register_irq_handlers(dm->adev)) {
4430 				DRM_ERROR("DM: Failed to initialize IRQ\n");
4431 				goto fail;
4432 			}
4433 			break;
4434 		default:
4435 			DRM_ERROR("Unsupported DCE IP versions: 0x%X\n",
4436 					adev->ip_versions[DCE_HWIP][0]);
4437 			goto fail;
4438 		}
4439 		break;
4440 	}
4441 
4442 	return 0;
4443 fail:
4444 	kfree(aencoder);
4445 	kfree(aconnector);
4446 
4447 	return -EINVAL;
4448 }
4449 
4450 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
4451 {
4452 	drm_atomic_private_obj_fini(&dm->atomic_obj);
4453 	return;
4454 }
4455 
4456 /******************************************************************************
4457  * amdgpu_display_funcs functions
4458  *****************************************************************************/
4459 
4460 /*
4461  * dm_bandwidth_update - program display watermarks
4462  *
4463  * @adev: amdgpu_device pointer
4464  *
4465  * Calculate and program the display watermarks and line buffer allocation.
4466  */
4467 static void dm_bandwidth_update(struct amdgpu_device *adev)
4468 {
4469 	/* TODO: implement later */
4470 }
4471 
4472 static const struct amdgpu_display_funcs dm_display_funcs = {
4473 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
4474 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
4475 	.backlight_set_level = NULL, /* never called for DC */
4476 	.backlight_get_level = NULL, /* never called for DC */
4477 	.hpd_sense = NULL,/* called unconditionally */
4478 	.hpd_set_polarity = NULL, /* called unconditionally */
4479 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
4480 	.page_flip_get_scanoutpos =
4481 		dm_crtc_get_scanoutpos,/* called unconditionally */
4482 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
4483 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
4484 };
4485 
4486 #if defined(CONFIG_DEBUG_KERNEL_DC)
4487 
4488 static ssize_t s3_debug_store(struct device *device,
4489 			      struct device_attribute *attr,
4490 			      const char *buf,
4491 			      size_t count)
4492 {
4493 	int ret;
4494 	int s3_state;
4495 	struct drm_device *drm_dev = dev_get_drvdata(device);
4496 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
4497 
4498 	ret = kstrtoint(buf, 0, &s3_state);
4499 
4500 	if (ret == 0) {
4501 		if (s3_state) {
4502 			dm_resume(adev);
4503 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
4504 		} else
4505 			dm_suspend(adev);
4506 	}
4507 
4508 	return ret == 0 ? count : 0;
4509 }
4510 
4511 DEVICE_ATTR_WO(s3_debug);
4512 
4513 #endif
4514 
4515 static int dm_early_init(void *handle)
4516 {
4517 	struct amdgpu_device *adev = (struct amdgpu_device *)handle;
4518 
4519 	switch (adev->asic_type) {
4520 #if defined(CONFIG_DRM_AMD_DC_SI)
4521 	case CHIP_TAHITI:
4522 	case CHIP_PITCAIRN:
4523 	case CHIP_VERDE:
4524 		adev->mode_info.num_crtc = 6;
4525 		adev->mode_info.num_hpd = 6;
4526 		adev->mode_info.num_dig = 6;
4527 		break;
4528 	case CHIP_OLAND:
4529 		adev->mode_info.num_crtc = 2;
4530 		adev->mode_info.num_hpd = 2;
4531 		adev->mode_info.num_dig = 2;
4532 		break;
4533 #endif
4534 	case CHIP_BONAIRE:
4535 	case CHIP_HAWAII:
4536 		adev->mode_info.num_crtc = 6;
4537 		adev->mode_info.num_hpd = 6;
4538 		adev->mode_info.num_dig = 6;
4539 		break;
4540 	case CHIP_KAVERI:
4541 		adev->mode_info.num_crtc = 4;
4542 		adev->mode_info.num_hpd = 6;
4543 		adev->mode_info.num_dig = 7;
4544 		break;
4545 	case CHIP_KABINI:
4546 	case CHIP_MULLINS:
4547 		adev->mode_info.num_crtc = 2;
4548 		adev->mode_info.num_hpd = 6;
4549 		adev->mode_info.num_dig = 6;
4550 		break;
4551 	case CHIP_FIJI:
4552 	case CHIP_TONGA:
4553 		adev->mode_info.num_crtc = 6;
4554 		adev->mode_info.num_hpd = 6;
4555 		adev->mode_info.num_dig = 7;
4556 		break;
4557 	case CHIP_CARRIZO:
4558 		adev->mode_info.num_crtc = 3;
4559 		adev->mode_info.num_hpd = 6;
4560 		adev->mode_info.num_dig = 9;
4561 		break;
4562 	case CHIP_STONEY:
4563 		adev->mode_info.num_crtc = 2;
4564 		adev->mode_info.num_hpd = 6;
4565 		adev->mode_info.num_dig = 9;
4566 		break;
4567 	case CHIP_POLARIS11:
4568 	case CHIP_POLARIS12:
4569 		adev->mode_info.num_crtc = 5;
4570 		adev->mode_info.num_hpd = 5;
4571 		adev->mode_info.num_dig = 5;
4572 		break;
4573 	case CHIP_POLARIS10:
4574 	case CHIP_VEGAM:
4575 		adev->mode_info.num_crtc = 6;
4576 		adev->mode_info.num_hpd = 6;
4577 		adev->mode_info.num_dig = 6;
4578 		break;
4579 	case CHIP_VEGA10:
4580 	case CHIP_VEGA12:
4581 	case CHIP_VEGA20:
4582 		adev->mode_info.num_crtc = 6;
4583 		adev->mode_info.num_hpd = 6;
4584 		adev->mode_info.num_dig = 6;
4585 		break;
4586 	default:
4587 
4588 		switch (adev->ip_versions[DCE_HWIP][0]) {
4589 		case IP_VERSION(2, 0, 2):
4590 		case IP_VERSION(3, 0, 0):
4591 			adev->mode_info.num_crtc = 6;
4592 			adev->mode_info.num_hpd = 6;
4593 			adev->mode_info.num_dig = 6;
4594 			break;
4595 		case IP_VERSION(2, 0, 0):
4596 		case IP_VERSION(3, 0, 2):
4597 			adev->mode_info.num_crtc = 5;
4598 			adev->mode_info.num_hpd = 5;
4599 			adev->mode_info.num_dig = 5;
4600 			break;
4601 		case IP_VERSION(2, 0, 3):
4602 		case IP_VERSION(3, 0, 3):
4603 			adev->mode_info.num_crtc = 2;
4604 			adev->mode_info.num_hpd = 2;
4605 			adev->mode_info.num_dig = 2;
4606 			break;
4607 		case IP_VERSION(1, 0, 0):
4608 		case IP_VERSION(1, 0, 1):
4609 		case IP_VERSION(3, 0, 1):
4610 		case IP_VERSION(2, 1, 0):
4611 		case IP_VERSION(3, 1, 2):
4612 		case IP_VERSION(3, 1, 3):
4613 		case IP_VERSION(3, 1, 4):
4614 		case IP_VERSION(3, 1, 5):
4615 		case IP_VERSION(3, 1, 6):
4616 		case IP_VERSION(3, 2, 0):
4617 		case IP_VERSION(3, 2, 1):
4618 			adev->mode_info.num_crtc = 4;
4619 			adev->mode_info.num_hpd = 4;
4620 			adev->mode_info.num_dig = 4;
4621 			break;
4622 		default:
4623 			DRM_ERROR("Unsupported DCE IP versions: 0x%x\n",
4624 					adev->ip_versions[DCE_HWIP][0]);
4625 			return -EINVAL;
4626 		}
4627 		break;
4628 	}
4629 
4630 	amdgpu_dm_set_irq_funcs(adev);
4631 
4632 	if (adev->mode_info.funcs == NULL)
4633 		adev->mode_info.funcs = &dm_display_funcs;
4634 
4635 	/*
4636 	 * Note: Do NOT change adev->audio_endpt_rreg and
4637 	 * adev->audio_endpt_wreg because they are initialised in
4638 	 * amdgpu_device_init()
4639 	 */
4640 #if defined(CONFIG_DEBUG_KERNEL_DC)
4641 	device_create_file(
4642 		adev_to_drm(adev)->dev,
4643 		&dev_attr_s3_debug);
4644 #endif
4645 
4646 	return 0;
4647 }
4648 
4649 static bool modereset_required(struct drm_crtc_state *crtc_state)
4650 {
4651 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
4652 }
4653 
4654 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
4655 {
4656 	drm_encoder_cleanup(encoder);
4657 	kfree(encoder);
4658 }
4659 
4660 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
4661 	.destroy = amdgpu_dm_encoder_destroy,
4662 };
4663 
4664 static int
4665 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
4666 			    const enum surface_pixel_format format,
4667 			    enum dc_color_space *color_space)
4668 {
4669 	bool full_range;
4670 
4671 	*color_space = COLOR_SPACE_SRGB;
4672 
4673 	/* DRM color properties only affect non-RGB formats. */
4674 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
4675 		return 0;
4676 
4677 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
4678 
4679 	switch (plane_state->color_encoding) {
4680 	case DRM_COLOR_YCBCR_BT601:
4681 		if (full_range)
4682 			*color_space = COLOR_SPACE_YCBCR601;
4683 		else
4684 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
4685 		break;
4686 
4687 	case DRM_COLOR_YCBCR_BT709:
4688 		if (full_range)
4689 			*color_space = COLOR_SPACE_YCBCR709;
4690 		else
4691 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
4692 		break;
4693 
4694 	case DRM_COLOR_YCBCR_BT2020:
4695 		if (full_range)
4696 			*color_space = COLOR_SPACE_2020_YCBCR;
4697 		else
4698 			return -EINVAL;
4699 		break;
4700 
4701 	default:
4702 		return -EINVAL;
4703 	}
4704 
4705 	return 0;
4706 }
4707 
4708 static int
4709 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
4710 			    const struct drm_plane_state *plane_state,
4711 			    const uint64_t tiling_flags,
4712 			    struct dc_plane_info *plane_info,
4713 			    struct dc_plane_address *address,
4714 			    bool tmz_surface,
4715 			    bool force_disable_dcc)
4716 {
4717 	const struct drm_framebuffer *fb = plane_state->fb;
4718 	const struct amdgpu_framebuffer *afb =
4719 		to_amdgpu_framebuffer(plane_state->fb);
4720 	int ret;
4721 
4722 	memset(plane_info, 0, sizeof(*plane_info));
4723 
4724 	switch (fb->format->format) {
4725 	case DRM_FORMAT_C8:
4726 		plane_info->format =
4727 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
4728 		break;
4729 	case DRM_FORMAT_RGB565:
4730 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
4731 		break;
4732 	case DRM_FORMAT_XRGB8888:
4733 	case DRM_FORMAT_ARGB8888:
4734 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
4735 		break;
4736 	case DRM_FORMAT_XRGB2101010:
4737 	case DRM_FORMAT_ARGB2101010:
4738 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
4739 		break;
4740 	case DRM_FORMAT_XBGR2101010:
4741 	case DRM_FORMAT_ABGR2101010:
4742 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
4743 		break;
4744 	case DRM_FORMAT_XBGR8888:
4745 	case DRM_FORMAT_ABGR8888:
4746 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
4747 		break;
4748 	case DRM_FORMAT_NV21:
4749 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
4750 		break;
4751 	case DRM_FORMAT_NV12:
4752 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
4753 		break;
4754 	case DRM_FORMAT_P010:
4755 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
4756 		break;
4757 	case DRM_FORMAT_XRGB16161616F:
4758 	case DRM_FORMAT_ARGB16161616F:
4759 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
4760 		break;
4761 	case DRM_FORMAT_XBGR16161616F:
4762 	case DRM_FORMAT_ABGR16161616F:
4763 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
4764 		break;
4765 	case DRM_FORMAT_XRGB16161616:
4766 	case DRM_FORMAT_ARGB16161616:
4767 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
4768 		break;
4769 	case DRM_FORMAT_XBGR16161616:
4770 	case DRM_FORMAT_ABGR16161616:
4771 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
4772 		break;
4773 	default:
4774 		DRM_ERROR(
4775 			"Unsupported screen format %p4cc\n",
4776 			&fb->format->format);
4777 		return -EINVAL;
4778 	}
4779 
4780 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
4781 	case DRM_MODE_ROTATE_0:
4782 		plane_info->rotation = ROTATION_ANGLE_0;
4783 		break;
4784 	case DRM_MODE_ROTATE_90:
4785 		plane_info->rotation = ROTATION_ANGLE_90;
4786 		break;
4787 	case DRM_MODE_ROTATE_180:
4788 		plane_info->rotation = ROTATION_ANGLE_180;
4789 		break;
4790 	case DRM_MODE_ROTATE_270:
4791 		plane_info->rotation = ROTATION_ANGLE_270;
4792 		break;
4793 	default:
4794 		plane_info->rotation = ROTATION_ANGLE_0;
4795 		break;
4796 	}
4797 
4798 
4799 	plane_info->visible = true;
4800 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
4801 
4802 	plane_info->layer_index = plane_state->normalized_zpos;
4803 
4804 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
4805 					  &plane_info->color_space);
4806 	if (ret)
4807 		return ret;
4808 
4809 	ret = fill_plane_buffer_attributes(adev, afb, plane_info->format,
4810 					   plane_info->rotation, tiling_flags,
4811 					   &plane_info->tiling_info,
4812 					   &plane_info->plane_size,
4813 					   &plane_info->dcc, address,
4814 					   tmz_surface, force_disable_dcc);
4815 	if (ret)
4816 		return ret;
4817 
4818 	fill_blending_from_plane_state(
4819 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
4820 		&plane_info->global_alpha, &plane_info->global_alpha_value);
4821 
4822 	return 0;
4823 }
4824 
4825 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
4826 				    struct dc_plane_state *dc_plane_state,
4827 				    struct drm_plane_state *plane_state,
4828 				    struct drm_crtc_state *crtc_state)
4829 {
4830 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
4831 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
4832 	struct dc_scaling_info scaling_info;
4833 	struct dc_plane_info plane_info;
4834 	int ret;
4835 	bool force_disable_dcc = false;
4836 
4837 	ret = fill_dc_scaling_info(adev, plane_state, &scaling_info);
4838 	if (ret)
4839 		return ret;
4840 
4841 	dc_plane_state->src_rect = scaling_info.src_rect;
4842 	dc_plane_state->dst_rect = scaling_info.dst_rect;
4843 	dc_plane_state->clip_rect = scaling_info.clip_rect;
4844 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
4845 
4846 	force_disable_dcc = adev->asic_type == CHIP_RAVEN && adev->in_suspend;
4847 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
4848 					  afb->tiling_flags,
4849 					  &plane_info,
4850 					  &dc_plane_state->address,
4851 					  afb->tmz_surface,
4852 					  force_disable_dcc);
4853 	if (ret)
4854 		return ret;
4855 
4856 	dc_plane_state->format = plane_info.format;
4857 	dc_plane_state->color_space = plane_info.color_space;
4858 	dc_plane_state->format = plane_info.format;
4859 	dc_plane_state->plane_size = plane_info.plane_size;
4860 	dc_plane_state->rotation = plane_info.rotation;
4861 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
4862 	dc_plane_state->stereo_format = plane_info.stereo_format;
4863 	dc_plane_state->tiling_info = plane_info.tiling_info;
4864 	dc_plane_state->visible = plane_info.visible;
4865 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
4866 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
4867 	dc_plane_state->global_alpha = plane_info.global_alpha;
4868 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
4869 	dc_plane_state->dcc = plane_info.dcc;
4870 	dc_plane_state->layer_index = plane_info.layer_index;
4871 	dc_plane_state->flip_int_enabled = true;
4872 
4873 	/*
4874 	 * Always set input transfer function, since plane state is refreshed
4875 	 * every time.
4876 	 */
4877 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state, dc_plane_state);
4878 	if (ret)
4879 		return ret;
4880 
4881 	return 0;
4882 }
4883 
4884 /**
4885  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
4886  *
4887  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
4888  *         remote fb
4889  * @old_plane_state: Old state of @plane
4890  * @new_plane_state: New state of @plane
4891  * @crtc_state: New state of CRTC connected to the @plane
4892  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
4893  *
4894  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
4895  * (referred to as "damage clips" in DRM nomenclature) that require updating on
4896  * the eDP remote buffer. The responsibility of specifying the dirty regions is
4897  * amdgpu_dm's.
4898  *
4899  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
4900  * plane with regions that require flushing to the eDP remote buffer. In
4901  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
4902  * implicitly provide damage clips without any client support via the plane
4903  * bounds.
4904  *
4905  * Today, amdgpu_dm only supports the MPO and cursor usecase.
4906  *
4907  * TODO: Also enable for FB_DAMAGE_CLIPS
4908  */
4909 static void fill_dc_dirty_rects(struct drm_plane *plane,
4910 				struct drm_plane_state *old_plane_state,
4911 				struct drm_plane_state *new_plane_state,
4912 				struct drm_crtc_state *crtc_state,
4913 				struct dc_flip_addrs *flip_addrs)
4914 {
4915 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
4916 	struct rect *dirty_rects = flip_addrs->dirty_rects;
4917 	uint32_t num_clips;
4918 	bool bb_changed;
4919 	bool fb_changed;
4920 	uint32_t i = 0;
4921 
4922 	flip_addrs->dirty_rect_count = 0;
4923 
4924 	/*
4925 	 * Cursor plane has it's own dirty rect update interface. See
4926 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
4927 	 */
4928 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
4929 		return;
4930 
4931 	/*
4932 	 * Today, we only consider MPO use-case for PSR SU. If MPO not
4933 	 * requested, and there is a plane update, do FFU.
4934 	 */
4935 	if (!dm_crtc_state->mpo_requested) {
4936 		dirty_rects[0].x = 0;
4937 		dirty_rects[0].y = 0;
4938 		dirty_rects[0].width = dm_crtc_state->base.mode.crtc_hdisplay;
4939 		dirty_rects[0].height = dm_crtc_state->base.mode.crtc_vdisplay;
4940 		flip_addrs->dirty_rect_count = 1;
4941 		DRM_DEBUG_DRIVER("[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
4942 				 new_plane_state->plane->base.id,
4943 				 dm_crtc_state->base.mode.crtc_hdisplay,
4944 				 dm_crtc_state->base.mode.crtc_vdisplay);
4945 		return;
4946 	}
4947 
4948 	/*
4949 	 * MPO is requested. Add entire plane bounding box to dirty rects if
4950 	 * flipped to or damaged.
4951 	 *
4952 	 * If plane is moved or resized, also add old bounding box to dirty
4953 	 * rects.
4954 	 */
4955 	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
4956 	fb_changed = old_plane_state->fb->base.id !=
4957 		     new_plane_state->fb->base.id;
4958 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
4959 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
4960 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
4961 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
4962 
4963 	DRM_DEBUG_DRIVER("[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
4964 			 new_plane_state->plane->base.id,
4965 			 bb_changed, fb_changed, num_clips);
4966 
4967 	if (num_clips || fb_changed || bb_changed) {
4968 		dirty_rects[i].x = new_plane_state->crtc_x;
4969 		dirty_rects[i].y = new_plane_state->crtc_y;
4970 		dirty_rects[i].width = new_plane_state->crtc_w;
4971 		dirty_rects[i].height = new_plane_state->crtc_h;
4972 		DRM_DEBUG_DRIVER("[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)\n",
4973 				 new_plane_state->plane->base.id,
4974 				 dirty_rects[i].x, dirty_rects[i].y,
4975 				 dirty_rects[i].width, dirty_rects[i].height);
4976 		i += 1;
4977 	}
4978 
4979 	/* Add old plane bounding-box if plane is moved or resized */
4980 	if (bb_changed) {
4981 		dirty_rects[i].x = old_plane_state->crtc_x;
4982 		dirty_rects[i].y = old_plane_state->crtc_y;
4983 		dirty_rects[i].width = old_plane_state->crtc_w;
4984 		dirty_rects[i].height = old_plane_state->crtc_h;
4985 		DRM_DEBUG_DRIVER("[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)\n",
4986 				old_plane_state->plane->base.id,
4987 				dirty_rects[i].x, dirty_rects[i].y,
4988 				dirty_rects[i].width, dirty_rects[i].height);
4989 		i += 1;
4990 	}
4991 
4992 	flip_addrs->dirty_rect_count = i;
4993 }
4994 
4995 static void update_stream_scaling_settings(const struct drm_display_mode *mode,
4996 					   const struct dm_connector_state *dm_state,
4997 					   struct dc_stream_state *stream)
4998 {
4999 	enum amdgpu_rmx_type rmx_type;
5000 
5001 	struct rect src = { 0 }; /* viewport in composition space*/
5002 	struct rect dst = { 0 }; /* stream addressable area */
5003 
5004 	/* no mode. nothing to be done */
5005 	if (!mode)
5006 		return;
5007 
5008 	/* Full screen scaling by default */
5009 	src.width = mode->hdisplay;
5010 	src.height = mode->vdisplay;
5011 	dst.width = stream->timing.h_addressable;
5012 	dst.height = stream->timing.v_addressable;
5013 
5014 	if (dm_state) {
5015 		rmx_type = dm_state->scaling;
5016 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
5017 			if (src.width * dst.height <
5018 					src.height * dst.width) {
5019 				/* height needs less upscaling/more downscaling */
5020 				dst.width = src.width *
5021 						dst.height / src.height;
5022 			} else {
5023 				/* width needs less upscaling/more downscaling */
5024 				dst.height = src.height *
5025 						dst.width / src.width;
5026 			}
5027 		} else if (rmx_type == RMX_CENTER) {
5028 			dst = src;
5029 		}
5030 
5031 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
5032 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
5033 
5034 		if (dm_state->underscan_enable) {
5035 			dst.x += dm_state->underscan_hborder / 2;
5036 			dst.y += dm_state->underscan_vborder / 2;
5037 			dst.width -= dm_state->underscan_hborder;
5038 			dst.height -= dm_state->underscan_vborder;
5039 		}
5040 	}
5041 
5042 	stream->src = src;
5043 	stream->dst = dst;
5044 
5045 	DRM_DEBUG_KMS("Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
5046 		      dst.x, dst.y, dst.width, dst.height);
5047 
5048 }
5049 
5050 static enum dc_color_depth
5051 convert_color_depth_from_display_info(const struct drm_connector *connector,
5052 				      bool is_y420, int requested_bpc)
5053 {
5054 	uint8_t bpc;
5055 
5056 	if (is_y420) {
5057 		bpc = 8;
5058 
5059 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
5060 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
5061 			bpc = 16;
5062 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
5063 			bpc = 12;
5064 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
5065 			bpc = 10;
5066 	} else {
5067 		bpc = (uint8_t)connector->display_info.bpc;
5068 		/* Assume 8 bpc by default if no bpc is specified. */
5069 		bpc = bpc ? bpc : 8;
5070 	}
5071 
5072 	if (requested_bpc > 0) {
5073 		/*
5074 		 * Cap display bpc based on the user requested value.
5075 		 *
5076 		 * The value for state->max_bpc may not correctly updated
5077 		 * depending on when the connector gets added to the state
5078 		 * or if this was called outside of atomic check, so it
5079 		 * can't be used directly.
5080 		 */
5081 		bpc = min_t(u8, bpc, requested_bpc);
5082 
5083 		/* Round down to the nearest even number. */
5084 		bpc = bpc - (bpc & 1);
5085 	}
5086 
5087 	switch (bpc) {
5088 	case 0:
5089 		/*
5090 		 * Temporary Work around, DRM doesn't parse color depth for
5091 		 * EDID revision before 1.4
5092 		 * TODO: Fix edid parsing
5093 		 */
5094 		return COLOR_DEPTH_888;
5095 	case 6:
5096 		return COLOR_DEPTH_666;
5097 	case 8:
5098 		return COLOR_DEPTH_888;
5099 	case 10:
5100 		return COLOR_DEPTH_101010;
5101 	case 12:
5102 		return COLOR_DEPTH_121212;
5103 	case 14:
5104 		return COLOR_DEPTH_141414;
5105 	case 16:
5106 		return COLOR_DEPTH_161616;
5107 	default:
5108 		return COLOR_DEPTH_UNDEFINED;
5109 	}
5110 }
5111 
5112 static enum dc_aspect_ratio
5113 get_aspect_ratio(const struct drm_display_mode *mode_in)
5114 {
5115 	/* 1-1 mapping, since both enums follow the HDMI spec. */
5116 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
5117 }
5118 
5119 static enum dc_color_space
5120 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing)
5121 {
5122 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
5123 
5124 	switch (dc_crtc_timing->pixel_encoding)	{
5125 	case PIXEL_ENCODING_YCBCR422:
5126 	case PIXEL_ENCODING_YCBCR444:
5127 	case PIXEL_ENCODING_YCBCR420:
5128 	{
5129 		/*
5130 		 * 27030khz is the separation point between HDTV and SDTV
5131 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
5132 		 * respectively
5133 		 */
5134 		if (dc_crtc_timing->pix_clk_100hz > 270300) {
5135 			if (dc_crtc_timing->flags.Y_ONLY)
5136 				color_space =
5137 					COLOR_SPACE_YCBCR709_LIMITED;
5138 			else
5139 				color_space = COLOR_SPACE_YCBCR709;
5140 		} else {
5141 			if (dc_crtc_timing->flags.Y_ONLY)
5142 				color_space =
5143 					COLOR_SPACE_YCBCR601_LIMITED;
5144 			else
5145 				color_space = COLOR_SPACE_YCBCR601;
5146 		}
5147 
5148 	}
5149 	break;
5150 	case PIXEL_ENCODING_RGB:
5151 		color_space = COLOR_SPACE_SRGB;
5152 		break;
5153 
5154 	default:
5155 		WARN_ON(1);
5156 		break;
5157 	}
5158 
5159 	return color_space;
5160 }
5161 
5162 static bool adjust_colour_depth_from_display_info(
5163 	struct dc_crtc_timing *timing_out,
5164 	const struct drm_display_info *info)
5165 {
5166 	enum dc_color_depth depth = timing_out->display_color_depth;
5167 	int normalized_clk;
5168 	do {
5169 		normalized_clk = timing_out->pix_clk_100hz / 10;
5170 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
5171 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
5172 			normalized_clk /= 2;
5173 		/* Adjusting pix clock following on HDMI spec based on colour depth */
5174 		switch (depth) {
5175 		case COLOR_DEPTH_888:
5176 			break;
5177 		case COLOR_DEPTH_101010:
5178 			normalized_clk = (normalized_clk * 30) / 24;
5179 			break;
5180 		case COLOR_DEPTH_121212:
5181 			normalized_clk = (normalized_clk * 36) / 24;
5182 			break;
5183 		case COLOR_DEPTH_161616:
5184 			normalized_clk = (normalized_clk * 48) / 24;
5185 			break;
5186 		default:
5187 			/* The above depths are the only ones valid for HDMI. */
5188 			return false;
5189 		}
5190 		if (normalized_clk <= info->max_tmds_clock) {
5191 			timing_out->display_color_depth = depth;
5192 			return true;
5193 		}
5194 	} while (--depth > COLOR_DEPTH_666);
5195 	return false;
5196 }
5197 
5198 static void fill_stream_properties_from_drm_display_mode(
5199 	struct dc_stream_state *stream,
5200 	const struct drm_display_mode *mode_in,
5201 	const struct drm_connector *connector,
5202 	const struct drm_connector_state *connector_state,
5203 	const struct dc_stream_state *old_stream,
5204 	int requested_bpc)
5205 {
5206 	struct dc_crtc_timing *timing_out = &stream->timing;
5207 	const struct drm_display_info *info = &connector->display_info;
5208 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5209 	struct hdmi_vendor_infoframe hv_frame;
5210 	struct hdmi_avi_infoframe avi_frame;
5211 
5212 	memset(&hv_frame, 0, sizeof(hv_frame));
5213 	memset(&avi_frame, 0, sizeof(avi_frame));
5214 
5215 	timing_out->h_border_left = 0;
5216 	timing_out->h_border_right = 0;
5217 	timing_out->v_border_top = 0;
5218 	timing_out->v_border_bottom = 0;
5219 	/* TODO: un-hardcode */
5220 	if (drm_mode_is_420_only(info, mode_in)
5221 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5222 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5223 	else if (drm_mode_is_420_also(info, mode_in)
5224 			&& aconnector->force_yuv420_output)
5225 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5226 	else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCBCR444)
5227 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5228 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
5229 	else
5230 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
5231 
5232 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
5233 	timing_out->display_color_depth = convert_color_depth_from_display_info(
5234 		connector,
5235 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
5236 		requested_bpc);
5237 	timing_out->scan_type = SCANNING_TYPE_NODATA;
5238 	timing_out->hdmi_vic = 0;
5239 
5240 	if (old_stream) {
5241 		timing_out->vic = old_stream->timing.vic;
5242 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
5243 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
5244 	} else {
5245 		timing_out->vic = drm_match_cea_mode(mode_in);
5246 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
5247 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
5248 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
5249 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
5250 	}
5251 
5252 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
5253 		drm_hdmi_avi_infoframe_from_display_mode(&avi_frame, (struct drm_connector *)connector, mode_in);
5254 		timing_out->vic = avi_frame.video_code;
5255 		drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame, (struct drm_connector *)connector, mode_in);
5256 		timing_out->hdmi_vic = hv_frame.vic;
5257 	}
5258 
5259 	if (is_freesync_video_mode(mode_in, aconnector)) {
5260 		timing_out->h_addressable = mode_in->hdisplay;
5261 		timing_out->h_total = mode_in->htotal;
5262 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
5263 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
5264 		timing_out->v_total = mode_in->vtotal;
5265 		timing_out->v_addressable = mode_in->vdisplay;
5266 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
5267 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
5268 		timing_out->pix_clk_100hz = mode_in->clock * 10;
5269 	} else {
5270 		timing_out->h_addressable = mode_in->crtc_hdisplay;
5271 		timing_out->h_total = mode_in->crtc_htotal;
5272 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
5273 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
5274 		timing_out->v_total = mode_in->crtc_vtotal;
5275 		timing_out->v_addressable = mode_in->crtc_vdisplay;
5276 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
5277 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
5278 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
5279 	}
5280 
5281 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
5282 
5283 	stream->output_color_space = get_output_color_space(timing_out);
5284 
5285 	stream->out_transfer_func->type = TF_TYPE_PREDEFINED;
5286 	stream->out_transfer_func->tf = TRANSFER_FUNCTION_SRGB;
5287 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
5288 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
5289 		    drm_mode_is_420_also(info, mode_in) &&
5290 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
5291 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
5292 			adjust_colour_depth_from_display_info(timing_out, info);
5293 		}
5294 	}
5295 }
5296 
5297 static void fill_audio_info(struct audio_info *audio_info,
5298 			    const struct drm_connector *drm_connector,
5299 			    const struct dc_sink *dc_sink)
5300 {
5301 	int i = 0;
5302 	int cea_revision = 0;
5303 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
5304 
5305 	audio_info->manufacture_id = edid_caps->manufacturer_id;
5306 	audio_info->product_id = edid_caps->product_id;
5307 
5308 	cea_revision = drm_connector->display_info.cea_rev;
5309 
5310 #ifdef __linux__
5311 	strscpy(audio_info->display_name,
5312 		edid_caps->display_name,
5313 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
5314 #else
5315 	strncpy(audio_info->display_name,
5316 		edid_caps->display_name,
5317 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS - 1);
5318 #endif
5319 
5320 	if (cea_revision >= 3) {
5321 		audio_info->mode_count = edid_caps->audio_mode_count;
5322 
5323 		for (i = 0; i < audio_info->mode_count; ++i) {
5324 			audio_info->modes[i].format_code =
5325 					(enum audio_format_code)
5326 					(edid_caps->audio_modes[i].format_code);
5327 			audio_info->modes[i].channel_count =
5328 					edid_caps->audio_modes[i].channel_count;
5329 			audio_info->modes[i].sample_rates.all =
5330 					edid_caps->audio_modes[i].sample_rate;
5331 			audio_info->modes[i].sample_size =
5332 					edid_caps->audio_modes[i].sample_size;
5333 		}
5334 	}
5335 
5336 	audio_info->flags.all = edid_caps->speaker_flags;
5337 
5338 	/* TODO: We only check for the progressive mode, check for interlace mode too */
5339 	if (drm_connector->latency_present[0]) {
5340 		audio_info->video_latency = drm_connector->video_latency[0];
5341 		audio_info->audio_latency = drm_connector->audio_latency[0];
5342 	}
5343 
5344 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
5345 
5346 }
5347 
5348 static void
5349 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
5350 				      struct drm_display_mode *dst_mode)
5351 {
5352 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
5353 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
5354 	dst_mode->crtc_clock = src_mode->crtc_clock;
5355 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
5356 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
5357 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
5358 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
5359 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
5360 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
5361 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
5362 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
5363 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
5364 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
5365 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
5366 }
5367 
5368 static void
5369 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
5370 					const struct drm_display_mode *native_mode,
5371 					bool scale_enabled)
5372 {
5373 	if (scale_enabled) {
5374 		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
5375 	} else if (native_mode->clock == drm_mode->clock &&
5376 			native_mode->htotal == drm_mode->htotal &&
5377 			native_mode->vtotal == drm_mode->vtotal) {
5378 		copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
5379 	} else {
5380 		/* no scaling nor amdgpu inserted, no need to patch */
5381 	}
5382 }
5383 
5384 static struct dc_sink *
5385 create_fake_sink(struct amdgpu_dm_connector *aconnector)
5386 {
5387 	struct dc_sink_init_data sink_init_data = { 0 };
5388 	struct dc_sink *sink = NULL;
5389 	sink_init_data.link = aconnector->dc_link;
5390 	sink_init_data.sink_signal = aconnector->dc_link->connector_signal;
5391 
5392 	sink = dc_sink_create(&sink_init_data);
5393 	if (!sink) {
5394 		DRM_ERROR("Failed to create sink!\n");
5395 		return NULL;
5396 	}
5397 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
5398 
5399 	return sink;
5400 }
5401 
5402 static void set_multisync_trigger_params(
5403 		struct dc_stream_state *stream)
5404 {
5405 	struct dc_stream_state *master = NULL;
5406 
5407 	if (stream->triggered_crtc_reset.enabled) {
5408 		master = stream->triggered_crtc_reset.event_source;
5409 		stream->triggered_crtc_reset.event =
5410 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
5411 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
5412 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
5413 	}
5414 }
5415 
5416 static void set_master_stream(struct dc_stream_state *stream_set[],
5417 			      int stream_count)
5418 {
5419 	int j, highest_rfr = 0, master_stream = 0;
5420 
5421 	for (j = 0;  j < stream_count; j++) {
5422 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
5423 			int refresh_rate = 0;
5424 
5425 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
5426 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
5427 			if (refresh_rate > highest_rfr) {
5428 				highest_rfr = refresh_rate;
5429 				master_stream = j;
5430 			}
5431 		}
5432 	}
5433 	for (j = 0;  j < stream_count; j++) {
5434 		if (stream_set[j])
5435 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
5436 	}
5437 }
5438 
5439 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
5440 {
5441 	int i = 0;
5442 	struct dc_stream_state *stream;
5443 
5444 	if (context->stream_count < 2)
5445 		return;
5446 	for (i = 0; i < context->stream_count ; i++) {
5447 		if (!context->streams[i])
5448 			continue;
5449 		/*
5450 		 * TODO: add a function to read AMD VSDB bits and set
5451 		 * crtc_sync_master.multi_sync_enabled flag
5452 		 * For now it's set to false
5453 		 */
5454 	}
5455 
5456 	set_master_stream(context->streams, context->stream_count);
5457 
5458 	for (i = 0; i < context->stream_count ; i++) {
5459 		stream = context->streams[i];
5460 
5461 		if (!stream)
5462 			continue;
5463 
5464 		set_multisync_trigger_params(stream);
5465 	}
5466 }
5467 
5468 /**
5469  * DOC: FreeSync Video
5470  *
5471  * When a userspace application wants to play a video, the content follows a
5472  * standard format definition that usually specifies the FPS for that format.
5473  * The below list illustrates some video format and the expected FPS,
5474  * respectively:
5475  *
5476  * - TV/NTSC (23.976 FPS)
5477  * - Cinema (24 FPS)
5478  * - TV/PAL (25 FPS)
5479  * - TV/NTSC (29.97 FPS)
5480  * - TV/NTSC (30 FPS)
5481  * - Cinema HFR (48 FPS)
5482  * - TV/PAL (50 FPS)
5483  * - Commonly used (60 FPS)
5484  * - Multiples of 24 (48,72,96 FPS)
5485  *
5486  * The list of standards video format is not huge and can be added to the
5487  * connector modeset list beforehand. With that, userspace can leverage
5488  * FreeSync to extends the front porch in order to attain the target refresh
5489  * rate. Such a switch will happen seamlessly, without screen blanking or
5490  * reprogramming of the output in any other way. If the userspace requests a
5491  * modesetting change compatible with FreeSync modes that only differ in the
5492  * refresh rate, DC will skip the full update and avoid blink during the
5493  * transition. For example, the video player can change the modesetting from
5494  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
5495  * causing any display blink. This same concept can be applied to a mode
5496  * setting change.
5497  */
5498 static struct drm_display_mode *
5499 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
5500 		bool use_probed_modes)
5501 {
5502 	struct drm_display_mode *m, *m_pref = NULL;
5503 	u16 current_refresh, highest_refresh;
5504 	struct list_head *list_head = use_probed_modes ?
5505 		&aconnector->base.probed_modes :
5506 		&aconnector->base.modes;
5507 
5508 	if (aconnector->freesync_vid_base.clock != 0)
5509 		return &aconnector->freesync_vid_base;
5510 
5511 	/* Find the preferred mode */
5512 	list_for_each_entry (m, list_head, head) {
5513 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
5514 			m_pref = m;
5515 			break;
5516 		}
5517 	}
5518 
5519 	if (!m_pref) {
5520 		/* Probably an EDID with no preferred mode. Fallback to first entry */
5521 		m_pref = list_first_entry_or_null(
5522 				&aconnector->base.modes, struct drm_display_mode, head);
5523 		if (!m_pref) {
5524 			DRM_DEBUG_DRIVER("No preferred mode found in EDID\n");
5525 			return NULL;
5526 		}
5527 	}
5528 
5529 	highest_refresh = drm_mode_vrefresh(m_pref);
5530 
5531 	/*
5532 	 * Find the mode with highest refresh rate with same resolution.
5533 	 * For some monitors, preferred mode is not the mode with highest
5534 	 * supported refresh rate.
5535 	 */
5536 	list_for_each_entry (m, list_head, head) {
5537 		current_refresh  = drm_mode_vrefresh(m);
5538 
5539 		if (m->hdisplay == m_pref->hdisplay &&
5540 		    m->vdisplay == m_pref->vdisplay &&
5541 		    highest_refresh < current_refresh) {
5542 			highest_refresh = current_refresh;
5543 			m_pref = m;
5544 		}
5545 	}
5546 
5547 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
5548 	return m_pref;
5549 }
5550 
5551 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
5552 		struct amdgpu_dm_connector *aconnector)
5553 {
5554 	struct drm_display_mode *high_mode;
5555 	int timing_diff;
5556 
5557 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
5558 	if (!high_mode || !mode)
5559 		return false;
5560 
5561 	timing_diff = high_mode->vtotal - mode->vtotal;
5562 
5563 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
5564 	    high_mode->hdisplay != mode->hdisplay ||
5565 	    high_mode->vdisplay != mode->vdisplay ||
5566 	    high_mode->hsync_start != mode->hsync_start ||
5567 	    high_mode->hsync_end != mode->hsync_end ||
5568 	    high_mode->htotal != mode->htotal ||
5569 	    high_mode->hskew != mode->hskew ||
5570 	    high_mode->vscan != mode->vscan ||
5571 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
5572 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
5573 		return false;
5574 	else
5575 		return true;
5576 }
5577 
5578 #if defined(CONFIG_DRM_AMD_DC_DCN)
5579 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
5580 			    struct dc_sink *sink, struct dc_stream_state *stream,
5581 			    struct dsc_dec_dpcd_caps *dsc_caps)
5582 {
5583 	stream->timing.flags.DSC = 0;
5584 	dsc_caps->is_dsc_supported = false;
5585 
5586 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
5587 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
5588 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
5589 			sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
5590 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
5591 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
5592 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
5593 				dsc_caps);
5594 	}
5595 }
5596 
5597 
5598 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
5599 				    struct dc_sink *sink, struct dc_stream_state *stream,
5600 				    struct dsc_dec_dpcd_caps *dsc_caps,
5601 				    uint32_t max_dsc_target_bpp_limit_override)
5602 {
5603 	const struct dc_link_settings *verified_link_cap = NULL;
5604 	uint32_t link_bw_in_kbps;
5605 	uint32_t edp_min_bpp_x16, edp_max_bpp_x16;
5606 	struct dc *dc = sink->ctx->dc;
5607 	struct dc_dsc_bw_range bw_range = {0};
5608 	struct dc_dsc_config dsc_cfg = {0};
5609 
5610 	verified_link_cap = dc_link_get_link_cap(stream->link);
5611 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
5612 	edp_min_bpp_x16 = 8 * 16;
5613 	edp_max_bpp_x16 = 8 * 16;
5614 
5615 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
5616 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
5617 
5618 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
5619 		edp_min_bpp_x16 = edp_max_bpp_x16;
5620 
5621 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
5622 				dc->debug.dsc_min_slice_height_override,
5623 				edp_min_bpp_x16, edp_max_bpp_x16,
5624 				dsc_caps,
5625 				&stream->timing,
5626 				&bw_range)) {
5627 
5628 		if (bw_range.max_kbps < link_bw_in_kbps) {
5629 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
5630 					dsc_caps,
5631 					dc->debug.dsc_min_slice_height_override,
5632 					max_dsc_target_bpp_limit_override,
5633 					0,
5634 					&stream->timing,
5635 					&dsc_cfg)) {
5636 				stream->timing.dsc_cfg = dsc_cfg;
5637 				stream->timing.flags.DSC = 1;
5638 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
5639 			}
5640 			return;
5641 		}
5642 	}
5643 
5644 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
5645 				dsc_caps,
5646 				dc->debug.dsc_min_slice_height_override,
5647 				max_dsc_target_bpp_limit_override,
5648 				link_bw_in_kbps,
5649 				&stream->timing,
5650 				&dsc_cfg)) {
5651 		stream->timing.dsc_cfg = dsc_cfg;
5652 		stream->timing.flags.DSC = 1;
5653 	}
5654 }
5655 
5656 
5657 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
5658 					struct dc_sink *sink, struct dc_stream_state *stream,
5659 					struct dsc_dec_dpcd_caps *dsc_caps)
5660 {
5661 	struct drm_connector *drm_connector = &aconnector->base;
5662 	uint32_t link_bandwidth_kbps;
5663 	uint32_t max_dsc_target_bpp_limit_override = 0;
5664 	struct dc *dc = sink->ctx->dc;
5665 	uint32_t max_supported_bw_in_kbps, timing_bw_in_kbps;
5666 	uint32_t dsc_max_supported_bw_in_kbps;
5667 
5668 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
5669 							dc_link_get_link_cap(aconnector->dc_link));
5670 	if (stream->link && stream->link->local_sink)
5671 		max_dsc_target_bpp_limit_override =
5672 			stream->link->local_sink->edid_caps.panel_patch.max_dsc_target_bpp_limit;
5673 
5674 	/* Set DSC policy according to dsc_clock_en */
5675 	dc_dsc_policy_set_enable_dsc_when_not_needed(
5676 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
5677 
5678 	if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_EDP &&
5679 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
5680 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
5681 
5682 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
5683 
5684 	} else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
5685 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
5686 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
5687 						dsc_caps,
5688 						aconnector->dc_link->ctx->dc->debug.dsc_min_slice_height_override,
5689 						max_dsc_target_bpp_limit_override,
5690 						link_bandwidth_kbps,
5691 						&stream->timing,
5692 						&stream->timing.dsc_cfg)) {
5693 				stream->timing.flags.DSC = 1;
5694 				DRM_DEBUG_DRIVER("%s: [%s] DSC is selected from SST RX\n", __func__, drm_connector->name);
5695 			}
5696 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
5697 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing);
5698 			max_supported_bw_in_kbps = link_bandwidth_kbps;
5699 			dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
5700 
5701 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
5702 					max_supported_bw_in_kbps > 0 &&
5703 					dsc_max_supported_bw_in_kbps > 0)
5704 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
5705 						dsc_caps,
5706 						aconnector->dc_link->ctx->dc->debug.dsc_min_slice_height_override,
5707 						max_dsc_target_bpp_limit_override,
5708 						dsc_max_supported_bw_in_kbps,
5709 						&stream->timing,
5710 						&stream->timing.dsc_cfg)) {
5711 					stream->timing.flags.DSC = 1;
5712 					DRM_DEBUG_DRIVER("%s: [%s] DSC is selected from DP-HDMI PCON\n",
5713 									 __func__, drm_connector->name);
5714 				}
5715 		}
5716 	}
5717 
5718 	/* Overwrite the stream flag if DSC is enabled through debugfs */
5719 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
5720 		stream->timing.flags.DSC = 1;
5721 
5722 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
5723 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
5724 
5725 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
5726 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
5727 
5728 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
5729 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
5730 }
5731 #endif /* CONFIG_DRM_AMD_DC_DCN */
5732 
5733 static struct dc_stream_state *
5734 create_stream_for_sink(struct amdgpu_dm_connector *aconnector,
5735 		       const struct drm_display_mode *drm_mode,
5736 		       const struct dm_connector_state *dm_state,
5737 		       const struct dc_stream_state *old_stream,
5738 		       int requested_bpc)
5739 {
5740 	struct drm_display_mode *preferred_mode = NULL;
5741 	struct drm_connector *drm_connector;
5742 	const struct drm_connector_state *con_state =
5743 		dm_state ? &dm_state->base : NULL;
5744 	struct dc_stream_state *stream = NULL;
5745 	struct drm_display_mode mode = *drm_mode;
5746 	struct drm_display_mode saved_mode;
5747 	struct drm_display_mode *freesync_mode = NULL;
5748 	bool native_mode_found = false;
5749 	bool recalculate_timing = false;
5750 	bool scale = dm_state ? (dm_state->scaling != RMX_OFF) : false;
5751 	int mode_refresh;
5752 	int preferred_refresh = 0;
5753 #if defined(CONFIG_DRM_AMD_DC_DCN)
5754 	struct dsc_dec_dpcd_caps dsc_caps;
5755 #endif
5756 
5757 	struct dc_sink *sink = NULL;
5758 
5759 	memset(&saved_mode, 0, sizeof(saved_mode));
5760 
5761 	if (aconnector == NULL) {
5762 		DRM_ERROR("aconnector is NULL!\n");
5763 		return stream;
5764 	}
5765 
5766 	drm_connector = &aconnector->base;
5767 
5768 	if (!aconnector->dc_sink) {
5769 		sink = create_fake_sink(aconnector);
5770 		if (!sink)
5771 			return stream;
5772 	} else {
5773 		sink = aconnector->dc_sink;
5774 		dc_sink_retain(sink);
5775 	}
5776 
5777 	stream = dc_create_stream_for_sink(sink);
5778 
5779 	if (stream == NULL) {
5780 		DRM_ERROR("Failed to create stream for sink!\n");
5781 		goto finish;
5782 	}
5783 
5784 	stream->dm_stream_context = aconnector;
5785 
5786 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
5787 		drm_connector->display_info.hdmi.scdc.scrambling.low_rates;
5788 
5789 	list_for_each_entry(preferred_mode, &aconnector->base.modes, head) {
5790 		/* Search for preferred mode */
5791 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
5792 			native_mode_found = true;
5793 			break;
5794 		}
5795 	}
5796 	if (!native_mode_found)
5797 		preferred_mode = list_first_entry_or_null(
5798 				&aconnector->base.modes,
5799 				struct drm_display_mode,
5800 				head);
5801 
5802 	mode_refresh = drm_mode_vrefresh(&mode);
5803 
5804 	if (preferred_mode == NULL) {
5805 		/*
5806 		 * This may not be an error, the use case is when we have no
5807 		 * usermode calls to reset and set mode upon hotplug. In this
5808 		 * case, we call set mode ourselves to restore the previous mode
5809 		 * and the modelist may not be filled in in time.
5810 		 */
5811 		DRM_DEBUG_DRIVER("No preferred mode found\n");
5812 	} else {
5813 		recalculate_timing = is_freesync_video_mode(&mode, aconnector);
5814 		if (recalculate_timing) {
5815 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
5816 			drm_mode_copy(&saved_mode, &mode);
5817 			drm_mode_copy(&mode, freesync_mode);
5818 		} else {
5819 			decide_crtc_timing_for_drm_display_mode(
5820 					&mode, preferred_mode, scale);
5821 
5822 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
5823 		}
5824 	}
5825 
5826 	if (recalculate_timing)
5827 		drm_mode_set_crtcinfo(&saved_mode, 0);
5828 	else if (!dm_state)
5829 		drm_mode_set_crtcinfo(&mode, 0);
5830 
5831 	/*
5832 	* If scaling is enabled and refresh rate didn't change
5833 	* we copy the vic and polarities of the old timings
5834 	*/
5835 	if (!scale || mode_refresh != preferred_refresh)
5836 		fill_stream_properties_from_drm_display_mode(
5837 			stream, &mode, &aconnector->base, con_state, NULL,
5838 			requested_bpc);
5839 	else
5840 		fill_stream_properties_from_drm_display_mode(
5841 			stream, &mode, &aconnector->base, con_state, old_stream,
5842 			requested_bpc);
5843 
5844 #if defined(CONFIG_DRM_AMD_DC_DCN)
5845 	/* SST DSC determination policy */
5846 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
5847 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
5848 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
5849 #endif
5850 
5851 	update_stream_scaling_settings(&mode, dm_state, stream);
5852 
5853 	fill_audio_info(
5854 		&stream->audio_info,
5855 		drm_connector,
5856 		sink);
5857 
5858 	update_stream_signal(stream, sink);
5859 
5860 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
5861 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket);
5862 
5863 	if (stream->link->psr_settings.psr_feature_enabled) {
5864 		//
5865 		// should decide stream support vsc sdp colorimetry capability
5866 		// before building vsc info packet
5867 		//
5868 		stream->use_vsc_sdp_for_colorimetry = false;
5869 		if (aconnector->dc_sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST) {
5870 			stream->use_vsc_sdp_for_colorimetry =
5871 				aconnector->dc_sink->is_vsc_sdp_colorimetry_supported;
5872 		} else {
5873 			if (stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED)
5874 				stream->use_vsc_sdp_for_colorimetry = true;
5875 		}
5876 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space);
5877 		aconnector->psr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
5878 
5879 	}
5880 finish:
5881 	dc_sink_release(sink);
5882 
5883 	return stream;
5884 }
5885 
5886 static enum drm_connector_status
5887 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
5888 {
5889 	bool connected;
5890 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5891 
5892 	/*
5893 	 * Notes:
5894 	 * 1. This interface is NOT called in context of HPD irq.
5895 	 * 2. This interface *is called* in context of user-mode ioctl. Which
5896 	 * makes it a bad place for *any* MST-related activity.
5897 	 */
5898 
5899 	if (aconnector->base.force == DRM_FORCE_UNSPECIFIED &&
5900 	    !aconnector->fake_enable)
5901 		connected = (aconnector->dc_sink != NULL);
5902 	else
5903 		connected = (aconnector->base.force == DRM_FORCE_ON ||
5904 				aconnector->base.force == DRM_FORCE_ON_DIGITAL);
5905 
5906 	update_subconnector_property(aconnector);
5907 
5908 	return (connected ? connector_status_connected :
5909 			connector_status_disconnected);
5910 }
5911 
5912 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
5913 					    struct drm_connector_state *connector_state,
5914 					    struct drm_property *property,
5915 					    uint64_t val)
5916 {
5917 	struct drm_device *dev = connector->dev;
5918 	struct amdgpu_device *adev = drm_to_adev(dev);
5919 	struct dm_connector_state *dm_old_state =
5920 		to_dm_connector_state(connector->state);
5921 	struct dm_connector_state *dm_new_state =
5922 		to_dm_connector_state(connector_state);
5923 
5924 	int ret = -EINVAL;
5925 
5926 	if (property == dev->mode_config.scaling_mode_property) {
5927 		enum amdgpu_rmx_type rmx_type;
5928 
5929 		switch (val) {
5930 		case DRM_MODE_SCALE_CENTER:
5931 			rmx_type = RMX_CENTER;
5932 			break;
5933 		case DRM_MODE_SCALE_ASPECT:
5934 			rmx_type = RMX_ASPECT;
5935 			break;
5936 		case DRM_MODE_SCALE_FULLSCREEN:
5937 			rmx_type = RMX_FULL;
5938 			break;
5939 		case DRM_MODE_SCALE_NONE:
5940 		default:
5941 			rmx_type = RMX_OFF;
5942 			break;
5943 		}
5944 
5945 		if (dm_old_state->scaling == rmx_type)
5946 			return 0;
5947 
5948 		dm_new_state->scaling = rmx_type;
5949 		ret = 0;
5950 	} else if (property == adev->mode_info.underscan_hborder_property) {
5951 		dm_new_state->underscan_hborder = val;
5952 		ret = 0;
5953 	} else if (property == adev->mode_info.underscan_vborder_property) {
5954 		dm_new_state->underscan_vborder = val;
5955 		ret = 0;
5956 	} else if (property == adev->mode_info.underscan_property) {
5957 		dm_new_state->underscan_enable = val;
5958 		ret = 0;
5959 	} else if (property == adev->mode_info.abm_level_property) {
5960 		dm_new_state->abm_level = val;
5961 		ret = 0;
5962 	}
5963 
5964 	return ret;
5965 }
5966 
5967 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
5968 					    const struct drm_connector_state *state,
5969 					    struct drm_property *property,
5970 					    uint64_t *val)
5971 {
5972 	struct drm_device *dev = connector->dev;
5973 	struct amdgpu_device *adev = drm_to_adev(dev);
5974 	struct dm_connector_state *dm_state =
5975 		to_dm_connector_state(state);
5976 	int ret = -EINVAL;
5977 
5978 	if (property == dev->mode_config.scaling_mode_property) {
5979 		switch (dm_state->scaling) {
5980 		case RMX_CENTER:
5981 			*val = DRM_MODE_SCALE_CENTER;
5982 			break;
5983 		case RMX_ASPECT:
5984 			*val = DRM_MODE_SCALE_ASPECT;
5985 			break;
5986 		case RMX_FULL:
5987 			*val = DRM_MODE_SCALE_FULLSCREEN;
5988 			break;
5989 		case RMX_OFF:
5990 		default:
5991 			*val = DRM_MODE_SCALE_NONE;
5992 			break;
5993 		}
5994 		ret = 0;
5995 	} else if (property == adev->mode_info.underscan_hborder_property) {
5996 		*val = dm_state->underscan_hborder;
5997 		ret = 0;
5998 	} else if (property == adev->mode_info.underscan_vborder_property) {
5999 		*val = dm_state->underscan_vborder;
6000 		ret = 0;
6001 	} else if (property == adev->mode_info.underscan_property) {
6002 		*val = dm_state->underscan_enable;
6003 		ret = 0;
6004 	} else if (property == adev->mode_info.abm_level_property) {
6005 		*val = dm_state->abm_level;
6006 		ret = 0;
6007 	}
6008 
6009 	return ret;
6010 }
6011 
6012 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
6013 {
6014 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
6015 
6016 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
6017 }
6018 
6019 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
6020 {
6021 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6022 	const struct dc_link *link = aconnector->dc_link;
6023 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
6024 	struct amdgpu_display_manager *dm = &adev->dm;
6025 	int i;
6026 
6027 	/*
6028 	 * Call only if mst_mgr was initialized before since it's not done
6029 	 * for all connector types.
6030 	 */
6031 	if (aconnector->mst_mgr.dev)
6032 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
6033 
6034 #if defined(CONFIG_BACKLIGHT_CLASS_DEVICE) ||\
6035 	defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE)
6036 	for (i = 0; i < dm->num_of_edps; i++) {
6037 		if ((link == dm->backlight_link[i]) && dm->backlight_dev[i]) {
6038 			backlight_device_unregister(dm->backlight_dev[i]);
6039 			dm->backlight_dev[i] = NULL;
6040 		}
6041 	}
6042 #endif
6043 
6044 	if (aconnector->dc_em_sink)
6045 		dc_sink_release(aconnector->dc_em_sink);
6046 	aconnector->dc_em_sink = NULL;
6047 	if (aconnector->dc_sink)
6048 		dc_sink_release(aconnector->dc_sink);
6049 	aconnector->dc_sink = NULL;
6050 
6051 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
6052 	drm_connector_unregister(connector);
6053 	drm_connector_cleanup(connector);
6054 	if (aconnector->i2c) {
6055 		i2c_del_adapter(&aconnector->i2c->base);
6056 		kfree(aconnector->i2c);
6057 	}
6058 	kfree(aconnector->dm_dp_aux.aux.name);
6059 
6060 	kfree(connector);
6061 }
6062 
6063 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
6064 {
6065 	struct dm_connector_state *state =
6066 		to_dm_connector_state(connector->state);
6067 
6068 	if (connector->state)
6069 		__drm_atomic_helper_connector_destroy_state(connector->state);
6070 
6071 	kfree(state);
6072 
6073 	state = kzalloc(sizeof(*state), GFP_KERNEL);
6074 
6075 	if (state) {
6076 		state->scaling = RMX_OFF;
6077 		state->underscan_enable = false;
6078 		state->underscan_hborder = 0;
6079 		state->underscan_vborder = 0;
6080 		state->base.max_requested_bpc = 8;
6081 		state->vcpi_slots = 0;
6082 		state->pbn = 0;
6083 
6084 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP)
6085 			state->abm_level = amdgpu_dm_abm_level;
6086 
6087 		__drm_atomic_helper_connector_reset(connector, &state->base);
6088 	}
6089 }
6090 
6091 struct drm_connector_state *
6092 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
6093 {
6094 	struct dm_connector_state *state =
6095 		to_dm_connector_state(connector->state);
6096 
6097 	struct dm_connector_state *new_state =
6098 			kmemdup(state, sizeof(*state), GFP_KERNEL);
6099 
6100 	if (!new_state)
6101 		return NULL;
6102 
6103 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
6104 
6105 	new_state->freesync_capable = state->freesync_capable;
6106 	new_state->abm_level = state->abm_level;
6107 	new_state->scaling = state->scaling;
6108 	new_state->underscan_enable = state->underscan_enable;
6109 	new_state->underscan_hborder = state->underscan_hborder;
6110 	new_state->underscan_vborder = state->underscan_vborder;
6111 	new_state->vcpi_slots = state->vcpi_slots;
6112 	new_state->pbn = state->pbn;
6113 	return &new_state->base;
6114 }
6115 
6116 static int
6117 amdgpu_dm_connector_late_register(struct drm_connector *connector)
6118 {
6119 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6120 		to_amdgpu_dm_connector(connector);
6121 	int r;
6122 
6123 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
6124 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
6125 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
6126 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
6127 		if (r)
6128 			return r;
6129 	}
6130 
6131 #if defined(CONFIG_DEBUG_FS)
6132 	connector_debugfs_init(amdgpu_dm_connector);
6133 #endif
6134 
6135 	return 0;
6136 }
6137 
6138 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
6139 	.reset = amdgpu_dm_connector_funcs_reset,
6140 	.detect = amdgpu_dm_connector_detect,
6141 	.fill_modes = drm_helper_probe_single_connector_modes,
6142 	.destroy = amdgpu_dm_connector_destroy,
6143 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
6144 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
6145 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
6146 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
6147 	.late_register = amdgpu_dm_connector_late_register,
6148 	.early_unregister = amdgpu_dm_connector_unregister
6149 };
6150 
6151 static int get_modes(struct drm_connector *connector)
6152 {
6153 	return amdgpu_dm_connector_get_modes(connector);
6154 }
6155 
6156 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
6157 {
6158 	struct dc_sink_init_data init_params = {
6159 			.link = aconnector->dc_link,
6160 			.sink_signal = SIGNAL_TYPE_VIRTUAL
6161 	};
6162 	struct edid *edid;
6163 
6164 	if (!aconnector->base.edid_blob_ptr) {
6165 		DRM_ERROR("No EDID firmware found on connector: %s ,forcing to OFF!\n",
6166 				aconnector->base.name);
6167 
6168 		aconnector->base.force = DRM_FORCE_OFF;
6169 		aconnector->base.override_edid = false;
6170 		return;
6171 	}
6172 
6173 	edid = (struct edid *) aconnector->base.edid_blob_ptr->data;
6174 
6175 	aconnector->edid = edid;
6176 
6177 	aconnector->dc_em_sink = dc_link_add_remote_sink(
6178 		aconnector->dc_link,
6179 		(uint8_t *)edid,
6180 		(edid->extensions + 1) * EDID_LENGTH,
6181 		&init_params);
6182 
6183 	if (aconnector->base.force == DRM_FORCE_ON) {
6184 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
6185 		aconnector->dc_link->local_sink :
6186 		aconnector->dc_em_sink;
6187 		dc_sink_retain(aconnector->dc_sink);
6188 	}
6189 }
6190 
6191 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
6192 {
6193 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
6194 
6195 	/*
6196 	 * In case of headless boot with force on for DP managed connector
6197 	 * Those settings have to be != 0 to get initial modeset
6198 	 */
6199 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
6200 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
6201 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
6202 	}
6203 
6204 
6205 	aconnector->base.override_edid = true;
6206 	create_eml_sink(aconnector);
6207 }
6208 
6209 struct dc_stream_state *
6210 create_validate_stream_for_sink(struct amdgpu_dm_connector *aconnector,
6211 				const struct drm_display_mode *drm_mode,
6212 				const struct dm_connector_state *dm_state,
6213 				const struct dc_stream_state *old_stream)
6214 {
6215 	struct drm_connector *connector = &aconnector->base;
6216 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
6217 	struct dc_stream_state *stream;
6218 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
6219 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
6220 	enum dc_status dc_result = DC_OK;
6221 
6222 	do {
6223 		stream = create_stream_for_sink(aconnector, drm_mode,
6224 						dm_state, old_stream,
6225 						requested_bpc);
6226 		if (stream == NULL) {
6227 			DRM_ERROR("Failed to create stream for sink!\n");
6228 			break;
6229 		}
6230 
6231 		dc_result = dc_validate_stream(adev->dm.dc, stream);
6232 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
6233 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
6234 
6235 		if (dc_result != DC_OK) {
6236 			DRM_DEBUG_KMS("Mode %dx%d (clk %d) failed DC validation with error %d (%s)\n",
6237 				      drm_mode->hdisplay,
6238 				      drm_mode->vdisplay,
6239 				      drm_mode->clock,
6240 				      dc_result,
6241 				      dc_status_to_str(dc_result));
6242 
6243 			dc_stream_release(stream);
6244 			stream = NULL;
6245 			requested_bpc -= 2; /* lower bpc to retry validation */
6246 		}
6247 
6248 	} while (stream == NULL && requested_bpc >= 6);
6249 
6250 	if (dc_result == DC_FAIL_ENC_VALIDATE && !aconnector->force_yuv420_output) {
6251 		DRM_DEBUG_KMS("Retry forcing YCbCr420 encoding\n");
6252 
6253 		aconnector->force_yuv420_output = true;
6254 		stream = create_validate_stream_for_sink(aconnector, drm_mode,
6255 						dm_state, old_stream);
6256 		aconnector->force_yuv420_output = false;
6257 	}
6258 
6259 	return stream;
6260 }
6261 
6262 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
6263 				   struct drm_display_mode *mode)
6264 {
6265 	int result = MODE_ERROR;
6266 	struct dc_sink *dc_sink;
6267 	/* TODO: Unhardcode stream count */
6268 	struct dc_stream_state *stream;
6269 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6270 
6271 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
6272 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
6273 		return result;
6274 
6275 	/*
6276 	 * Only run this the first time mode_valid is called to initilialize
6277 	 * EDID mgmt
6278 	 */
6279 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
6280 		!aconnector->dc_em_sink)
6281 		handle_edid_mgmt(aconnector);
6282 
6283 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
6284 
6285 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
6286 				aconnector->base.force != DRM_FORCE_ON) {
6287 		DRM_ERROR("dc_sink is NULL!\n");
6288 		goto fail;
6289 	}
6290 
6291 	stream = create_validate_stream_for_sink(aconnector, mode, NULL, NULL);
6292 	if (stream) {
6293 		dc_stream_release(stream);
6294 		result = MODE_OK;
6295 	}
6296 
6297 fail:
6298 	/* TODO: error handling*/
6299 	return result;
6300 }
6301 
6302 static int fill_hdr_info_packet(const struct drm_connector_state *state,
6303 				struct dc_info_packet *out)
6304 {
6305 	struct hdmi_drm_infoframe frame;
6306 	unsigned char buf[30]; /* 26 + 4 */
6307 	ssize_t len;
6308 	int ret, i;
6309 
6310 	memset(out, 0, sizeof(*out));
6311 
6312 	if (!state->hdr_output_metadata)
6313 		return 0;
6314 
6315 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
6316 	if (ret)
6317 		return ret;
6318 
6319 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
6320 	if (len < 0)
6321 		return (int)len;
6322 
6323 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
6324 	if (len != 30)
6325 		return -EINVAL;
6326 
6327 	/* Prepare the infopacket for DC. */
6328 	switch (state->connector->connector_type) {
6329 	case DRM_MODE_CONNECTOR_HDMIA:
6330 		out->hb0 = 0x87; /* type */
6331 		out->hb1 = 0x01; /* version */
6332 		out->hb2 = 0x1A; /* length */
6333 		out->sb[0] = buf[3]; /* checksum */
6334 		i = 1;
6335 		break;
6336 
6337 	case DRM_MODE_CONNECTOR_DisplayPort:
6338 	case DRM_MODE_CONNECTOR_eDP:
6339 		out->hb0 = 0x00; /* sdp id, zero */
6340 		out->hb1 = 0x87; /* type */
6341 		out->hb2 = 0x1D; /* payload len - 1 */
6342 		out->hb3 = (0x13 << 2); /* sdp version */
6343 		out->sb[0] = 0x01; /* version */
6344 		out->sb[1] = 0x1A; /* length */
6345 		i = 2;
6346 		break;
6347 
6348 	default:
6349 		return -EINVAL;
6350 	}
6351 
6352 	memcpy(&out->sb[i], &buf[4], 26);
6353 	out->valid = true;
6354 
6355 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
6356 		       sizeof(out->sb), false);
6357 
6358 	return 0;
6359 }
6360 
6361 static int
6362 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
6363 				 struct drm_atomic_state *state)
6364 {
6365 	struct drm_connector_state *new_con_state =
6366 		drm_atomic_get_new_connector_state(state, conn);
6367 	struct drm_connector_state *old_con_state =
6368 		drm_atomic_get_old_connector_state(state, conn);
6369 	struct drm_crtc *crtc = new_con_state->crtc;
6370 	struct drm_crtc_state *new_crtc_state;
6371 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
6372 	int ret;
6373 
6374 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
6375 
6376 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
6377 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
6378 		if (ret < 0)
6379 			return ret;
6380 	}
6381 
6382 	if (!crtc)
6383 		return 0;
6384 
6385 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
6386 		struct dc_info_packet hdr_infopacket;
6387 
6388 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
6389 		if (ret)
6390 			return ret;
6391 
6392 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
6393 		if (IS_ERR(new_crtc_state))
6394 			return PTR_ERR(new_crtc_state);
6395 
6396 		/*
6397 		 * DC considers the stream backends changed if the
6398 		 * static metadata changes. Forcing the modeset also
6399 		 * gives a simple way for userspace to switch from
6400 		 * 8bpc to 10bpc when setting the metadata to enter
6401 		 * or exit HDR.
6402 		 *
6403 		 * Changing the static metadata after it's been
6404 		 * set is permissible, however. So only force a
6405 		 * modeset if we're entering or exiting HDR.
6406 		 */
6407 		new_crtc_state->mode_changed =
6408 			!old_con_state->hdr_output_metadata ||
6409 			!new_con_state->hdr_output_metadata;
6410 	}
6411 
6412 	return 0;
6413 }
6414 
6415 static const struct drm_connector_helper_funcs
6416 amdgpu_dm_connector_helper_funcs = {
6417 	/*
6418 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
6419 	 * modes will be filtered by drm_mode_validate_size(), and those modes
6420 	 * are missing after user start lightdm. So we need to renew modes list.
6421 	 * in get_modes call back, not just return the modes count
6422 	 */
6423 	.get_modes = get_modes,
6424 	.mode_valid = amdgpu_dm_connector_mode_valid,
6425 	.atomic_check = amdgpu_dm_connector_atomic_check,
6426 };
6427 
6428 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
6429 {
6430 
6431 }
6432 
6433 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
6434 {
6435 	switch (display_color_depth) {
6436 	case COLOR_DEPTH_666:
6437 		return 6;
6438 	case COLOR_DEPTH_888:
6439 		return 8;
6440 	case COLOR_DEPTH_101010:
6441 		return 10;
6442 	case COLOR_DEPTH_121212:
6443 		return 12;
6444 	case COLOR_DEPTH_141414:
6445 		return 14;
6446 	case COLOR_DEPTH_161616:
6447 		return 16;
6448 	default:
6449 		break;
6450 	}
6451 	return 0;
6452 }
6453 
6454 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
6455 					  struct drm_crtc_state *crtc_state,
6456 					  struct drm_connector_state *conn_state)
6457 {
6458 	struct drm_atomic_state *state = crtc_state->state;
6459 	struct drm_connector *connector = conn_state->connector;
6460 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
6461 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
6462 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
6463 	struct drm_dp_mst_topology_mgr *mst_mgr;
6464 	struct drm_dp_mst_port *mst_port;
6465 	struct drm_dp_mst_topology_state *mst_state;
6466 	enum dc_color_depth color_depth;
6467 	int clock, bpp = 0;
6468 	bool is_y420 = false;
6469 
6470 	if (!aconnector->port || !aconnector->dc_sink)
6471 		return 0;
6472 
6473 	mst_port = aconnector->port;
6474 	mst_mgr = &aconnector->mst_port->mst_mgr;
6475 
6476 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
6477 		return 0;
6478 
6479 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
6480 	if (IS_ERR(mst_state))
6481 		return PTR_ERR(mst_state);
6482 
6483 	if (!mst_state->pbn_div)
6484 		mst_state->pbn_div = dm_mst_get_pbn_divider(aconnector->mst_port->dc_link);
6485 
6486 	if (!state->duplicated) {
6487 		int max_bpc = conn_state->max_requested_bpc;
6488 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
6489 			  aconnector->force_yuv420_output;
6490 		color_depth = convert_color_depth_from_display_info(connector,
6491 								    is_y420,
6492 								    max_bpc);
6493 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
6494 		clock = adjusted_mode->clock;
6495 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp, false);
6496 	}
6497 
6498 	dm_new_connector_state->vcpi_slots =
6499 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
6500 					      dm_new_connector_state->pbn);
6501 	if (dm_new_connector_state->vcpi_slots < 0) {
6502 		DRM_DEBUG_ATOMIC("failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
6503 		return dm_new_connector_state->vcpi_slots;
6504 	}
6505 	return 0;
6506 }
6507 
6508 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
6509 	.disable = dm_encoder_helper_disable,
6510 	.atomic_check = dm_encoder_helper_atomic_check
6511 };
6512 
6513 #if defined(CONFIG_DRM_AMD_DC_DCN)
6514 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state *state,
6515 					    struct dc_state *dc_state,
6516 					    struct dsc_mst_fairness_vars *vars)
6517 {
6518 	struct dc_stream_state *stream = NULL;
6519 	struct drm_connector *connector;
6520 	struct drm_connector_state *new_con_state;
6521 	struct amdgpu_dm_connector *aconnector;
6522 	struct dm_connector_state *dm_conn_state;
6523 	int i, j, ret;
6524 	int vcpi, pbn_div, pbn, slot_num = 0;
6525 
6526 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
6527 
6528 		aconnector = to_amdgpu_dm_connector(connector);
6529 
6530 		if (!aconnector->port)
6531 			continue;
6532 
6533 		if (!new_con_state || !new_con_state->crtc)
6534 			continue;
6535 
6536 		dm_conn_state = to_dm_connector_state(new_con_state);
6537 
6538 		for (j = 0; j < dc_state->stream_count; j++) {
6539 			stream = dc_state->streams[j];
6540 			if (!stream)
6541 				continue;
6542 
6543 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
6544 				break;
6545 
6546 			stream = NULL;
6547 		}
6548 
6549 		if (!stream)
6550 			continue;
6551 
6552 		pbn_div = dm_mst_get_pbn_divider(stream->link);
6553 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
6554 		for (j = 0; j < dc_state->stream_count; j++) {
6555 			if (vars[j].aconnector == aconnector) {
6556 				pbn = vars[j].pbn;
6557 				break;
6558 			}
6559 		}
6560 
6561 		if (j == dc_state->stream_count)
6562 			continue;
6563 
6564 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
6565 
6566 		if (stream->timing.flags.DSC != 1) {
6567 			dm_conn_state->pbn = pbn;
6568 			dm_conn_state->vcpi_slots = slot_num;
6569 
6570 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->port,
6571 							   dm_conn_state->pbn, false);
6572 			if (ret < 0)
6573 				return ret;
6574 
6575 			continue;
6576 		}
6577 
6578 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->port, pbn, true);
6579 		if (vcpi < 0)
6580 			return vcpi;
6581 
6582 		dm_conn_state->pbn = pbn;
6583 		dm_conn_state->vcpi_slots = vcpi;
6584 	}
6585 	return 0;
6586 }
6587 #endif
6588 
6589 static int to_drm_connector_type(enum amd_signal_type st)
6590 {
6591 	switch (st) {
6592 	case SIGNAL_TYPE_HDMI_TYPE_A:
6593 		return DRM_MODE_CONNECTOR_HDMIA;
6594 	case SIGNAL_TYPE_EDP:
6595 		return DRM_MODE_CONNECTOR_eDP;
6596 	case SIGNAL_TYPE_LVDS:
6597 		return DRM_MODE_CONNECTOR_LVDS;
6598 	case SIGNAL_TYPE_RGB:
6599 		return DRM_MODE_CONNECTOR_VGA;
6600 	case SIGNAL_TYPE_DISPLAY_PORT:
6601 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
6602 		return DRM_MODE_CONNECTOR_DisplayPort;
6603 	case SIGNAL_TYPE_DVI_DUAL_LINK:
6604 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
6605 		return DRM_MODE_CONNECTOR_DVID;
6606 	case SIGNAL_TYPE_VIRTUAL:
6607 		return DRM_MODE_CONNECTOR_VIRTUAL;
6608 
6609 	default:
6610 		return DRM_MODE_CONNECTOR_Unknown;
6611 	}
6612 }
6613 
6614 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
6615 {
6616 	struct drm_encoder *encoder;
6617 
6618 	/* There is only one encoder per connector */
6619 	drm_connector_for_each_possible_encoder(connector, encoder)
6620 		return encoder;
6621 
6622 	return NULL;
6623 }
6624 
6625 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
6626 {
6627 	struct drm_encoder *encoder;
6628 	struct amdgpu_encoder *amdgpu_encoder;
6629 
6630 	encoder = amdgpu_dm_connector_to_encoder(connector);
6631 
6632 	if (encoder == NULL)
6633 		return;
6634 
6635 	amdgpu_encoder = to_amdgpu_encoder(encoder);
6636 
6637 	amdgpu_encoder->native_mode.clock = 0;
6638 
6639 	if (!list_empty(&connector->probed_modes)) {
6640 		struct drm_display_mode *preferred_mode = NULL;
6641 
6642 		list_for_each_entry(preferred_mode,
6643 				    &connector->probed_modes,
6644 				    head) {
6645 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
6646 				amdgpu_encoder->native_mode = *preferred_mode;
6647 
6648 			break;
6649 		}
6650 
6651 	}
6652 }
6653 
6654 static struct drm_display_mode *
6655 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
6656 			     char *name,
6657 			     int hdisplay, int vdisplay)
6658 {
6659 	struct drm_device *dev = encoder->dev;
6660 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
6661 	struct drm_display_mode *mode = NULL;
6662 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
6663 
6664 	mode = drm_mode_duplicate(dev, native_mode);
6665 
6666 	if (mode == NULL)
6667 		return NULL;
6668 
6669 	mode->hdisplay = hdisplay;
6670 	mode->vdisplay = vdisplay;
6671 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
6672 #ifdef __linux__
6673 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
6674 #else
6675 	strncpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
6676 #endif
6677 
6678 	return mode;
6679 
6680 }
6681 
6682 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
6683 						 struct drm_connector *connector)
6684 {
6685 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
6686 	struct drm_display_mode *mode = NULL;
6687 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
6688 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6689 				to_amdgpu_dm_connector(connector);
6690 	int i;
6691 	int n;
6692 	struct mode_size {
6693 		char name[DRM_DISPLAY_MODE_LEN];
6694 		int w;
6695 		int h;
6696 	} common_modes[] = {
6697 		{  "640x480",  640,  480},
6698 		{  "800x600",  800,  600},
6699 		{ "1024x768", 1024,  768},
6700 		{ "1280x720", 1280,  720},
6701 		{ "1280x800", 1280,  800},
6702 		{"1280x1024", 1280, 1024},
6703 		{ "1440x900", 1440,  900},
6704 		{"1680x1050", 1680, 1050},
6705 		{"1600x1200", 1600, 1200},
6706 		{"1920x1080", 1920, 1080},
6707 		{"1920x1200", 1920, 1200}
6708 	};
6709 
6710 	n = ARRAY_SIZE(common_modes);
6711 
6712 	for (i = 0; i < n; i++) {
6713 		struct drm_display_mode *curmode = NULL;
6714 		bool mode_existed = false;
6715 
6716 		if (common_modes[i].w > native_mode->hdisplay ||
6717 		    common_modes[i].h > native_mode->vdisplay ||
6718 		   (common_modes[i].w == native_mode->hdisplay &&
6719 		    common_modes[i].h == native_mode->vdisplay))
6720 			continue;
6721 
6722 		list_for_each_entry(curmode, &connector->probed_modes, head) {
6723 			if (common_modes[i].w == curmode->hdisplay &&
6724 			    common_modes[i].h == curmode->vdisplay) {
6725 				mode_existed = true;
6726 				break;
6727 			}
6728 		}
6729 
6730 		if (mode_existed)
6731 			continue;
6732 
6733 		mode = amdgpu_dm_create_common_mode(encoder,
6734 				common_modes[i].name, common_modes[i].w,
6735 				common_modes[i].h);
6736 		if (!mode)
6737 			continue;
6738 
6739 		drm_mode_probed_add(connector, mode);
6740 		amdgpu_dm_connector->num_modes++;
6741 	}
6742 }
6743 
6744 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
6745 {
6746 	struct drm_encoder *encoder;
6747 	struct amdgpu_encoder *amdgpu_encoder;
6748 	const struct drm_display_mode *native_mode;
6749 
6750 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
6751 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
6752 		return;
6753 
6754 	mutex_lock(&connector->dev->mode_config.mutex);
6755 	amdgpu_dm_connector_get_modes(connector);
6756 	mutex_unlock(&connector->dev->mode_config.mutex);
6757 
6758 	encoder = amdgpu_dm_connector_to_encoder(connector);
6759 	if (!encoder)
6760 		return;
6761 
6762 	amdgpu_encoder = to_amdgpu_encoder(encoder);
6763 
6764 	native_mode = &amdgpu_encoder->native_mode;
6765 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
6766 		return;
6767 
6768 	drm_connector_set_panel_orientation_with_quirk(connector,
6769 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
6770 						       native_mode->hdisplay,
6771 						       native_mode->vdisplay);
6772 }
6773 
6774 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
6775 					      struct edid *edid)
6776 {
6777 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6778 			to_amdgpu_dm_connector(connector);
6779 
6780 	if (edid) {
6781 		/* empty probed_modes */
6782 		INIT_LIST_HEAD(&connector->probed_modes);
6783 		amdgpu_dm_connector->num_modes =
6784 				drm_add_edid_modes(connector, edid);
6785 
6786 		/* sorting the probed modes before calling function
6787 		 * amdgpu_dm_get_native_mode() since EDID can have
6788 		 * more than one preferred mode. The modes that are
6789 		 * later in the probed mode list could be of higher
6790 		 * and preferred resolution. For example, 3840x2160
6791 		 * resolution in base EDID preferred timing and 4096x2160
6792 		 * preferred resolution in DID extension block later.
6793 		 */
6794 		drm_mode_sort(&connector->probed_modes);
6795 		amdgpu_dm_get_native_mode(connector);
6796 
6797 		/* Freesync capabilities are reset by calling
6798 		 * drm_add_edid_modes() and need to be
6799 		 * restored here.
6800 		 */
6801 		amdgpu_dm_update_freesync_caps(connector, edid);
6802 	} else {
6803 		amdgpu_dm_connector->num_modes = 0;
6804 	}
6805 }
6806 
6807 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
6808 			      struct drm_display_mode *mode)
6809 {
6810 	struct drm_display_mode *m;
6811 
6812 	list_for_each_entry (m, &aconnector->base.probed_modes, head) {
6813 		if (drm_mode_equal(m, mode))
6814 			return true;
6815 	}
6816 
6817 	return false;
6818 }
6819 
6820 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
6821 {
6822 	const struct drm_display_mode *m;
6823 	struct drm_display_mode *new_mode;
6824 	uint i;
6825 	uint32_t new_modes_count = 0;
6826 
6827 	/* Standard FPS values
6828 	 *
6829 	 * 23.976       - TV/NTSC
6830 	 * 24 	        - Cinema
6831 	 * 25 	        - TV/PAL
6832 	 * 29.97        - TV/NTSC
6833 	 * 30 	        - TV/NTSC
6834 	 * 48 	        - Cinema HFR
6835 	 * 50 	        - TV/PAL
6836 	 * 60 	        - Commonly used
6837 	 * 48,72,96,120 - Multiples of 24
6838 	 */
6839 	static const uint32_t common_rates[] = {
6840 		23976, 24000, 25000, 29970, 30000,
6841 		48000, 50000, 60000, 72000, 96000, 120000
6842 	};
6843 
6844 	/*
6845 	 * Find mode with highest refresh rate with the same resolution
6846 	 * as the preferred mode. Some monitors report a preferred mode
6847 	 * with lower resolution than the highest refresh rate supported.
6848 	 */
6849 
6850 	m = get_highest_refresh_rate_mode(aconnector, true);
6851 	if (!m)
6852 		return 0;
6853 
6854 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
6855 		uint64_t target_vtotal, target_vtotal_diff;
6856 		uint64_t num, den;
6857 
6858 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
6859 			continue;
6860 
6861 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
6862 		    common_rates[i] > aconnector->max_vfreq * 1000)
6863 			continue;
6864 
6865 		num = (unsigned long long)m->clock * 1000 * 1000;
6866 		den = common_rates[i] * (unsigned long long)m->htotal;
6867 		target_vtotal = div_u64(num, den);
6868 		target_vtotal_diff = target_vtotal - m->vtotal;
6869 
6870 		/* Check for illegal modes */
6871 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
6872 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
6873 		    m->vtotal + target_vtotal_diff < m->vsync_end)
6874 			continue;
6875 
6876 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
6877 		if (!new_mode)
6878 			goto out;
6879 
6880 		new_mode->vtotal += (u16)target_vtotal_diff;
6881 		new_mode->vsync_start += (u16)target_vtotal_diff;
6882 		new_mode->vsync_end += (u16)target_vtotal_diff;
6883 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
6884 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
6885 
6886 		if (!is_duplicate_mode(aconnector, new_mode)) {
6887 			drm_mode_probed_add(&aconnector->base, new_mode);
6888 			new_modes_count += 1;
6889 		} else
6890 			drm_mode_destroy(aconnector->base.dev, new_mode);
6891 	}
6892  out:
6893 	return new_modes_count;
6894 }
6895 
6896 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
6897 						   struct edid *edid)
6898 {
6899 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6900 		to_amdgpu_dm_connector(connector);
6901 
6902 	if (!edid)
6903 		return;
6904 
6905 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
6906 		amdgpu_dm_connector->num_modes +=
6907 			add_fs_modes(amdgpu_dm_connector);
6908 }
6909 
6910 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
6911 {
6912 	struct amdgpu_dm_connector *amdgpu_dm_connector =
6913 			to_amdgpu_dm_connector(connector);
6914 	struct drm_encoder *encoder;
6915 	struct edid *edid = amdgpu_dm_connector->edid;
6916 
6917 	encoder = amdgpu_dm_connector_to_encoder(connector);
6918 
6919 	if (!drm_edid_is_valid(edid)) {
6920 		amdgpu_dm_connector->num_modes =
6921 				drm_add_modes_noedid(connector, 640, 480);
6922 	} else {
6923 		amdgpu_dm_connector_ddc_get_modes(connector, edid);
6924 		amdgpu_dm_connector_add_common_modes(encoder, connector);
6925 		amdgpu_dm_connector_add_freesync_modes(connector, edid);
6926 	}
6927 	amdgpu_dm_fbc_init(connector);
6928 
6929 	return amdgpu_dm_connector->num_modes;
6930 }
6931 
6932 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
6933 				     struct amdgpu_dm_connector *aconnector,
6934 				     int connector_type,
6935 				     struct dc_link *link,
6936 				     int link_index)
6937 {
6938 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
6939 
6940 	/*
6941 	 * Some of the properties below require access to state, like bpc.
6942 	 * Allocate some default initial connector state with our reset helper.
6943 	 */
6944 	if (aconnector->base.funcs->reset)
6945 		aconnector->base.funcs->reset(&aconnector->base);
6946 
6947 	aconnector->connector_id = link_index;
6948 	aconnector->dc_link = link;
6949 	aconnector->base.interlace_allowed = false;
6950 	aconnector->base.doublescan_allowed = false;
6951 	aconnector->base.stereo_allowed = false;
6952 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
6953 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
6954 	aconnector->audio_inst = -1;
6955 	rw_init(&aconnector->hpd_lock, "dmhpd");
6956 
6957 	/*
6958 	 * configure support HPD hot plug connector_>polled default value is 0
6959 	 * which means HPD hot plug not supported
6960 	 */
6961 	switch (connector_type) {
6962 	case DRM_MODE_CONNECTOR_HDMIA:
6963 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
6964 		aconnector->base.ycbcr_420_allowed =
6965 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
6966 		break;
6967 	case DRM_MODE_CONNECTOR_DisplayPort:
6968 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
6969 		link->link_enc = link_enc_cfg_get_link_enc(link);
6970 		ASSERT(link->link_enc);
6971 		if (link->link_enc)
6972 			aconnector->base.ycbcr_420_allowed =
6973 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
6974 		break;
6975 	case DRM_MODE_CONNECTOR_DVID:
6976 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
6977 		break;
6978 	default:
6979 		break;
6980 	}
6981 
6982 	drm_object_attach_property(&aconnector->base.base,
6983 				dm->ddev->mode_config.scaling_mode_property,
6984 				DRM_MODE_SCALE_NONE);
6985 
6986 	drm_object_attach_property(&aconnector->base.base,
6987 				adev->mode_info.underscan_property,
6988 				UNDERSCAN_OFF);
6989 	drm_object_attach_property(&aconnector->base.base,
6990 				adev->mode_info.underscan_hborder_property,
6991 				0);
6992 	drm_object_attach_property(&aconnector->base.base,
6993 				adev->mode_info.underscan_vborder_property,
6994 				0);
6995 
6996 	if (!aconnector->mst_port)
6997 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
6998 
6999 	/* This defaults to the max in the range, but we want 8bpc for non-edp. */
7000 	aconnector->base.state->max_bpc = (connector_type == DRM_MODE_CONNECTOR_eDP) ? 16 : 8;
7001 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
7002 
7003 	if (connector_type == DRM_MODE_CONNECTOR_eDP &&
7004 	    (dc_is_dmcu_initialized(adev->dm.dc) || adev->dm.dc->ctx->dmub_srv)) {
7005 		drm_object_attach_property(&aconnector->base.base,
7006 				adev->mode_info.abm_level_property, 0);
7007 	}
7008 
7009 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
7010 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
7011 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
7012 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
7013 
7014 		if (!aconnector->mst_port)
7015 			drm_connector_attach_vrr_capable_property(&aconnector->base);
7016 
7017 #ifdef CONFIG_DRM_AMD_DC_HDCP
7018 		if (adev->dm.hdcp_workqueue)
7019 			drm_connector_attach_content_protection_property(&aconnector->base, true);
7020 #endif
7021 	}
7022 }
7023 
7024 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
7025 			      struct i2c_msg *msgs, int num)
7026 {
7027 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
7028 	struct ddc_service *ddc_service = i2c->ddc_service;
7029 	struct i2c_command cmd;
7030 	int i;
7031 	int result = -EIO;
7032 
7033 	cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
7034 
7035 	if (!cmd.payloads)
7036 		return result;
7037 
7038 	cmd.number_of_payloads = num;
7039 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
7040 	cmd.speed = 100;
7041 
7042 	for (i = 0; i < num; i++) {
7043 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
7044 		cmd.payloads[i].address = msgs[i].addr;
7045 		cmd.payloads[i].length = msgs[i].len;
7046 		cmd.payloads[i].data = msgs[i].buf;
7047 	}
7048 
7049 	if (dc_submit_i2c(
7050 			ddc_service->ctx->dc,
7051 			ddc_service->link->link_index,
7052 			&cmd))
7053 		result = num;
7054 
7055 	kfree(cmd.payloads);
7056 	return result;
7057 }
7058 
7059 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
7060 {
7061 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
7062 }
7063 
7064 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
7065 	.master_xfer = amdgpu_dm_i2c_xfer,
7066 	.functionality = amdgpu_dm_i2c_func,
7067 };
7068 
7069 static struct amdgpu_i2c_adapter *
7070 create_i2c(struct ddc_service *ddc_service,
7071 	   int link_index,
7072 	   int *res)
7073 {
7074 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
7075 	struct amdgpu_i2c_adapter *i2c;
7076 
7077 	i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
7078 	if (!i2c)
7079 		return NULL;
7080 #ifdef notyet
7081 	i2c->base.owner = THIS_MODULE;
7082 	i2c->base.class = I2C_CLASS_DDC;
7083 	i2c->base.dev.parent = &adev->pdev->dev;
7084 #endif
7085 	i2c->base.algo = &amdgpu_dm_i2c_algo;
7086 	snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d", link_index);
7087 	i2c_set_adapdata(&i2c->base, i2c);
7088 	i2c->ddc_service = ddc_service;
7089 
7090 	return i2c;
7091 }
7092 
7093 
7094 /*
7095  * Note: this function assumes that dc_link_detect() was called for the
7096  * dc_link which will be represented by this aconnector.
7097  */
7098 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
7099 				    struct amdgpu_dm_connector *aconnector,
7100 				    uint32_t link_index,
7101 				    struct amdgpu_encoder *aencoder)
7102 {
7103 	int res = 0;
7104 	int connector_type;
7105 	struct dc *dc = dm->dc;
7106 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
7107 	struct amdgpu_i2c_adapter *i2c;
7108 
7109 	link->priv = aconnector;
7110 
7111 	DRM_DEBUG_DRIVER("%s()\n", __func__);
7112 
7113 	i2c = create_i2c(link->ddc, link->link_index, &res);
7114 	if (!i2c) {
7115 		DRM_ERROR("Failed to create i2c adapter data\n");
7116 		return -ENOMEM;
7117 	}
7118 
7119 	aconnector->i2c = i2c;
7120 	res = i2c_add_adapter(&i2c->base);
7121 
7122 	if (res) {
7123 		DRM_ERROR("Failed to register hw i2c %d\n", link->link_index);
7124 		goto out_free;
7125 	}
7126 
7127 	connector_type = to_drm_connector_type(link->connector_signal);
7128 
7129 	res = drm_connector_init_with_ddc(
7130 			dm->ddev,
7131 			&aconnector->base,
7132 			&amdgpu_dm_connector_funcs,
7133 			connector_type,
7134 			&i2c->base);
7135 
7136 	if (res) {
7137 		DRM_ERROR("connector_init failed\n");
7138 		aconnector->connector_id = -1;
7139 		goto out_free;
7140 	}
7141 
7142 	drm_connector_helper_add(
7143 			&aconnector->base,
7144 			&amdgpu_dm_connector_helper_funcs);
7145 
7146 	amdgpu_dm_connector_init_helper(
7147 		dm,
7148 		aconnector,
7149 		connector_type,
7150 		link,
7151 		link_index);
7152 
7153 	drm_connector_attach_encoder(
7154 		&aconnector->base, &aencoder->base);
7155 
7156 	if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
7157 		|| connector_type == DRM_MODE_CONNECTOR_eDP)
7158 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
7159 
7160 out_free:
7161 	if (res) {
7162 		kfree(i2c);
7163 		aconnector->i2c = NULL;
7164 	}
7165 	return res;
7166 }
7167 
7168 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
7169 {
7170 	switch (adev->mode_info.num_crtc) {
7171 	case 1:
7172 		return 0x1;
7173 	case 2:
7174 		return 0x3;
7175 	case 3:
7176 		return 0x7;
7177 	case 4:
7178 		return 0xf;
7179 	case 5:
7180 		return 0x1f;
7181 	case 6:
7182 	default:
7183 		return 0x3f;
7184 	}
7185 }
7186 
7187 static int amdgpu_dm_encoder_init(struct drm_device *dev,
7188 				  struct amdgpu_encoder *aencoder,
7189 				  uint32_t link_index)
7190 {
7191 	struct amdgpu_device *adev = drm_to_adev(dev);
7192 
7193 	int res = drm_encoder_init(dev,
7194 				   &aencoder->base,
7195 				   &amdgpu_dm_encoder_funcs,
7196 				   DRM_MODE_ENCODER_TMDS,
7197 				   NULL);
7198 
7199 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
7200 
7201 	if (!res)
7202 		aencoder->encoder_id = link_index;
7203 	else
7204 		aencoder->encoder_id = -1;
7205 
7206 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
7207 
7208 	return res;
7209 }
7210 
7211 static void manage_dm_interrupts(struct amdgpu_device *adev,
7212 				 struct amdgpu_crtc *acrtc,
7213 				 bool enable)
7214 {
7215 	/*
7216 	 * We have no guarantee that the frontend index maps to the same
7217 	 * backend index - some even map to more than one.
7218 	 *
7219 	 * TODO: Use a different interrupt or check DC itself for the mapping.
7220 	 */
7221 	int irq_type =
7222 		amdgpu_display_crtc_idx_to_irq_type(
7223 			adev,
7224 			acrtc->crtc_id);
7225 
7226 	if (enable) {
7227 		drm_crtc_vblank_on(&acrtc->base);
7228 		amdgpu_irq_get(
7229 			adev,
7230 			&adev->pageflip_irq,
7231 			irq_type);
7232 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
7233 		amdgpu_irq_get(
7234 			adev,
7235 			&adev->vline0_irq,
7236 			irq_type);
7237 #endif
7238 	} else {
7239 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
7240 		amdgpu_irq_put(
7241 			adev,
7242 			&adev->vline0_irq,
7243 			irq_type);
7244 #endif
7245 		amdgpu_irq_put(
7246 			adev,
7247 			&adev->pageflip_irq,
7248 			irq_type);
7249 		drm_crtc_vblank_off(&acrtc->base);
7250 	}
7251 }
7252 
7253 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
7254 				      struct amdgpu_crtc *acrtc)
7255 {
7256 	int irq_type =
7257 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
7258 
7259 	/**
7260 	 * This reads the current state for the IRQ and force reapplies
7261 	 * the setting to hardware.
7262 	 */
7263 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
7264 }
7265 
7266 static bool
7267 is_scaling_state_different(const struct dm_connector_state *dm_state,
7268 			   const struct dm_connector_state *old_dm_state)
7269 {
7270 	if (dm_state->scaling != old_dm_state->scaling)
7271 		return true;
7272 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
7273 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
7274 			return true;
7275 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
7276 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
7277 			return true;
7278 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
7279 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
7280 		return true;
7281 	return false;
7282 }
7283 
7284 #ifdef CONFIG_DRM_AMD_DC_HDCP
7285 static bool is_content_protection_different(struct drm_connector_state *state,
7286 					    const struct drm_connector_state *old_state,
7287 					    const struct drm_connector *connector, struct hdcp_workqueue *hdcp_w)
7288 {
7289 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7290 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
7291 
7292 	/* Handle: Type0/1 change */
7293 	if (old_state->hdcp_content_type != state->hdcp_content_type &&
7294 	    state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
7295 		state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7296 		return true;
7297 	}
7298 
7299 	/* CP is being re enabled, ignore this
7300 	 *
7301 	 * Handles:	ENABLED -> DESIRED
7302 	 */
7303 	if (old_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
7304 	    state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7305 		state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
7306 		return false;
7307 	}
7308 
7309 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
7310 	 *
7311 	 * Handles:	UNDESIRED -> ENABLED
7312 	 */
7313 	if (old_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
7314 	    state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
7315 		state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
7316 
7317 	/* Stream removed and re-enabled
7318 	 *
7319 	 * Can sometimes overlap with the HPD case,
7320 	 * thus set update_hdcp to false to avoid
7321 	 * setting HDCP multiple times.
7322 	 *
7323 	 * Handles:	DESIRED -> DESIRED (Special case)
7324 	 */
7325 	if (!(old_state->crtc && old_state->crtc->enabled) &&
7326 		state->crtc && state->crtc->enabled &&
7327 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
7328 		dm_con_state->update_hdcp = false;
7329 		return true;
7330 	}
7331 
7332 	/* Hot-plug, headless s3, dpms
7333 	 *
7334 	 * Only start HDCP if the display is connected/enabled.
7335 	 * update_hdcp flag will be set to false until the next
7336 	 * HPD comes in.
7337 	 *
7338 	 * Handles:	DESIRED -> DESIRED (Special case)
7339 	 */
7340 	if (dm_con_state->update_hdcp && state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
7341 	    connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
7342 		dm_con_state->update_hdcp = false;
7343 		return true;
7344 	}
7345 
7346 	/*
7347 	 * Handles:	UNDESIRED -> UNDESIRED
7348 	 *		DESIRED -> DESIRED
7349 	 *		ENABLED -> ENABLED
7350 	 */
7351 	if (old_state->content_protection == state->content_protection)
7352 		return false;
7353 
7354 	/*
7355 	 * Handles:	UNDESIRED -> DESIRED
7356 	 *		DESIRED -> UNDESIRED
7357 	 *		ENABLED -> UNDESIRED
7358 	 */
7359 	if (state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED)
7360 		return true;
7361 
7362 	/*
7363 	 * Handles:	DESIRED -> ENABLED
7364 	 */
7365 	return false;
7366 }
7367 
7368 #endif
7369 static void remove_stream(struct amdgpu_device *adev,
7370 			  struct amdgpu_crtc *acrtc,
7371 			  struct dc_stream_state *stream)
7372 {
7373 	/* this is the update mode case */
7374 
7375 	acrtc->otg_inst = -1;
7376 	acrtc->enabled = false;
7377 }
7378 
7379 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
7380 {
7381 
7382 	assert_spin_locked(&acrtc->base.dev->event_lock);
7383 	WARN_ON(acrtc->event);
7384 
7385 	acrtc->event = acrtc->base.state->event;
7386 
7387 	/* Set the flip status */
7388 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
7389 
7390 	/* Mark this event as consumed */
7391 	acrtc->base.state->event = NULL;
7392 
7393 	DC_LOG_PFLIP("crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
7394 		     acrtc->crtc_id);
7395 }
7396 
7397 static void update_freesync_state_on_stream(
7398 	struct amdgpu_display_manager *dm,
7399 	struct dm_crtc_state *new_crtc_state,
7400 	struct dc_stream_state *new_stream,
7401 	struct dc_plane_state *surface,
7402 	u32 flip_timestamp_in_us)
7403 {
7404 	struct mod_vrr_params vrr_params;
7405 	struct dc_info_packet vrr_infopacket = {0};
7406 	struct amdgpu_device *adev = dm->adev;
7407 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
7408 	unsigned long flags;
7409 	bool pack_sdp_v1_3 = false;
7410 
7411 	if (!new_stream)
7412 		return;
7413 
7414 	/*
7415 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
7416 	 * For now it's sufficient to just guard against these conditions.
7417 	 */
7418 
7419 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
7420 		return;
7421 
7422 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
7423         vrr_params = acrtc->dm_irq_params.vrr_params;
7424 
7425 	if (surface) {
7426 		mod_freesync_handle_preflip(
7427 			dm->freesync_module,
7428 			surface,
7429 			new_stream,
7430 			flip_timestamp_in_us,
7431 			&vrr_params);
7432 
7433 		if (adev->family < AMDGPU_FAMILY_AI &&
7434 		    amdgpu_dm_vrr_active(new_crtc_state)) {
7435 			mod_freesync_handle_v_update(dm->freesync_module,
7436 						     new_stream, &vrr_params);
7437 
7438 			/* Need to call this before the frame ends. */
7439 			dc_stream_adjust_vmin_vmax(dm->dc,
7440 						   new_crtc_state->stream,
7441 						   &vrr_params.adjust);
7442 		}
7443 	}
7444 
7445 	mod_freesync_build_vrr_infopacket(
7446 		dm->freesync_module,
7447 		new_stream,
7448 		&vrr_params,
7449 		PACKET_TYPE_VRR,
7450 		TRANSFER_FUNC_UNKNOWN,
7451 		&vrr_infopacket,
7452 		pack_sdp_v1_3);
7453 
7454 	new_crtc_state->freesync_vrr_info_changed |=
7455 		(memcmp(&new_crtc_state->vrr_infopacket,
7456 			&vrr_infopacket,
7457 			sizeof(vrr_infopacket)) != 0);
7458 
7459 	acrtc->dm_irq_params.vrr_params = vrr_params;
7460 	new_crtc_state->vrr_infopacket = vrr_infopacket;
7461 
7462 	new_stream->vrr_infopacket = vrr_infopacket;
7463 
7464 	if (new_crtc_state->freesync_vrr_info_changed)
7465 		DRM_DEBUG_KMS("VRR packet update: crtc=%u enabled=%d state=%d",
7466 			      new_crtc_state->base.crtc->base.id,
7467 			      (int)new_crtc_state->base.vrr_enabled,
7468 			      (int)vrr_params.state);
7469 
7470 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
7471 }
7472 
7473 static void update_stream_irq_parameters(
7474 	struct amdgpu_display_manager *dm,
7475 	struct dm_crtc_state *new_crtc_state)
7476 {
7477 	struct dc_stream_state *new_stream = new_crtc_state->stream;
7478 	struct mod_vrr_params vrr_params;
7479 	struct mod_freesync_config config = new_crtc_state->freesync_config;
7480 	struct amdgpu_device *adev = dm->adev;
7481 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
7482 	unsigned long flags;
7483 
7484 	if (!new_stream)
7485 		return;
7486 
7487 	/*
7488 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
7489 	 * For now it's sufficient to just guard against these conditions.
7490 	 */
7491 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
7492 		return;
7493 
7494 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
7495 	vrr_params = acrtc->dm_irq_params.vrr_params;
7496 
7497 	if (new_crtc_state->vrr_supported &&
7498 	    config.min_refresh_in_uhz &&
7499 	    config.max_refresh_in_uhz) {
7500 		/*
7501 		 * if freesync compatible mode was set, config.state will be set
7502 		 * in atomic check
7503 		 */
7504 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
7505 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
7506 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
7507 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
7508 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
7509 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
7510 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
7511 		} else {
7512 			config.state = new_crtc_state->base.vrr_enabled ?
7513 						     VRR_STATE_ACTIVE_VARIABLE :
7514 						     VRR_STATE_INACTIVE;
7515 		}
7516 	} else {
7517 		config.state = VRR_STATE_UNSUPPORTED;
7518 	}
7519 
7520 	mod_freesync_build_vrr_params(dm->freesync_module,
7521 				      new_stream,
7522 				      &config, &vrr_params);
7523 
7524 	new_crtc_state->freesync_config = config;
7525 	/* Copy state for access from DM IRQ handler */
7526 	acrtc->dm_irq_params.freesync_config = config;
7527 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
7528 	acrtc->dm_irq_params.vrr_params = vrr_params;
7529 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
7530 }
7531 
7532 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
7533 					    struct dm_crtc_state *new_state)
7534 {
7535 	bool old_vrr_active = amdgpu_dm_vrr_active(old_state);
7536 	bool new_vrr_active = amdgpu_dm_vrr_active(new_state);
7537 
7538 	if (!old_vrr_active && new_vrr_active) {
7539 		/* Transition VRR inactive -> active:
7540 		 * While VRR is active, we must not disable vblank irq, as a
7541 		 * reenable after disable would compute bogus vblank/pflip
7542 		 * timestamps if it likely happened inside display front-porch.
7543 		 *
7544 		 * We also need vupdate irq for the actual core vblank handling
7545 		 * at end of vblank.
7546 		 */
7547 		WARN_ON(dm_set_vupdate_irq(new_state->base.crtc, true) != 0);
7548 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
7549 		DRM_DEBUG_DRIVER("%s: crtc=%u VRR off->on: Get vblank ref\n",
7550 				 __func__, new_state->base.crtc->base.id);
7551 	} else if (old_vrr_active && !new_vrr_active) {
7552 		/* Transition VRR active -> inactive:
7553 		 * Allow vblank irq disable again for fixed refresh rate.
7554 		 */
7555 		WARN_ON(dm_set_vupdate_irq(new_state->base.crtc, false) != 0);
7556 		drm_crtc_vblank_put(new_state->base.crtc);
7557 		DRM_DEBUG_DRIVER("%s: crtc=%u VRR on->off: Drop vblank ref\n",
7558 				 __func__, new_state->base.crtc->base.id);
7559 	}
7560 }
7561 
7562 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
7563 {
7564 	struct drm_plane *plane;
7565 	struct drm_plane_state *old_plane_state;
7566 	int i;
7567 
7568 	/*
7569 	 * TODO: Make this per-stream so we don't issue redundant updates for
7570 	 * commits with multiple streams.
7571 	 */
7572 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
7573 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
7574 			handle_cursor_update(plane, old_plane_state);
7575 }
7576 
7577 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
7578 				    struct dc_state *dc_state,
7579 				    struct drm_device *dev,
7580 				    struct amdgpu_display_manager *dm,
7581 				    struct drm_crtc *pcrtc,
7582 				    bool wait_for_vblank)
7583 {
7584 	uint32_t i;
7585 	uint64_t timestamp_ns;
7586 	struct drm_plane *plane;
7587 	struct drm_plane_state *old_plane_state, *new_plane_state;
7588 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
7589 	struct drm_crtc_state *new_pcrtc_state =
7590 			drm_atomic_get_new_crtc_state(state, pcrtc);
7591 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
7592 	struct dm_crtc_state *dm_old_crtc_state =
7593 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
7594 	int planes_count = 0, vpos, hpos;
7595 	unsigned long flags;
7596 	uint32_t target_vblank, last_flip_vblank;
7597 	bool vrr_active = amdgpu_dm_vrr_active(acrtc_state);
7598 	bool cursor_update = false;
7599 	bool pflip_present = false;
7600 	struct {
7601 		struct dc_surface_update surface_updates[MAX_SURFACES];
7602 		struct dc_plane_info plane_infos[MAX_SURFACES];
7603 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
7604 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
7605 		struct dc_stream_update stream_update;
7606 	} *bundle;
7607 
7608 	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
7609 
7610 	if (!bundle) {
7611 		dm_error("Failed to allocate update bundle\n");
7612 		goto cleanup;
7613 	}
7614 
7615 	/*
7616 	 * Disable the cursor first if we're disabling all the planes.
7617 	 * It'll remain on the screen after the planes are re-enabled
7618 	 * if we don't.
7619 	 */
7620 	if (acrtc_state->active_planes == 0)
7621 		amdgpu_dm_commit_cursors(state);
7622 
7623 	/* update planes when needed */
7624 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
7625 		struct drm_crtc *crtc = new_plane_state->crtc;
7626 		struct drm_crtc_state *new_crtc_state;
7627 		struct drm_framebuffer *fb = new_plane_state->fb;
7628 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
7629 		bool plane_needs_flip;
7630 		struct dc_plane_state *dc_plane;
7631 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
7632 
7633 		/* Cursor plane is handled after stream updates */
7634 		if (plane->type == DRM_PLANE_TYPE_CURSOR) {
7635 			if ((fb && crtc == pcrtc) ||
7636 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc))
7637 				cursor_update = true;
7638 
7639 			continue;
7640 		}
7641 
7642 		if (!fb || !crtc || pcrtc != crtc)
7643 			continue;
7644 
7645 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
7646 		if (!new_crtc_state->active)
7647 			continue;
7648 
7649 		dc_plane = dm_new_plane_state->dc_state;
7650 
7651 		bundle->surface_updates[planes_count].surface = dc_plane;
7652 		if (new_pcrtc_state->color_mgmt_changed) {
7653 			bundle->surface_updates[planes_count].gamma = dc_plane->gamma_correction;
7654 			bundle->surface_updates[planes_count].in_transfer_func = dc_plane->in_transfer_func;
7655 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
7656 		}
7657 
7658 		fill_dc_scaling_info(dm->adev, new_plane_state,
7659 				     &bundle->scaling_infos[planes_count]);
7660 
7661 		bundle->surface_updates[planes_count].scaling_info =
7662 			&bundle->scaling_infos[planes_count];
7663 
7664 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
7665 
7666 		pflip_present = pflip_present || plane_needs_flip;
7667 
7668 		if (!plane_needs_flip) {
7669 			planes_count += 1;
7670 			continue;
7671 		}
7672 
7673 		fill_dc_plane_info_and_addr(
7674 			dm->adev, new_plane_state,
7675 			afb->tiling_flags,
7676 			&bundle->plane_infos[planes_count],
7677 			&bundle->flip_addrs[planes_count].address,
7678 			afb->tmz_surface, false);
7679 
7680 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
7681 				 new_plane_state->plane->index,
7682 				 bundle->plane_infos[planes_count].dcc.enable);
7683 
7684 		bundle->surface_updates[planes_count].plane_info =
7685 			&bundle->plane_infos[planes_count];
7686 
7687 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled)
7688 			fill_dc_dirty_rects(plane, old_plane_state,
7689 					    new_plane_state, new_crtc_state,
7690 					    &bundle->flip_addrs[planes_count]);
7691 
7692 		/*
7693 		 * Only allow immediate flips for fast updates that don't
7694 		 * change FB pitch, DCC state, rotation or mirroing.
7695 		 */
7696 		bundle->flip_addrs[planes_count].flip_immediate =
7697 			crtc->state->async_flip &&
7698 			acrtc_state->update_type == UPDATE_TYPE_FAST;
7699 
7700 		timestamp_ns = ktime_get_ns();
7701 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
7702 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
7703 		bundle->surface_updates[planes_count].surface = dc_plane;
7704 
7705 		if (!bundle->surface_updates[planes_count].surface) {
7706 			DRM_ERROR("No surface for CRTC: id=%d\n",
7707 					acrtc_attach->crtc_id);
7708 			continue;
7709 		}
7710 
7711 		if (plane == pcrtc->primary)
7712 			update_freesync_state_on_stream(
7713 				dm,
7714 				acrtc_state,
7715 				acrtc_state->stream,
7716 				dc_plane,
7717 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
7718 
7719 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
7720 				 __func__,
7721 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
7722 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
7723 
7724 		planes_count += 1;
7725 
7726 	}
7727 
7728 	if (pflip_present) {
7729 		if (!vrr_active) {
7730 			/* Use old throttling in non-vrr fixed refresh rate mode
7731 			 * to keep flip scheduling based on target vblank counts
7732 			 * working in a backwards compatible way, e.g., for
7733 			 * clients using the GLX_OML_sync_control extension or
7734 			 * DRI3/Present extension with defined target_msc.
7735 			 */
7736 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
7737 		}
7738 		else {
7739 			/* For variable refresh rate mode only:
7740 			 * Get vblank of last completed flip to avoid > 1 vrr
7741 			 * flips per video frame by use of throttling, but allow
7742 			 * flip programming anywhere in the possibly large
7743 			 * variable vrr vblank interval for fine-grained flip
7744 			 * timing control and more opportunity to avoid stutter
7745 			 * on late submission of flips.
7746 			 */
7747 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7748 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
7749 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7750 		}
7751 
7752 		target_vblank = last_flip_vblank + wait_for_vblank;
7753 
7754 		/*
7755 		 * Wait until we're out of the vertical blank period before the one
7756 		 * targeted by the flip
7757 		 */
7758 		while ((acrtc_attach->enabled &&
7759 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
7760 							    0, &vpos, &hpos, NULL,
7761 							    NULL, &pcrtc->hwmode)
7762 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
7763 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
7764 			(int)(target_vblank -
7765 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
7766 			usleep_range(1000, 1100);
7767 		}
7768 
7769 		/**
7770 		 * Prepare the flip event for the pageflip interrupt to handle.
7771 		 *
7772 		 * This only works in the case where we've already turned on the
7773 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
7774 		 * from 0 -> n planes we have to skip a hardware generated event
7775 		 * and rely on sending it from software.
7776 		 */
7777 		if (acrtc_attach->base.state->event &&
7778 		    acrtc_state->active_planes > 0) {
7779 			drm_crtc_vblank_get(pcrtc);
7780 
7781 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7782 
7783 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
7784 			prepare_flip_isr(acrtc_attach);
7785 
7786 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7787 		}
7788 
7789 		if (acrtc_state->stream) {
7790 			if (acrtc_state->freesync_vrr_info_changed)
7791 				bundle->stream_update.vrr_infopacket =
7792 					&acrtc_state->stream->vrr_infopacket;
7793 		}
7794 	} else if (cursor_update && acrtc_state->active_planes > 0 &&
7795 		   acrtc_attach->base.state->event) {
7796 		drm_crtc_vblank_get(pcrtc);
7797 
7798 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7799 
7800 		acrtc_attach->event = acrtc_attach->base.state->event;
7801 		acrtc_attach->base.state->event = NULL;
7802 
7803 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7804 	}
7805 
7806 	/* Update the planes if changed or disable if we don't have any. */
7807 	if ((planes_count || acrtc_state->active_planes == 0) &&
7808 		acrtc_state->stream) {
7809 		/*
7810 		 * If PSR or idle optimizations are enabled then flush out
7811 		 * any pending work before hardware programming.
7812 		 */
7813 		if (dm->vblank_control_workqueue)
7814 			flush_workqueue(dm->vblank_control_workqueue);
7815 
7816 		bundle->stream_update.stream = acrtc_state->stream;
7817 		if (new_pcrtc_state->mode_changed) {
7818 			bundle->stream_update.src = acrtc_state->stream->src;
7819 			bundle->stream_update.dst = acrtc_state->stream->dst;
7820 		}
7821 
7822 		if (new_pcrtc_state->color_mgmt_changed) {
7823 			/*
7824 			 * TODO: This isn't fully correct since we've actually
7825 			 * already modified the stream in place.
7826 			 */
7827 			bundle->stream_update.gamut_remap =
7828 				&acrtc_state->stream->gamut_remap_matrix;
7829 			bundle->stream_update.output_csc_transform =
7830 				&acrtc_state->stream->csc_color_matrix;
7831 			bundle->stream_update.out_transfer_func =
7832 				acrtc_state->stream->out_transfer_func;
7833 		}
7834 
7835 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
7836 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
7837 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
7838 
7839 		/*
7840 		 * If FreeSync state on the stream has changed then we need to
7841 		 * re-adjust the min/max bounds now that DC doesn't handle this
7842 		 * as part of commit.
7843 		 */
7844 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
7845 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
7846 			dc_stream_adjust_vmin_vmax(
7847 				dm->dc, acrtc_state->stream,
7848 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
7849 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
7850 		}
7851 		mutex_lock(&dm->dc_lock);
7852 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
7853 				acrtc_state->stream->link->psr_settings.psr_allow_active)
7854 			amdgpu_dm_psr_disable(acrtc_state->stream);
7855 
7856 		dc_commit_updates_for_stream(dm->dc,
7857 						     bundle->surface_updates,
7858 						     planes_count,
7859 						     acrtc_state->stream,
7860 						     &bundle->stream_update,
7861 						     dc_state);
7862 
7863 		/**
7864 		 * Enable or disable the interrupts on the backend.
7865 		 *
7866 		 * Most pipes are put into power gating when unused.
7867 		 *
7868 		 * When power gating is enabled on a pipe we lose the
7869 		 * interrupt enablement state when power gating is disabled.
7870 		 *
7871 		 * So we need to update the IRQ control state in hardware
7872 		 * whenever the pipe turns on (since it could be previously
7873 		 * power gated) or off (since some pipes can't be power gated
7874 		 * on some ASICs).
7875 		 */
7876 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
7877 			dm_update_pflip_irq_state(drm_to_adev(dev),
7878 						  acrtc_attach);
7879 
7880 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) &&
7881 				acrtc_state->stream->link->psr_settings.psr_version != DC_PSR_VERSION_UNSUPPORTED &&
7882 				!acrtc_state->stream->link->psr_settings.psr_feature_enabled)
7883 			amdgpu_dm_link_setup_psr(acrtc_state->stream);
7884 
7885 		/* Decrement skip count when PSR is enabled and we're doing fast updates. */
7886 		if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
7887 		    acrtc_state->stream->link->psr_settings.psr_feature_enabled) {
7888 			struct amdgpu_dm_connector *aconn =
7889 				(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
7890 
7891 			if (aconn->psr_skip_count > 0)
7892 				aconn->psr_skip_count--;
7893 
7894 			/* Allow PSR when skip count is 0. */
7895 			acrtc_attach->dm_irq_params.allow_psr_entry = !aconn->psr_skip_count;
7896 
7897 			/*
7898 			 * If sink supports PSR SU, there is no need to rely on
7899 			 * a vblank event disable request to enable PSR. PSR SU
7900 			 * can be enabled immediately once OS demonstrates an
7901 			 * adequate number of fast atomic commits to notify KMD
7902 			 * of update events. See `vblank_control_worker()`.
7903 			 */
7904 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
7905 			    acrtc_attach->dm_irq_params.allow_psr_entry &&
7906 			    !acrtc_state->stream->link->psr_settings.psr_allow_active)
7907 				amdgpu_dm_psr_enable(acrtc_state->stream);
7908 		} else {
7909 			acrtc_attach->dm_irq_params.allow_psr_entry = false;
7910 		}
7911 
7912 		mutex_unlock(&dm->dc_lock);
7913 	}
7914 
7915 	/*
7916 	 * Update cursor state *after* programming all the planes.
7917 	 * This avoids redundant programming in the case where we're going
7918 	 * to be disabling a single plane - those pipes are being disabled.
7919 	 */
7920 	if (acrtc_state->active_planes)
7921 		amdgpu_dm_commit_cursors(state);
7922 
7923 cleanup:
7924 	kfree(bundle);
7925 }
7926 
7927 static void amdgpu_dm_commit_audio(struct drm_device *dev,
7928 				   struct drm_atomic_state *state)
7929 {
7930 	struct amdgpu_device *adev = drm_to_adev(dev);
7931 	struct amdgpu_dm_connector *aconnector;
7932 	struct drm_connector *connector;
7933 	struct drm_connector_state *old_con_state, *new_con_state;
7934 	struct drm_crtc_state *new_crtc_state;
7935 	struct dm_crtc_state *new_dm_crtc_state;
7936 	const struct dc_stream_status *status;
7937 	int i, inst;
7938 
7939 	/* Notify device removals. */
7940 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
7941 		if (old_con_state->crtc != new_con_state->crtc) {
7942 			/* CRTC changes require notification. */
7943 			goto notify;
7944 		}
7945 
7946 		if (!new_con_state->crtc)
7947 			continue;
7948 
7949 		new_crtc_state = drm_atomic_get_new_crtc_state(
7950 			state, new_con_state->crtc);
7951 
7952 		if (!new_crtc_state)
7953 			continue;
7954 
7955 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
7956 			continue;
7957 
7958 	notify:
7959 		aconnector = to_amdgpu_dm_connector(connector);
7960 
7961 		mutex_lock(&adev->dm.audio_lock);
7962 		inst = aconnector->audio_inst;
7963 		aconnector->audio_inst = -1;
7964 		mutex_unlock(&adev->dm.audio_lock);
7965 
7966 		amdgpu_dm_audio_eld_notify(adev, inst);
7967 	}
7968 
7969 	/* Notify audio device additions. */
7970 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
7971 		if (!new_con_state->crtc)
7972 			continue;
7973 
7974 		new_crtc_state = drm_atomic_get_new_crtc_state(
7975 			state, new_con_state->crtc);
7976 
7977 		if (!new_crtc_state)
7978 			continue;
7979 
7980 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
7981 			continue;
7982 
7983 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
7984 		if (!new_dm_crtc_state->stream)
7985 			continue;
7986 
7987 		status = dc_stream_get_status(new_dm_crtc_state->stream);
7988 		if (!status)
7989 			continue;
7990 
7991 		aconnector = to_amdgpu_dm_connector(connector);
7992 
7993 		mutex_lock(&adev->dm.audio_lock);
7994 		inst = status->audio_inst;
7995 		aconnector->audio_inst = inst;
7996 		mutex_unlock(&adev->dm.audio_lock);
7997 
7998 		amdgpu_dm_audio_eld_notify(adev, inst);
7999 	}
8000 }
8001 
8002 /*
8003  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
8004  * @crtc_state: the DRM CRTC state
8005  * @stream_state: the DC stream state.
8006  *
8007  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
8008  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
8009  */
8010 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
8011 						struct dc_stream_state *stream_state)
8012 {
8013 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
8014 }
8015 
8016 /**
8017  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
8018  * @state: The atomic state to commit
8019  *
8020  * This will tell DC to commit the constructed DC state from atomic_check,
8021  * programming the hardware. Any failures here implies a hardware failure, since
8022  * atomic check should have filtered anything non-kosher.
8023  */
8024 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
8025 {
8026 	struct drm_device *dev = state->dev;
8027 	struct amdgpu_device *adev = drm_to_adev(dev);
8028 	struct amdgpu_display_manager *dm = &adev->dm;
8029 	struct dm_atomic_state *dm_state;
8030 	struct dc_state *dc_state = NULL, *dc_state_temp = NULL;
8031 	uint32_t i, j;
8032 	struct drm_crtc *crtc;
8033 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
8034 	unsigned long flags;
8035 	bool wait_for_vblank = true;
8036 	struct drm_connector *connector;
8037 	struct drm_connector_state *old_con_state, *new_con_state;
8038 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
8039 	int crtc_disable_count = 0;
8040 	bool mode_set_reset_required = false;
8041 	int r;
8042 
8043 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
8044 
8045 	r = drm_atomic_helper_wait_for_fences(dev, state, false);
8046 	if (unlikely(r))
8047 		DRM_ERROR("Waiting for fences timed out!");
8048 
8049 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
8050 	drm_dp_mst_atomic_wait_for_dependencies(state);
8051 
8052 	dm_state = dm_atomic_get_new_state(state);
8053 	if (dm_state && dm_state->context) {
8054 		dc_state = dm_state->context;
8055 	} else {
8056 		/* No state changes, retain current state. */
8057 		dc_state_temp = dc_create_state(dm->dc);
8058 		ASSERT(dc_state_temp);
8059 		dc_state = dc_state_temp;
8060 		dc_resource_state_copy_construct_current(dm->dc, dc_state);
8061 	}
8062 
8063 	for_each_oldnew_crtc_in_state (state, crtc, old_crtc_state,
8064 				       new_crtc_state, i) {
8065 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8066 
8067 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8068 
8069 		if (old_crtc_state->active &&
8070 		    (!new_crtc_state->active ||
8071 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8072 			manage_dm_interrupts(adev, acrtc, false);
8073 			dc_stream_release(dm_old_crtc_state->stream);
8074 		}
8075 	}
8076 
8077 	drm_atomic_helper_calc_timestamping_constants(state);
8078 
8079 	/* update changed items */
8080 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
8081 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8082 
8083 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8084 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8085 
8086 		drm_dbg_state(state->dev,
8087 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
8088 			"planes_changed:%d, mode_changed:%d,active_changed:%d,"
8089 			"connectors_changed:%d\n",
8090 			acrtc->crtc_id,
8091 			new_crtc_state->enable,
8092 			new_crtc_state->active,
8093 			new_crtc_state->planes_changed,
8094 			new_crtc_state->mode_changed,
8095 			new_crtc_state->active_changed,
8096 			new_crtc_state->connectors_changed);
8097 
8098 		/* Disable cursor if disabling crtc */
8099 		if (old_crtc_state->active && !new_crtc_state->active) {
8100 			struct dc_cursor_position position;
8101 
8102 			memset(&position, 0, sizeof(position));
8103 			mutex_lock(&dm->dc_lock);
8104 			dc_stream_set_cursor_position(dm_old_crtc_state->stream, &position);
8105 			mutex_unlock(&dm->dc_lock);
8106 		}
8107 
8108 		/* Copy all transient state flags into dc state */
8109 		if (dm_new_crtc_state->stream) {
8110 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
8111 							    dm_new_crtc_state->stream);
8112 		}
8113 
8114 		/* handles headless hotplug case, updating new_state and
8115 		 * aconnector as needed
8116 		 */
8117 
8118 		if (modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
8119 
8120 			DRM_DEBUG_ATOMIC("Atomic commit: SET crtc id %d: [%p]\n", acrtc->crtc_id, acrtc);
8121 
8122 			if (!dm_new_crtc_state->stream) {
8123 				/*
8124 				 * this could happen because of issues with
8125 				 * userspace notifications delivery.
8126 				 * In this case userspace tries to set mode on
8127 				 * display which is disconnected in fact.
8128 				 * dc_sink is NULL in this case on aconnector.
8129 				 * We expect reset mode will come soon.
8130 				 *
8131 				 * This can also happen when unplug is done
8132 				 * during resume sequence ended
8133 				 *
8134 				 * In this case, we want to pretend we still
8135 				 * have a sink to keep the pipe running so that
8136 				 * hw state is consistent with the sw state
8137 				 */
8138 				DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
8139 						__func__, acrtc->base.base.id);
8140 				continue;
8141 			}
8142 
8143 			if (dm_old_crtc_state->stream)
8144 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
8145 
8146 			pm_runtime_get_noresume(dev->dev);
8147 
8148 			acrtc->enabled = true;
8149 			acrtc->hw_mode = new_crtc_state->mode;
8150 			crtc->hwmode = new_crtc_state->mode;
8151 			mode_set_reset_required = true;
8152 		} else if (modereset_required(new_crtc_state)) {
8153 			DRM_DEBUG_ATOMIC("Atomic commit: RESET. crtc id %d:[%p]\n", acrtc->crtc_id, acrtc);
8154 			/* i.e. reset mode */
8155 			if (dm_old_crtc_state->stream)
8156 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
8157 
8158 			mode_set_reset_required = true;
8159 		}
8160 	} /* for_each_crtc_in_state() */
8161 
8162 	if (dc_state) {
8163 		/* if there mode set or reset, disable eDP PSR */
8164 		if (mode_set_reset_required) {
8165 			if (dm->vblank_control_workqueue)
8166 				flush_workqueue(dm->vblank_control_workqueue);
8167 
8168 			amdgpu_dm_psr_disable_all(dm);
8169 		}
8170 
8171 		dm_enable_per_frame_crtc_master_sync(dc_state);
8172 		mutex_lock(&dm->dc_lock);
8173 		WARN_ON(!dc_commit_state(dm->dc, dc_state));
8174 
8175 		/* Allow idle optimization when vblank count is 0 for display off */
8176 		if (dm->active_vblank_irq_count == 0)
8177 			dc_allow_idle_optimizations(dm->dc, true);
8178 		mutex_unlock(&dm->dc_lock);
8179 	}
8180 
8181 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
8182 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8183 
8184 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8185 
8186 		if (dm_new_crtc_state->stream != NULL) {
8187 			const struct dc_stream_status *status =
8188 					dc_stream_get_status(dm_new_crtc_state->stream);
8189 
8190 			if (!status)
8191 				status = dc_stream_get_status_from_state(dc_state,
8192 									 dm_new_crtc_state->stream);
8193 			if (!status)
8194 				DC_ERR("got no status for stream %p on acrtc%p\n", dm_new_crtc_state->stream, acrtc);
8195 			else
8196 				acrtc->otg_inst = status->primary_otg_inst;
8197 		}
8198 	}
8199 #ifdef CONFIG_DRM_AMD_DC_HDCP
8200 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8201 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8202 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8203 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8204 
8205 		new_crtc_state = NULL;
8206 
8207 		if (acrtc)
8208 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8209 
8210 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8211 
8212 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
8213 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
8214 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
8215 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
8216 			dm_new_con_state->update_hdcp = true;
8217 			continue;
8218 		}
8219 
8220 		if (is_content_protection_different(new_con_state, old_con_state, connector, adev->dm.hdcp_workqueue))
8221 			hdcp_update_display(
8222 				adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
8223 				new_con_state->hdcp_content_type,
8224 				new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED);
8225 	}
8226 #endif
8227 
8228 	/* Handle connector state changes */
8229 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
8230 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
8231 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
8232 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
8233 		struct dc_surface_update dummy_updates[MAX_SURFACES];
8234 		struct dc_stream_update stream_update;
8235 		struct dc_info_packet hdr_packet;
8236 		struct dc_stream_status *status = NULL;
8237 		bool abm_changed, hdr_changed, scaling_changed;
8238 
8239 		memset(&dummy_updates, 0, sizeof(dummy_updates));
8240 		memset(&stream_update, 0, sizeof(stream_update));
8241 
8242 		if (acrtc) {
8243 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
8244 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
8245 		}
8246 
8247 		/* Skip any modesets/resets */
8248 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
8249 			continue;
8250 
8251 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8252 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8253 
8254 		scaling_changed = is_scaling_state_different(dm_new_con_state,
8255 							     dm_old_con_state);
8256 
8257 		abm_changed = dm_new_crtc_state->abm_level !=
8258 			      dm_old_crtc_state->abm_level;
8259 
8260 		hdr_changed =
8261 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
8262 
8263 		if (!scaling_changed && !abm_changed && !hdr_changed)
8264 			continue;
8265 
8266 		stream_update.stream = dm_new_crtc_state->stream;
8267 		if (scaling_changed) {
8268 			update_stream_scaling_settings(&dm_new_con_state->base.crtc->mode,
8269 					dm_new_con_state, dm_new_crtc_state->stream);
8270 
8271 			stream_update.src = dm_new_crtc_state->stream->src;
8272 			stream_update.dst = dm_new_crtc_state->stream->dst;
8273 		}
8274 
8275 		if (abm_changed) {
8276 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
8277 
8278 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
8279 		}
8280 
8281 		if (hdr_changed) {
8282 			fill_hdr_info_packet(new_con_state, &hdr_packet);
8283 			stream_update.hdr_static_metadata = &hdr_packet;
8284 		}
8285 
8286 		status = dc_stream_get_status(dm_new_crtc_state->stream);
8287 
8288 		if (WARN_ON(!status))
8289 			continue;
8290 
8291 		WARN_ON(!status->plane_count);
8292 
8293 		/*
8294 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
8295 		 * Here we create an empty update on each plane.
8296 		 * To fix this, DC should permit updating only stream properties.
8297 		 */
8298 		for (j = 0; j < status->plane_count; j++)
8299 			dummy_updates[j].surface = status->plane_states[0];
8300 
8301 
8302 		mutex_lock(&dm->dc_lock);
8303 		dc_commit_updates_for_stream(dm->dc,
8304 						     dummy_updates,
8305 						     status->plane_count,
8306 						     dm_new_crtc_state->stream,
8307 						     &stream_update,
8308 						     dc_state);
8309 		mutex_unlock(&dm->dc_lock);
8310 	}
8311 
8312 	/**
8313 	 * Enable interrupts for CRTCs that are newly enabled or went through
8314 	 * a modeset. It was intentionally deferred until after the front end
8315 	 * state was modified to wait until the OTG was on and so the IRQ
8316 	 * handlers didn't access stale or invalid state.
8317 	 */
8318 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
8319 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
8320 #ifdef CONFIG_DEBUG_FS
8321 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
8322 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
8323 		struct crc_rd_work *crc_rd_wrk;
8324 #endif
8325 #endif
8326 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
8327 		if (old_crtc_state->active && !new_crtc_state->active)
8328 			crtc_disable_count++;
8329 
8330 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8331 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8332 
8333 		/* For freesync config update on crtc state and params for irq */
8334 		update_stream_irq_parameters(dm, dm_new_crtc_state);
8335 
8336 #ifdef CONFIG_DEBUG_FS
8337 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
8338 		crc_rd_wrk = dm->crc_rd_wrk;
8339 #endif
8340 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8341 		cur_crc_src = acrtc->dm_irq_params.crc_src;
8342 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8343 #endif
8344 
8345 		if (new_crtc_state->active &&
8346 		    (!old_crtc_state->active ||
8347 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8348 			dc_stream_retain(dm_new_crtc_state->stream);
8349 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
8350 			manage_dm_interrupts(adev, acrtc, true);
8351 		}
8352 		/* Handle vrr on->off / off->on transitions */
8353 		amdgpu_dm_handle_vrr_transition(dm_old_crtc_state, dm_new_crtc_state);
8354 
8355 #ifdef CONFIG_DEBUG_FS
8356 		if (new_crtc_state->active &&
8357 		    (!old_crtc_state->active ||
8358 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
8359 			/**
8360 			 * Frontend may have changed so reapply the CRC capture
8361 			 * settings for the stream.
8362 			 */
8363 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
8364 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
8365 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
8366 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8367 					acrtc->dm_irq_params.crc_window.update_win = true;
8368 					acrtc->dm_irq_params.crc_window.skip_frame_cnt = 2;
8369 					spin_lock_irq(&crc_rd_wrk->crc_rd_work_lock);
8370 					crc_rd_wrk->crtc = crtc;
8371 					spin_unlock_irq(&crc_rd_wrk->crc_rd_work_lock);
8372 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8373 				}
8374 #endif
8375 				if (amdgpu_dm_crtc_configure_crc_source(
8376 					crtc, dm_new_crtc_state, cur_crc_src))
8377 					DRM_DEBUG_DRIVER("Failed to configure crc source");
8378 			}
8379 		}
8380 #endif
8381 	}
8382 
8383 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
8384 		if (new_crtc_state->async_flip)
8385 			wait_for_vblank = false;
8386 
8387 	/* update planes when needed per crtc*/
8388 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
8389 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8390 
8391 		if (dm_new_crtc_state->stream)
8392 			amdgpu_dm_commit_planes(state, dc_state, dev,
8393 						dm, crtc, wait_for_vblank);
8394 	}
8395 
8396 	/* Update audio instances for each connector. */
8397 	amdgpu_dm_commit_audio(dev, state);
8398 
8399 	/* restore the backlight level */
8400 	for (i = 0; i < dm->num_of_edps; i++) {
8401 		if (dm->backlight_dev[i] &&
8402 		    (dm->actual_brightness[i] != dm->brightness[i]))
8403 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
8404 	}
8405 
8406 	/*
8407 	 * send vblank event on all events not handled in flip and
8408 	 * mark consumed event for drm_atomic_helper_commit_hw_done
8409 	 */
8410 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
8411 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
8412 
8413 		if (new_crtc_state->event)
8414 			drm_send_event_locked(dev, &new_crtc_state->event->base);
8415 
8416 		new_crtc_state->event = NULL;
8417 	}
8418 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
8419 
8420 	/* Signal HW programming completion */
8421 	drm_atomic_helper_commit_hw_done(state);
8422 
8423 	if (wait_for_vblank)
8424 		drm_atomic_helper_wait_for_flip_done(dev, state);
8425 
8426 	drm_atomic_helper_cleanup_planes(dev, state);
8427 
8428 	/* return the stolen vga memory back to VRAM */
8429 	if (!adev->mman.keep_stolen_vga_memory)
8430 		amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
8431 	amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
8432 
8433 	/*
8434 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
8435 	 * so we can put the GPU into runtime suspend if we're not driving any
8436 	 * displays anymore
8437 	 */
8438 	for (i = 0; i < crtc_disable_count; i++)
8439 		pm_runtime_put_autosuspend(dev->dev);
8440 	pm_runtime_mark_last_busy(dev->dev);
8441 
8442 	if (dc_state_temp)
8443 		dc_release_state(dc_state_temp);
8444 }
8445 
8446 static int dm_force_atomic_commit(struct drm_connector *connector)
8447 {
8448 	int ret = 0;
8449 	struct drm_device *ddev = connector->dev;
8450 	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
8451 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
8452 	struct drm_plane *plane = disconnected_acrtc->base.primary;
8453 	struct drm_connector_state *conn_state;
8454 	struct drm_crtc_state *crtc_state;
8455 	struct drm_plane_state *plane_state;
8456 
8457 	if (!state)
8458 		return -ENOMEM;
8459 
8460 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
8461 
8462 	/* Construct an atomic state to restore previous display setting */
8463 
8464 	/*
8465 	 * Attach connectors to drm_atomic_state
8466 	 */
8467 	conn_state = drm_atomic_get_connector_state(state, connector);
8468 
8469 	ret = PTR_ERR_OR_ZERO(conn_state);
8470 	if (ret)
8471 		goto out;
8472 
8473 	/* Attach crtc to drm_atomic_state*/
8474 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
8475 
8476 	ret = PTR_ERR_OR_ZERO(crtc_state);
8477 	if (ret)
8478 		goto out;
8479 
8480 	/* force a restore */
8481 	crtc_state->mode_changed = true;
8482 
8483 	/* Attach plane to drm_atomic_state */
8484 	plane_state = drm_atomic_get_plane_state(state, plane);
8485 
8486 	ret = PTR_ERR_OR_ZERO(plane_state);
8487 	if (ret)
8488 		goto out;
8489 
8490 	/* Call commit internally with the state we just constructed */
8491 	ret = drm_atomic_commit(state);
8492 
8493 out:
8494 	drm_atomic_state_put(state);
8495 	if (ret)
8496 		DRM_ERROR("Restoring old state failed with %i\n", ret);
8497 
8498 	return ret;
8499 }
8500 
8501 /*
8502  * This function handles all cases when set mode does not come upon hotplug.
8503  * This includes when a display is unplugged then plugged back into the
8504  * same port and when running without usermode desktop manager supprot
8505  */
8506 void dm_restore_drm_connector_state(struct drm_device *dev,
8507 				    struct drm_connector *connector)
8508 {
8509 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8510 	struct amdgpu_crtc *disconnected_acrtc;
8511 	struct dm_crtc_state *acrtc_state;
8512 
8513 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
8514 		return;
8515 
8516 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
8517 	if (!disconnected_acrtc)
8518 		return;
8519 
8520 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
8521 	if (!acrtc_state->stream)
8522 		return;
8523 
8524 	/*
8525 	 * If the previous sink is not released and different from the current,
8526 	 * we deduce we are in a state where we can not rely on usermode call
8527 	 * to turn on the display, so we do it here
8528 	 */
8529 	if (acrtc_state->stream->sink != aconnector->dc_sink)
8530 		dm_force_atomic_commit(&aconnector->base);
8531 }
8532 
8533 /*
8534  * Grabs all modesetting locks to serialize against any blocking commits,
8535  * Waits for completion of all non blocking commits.
8536  */
8537 static int do_aquire_global_lock(struct drm_device *dev,
8538 				 struct drm_atomic_state *state)
8539 {
8540 	struct drm_crtc *crtc;
8541 	struct drm_crtc_commit *commit;
8542 	long ret;
8543 
8544 	/*
8545 	 * Adding all modeset locks to aquire_ctx will
8546 	 * ensure that when the framework release it the
8547 	 * extra locks we are locking here will get released to
8548 	 */
8549 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
8550 	if (ret)
8551 		return ret;
8552 
8553 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
8554 		spin_lock(&crtc->commit_lock);
8555 		commit = list_first_entry_or_null(&crtc->commit_list,
8556 				struct drm_crtc_commit, commit_entry);
8557 		if (commit)
8558 			drm_crtc_commit_get(commit);
8559 		spin_unlock(&crtc->commit_lock);
8560 
8561 		if (!commit)
8562 			continue;
8563 
8564 		/*
8565 		 * Make sure all pending HW programming completed and
8566 		 * page flips done
8567 		 */
8568 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
8569 
8570 		if (ret > 0)
8571 			ret = wait_for_completion_interruptible_timeout(
8572 					&commit->flip_done, 10*HZ);
8573 
8574 		if (ret == 0)
8575 			DRM_ERROR("[CRTC:%d:%s] hw_done or flip_done "
8576 				  "timed out\n", crtc->base.id, crtc->name);
8577 
8578 		drm_crtc_commit_put(commit);
8579 	}
8580 
8581 	return ret < 0 ? ret : 0;
8582 }
8583 
8584 static void get_freesync_config_for_crtc(
8585 	struct dm_crtc_state *new_crtc_state,
8586 	struct dm_connector_state *new_con_state)
8587 {
8588 	struct mod_freesync_config config = {0};
8589 	struct amdgpu_dm_connector *aconnector =
8590 			to_amdgpu_dm_connector(new_con_state->base.connector);
8591 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
8592 	int vrefresh = drm_mode_vrefresh(mode);
8593 	bool fs_vid_mode = false;
8594 
8595 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
8596 					vrefresh >= aconnector->min_vfreq &&
8597 					vrefresh <= aconnector->max_vfreq;
8598 
8599 	if (new_crtc_state->vrr_supported) {
8600 		new_crtc_state->stream->ignore_msa_timing_param = true;
8601 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
8602 
8603 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
8604 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
8605 		config.vsif_supported = true;
8606 		config.btr = true;
8607 
8608 		if (fs_vid_mode) {
8609 			config.state = VRR_STATE_ACTIVE_FIXED;
8610 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
8611 			goto out;
8612 		} else if (new_crtc_state->base.vrr_enabled) {
8613 			config.state = VRR_STATE_ACTIVE_VARIABLE;
8614 		} else {
8615 			config.state = VRR_STATE_INACTIVE;
8616 		}
8617 	}
8618 out:
8619 	new_crtc_state->freesync_config = config;
8620 }
8621 
8622 static void reset_freesync_config_for_crtc(
8623 	struct dm_crtc_state *new_crtc_state)
8624 {
8625 	new_crtc_state->vrr_supported = false;
8626 
8627 	memset(&new_crtc_state->vrr_infopacket, 0,
8628 	       sizeof(new_crtc_state->vrr_infopacket));
8629 }
8630 
8631 static bool
8632 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
8633 				 struct drm_crtc_state *new_crtc_state)
8634 {
8635 	const struct drm_display_mode *old_mode, *new_mode;
8636 
8637 	if (!old_crtc_state || !new_crtc_state)
8638 		return false;
8639 
8640 	old_mode = &old_crtc_state->mode;
8641 	new_mode = &new_crtc_state->mode;
8642 
8643 	if (old_mode->clock       == new_mode->clock &&
8644 	    old_mode->hdisplay    == new_mode->hdisplay &&
8645 	    old_mode->vdisplay    == new_mode->vdisplay &&
8646 	    old_mode->htotal      == new_mode->htotal &&
8647 	    old_mode->vtotal      != new_mode->vtotal &&
8648 	    old_mode->hsync_start == new_mode->hsync_start &&
8649 	    old_mode->vsync_start != new_mode->vsync_start &&
8650 	    old_mode->hsync_end   == new_mode->hsync_end &&
8651 	    old_mode->vsync_end   != new_mode->vsync_end &&
8652 	    old_mode->hskew       == new_mode->hskew &&
8653 	    old_mode->vscan       == new_mode->vscan &&
8654 	    (old_mode->vsync_end - old_mode->vsync_start) ==
8655 	    (new_mode->vsync_end - new_mode->vsync_start))
8656 		return true;
8657 
8658 	return false;
8659 }
8660 
8661 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state) {
8662 	uint64_t num, den, res;
8663 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
8664 
8665 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
8666 
8667 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
8668 	den = (unsigned long long)new_crtc_state->mode.htotal *
8669 	      (unsigned long long)new_crtc_state->mode.vtotal;
8670 
8671 	res = div_u64(num, den);
8672 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
8673 }
8674 
8675 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
8676 			 struct drm_atomic_state *state,
8677 			 struct drm_crtc *crtc,
8678 			 struct drm_crtc_state *old_crtc_state,
8679 			 struct drm_crtc_state *new_crtc_state,
8680 			 bool enable,
8681 			 bool *lock_and_validation_needed)
8682 {
8683 	struct dm_atomic_state *dm_state = NULL;
8684 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
8685 	struct dc_stream_state *new_stream;
8686 	int ret = 0;
8687 
8688 	/*
8689 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
8690 	 * update changed items
8691 	 */
8692 	struct amdgpu_crtc *acrtc = NULL;
8693 	struct amdgpu_dm_connector *aconnector = NULL;
8694 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
8695 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
8696 
8697 	new_stream = NULL;
8698 
8699 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
8700 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
8701 	acrtc = to_amdgpu_crtc(crtc);
8702 	aconnector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
8703 
8704 	/* TODO This hack should go away */
8705 	if (aconnector && enable) {
8706 		/* Make sure fake sink is created in plug-in scenario */
8707 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
8708 							    &aconnector->base);
8709 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
8710 							    &aconnector->base);
8711 
8712 		if (IS_ERR(drm_new_conn_state)) {
8713 			ret = PTR_ERR_OR_ZERO(drm_new_conn_state);
8714 			goto fail;
8715 		}
8716 
8717 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
8718 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
8719 
8720 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8721 			goto skip_modeset;
8722 
8723 		new_stream = create_validate_stream_for_sink(aconnector,
8724 							     &new_crtc_state->mode,
8725 							     dm_new_conn_state,
8726 							     dm_old_crtc_state->stream);
8727 
8728 		/*
8729 		 * we can have no stream on ACTION_SET if a display
8730 		 * was disconnected during S3, in this case it is not an
8731 		 * error, the OS will be updated after detection, and
8732 		 * will do the right thing on next atomic commit
8733 		 */
8734 
8735 		if (!new_stream) {
8736 			DRM_DEBUG_DRIVER("%s: Failed to create new stream for crtc %d\n",
8737 					__func__, acrtc->base.base.id);
8738 			ret = -ENOMEM;
8739 			goto fail;
8740 		}
8741 
8742 		/*
8743 		 * TODO: Check VSDB bits to decide whether this should
8744 		 * be enabled or not.
8745 		 */
8746 		new_stream->triggered_crtc_reset.enabled =
8747 			dm->force_timing_sync;
8748 
8749 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
8750 
8751 		ret = fill_hdr_info_packet(drm_new_conn_state,
8752 					   &new_stream->hdr_static_metadata);
8753 		if (ret)
8754 			goto fail;
8755 
8756 		/*
8757 		 * If we already removed the old stream from the context
8758 		 * (and set the new stream to NULL) then we can't reuse
8759 		 * the old stream even if the stream and scaling are unchanged.
8760 		 * We'll hit the BUG_ON and black screen.
8761 		 *
8762 		 * TODO: Refactor this function to allow this check to work
8763 		 * in all conditions.
8764 		 */
8765 		if (dm_new_crtc_state->stream &&
8766 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
8767 			goto skip_modeset;
8768 
8769 		if (dm_new_crtc_state->stream &&
8770 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
8771 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
8772 			new_crtc_state->mode_changed = false;
8773 			DRM_DEBUG_DRIVER("Mode change not required, setting mode_changed to %d",
8774 					 new_crtc_state->mode_changed);
8775 		}
8776 	}
8777 
8778 	/* mode_changed flag may get updated above, need to check again */
8779 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
8780 		goto skip_modeset;
8781 
8782 	drm_dbg_state(state->dev,
8783 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, "
8784 		"planes_changed:%d, mode_changed:%d,active_changed:%d,"
8785 		"connectors_changed:%d\n",
8786 		acrtc->crtc_id,
8787 		new_crtc_state->enable,
8788 		new_crtc_state->active,
8789 		new_crtc_state->planes_changed,
8790 		new_crtc_state->mode_changed,
8791 		new_crtc_state->active_changed,
8792 		new_crtc_state->connectors_changed);
8793 
8794 	/* Remove stream for any changed/disabled CRTC */
8795 	if (!enable) {
8796 
8797 		if (!dm_old_crtc_state->stream)
8798 			goto skip_modeset;
8799 
8800 		if (dm_new_crtc_state->stream &&
8801 		    is_timing_unchanged_for_freesync(new_crtc_state,
8802 						     old_crtc_state)) {
8803 			new_crtc_state->mode_changed = false;
8804 			DRM_DEBUG_DRIVER(
8805 				"Mode change not required for front porch change, "
8806 				"setting mode_changed to %d",
8807 				new_crtc_state->mode_changed);
8808 
8809 			set_freesync_fixed_config(dm_new_crtc_state);
8810 
8811 			goto skip_modeset;
8812 		} else if (aconnector &&
8813 			   is_freesync_video_mode(&new_crtc_state->mode,
8814 						  aconnector)) {
8815 			struct drm_display_mode *high_mode;
8816 
8817 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
8818 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode)) {
8819 				set_freesync_fixed_config(dm_new_crtc_state);
8820 			}
8821 		}
8822 
8823 		ret = dm_atomic_get_state(state, &dm_state);
8824 		if (ret)
8825 			goto fail;
8826 
8827 		DRM_DEBUG_DRIVER("Disabling DRM crtc: %d\n",
8828 				crtc->base.id);
8829 
8830 		/* i.e. reset mode */
8831 		if (dc_remove_stream_from_ctx(
8832 				dm->dc,
8833 				dm_state->context,
8834 				dm_old_crtc_state->stream) != DC_OK) {
8835 			ret = -EINVAL;
8836 			goto fail;
8837 		}
8838 
8839 		dc_stream_release(dm_old_crtc_state->stream);
8840 		dm_new_crtc_state->stream = NULL;
8841 
8842 		reset_freesync_config_for_crtc(dm_new_crtc_state);
8843 
8844 		*lock_and_validation_needed = true;
8845 
8846 	} else {/* Add stream for any updated/enabled CRTC */
8847 		/*
8848 		 * Quick fix to prevent NULL pointer on new_stream when
8849 		 * added MST connectors not found in existing crtc_state in the chained mode
8850 		 * TODO: need to dig out the root cause of that
8851 		 */
8852 		if (!aconnector)
8853 			goto skip_modeset;
8854 
8855 		if (modereset_required(new_crtc_state))
8856 			goto skip_modeset;
8857 
8858 		if (modeset_required(new_crtc_state, new_stream,
8859 				     dm_old_crtc_state->stream)) {
8860 
8861 			WARN_ON(dm_new_crtc_state->stream);
8862 
8863 			ret = dm_atomic_get_state(state, &dm_state);
8864 			if (ret)
8865 				goto fail;
8866 
8867 			dm_new_crtc_state->stream = new_stream;
8868 
8869 			dc_stream_retain(new_stream);
8870 
8871 			DRM_DEBUG_ATOMIC("Enabling DRM crtc: %d\n",
8872 					 crtc->base.id);
8873 
8874 			if (dc_add_stream_to_ctx(
8875 					dm->dc,
8876 					dm_state->context,
8877 					dm_new_crtc_state->stream) != DC_OK) {
8878 				ret = -EINVAL;
8879 				goto fail;
8880 			}
8881 
8882 			*lock_and_validation_needed = true;
8883 		}
8884 	}
8885 
8886 skip_modeset:
8887 	/* Release extra reference */
8888 	if (new_stream)
8889 		 dc_stream_release(new_stream);
8890 
8891 	/*
8892 	 * We want to do dc stream updates that do not require a
8893 	 * full modeset below.
8894 	 */
8895 	if (!(enable && aconnector && new_crtc_state->active))
8896 		return 0;
8897 	/*
8898 	 * Given above conditions, the dc state cannot be NULL because:
8899 	 * 1. We're in the process of enabling CRTCs (just been added
8900 	 *    to the dc context, or already is on the context)
8901 	 * 2. Has a valid connector attached, and
8902 	 * 3. Is currently active and enabled.
8903 	 * => The dc stream state currently exists.
8904 	 */
8905 	BUG_ON(dm_new_crtc_state->stream == NULL);
8906 
8907 	/* Scaling or underscan settings */
8908 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
8909 				drm_atomic_crtc_needs_modeset(new_crtc_state))
8910 		update_stream_scaling_settings(
8911 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
8912 
8913 	/* ABM settings */
8914 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
8915 
8916 	/*
8917 	 * Color management settings. We also update color properties
8918 	 * when a modeset is needed, to ensure it gets reprogrammed.
8919 	 */
8920 	if (dm_new_crtc_state->base.color_mgmt_changed ||
8921 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
8922 		ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
8923 		if (ret)
8924 			goto fail;
8925 	}
8926 
8927 	/* Update Freesync settings. */
8928 	get_freesync_config_for_crtc(dm_new_crtc_state,
8929 				     dm_new_conn_state);
8930 
8931 	return ret;
8932 
8933 fail:
8934 	if (new_stream)
8935 		dc_stream_release(new_stream);
8936 	return ret;
8937 }
8938 
8939 static bool should_reset_plane(struct drm_atomic_state *state,
8940 			       struct drm_plane *plane,
8941 			       struct drm_plane_state *old_plane_state,
8942 			       struct drm_plane_state *new_plane_state)
8943 {
8944 	struct drm_plane *other;
8945 	struct drm_plane_state *old_other_state, *new_other_state;
8946 	struct drm_crtc_state *new_crtc_state;
8947 	int i;
8948 
8949 	/*
8950 	 * TODO: Remove this hack once the checks below are sufficient
8951 	 * enough to determine when we need to reset all the planes on
8952 	 * the stream.
8953 	 */
8954 	if (state->allow_modeset)
8955 		return true;
8956 
8957 	/* Exit early if we know that we're adding or removing the plane. */
8958 	if (old_plane_state->crtc != new_plane_state->crtc)
8959 		return true;
8960 
8961 	/* old crtc == new_crtc == NULL, plane not in context. */
8962 	if (!new_plane_state->crtc)
8963 		return false;
8964 
8965 	new_crtc_state =
8966 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
8967 
8968 	if (!new_crtc_state)
8969 		return true;
8970 
8971 	/* CRTC Degamma changes currently require us to recreate planes. */
8972 	if (new_crtc_state->color_mgmt_changed)
8973 		return true;
8974 
8975 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
8976 		return true;
8977 
8978 	/*
8979 	 * If there are any new primary or overlay planes being added or
8980 	 * removed then the z-order can potentially change. To ensure
8981 	 * correct z-order and pipe acquisition the current DC architecture
8982 	 * requires us to remove and recreate all existing planes.
8983 	 *
8984 	 * TODO: Come up with a more elegant solution for this.
8985 	 */
8986 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
8987 		struct amdgpu_framebuffer *old_afb, *new_afb;
8988 		if (other->type == DRM_PLANE_TYPE_CURSOR)
8989 			continue;
8990 
8991 		if (old_other_state->crtc != new_plane_state->crtc &&
8992 		    new_other_state->crtc != new_plane_state->crtc)
8993 			continue;
8994 
8995 		if (old_other_state->crtc != new_other_state->crtc)
8996 			return true;
8997 
8998 		/* Src/dst size and scaling updates. */
8999 		if (old_other_state->src_w != new_other_state->src_w ||
9000 		    old_other_state->src_h != new_other_state->src_h ||
9001 		    old_other_state->crtc_w != new_other_state->crtc_w ||
9002 		    old_other_state->crtc_h != new_other_state->crtc_h)
9003 			return true;
9004 
9005 		/* Rotation / mirroring updates. */
9006 		if (old_other_state->rotation != new_other_state->rotation)
9007 			return true;
9008 
9009 		/* Blending updates. */
9010 		if (old_other_state->pixel_blend_mode !=
9011 		    new_other_state->pixel_blend_mode)
9012 			return true;
9013 
9014 		/* Alpha updates. */
9015 		if (old_other_state->alpha != new_other_state->alpha)
9016 			return true;
9017 
9018 		/* Colorspace changes. */
9019 		if (old_other_state->color_range != new_other_state->color_range ||
9020 		    old_other_state->color_encoding != new_other_state->color_encoding)
9021 			return true;
9022 
9023 		/* Framebuffer checks fall at the end. */
9024 		if (!old_other_state->fb || !new_other_state->fb)
9025 			continue;
9026 
9027 		/* Pixel format changes can require bandwidth updates. */
9028 		if (old_other_state->fb->format != new_other_state->fb->format)
9029 			return true;
9030 
9031 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
9032 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
9033 
9034 		/* Tiling and DCC changes also require bandwidth updates. */
9035 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
9036 		    old_afb->base.modifier != new_afb->base.modifier)
9037 			return true;
9038 	}
9039 
9040 	return false;
9041 }
9042 
9043 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
9044 			      struct drm_plane_state *new_plane_state,
9045 			      struct drm_framebuffer *fb)
9046 {
9047 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
9048 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
9049 	unsigned int pitch;
9050 	bool linear;
9051 
9052 	if (fb->width > new_acrtc->max_cursor_width ||
9053 	    fb->height > new_acrtc->max_cursor_height) {
9054 		DRM_DEBUG_ATOMIC("Bad cursor FB size %dx%d\n",
9055 				 new_plane_state->fb->width,
9056 				 new_plane_state->fb->height);
9057 		return -EINVAL;
9058 	}
9059 	if (new_plane_state->src_w != fb->width << 16 ||
9060 	    new_plane_state->src_h != fb->height << 16) {
9061 		DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
9062 		return -EINVAL;
9063 	}
9064 
9065 	/* Pitch in pixels */
9066 	pitch = fb->pitches[0] / fb->format->cpp[0];
9067 
9068 	if (fb->width != pitch) {
9069 		DRM_DEBUG_ATOMIC("Cursor FB width %d doesn't match pitch %d",
9070 				 fb->width, pitch);
9071 		return -EINVAL;
9072 	}
9073 
9074 	switch (pitch) {
9075 	case 64:
9076 	case 128:
9077 	case 256:
9078 		/* FB pitch is supported by cursor plane */
9079 		break;
9080 	default:
9081 		DRM_DEBUG_ATOMIC("Bad cursor FB pitch %d px\n", pitch);
9082 		return -EINVAL;
9083 	}
9084 
9085 	/* Core DRM takes care of checking FB modifiers, so we only need to
9086 	 * check tiling flags when the FB doesn't have a modifier. */
9087 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
9088 		if (adev->family < AMDGPU_FAMILY_AI) {
9089 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
9090 			         AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
9091 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
9092 		} else {
9093 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
9094 		}
9095 		if (!linear) {
9096 			DRM_DEBUG_ATOMIC("Cursor FB not linear");
9097 			return -EINVAL;
9098 		}
9099 	}
9100 
9101 	return 0;
9102 }
9103 
9104 static int dm_update_plane_state(struct dc *dc,
9105 				 struct drm_atomic_state *state,
9106 				 struct drm_plane *plane,
9107 				 struct drm_plane_state *old_plane_state,
9108 				 struct drm_plane_state *new_plane_state,
9109 				 bool enable,
9110 				 bool *lock_and_validation_needed)
9111 {
9112 
9113 	struct dm_atomic_state *dm_state = NULL;
9114 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
9115 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9116 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
9117 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
9118 	struct amdgpu_crtc *new_acrtc;
9119 	bool needs_reset;
9120 	int ret = 0;
9121 
9122 
9123 	new_plane_crtc = new_plane_state->crtc;
9124 	old_plane_crtc = old_plane_state->crtc;
9125 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
9126 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
9127 
9128 	if (plane->type == DRM_PLANE_TYPE_CURSOR) {
9129 		if (!enable || !new_plane_crtc ||
9130 			drm_atomic_plane_disabling(plane->state, new_plane_state))
9131 			return 0;
9132 
9133 		new_acrtc = to_amdgpu_crtc(new_plane_crtc);
9134 
9135 		if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
9136 			DRM_DEBUG_ATOMIC("Cropping not supported for cursor plane\n");
9137 			return -EINVAL;
9138 		}
9139 
9140 		if (new_plane_state->fb) {
9141 			ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
9142 						 new_plane_state->fb);
9143 			if (ret)
9144 				return ret;
9145 		}
9146 
9147 		return 0;
9148 	}
9149 
9150 	needs_reset = should_reset_plane(state, plane, old_plane_state,
9151 					 new_plane_state);
9152 
9153 	/* Remove any changed/removed planes */
9154 	if (!enable) {
9155 		if (!needs_reset)
9156 			return 0;
9157 
9158 		if (!old_plane_crtc)
9159 			return 0;
9160 
9161 		old_crtc_state = drm_atomic_get_old_crtc_state(
9162 				state, old_plane_crtc);
9163 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9164 
9165 		if (!dm_old_crtc_state->stream)
9166 			return 0;
9167 
9168 		DRM_DEBUG_ATOMIC("Disabling DRM plane: %d on DRM crtc %d\n",
9169 				plane->base.id, old_plane_crtc->base.id);
9170 
9171 		ret = dm_atomic_get_state(state, &dm_state);
9172 		if (ret)
9173 			return ret;
9174 
9175 		if (!dc_remove_plane_from_context(
9176 				dc,
9177 				dm_old_crtc_state->stream,
9178 				dm_old_plane_state->dc_state,
9179 				dm_state->context)) {
9180 
9181 			return -EINVAL;
9182 		}
9183 
9184 
9185 		dc_plane_state_release(dm_old_plane_state->dc_state);
9186 		dm_new_plane_state->dc_state = NULL;
9187 
9188 		*lock_and_validation_needed = true;
9189 
9190 	} else { /* Add new planes */
9191 		struct dc_plane_state *dc_new_plane_state;
9192 
9193 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
9194 			return 0;
9195 
9196 		if (!new_plane_crtc)
9197 			return 0;
9198 
9199 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
9200 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9201 
9202 		if (!dm_new_crtc_state->stream)
9203 			return 0;
9204 
9205 		if (!needs_reset)
9206 			return 0;
9207 
9208 		ret = dm_plane_helper_check_state(new_plane_state, new_crtc_state);
9209 		if (ret)
9210 			return ret;
9211 
9212 		WARN_ON(dm_new_plane_state->dc_state);
9213 
9214 		dc_new_plane_state = dc_create_plane_state(dc);
9215 		if (!dc_new_plane_state)
9216 			return -ENOMEM;
9217 
9218 		DRM_DEBUG_ATOMIC("Enabling DRM plane: %d on DRM crtc %d\n",
9219 				 plane->base.id, new_plane_crtc->base.id);
9220 
9221 		ret = fill_dc_plane_attributes(
9222 			drm_to_adev(new_plane_crtc->dev),
9223 			dc_new_plane_state,
9224 			new_plane_state,
9225 			new_crtc_state);
9226 		if (ret) {
9227 			dc_plane_state_release(dc_new_plane_state);
9228 			return ret;
9229 		}
9230 
9231 		ret = dm_atomic_get_state(state, &dm_state);
9232 		if (ret) {
9233 			dc_plane_state_release(dc_new_plane_state);
9234 			return ret;
9235 		}
9236 
9237 		/*
9238 		 * Any atomic check errors that occur after this will
9239 		 * not need a release. The plane state will be attached
9240 		 * to the stream, and therefore part of the atomic
9241 		 * state. It'll be released when the atomic state is
9242 		 * cleaned.
9243 		 */
9244 		if (!dc_add_plane_to_context(
9245 				dc,
9246 				dm_new_crtc_state->stream,
9247 				dc_new_plane_state,
9248 				dm_state->context)) {
9249 
9250 			dc_plane_state_release(dc_new_plane_state);
9251 			return -EINVAL;
9252 		}
9253 
9254 		dm_new_plane_state->dc_state = dc_new_plane_state;
9255 
9256 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
9257 
9258 		/* Tell DC to do a full surface update every time there
9259 		 * is a plane change. Inefficient, but works for now.
9260 		 */
9261 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
9262 
9263 		*lock_and_validation_needed = true;
9264 	}
9265 
9266 
9267 	return ret;
9268 }
9269 
9270 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
9271 				       int *src_w, int *src_h)
9272 {
9273 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
9274 	case DRM_MODE_ROTATE_90:
9275 	case DRM_MODE_ROTATE_270:
9276 		*src_w = plane_state->src_h >> 16;
9277 		*src_h = plane_state->src_w >> 16;
9278 		break;
9279 	case DRM_MODE_ROTATE_0:
9280 	case DRM_MODE_ROTATE_180:
9281 	default:
9282 		*src_w = plane_state->src_w >> 16;
9283 		*src_h = plane_state->src_h >> 16;
9284 		break;
9285 	}
9286 }
9287 
9288 static int dm_check_crtc_cursor(struct drm_atomic_state *state,
9289 				struct drm_crtc *crtc,
9290 				struct drm_crtc_state *new_crtc_state)
9291 {
9292 	struct drm_plane *cursor = crtc->cursor, *underlying;
9293 	struct drm_plane_state *new_cursor_state, *new_underlying_state;
9294 	int i;
9295 	int cursor_scale_w, cursor_scale_h, underlying_scale_w, underlying_scale_h;
9296 	int cursor_src_w, cursor_src_h;
9297 	int underlying_src_w, underlying_src_h;
9298 
9299 	/* On DCE and DCN there is no dedicated hardware cursor plane. We get a
9300 	 * cursor per pipe but it's going to inherit the scaling and
9301 	 * positioning from the underlying pipe. Check the cursor plane's
9302 	 * blending properties match the underlying planes'. */
9303 
9304 	new_cursor_state = drm_atomic_get_new_plane_state(state, cursor);
9305 	if (!new_cursor_state || !new_cursor_state->fb) {
9306 		return 0;
9307 	}
9308 
9309 	dm_get_oriented_plane_size(new_cursor_state, &cursor_src_w, &cursor_src_h);
9310 	cursor_scale_w = new_cursor_state->crtc_w * 1000 / cursor_src_w;
9311 	cursor_scale_h = new_cursor_state->crtc_h * 1000 / cursor_src_h;
9312 
9313 	for_each_new_plane_in_state_reverse(state, underlying, new_underlying_state, i) {
9314 		/* Narrow down to non-cursor planes on the same CRTC as the cursor */
9315 		if (new_underlying_state->crtc != crtc || underlying == crtc->cursor)
9316 			continue;
9317 
9318 		/* Ignore disabled planes */
9319 		if (!new_underlying_state->fb)
9320 			continue;
9321 
9322 		dm_get_oriented_plane_size(new_underlying_state,
9323 					   &underlying_src_w, &underlying_src_h);
9324 		underlying_scale_w = new_underlying_state->crtc_w * 1000 / underlying_src_w;
9325 		underlying_scale_h = new_underlying_state->crtc_h * 1000 / underlying_src_h;
9326 
9327 		if (cursor_scale_w != underlying_scale_w ||
9328 		    cursor_scale_h != underlying_scale_h) {
9329 			drm_dbg_atomic(crtc->dev,
9330 				       "Cursor [PLANE:%d:%s] scaling doesn't match underlying [PLANE:%d:%s]\n",
9331 				       cursor->base.id, cursor->name, underlying->base.id, underlying->name);
9332 			return -EINVAL;
9333 		}
9334 
9335 		/* If this plane covers the whole CRTC, no need to check planes underneath */
9336 		if (new_underlying_state->crtc_x <= 0 &&
9337 		    new_underlying_state->crtc_y <= 0 &&
9338 		    new_underlying_state->crtc_x + new_underlying_state->crtc_w >= new_crtc_state->mode.hdisplay &&
9339 		    new_underlying_state->crtc_y + new_underlying_state->crtc_h >= new_crtc_state->mode.vdisplay)
9340 			break;
9341 	}
9342 
9343 	return 0;
9344 }
9345 
9346 #if defined(CONFIG_DRM_AMD_DC_DCN)
9347 static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
9348 {
9349 	struct drm_connector *connector;
9350 	struct drm_connector_state *conn_state, *old_conn_state;
9351 	struct amdgpu_dm_connector *aconnector = NULL;
9352 	int i;
9353 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
9354 		if (!conn_state->crtc)
9355 			conn_state = old_conn_state;
9356 
9357 		if (conn_state->crtc != crtc)
9358 			continue;
9359 
9360 		aconnector = to_amdgpu_dm_connector(connector);
9361 		if (!aconnector->port || !aconnector->mst_port)
9362 			aconnector = NULL;
9363 		else
9364 			break;
9365 	}
9366 
9367 	if (!aconnector)
9368 		return 0;
9369 
9370 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_port->mst_mgr);
9371 }
9372 #endif
9373 
9374 /**
9375  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
9376  *
9377  * @dev: The DRM device
9378  * @state: The atomic state to commit
9379  *
9380  * Validate that the given atomic state is programmable by DC into hardware.
9381  * This involves constructing a &struct dc_state reflecting the new hardware
9382  * state we wish to commit, then querying DC to see if it is programmable. It's
9383  * important not to modify the existing DC state. Otherwise, atomic_check
9384  * may unexpectedly commit hardware changes.
9385  *
9386  * When validating the DC state, it's important that the right locks are
9387  * acquired. For full updates case which removes/adds/updates streams on one
9388  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
9389  * that any such full update commit will wait for completion of any outstanding
9390  * flip using DRMs synchronization events.
9391  *
9392  * Note that DM adds the affected connectors for all CRTCs in state, when that
9393  * might not seem necessary. This is because DC stream creation requires the
9394  * DC sink, which is tied to the DRM connector state. Cleaning this up should
9395  * be possible but non-trivial - a possible TODO item.
9396  *
9397  * Return: -Error code if validation failed.
9398  */
9399 static int amdgpu_dm_atomic_check(struct drm_device *dev,
9400 				  struct drm_atomic_state *state)
9401 {
9402 	struct amdgpu_device *adev = drm_to_adev(dev);
9403 	struct dm_atomic_state *dm_state = NULL;
9404 	struct dc *dc = adev->dm.dc;
9405 	struct drm_connector *connector;
9406 	struct drm_connector_state *old_con_state, *new_con_state;
9407 	struct drm_crtc *crtc;
9408 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
9409 	struct drm_plane *plane;
9410 	struct drm_plane_state *old_plane_state, *new_plane_state;
9411 	enum dc_status status;
9412 	int ret, i;
9413 	bool lock_and_validation_needed = false;
9414 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
9415 #if defined(CONFIG_DRM_AMD_DC_DCN)
9416 	struct dsc_mst_fairness_vars vars[MAX_PIPES];
9417 #endif
9418 
9419 	trace_amdgpu_dm_atomic_check_begin(state);
9420 
9421 	ret = drm_atomic_helper_check_modeset(dev, state);
9422 	if (ret) {
9423 		DRM_DEBUG_DRIVER("drm_atomic_helper_check_modeset() failed\n");
9424 		goto fail;
9425 	}
9426 
9427 	/* Check connector changes */
9428 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9429 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
9430 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
9431 
9432 		/* Skip connectors that are disabled or part of modeset already. */
9433 		if (!new_con_state->crtc)
9434 			continue;
9435 
9436 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
9437 		if (IS_ERR(new_crtc_state)) {
9438 			DRM_DEBUG_DRIVER("drm_atomic_get_crtc_state() failed\n");
9439 			ret = PTR_ERR(new_crtc_state);
9440 			goto fail;
9441 		}
9442 
9443 		if (dm_old_con_state->abm_level !=
9444 		    dm_new_con_state->abm_level)
9445 			new_crtc_state->connectors_changed = true;
9446 	}
9447 
9448 #if defined(CONFIG_DRM_AMD_DC_DCN)
9449 	if (dc_resource_is_dsc_encoding_supported(dc)) {
9450 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9451 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
9452 				ret = add_affected_mst_dsc_crtcs(state, crtc);
9453 				if (ret) {
9454 					DRM_DEBUG_DRIVER("add_affected_mst_dsc_crtcs() failed\n");
9455 					goto fail;
9456 				}
9457 			}
9458 		}
9459 	}
9460 #endif
9461 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9462 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
9463 
9464 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
9465 		    !new_crtc_state->color_mgmt_changed &&
9466 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
9467 			dm_old_crtc_state->dsc_force_changed == false)
9468 			continue;
9469 
9470 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
9471 		if (ret) {
9472 			DRM_DEBUG_DRIVER("amdgpu_dm_verify_lut_sizes() failed\n");
9473 			goto fail;
9474 		}
9475 
9476 		if (!new_crtc_state->enable)
9477 			continue;
9478 
9479 		ret = drm_atomic_add_affected_connectors(state, crtc);
9480 		if (ret) {
9481 			DRM_DEBUG_DRIVER("drm_atomic_add_affected_connectors() failed\n");
9482 			goto fail;
9483 		}
9484 
9485 		ret = drm_atomic_add_affected_planes(state, crtc);
9486 		if (ret) {
9487 			DRM_DEBUG_DRIVER("drm_atomic_add_affected_planes() failed\n");
9488 			goto fail;
9489 		}
9490 
9491 		if (dm_old_crtc_state->dsc_force_changed)
9492 			new_crtc_state->mode_changed = true;
9493 	}
9494 
9495 	/*
9496 	 * Add all primary and overlay planes on the CRTC to the state
9497 	 * whenever a plane is enabled to maintain correct z-ordering
9498 	 * and to enable fast surface updates.
9499 	 */
9500 	drm_for_each_crtc(crtc, dev) {
9501 		bool modified = false;
9502 
9503 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
9504 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
9505 				continue;
9506 
9507 			if (new_plane_state->crtc == crtc ||
9508 			    old_plane_state->crtc == crtc) {
9509 				modified = true;
9510 				break;
9511 			}
9512 		}
9513 
9514 		if (!modified)
9515 			continue;
9516 
9517 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
9518 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
9519 				continue;
9520 
9521 			new_plane_state =
9522 				drm_atomic_get_plane_state(state, plane);
9523 
9524 			if (IS_ERR(new_plane_state)) {
9525 				ret = PTR_ERR(new_plane_state);
9526 				DRM_DEBUG_DRIVER("new_plane_state is BAD\n");
9527 				goto fail;
9528 			}
9529 		}
9530 	}
9531 
9532 	/*
9533 	 * DC consults the zpos (layer_index in DC terminology) to determine the
9534 	 * hw plane on which to enable the hw cursor (see
9535 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
9536 	 * atomic state, so call drm helper to normalize zpos.
9537 	 */
9538 	drm_atomic_normalize_zpos(dev, state);
9539 
9540 	/* Remove exiting planes if they are modified */
9541 	for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
9542 		ret = dm_update_plane_state(dc, state, plane,
9543 					    old_plane_state,
9544 					    new_plane_state,
9545 					    false,
9546 					    &lock_and_validation_needed);
9547 		if (ret) {
9548 			DRM_DEBUG_DRIVER("dm_update_plane_state() failed\n");
9549 			goto fail;
9550 		}
9551 	}
9552 
9553 	/* Disable all crtcs which require disable */
9554 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9555 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
9556 					   old_crtc_state,
9557 					   new_crtc_state,
9558 					   false,
9559 					   &lock_and_validation_needed);
9560 		if (ret) {
9561 			DRM_DEBUG_DRIVER("DISABLE: dm_update_crtc_state() failed\n");
9562 			goto fail;
9563 		}
9564 	}
9565 
9566 	/* Enable all crtcs which require enable */
9567 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
9568 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
9569 					   old_crtc_state,
9570 					   new_crtc_state,
9571 					   true,
9572 					   &lock_and_validation_needed);
9573 		if (ret) {
9574 			DRM_DEBUG_DRIVER("ENABLE: dm_update_crtc_state() failed\n");
9575 			goto fail;
9576 		}
9577 	}
9578 
9579 	/* Add new/modified planes */
9580 	for_each_oldnew_plane_in_state_reverse(state, plane, old_plane_state, new_plane_state, i) {
9581 		ret = dm_update_plane_state(dc, state, plane,
9582 					    old_plane_state,
9583 					    new_plane_state,
9584 					    true,
9585 					    &lock_and_validation_needed);
9586 		if (ret) {
9587 			DRM_DEBUG_DRIVER("dm_update_plane_state() failed\n");
9588 			goto fail;
9589 		}
9590 	}
9591 
9592 #if defined(CONFIG_DRM_AMD_DC_DCN)
9593 	if (dc_resource_is_dsc_encoding_supported(dc)) {
9594 		ret = pre_validate_dsc(state, &dm_state, vars);
9595 		if (ret != 0)
9596 			goto fail;
9597 	}
9598 #endif
9599 
9600 	/* Run this here since we want to validate the streams we created */
9601 	ret = drm_atomic_helper_check_planes(dev, state);
9602 	if (ret) {
9603 		DRM_DEBUG_DRIVER("drm_atomic_helper_check_planes() failed\n");
9604 		goto fail;
9605 	}
9606 
9607 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
9608 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
9609 		if (dm_new_crtc_state->mpo_requested)
9610 			DRM_DEBUG_DRIVER("MPO enablement requested on crtc:[%p]\n", crtc);
9611 	}
9612 
9613 	/* Check cursor planes scaling */
9614 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
9615 		ret = dm_check_crtc_cursor(state, crtc, new_crtc_state);
9616 		if (ret) {
9617 			DRM_DEBUG_DRIVER("dm_check_crtc_cursor() failed\n");
9618 			goto fail;
9619 		}
9620 	}
9621 
9622 	if (state->legacy_cursor_update) {
9623 		/*
9624 		 * This is a fast cursor update coming from the plane update
9625 		 * helper, check if it can be done asynchronously for better
9626 		 * performance.
9627 		 */
9628 		state->async_update =
9629 			!drm_atomic_helper_async_check(dev, state);
9630 
9631 		/*
9632 		 * Skip the remaining global validation if this is an async
9633 		 * update. Cursor updates can be done without affecting
9634 		 * state or bandwidth calcs and this avoids the performance
9635 		 * penalty of locking the private state object and
9636 		 * allocating a new dc_state.
9637 		 */
9638 		if (state->async_update)
9639 			return 0;
9640 	}
9641 
9642 	/* Check scaling and underscan changes*/
9643 	/* TODO Removed scaling changes validation due to inability to commit
9644 	 * new stream into context w\o causing full reset. Need to
9645 	 * decide how to handle.
9646 	 */
9647 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
9648 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
9649 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
9650 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
9651 
9652 		/* Skip any modesets/resets */
9653 		if (!acrtc || drm_atomic_crtc_needs_modeset(
9654 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
9655 			continue;
9656 
9657 		/* Skip any thing not scale or underscan changes */
9658 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
9659 			continue;
9660 
9661 		lock_and_validation_needed = true;
9662 	}
9663 
9664 	/**
9665 	 * Streams and planes are reset when there are changes that affect
9666 	 * bandwidth. Anything that affects bandwidth needs to go through
9667 	 * DC global validation to ensure that the configuration can be applied
9668 	 * to hardware.
9669 	 *
9670 	 * We have to currently stall out here in atomic_check for outstanding
9671 	 * commits to finish in this case because our IRQ handlers reference
9672 	 * DRM state directly - we can end up disabling interrupts too early
9673 	 * if we don't.
9674 	 *
9675 	 * TODO: Remove this stall and drop DM state private objects.
9676 	 */
9677 	if (lock_and_validation_needed) {
9678 		ret = dm_atomic_get_state(state, &dm_state);
9679 		if (ret) {
9680 			DRM_DEBUG_DRIVER("dm_atomic_get_state() failed\n");
9681 			goto fail;
9682 		}
9683 
9684 		ret = do_aquire_global_lock(dev, state);
9685 		if (ret) {
9686 			DRM_DEBUG_DRIVER("do_aquire_global_lock() failed\n");
9687 			goto fail;
9688 		}
9689 
9690 #if defined(CONFIG_DRM_AMD_DC_DCN)
9691 		ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
9692 		if (ret) {
9693 			DRM_DEBUG_DRIVER("compute_mst_dsc_configs_for_state() failed\n");
9694 			goto fail;
9695 		}
9696 
9697 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
9698 		if (ret) {
9699 			DRM_DEBUG_DRIVER("dm_update_mst_vcpi_slots_for_dsc() failed\n");
9700 			goto fail;
9701 		}
9702 #endif
9703 
9704 		/*
9705 		 * Perform validation of MST topology in the state:
9706 		 * We need to perform MST atomic check before calling
9707 		 * dc_validate_global_state(), or there is a chance
9708 		 * to get stuck in an infinite loop and hang eventually.
9709 		 */
9710 		ret = drm_dp_mst_atomic_check(state);
9711 		if (ret) {
9712 			DRM_DEBUG_DRIVER("drm_dp_mst_atomic_check() failed\n");
9713 			goto fail;
9714 		}
9715 		status = dc_validate_global_state(dc, dm_state->context, true);
9716 		if (status != DC_OK) {
9717 			DRM_DEBUG_DRIVER("DC global validation failure: %s (%d)",
9718 				       dc_status_to_str(status), status);
9719 			ret = -EINVAL;
9720 			goto fail;
9721 		}
9722 	} else {
9723 		/*
9724 		 * The commit is a fast update. Fast updates shouldn't change
9725 		 * the DC context, affect global validation, and can have their
9726 		 * commit work done in parallel with other commits not touching
9727 		 * the same resource. If we have a new DC context as part of
9728 		 * the DM atomic state from validation we need to free it and
9729 		 * retain the existing one instead.
9730 		 *
9731 		 * Furthermore, since the DM atomic state only contains the DC
9732 		 * context and can safely be annulled, we can free the state
9733 		 * and clear the associated private object now to free
9734 		 * some memory and avoid a possible use-after-free later.
9735 		 */
9736 
9737 		for (i = 0; i < state->num_private_objs; i++) {
9738 			struct drm_private_obj *obj = state->private_objs[i].ptr;
9739 
9740 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
9741 				int j = state->num_private_objs-1;
9742 
9743 				dm_atomic_destroy_state(obj,
9744 						state->private_objs[i].state);
9745 
9746 				/* If i is not at the end of the array then the
9747 				 * last element needs to be moved to where i was
9748 				 * before the array can safely be truncated.
9749 				 */
9750 				if (i != j)
9751 					state->private_objs[i] =
9752 						state->private_objs[j];
9753 
9754 				state->private_objs[j].ptr = NULL;
9755 				state->private_objs[j].state = NULL;
9756 				state->private_objs[j].old_state = NULL;
9757 				state->private_objs[j].new_state = NULL;
9758 
9759 				state->num_private_objs = j;
9760 				break;
9761 			}
9762 		}
9763 	}
9764 
9765 	/* Store the overall update type for use later in atomic check. */
9766 	for_each_new_crtc_in_state (state, crtc, new_crtc_state, i) {
9767 		struct dm_crtc_state *dm_new_crtc_state =
9768 			to_dm_crtc_state(new_crtc_state);
9769 
9770 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
9771 							 UPDATE_TYPE_FULL :
9772 							 UPDATE_TYPE_FAST;
9773 	}
9774 
9775 	/* Must be success */
9776 	WARN_ON(ret);
9777 
9778 	trace_amdgpu_dm_atomic_check_finish(state, ret);
9779 
9780 	return ret;
9781 
9782 fail:
9783 	if (ret == -EDEADLK)
9784 		DRM_DEBUG_DRIVER("Atomic check stopped to avoid deadlock.\n");
9785 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
9786 		DRM_DEBUG_DRIVER("Atomic check stopped due to signal.\n");
9787 	else
9788 		DRM_DEBUG_DRIVER("Atomic check failed with err: %d \n", ret);
9789 
9790 	trace_amdgpu_dm_atomic_check_finish(state, ret);
9791 
9792 	return ret;
9793 }
9794 
9795 static bool is_dp_capable_without_timing_msa(struct dc *dc,
9796 					     struct amdgpu_dm_connector *amdgpu_dm_connector)
9797 {
9798 	uint8_t dpcd_data;
9799 	bool capable = false;
9800 
9801 	if (amdgpu_dm_connector->dc_link &&
9802 		dm_helpers_dp_read_dpcd(
9803 				NULL,
9804 				amdgpu_dm_connector->dc_link,
9805 				DP_DOWN_STREAM_PORT_COUNT,
9806 				&dpcd_data,
9807 				sizeof(dpcd_data))) {
9808 		capable = (dpcd_data & DP_MSA_TIMING_PAR_IGNORED) ? true:false;
9809 	}
9810 
9811 	return capable;
9812 }
9813 
9814 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
9815 		unsigned int offset,
9816 		unsigned int total_length,
9817 		uint8_t *data,
9818 		unsigned int length,
9819 		struct amdgpu_hdmi_vsdb_info *vsdb)
9820 {
9821 	bool res;
9822 	union dmub_rb_cmd cmd;
9823 	struct dmub_cmd_send_edid_cea *input;
9824 	struct dmub_cmd_edid_cea_output *output;
9825 
9826 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
9827 		return false;
9828 
9829 	memset(&cmd, 0, sizeof(cmd));
9830 
9831 	input = &cmd.edid_cea.data.input;
9832 
9833 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
9834 	cmd.edid_cea.header.sub_type = 0;
9835 	cmd.edid_cea.header.payload_bytes =
9836 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
9837 	input->offset = offset;
9838 	input->length = length;
9839 	input->cea_total_length = total_length;
9840 	memcpy(input->payload, data, length);
9841 
9842 	res = dc_dmub_srv_cmd_with_reply_data(dm->dc->ctx->dmub_srv, &cmd);
9843 	if (!res) {
9844 		DRM_ERROR("EDID CEA parser failed\n");
9845 		return false;
9846 	}
9847 
9848 	output = &cmd.edid_cea.data.output;
9849 
9850 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
9851 		if (!output->ack.success) {
9852 			DRM_ERROR("EDID CEA ack failed at offset %d\n",
9853 					output->ack.offset);
9854 		}
9855 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
9856 		if (!output->amd_vsdb.vsdb_found)
9857 			return false;
9858 
9859 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
9860 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
9861 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
9862 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
9863 	} else {
9864 		if (output->type != 0)
9865 			DRM_WARN("Unknown EDID CEA parser results\n");
9866 		return false;
9867 	}
9868 
9869 	return true;
9870 }
9871 
9872 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
9873 		uint8_t *edid_ext, int len,
9874 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
9875 {
9876 	int i;
9877 
9878 	/* send extension block to DMCU for parsing */
9879 	for (i = 0; i < len; i += 8) {
9880 		bool res;
9881 		int offset;
9882 
9883 		/* send 8 bytes a time */
9884 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
9885 			return false;
9886 
9887 		if (i+8 == len) {
9888 			/* EDID block sent completed, expect result */
9889 			int version, min_rate, max_rate;
9890 
9891 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
9892 			if (res) {
9893 				/* amd vsdb found */
9894 				vsdb_info->freesync_supported = 1;
9895 				vsdb_info->amd_vsdb_version = version;
9896 				vsdb_info->min_refresh_rate_hz = min_rate;
9897 				vsdb_info->max_refresh_rate_hz = max_rate;
9898 				return true;
9899 			}
9900 			/* not amd vsdb */
9901 			return false;
9902 		}
9903 
9904 		/* check for ack*/
9905 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
9906 		if (!res)
9907 			return false;
9908 	}
9909 
9910 	return false;
9911 }
9912 
9913 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
9914 		uint8_t *edid_ext, int len,
9915 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
9916 {
9917 	int i;
9918 
9919 	/* send extension block to DMCU for parsing */
9920 	for (i = 0; i < len; i += 8) {
9921 		/* send 8 bytes a time */
9922 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
9923 			return false;
9924 	}
9925 
9926 	return vsdb_info->freesync_supported;
9927 }
9928 
9929 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
9930 		uint8_t *edid_ext, int len,
9931 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
9932 {
9933 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
9934 
9935 	if (adev->dm.dmub_srv)
9936 		return parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
9937 	else
9938 		return parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
9939 }
9940 
9941 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
9942 		struct edid *edid, struct amdgpu_hdmi_vsdb_info *vsdb_info)
9943 {
9944 	uint8_t *edid_ext = NULL;
9945 	int i;
9946 	bool valid_vsdb_found = false;
9947 
9948 	/*----- drm_find_cea_extension() -----*/
9949 	/* No EDID or EDID extensions */
9950 	if (edid == NULL || edid->extensions == 0)
9951 		return -ENODEV;
9952 
9953 	/* Find CEA extension */
9954 	for (i = 0; i < edid->extensions; i++) {
9955 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
9956 		if (edid_ext[0] == CEA_EXT)
9957 			break;
9958 	}
9959 
9960 	if (i == edid->extensions)
9961 		return -ENODEV;
9962 
9963 	/*----- cea_db_offsets() -----*/
9964 	if (edid_ext[0] != CEA_EXT)
9965 		return -ENODEV;
9966 
9967 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
9968 
9969 	return valid_vsdb_found ? i : -ENODEV;
9970 }
9971 
9972 /**
9973  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
9974  *
9975  * @connector: Connector to query.
9976  * @edid: EDID from monitor
9977  *
9978  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
9979  * track of some of the display information in the internal data struct used by
9980  * amdgpu_dm. This function checks which type of connector we need to set the
9981  * FreeSync parameters.
9982  */
9983 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
9984 				    struct edid *edid)
9985 {
9986 	int i = 0;
9987 	struct detailed_timing *timing;
9988 	struct detailed_non_pixel *data;
9989 	struct detailed_data_monitor_range *range;
9990 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9991 			to_amdgpu_dm_connector(connector);
9992 	struct dm_connector_state *dm_con_state = NULL;
9993 	struct dc_sink *sink;
9994 
9995 	struct drm_device *dev = connector->dev;
9996 	struct amdgpu_device *adev = drm_to_adev(dev);
9997 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
9998 	bool freesync_capable = false;
9999 
10000 	if (!connector->state) {
10001 		DRM_ERROR("%s - Connector has no state", __func__);
10002 		goto update;
10003 	}
10004 
10005 	sink = amdgpu_dm_connector->dc_sink ?
10006 		amdgpu_dm_connector->dc_sink :
10007 		amdgpu_dm_connector->dc_em_sink;
10008 
10009 	if (!edid || !sink) {
10010 		dm_con_state = to_dm_connector_state(connector->state);
10011 
10012 		amdgpu_dm_connector->min_vfreq = 0;
10013 		amdgpu_dm_connector->max_vfreq = 0;
10014 		amdgpu_dm_connector->pixel_clock_mhz = 0;
10015 		connector->display_info.monitor_range.min_vfreq = 0;
10016 		connector->display_info.monitor_range.max_vfreq = 0;
10017 		freesync_capable = false;
10018 
10019 		goto update;
10020 	}
10021 
10022 	dm_con_state = to_dm_connector_state(connector->state);
10023 
10024 	if (!adev->dm.freesync_module)
10025 		goto update;
10026 
10027 	if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT
10028 		|| sink->sink_signal == SIGNAL_TYPE_EDP) {
10029 		bool edid_check_required = false;
10030 
10031 		if (edid) {
10032 			edid_check_required = is_dp_capable_without_timing_msa(
10033 						adev->dm.dc,
10034 						amdgpu_dm_connector);
10035 		}
10036 
10037 		if (edid_check_required == true && (edid->version > 1 ||
10038 		   (edid->version == 1 && edid->revision > 1))) {
10039 			for (i = 0; i < 4; i++) {
10040 
10041 				timing	= &edid->detailed_timings[i];
10042 				data	= &timing->data.other_data;
10043 				range	= &data->data.range;
10044 				/*
10045 				 * Check if monitor has continuous frequency mode
10046 				 */
10047 				if (data->type != EDID_DETAIL_MONITOR_RANGE)
10048 					continue;
10049 				/*
10050 				 * Check for flag range limits only. If flag == 1 then
10051 				 * no additional timing information provided.
10052 				 * Default GTF, GTF Secondary curve and CVT are not
10053 				 * supported
10054 				 */
10055 				if (range->flags != 1)
10056 					continue;
10057 
10058 				amdgpu_dm_connector->min_vfreq = range->min_vfreq;
10059 				amdgpu_dm_connector->max_vfreq = range->max_vfreq;
10060 				amdgpu_dm_connector->pixel_clock_mhz =
10061 					range->pixel_clock_mhz * 10;
10062 
10063 				connector->display_info.monitor_range.min_vfreq = range->min_vfreq;
10064 				connector->display_info.monitor_range.max_vfreq = range->max_vfreq;
10065 
10066 				break;
10067 			}
10068 
10069 			if (amdgpu_dm_connector->max_vfreq -
10070 			    amdgpu_dm_connector->min_vfreq > 10) {
10071 
10072 				freesync_capable = true;
10073 			}
10074 		}
10075 	} else if (edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
10076 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
10077 		if (i >= 0 && vsdb_info.freesync_supported) {
10078 			timing  = &edid->detailed_timings[i];
10079 			data    = &timing->data.other_data;
10080 
10081 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
10082 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
10083 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
10084 				freesync_capable = true;
10085 
10086 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
10087 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
10088 		}
10089 	}
10090 
10091 update:
10092 	if (dm_con_state)
10093 		dm_con_state->freesync_capable = freesync_capable;
10094 
10095 	if (connector->vrr_capable_property)
10096 		drm_connector_set_vrr_capable_property(connector,
10097 						       freesync_capable);
10098 }
10099 
10100 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
10101 {
10102 	struct amdgpu_device *adev = drm_to_adev(dev);
10103 	struct dc *dc = adev->dm.dc;
10104 	int i;
10105 
10106 	mutex_lock(&adev->dm.dc_lock);
10107 	if (dc->current_state) {
10108 		for (i = 0; i < dc->current_state->stream_count; ++i)
10109 			dc->current_state->streams[i]
10110 				->triggered_crtc_reset.enabled =
10111 				adev->dm.force_timing_sync;
10112 
10113 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
10114 		dc_trigger_sync(dc, dc->current_state);
10115 	}
10116 	mutex_unlock(&adev->dm.dc_lock);
10117 }
10118 
10119 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
10120 		       uint32_t value, const char *func_name)
10121 {
10122 #ifdef DM_CHECK_ADDR_0
10123 	if (address == 0) {
10124 		DC_ERR("invalid register write. address = 0");
10125 		return;
10126 	}
10127 #endif
10128 	cgs_write_register(ctx->cgs_device, address, value);
10129 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
10130 }
10131 
10132 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
10133 			  const char *func_name)
10134 {
10135 	uint32_t value;
10136 #ifdef DM_CHECK_ADDR_0
10137 	if (address == 0) {
10138 		DC_ERR("invalid register read; address = 0\n");
10139 		return 0;
10140 	}
10141 #endif
10142 
10143 	if (ctx->dmub_srv &&
10144 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
10145 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
10146 		ASSERT(false);
10147 		return 0;
10148 	}
10149 
10150 	value = cgs_read_register(ctx->cgs_device, address);
10151 
10152 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
10153 
10154 	return value;
10155 }
10156 
10157 static int amdgpu_dm_set_dmub_async_sync_status(bool is_cmd_aux,
10158 						struct dc_context *ctx,
10159 						uint8_t status_type,
10160 						uint32_t *operation_result)
10161 {
10162 	struct amdgpu_device *adev = ctx->driver_context;
10163 	int return_status = -1;
10164 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
10165 
10166 	if (is_cmd_aux) {
10167 		if (status_type == DMUB_ASYNC_TO_SYNC_ACCESS_SUCCESS) {
10168 			return_status = p_notify->aux_reply.length;
10169 			*operation_result = p_notify->result;
10170 		} else if (status_type == DMUB_ASYNC_TO_SYNC_ACCESS_TIMEOUT) {
10171 			*operation_result = AUX_RET_ERROR_TIMEOUT;
10172 		} else if (status_type == DMUB_ASYNC_TO_SYNC_ACCESS_FAIL) {
10173 			*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
10174 		} else if (status_type == DMUB_ASYNC_TO_SYNC_ACCESS_INVALID) {
10175 			*operation_result = AUX_RET_ERROR_INVALID_REPLY;
10176 		} else {
10177 			*operation_result = AUX_RET_ERROR_UNKNOWN;
10178 		}
10179 	} else {
10180 		if (status_type == DMUB_ASYNC_TO_SYNC_ACCESS_SUCCESS) {
10181 			return_status = 0;
10182 			*operation_result = p_notify->sc_status;
10183 		} else {
10184 			*operation_result = SET_CONFIG_UNKNOWN_ERROR;
10185 		}
10186 	}
10187 
10188 	return return_status;
10189 }
10190 
10191 int amdgpu_dm_process_dmub_aux_transfer_sync(bool is_cmd_aux, struct dc_context *ctx,
10192 	unsigned int link_index, void *cmd_payload, void *operation_result)
10193 {
10194 	struct amdgpu_device *adev = ctx->driver_context;
10195 	int ret = 0;
10196 
10197 	if (is_cmd_aux) {
10198 		dc_process_dmub_aux_transfer_async(ctx->dc,
10199 			link_index, (struct aux_payload *)cmd_payload);
10200 	} else if (dc_process_dmub_set_config_async(ctx->dc, link_index,
10201 					(struct set_config_cmd_payload *)cmd_payload,
10202 					adev->dm.dmub_notify)) {
10203 		return amdgpu_dm_set_dmub_async_sync_status(is_cmd_aux,
10204 					ctx, DMUB_ASYNC_TO_SYNC_ACCESS_SUCCESS,
10205 					(uint32_t *)operation_result);
10206 	}
10207 
10208 	ret = wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ);
10209 	if (ret == 0) {
10210 		DRM_ERROR("wait_for_completion_timeout timeout!");
10211 		return amdgpu_dm_set_dmub_async_sync_status(is_cmd_aux,
10212 				ctx, DMUB_ASYNC_TO_SYNC_ACCESS_TIMEOUT,
10213 				(uint32_t *)operation_result);
10214 	}
10215 
10216 	if (is_cmd_aux) {
10217 		if (adev->dm.dmub_notify->result == AUX_RET_SUCCESS) {
10218 			struct aux_payload *payload = (struct aux_payload *)cmd_payload;
10219 
10220 			payload->reply[0] = adev->dm.dmub_notify->aux_reply.command;
10221 			if (!payload->write && adev->dm.dmub_notify->aux_reply.length &&
10222 			    payload->reply[0] == AUX_TRANSACTION_REPLY_AUX_ACK) {
10223 
10224 				if (payload->length != adev->dm.dmub_notify->aux_reply.length) {
10225 					DRM_WARN("invalid read from DPIA AUX %x(%d) got length %d!\n",
10226 							payload->address, payload->length,
10227 							adev->dm.dmub_notify->aux_reply.length);
10228 					return amdgpu_dm_set_dmub_async_sync_status(is_cmd_aux, ctx,
10229 							DMUB_ASYNC_TO_SYNC_ACCESS_INVALID,
10230 							(uint32_t *)operation_result);
10231 				}
10232 
10233 				memcpy(payload->data, adev->dm.dmub_notify->aux_reply.data,
10234 				       adev->dm.dmub_notify->aux_reply.length);
10235 			}
10236 		}
10237 	}
10238 
10239 	return amdgpu_dm_set_dmub_async_sync_status(is_cmd_aux,
10240 			ctx, DMUB_ASYNC_TO_SYNC_ACCESS_SUCCESS,
10241 			(uint32_t *)operation_result);
10242 }
10243 
10244 /*
10245  * Check whether seamless boot is supported.
10246  *
10247  * So far we only support seamless boot on CHIP_VANGOGH.
10248  * If everything goes well, we may consider expanding
10249  * seamless boot to other ASICs.
10250  */
10251 bool check_seamless_boot_capability(struct amdgpu_device *adev)
10252 {
10253 	switch (adev->asic_type) {
10254 	case CHIP_VANGOGH:
10255 		if (!adev->mman.keep_stolen_vga_memory)
10256 			return true;
10257 		break;
10258 	default:
10259 		break;
10260 	}
10261 
10262 	return false;
10263 }
10264