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