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