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