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