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