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