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