xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision fff46a322847a54cf11d5af3d7fc7fa07bc71b29)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright 2015-2026 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_stat.h"
40 #include "dc/dc_state.h"
41 #include "amdgpu_dm_trace.h"
42 #include "link/protocols/link_dpcd.h"
43 #include "link_service_types.h"
44 #include "link/protocols/link_dp_capability.h"
45 #include "link/protocols/link_ddc.h"
46 
47 #include "amdgpu.h"
48 #include "amdgpu_display.h"
49 #include "amdgpu_ucode.h"
50 #include "atom.h"
51 #include "amdgpu_dm.h"
52 #include "amdgpu_dm_plane.h"
53 #include "amdgpu_dm_crtc.h"
54 #include "amdgpu_dm_hdcp.h"
55 #include <drm/display/drm_hdcp_helper.h>
56 #include "amdgpu_dm_wb.h"
57 #include "amdgpu_atombios.h"
58 
59 #include "amd_shared.h"
60 #include "amdgpu_dm_irq.h"
61 #include "dm_helpers.h"
62 #include "amdgpu_dm_mst_types.h"
63 #if defined(CONFIG_DEBUG_FS)
64 #include "amdgpu_dm_debugfs.h"
65 #endif
66 #include "amdgpu_dm_psr.h"
67 #include "amdgpu_dm_replay.h"
68 #include "amdgpu_dm_backlight.h"
69 #include "amdgpu_dm_audio.h"
70 #include "amdgpu_dm_dmub.h"
71 #include "amdgpu_dm_connector.h"
72 #include "amdgpu_dm_pp_smu.h"
73 #include "amdgpu_dm_freesync.h"
74 #include "amdgpu_dm_cursor.h"
75 
76 #include "ivsrcid/ivsrcid_vislands30.h"
77 
78 #include <linux/backlight.h>
79 #include <linux/module.h>
80 #include <linux/moduleparam.h>
81 #include <linux/types.h>
82 #include <linux/pm_runtime.h>
83 #include <linux/pci.h>
84 #include <linux/power_supply.h>
85 #include <linux/firmware.h>
86 #include <linux/component.h>
87 #include <linux/sort.h>
88 
89 #include <drm/drm_privacy_screen_consumer.h>
90 #include <drm/display/drm_dp_mst_helper.h>
91 #include <drm/display/drm_hdmi_helper.h>
92 #include <drm/drm_atomic.h>
93 #include <drm/drm_atomic_uapi.h>
94 #include <drm/drm_atomic_helper.h>
95 #include <drm/drm_blend.h>
96 #include <drm/drm_fixed.h>
97 #include <drm/drm_fourcc.h>
98 #include <drm/drm_edid.h>
99 #include <drm/drm_eld.h>
100 #include <drm/drm_mode.h>
101 #include <drm/drm_vblank.h>
102 #include <drm/drm_colorop.h>
103 #include <drm/drm_gem_atomic_helper.h>
104 
105 #include <media/cec-notifier.h>
106 #include <acpi/video.h>
107 
108 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
109 
110 #include "modules/inc/mod_freesync.h"
111 #include "modules/inc/mod_power.h"
112 #include "modules/power/power_helpers.h"
113 
114 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
115 MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
116 
117 /**
118  * DOC: overview
119  *
120  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
121  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
122  * requests into DC requests, and DC responses into DRM responses.
123  *
124  * The root control structure is &struct amdgpu_display_manager.
125  */
126 
127 /* basic init/fini API */
128 static int amdgpu_dm_init(struct amdgpu_device *adev);
129 static void amdgpu_dm_fini(struct amdgpu_device *adev);
130 
131 /*
132  * initializes drm_device display related structures, based on the information
133  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
134  * drm_encoder, drm_mode_config
135  *
136  * Returns 0 on success
137  */
138 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
139 /* removes and deallocates the drm structures, created by the above function */
140 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
141 
142 STATIC_IFN_KUNIT int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state);
143 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state);
144 STATIC_IFN_KUNIT void dm_enable_per_frame_crtc_master_sync(struct dc_state *context);
145 
146 #if !IS_ENABLED(CONFIG_DRM_AMD_DC_KUNIT_TEST)
147 static int amdgpu_dm_atomic_check(struct drm_device *dev,
148 				  struct drm_atomic_commit *state);
149 #endif
150 
151 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
152 {
153 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
154 		dc_exit_ips_for_hw_access(dc);
155 }
156 
157 /*
158  * dm_vblank_get_counter
159  *
160  * @brief
161  * Get counter for number of vertical blanks
162  *
163  * @param
164  * struct amdgpu_device *adev - [in] desired amdgpu device
165  * int disp_idx - [in] which CRTC to get the counter from
166  *
167  * @return
168  * Counter for vertical blanks
169  */
170 STATIC_IFN_KUNIT u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
171 {
172 	struct amdgpu_crtc *acrtc = NULL;
173 
174 	if (crtc >= adev->mode_info.num_crtc)
175 		return 0;
176 
177 	acrtc = adev->mode_info.crtcs[crtc];
178 
179 	if (!acrtc->dm_irq_params.stream) {
180 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
181 			  crtc);
182 		return 0;
183 	}
184 
185 	return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
186 }
187 EXPORT_IF_KUNIT(dm_vblank_get_counter);
188 
189 STATIC_IFN_KUNIT int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
190 					    u32 *vbl, u32 *position)
191 {
192 	u32 v_blank_start = 0, v_blank_end = 0, h_position = 0, v_position = 0;
193 	struct amdgpu_crtc *acrtc = NULL;
194 	struct dc *dc = adev->dm.dc;
195 
196 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
197 		return -EINVAL;
198 
199 	acrtc = adev->mode_info.crtcs[crtc];
200 
201 	if (!acrtc->dm_irq_params.stream) {
202 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
203 			  crtc);
204 		return 0;
205 	}
206 
207 	if (dc && dc->caps.ips_support && dc->idle_optimizations_allowed)
208 		dc_allow_idle_optimizations(dc, false);
209 
210 	/*
211 	 * TODO rework base driver to use values directly.
212 	 * for now parse it back into reg-format
213 	 */
214 	dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
215 				 &v_blank_start,
216 				 &v_blank_end,
217 				 &h_position,
218 				 &v_position);
219 
220 	*position = v_position | (h_position << 16);
221 	*vbl = v_blank_start | (v_blank_end << 16);
222 
223 	return 0;
224 }
225 EXPORT_IF_KUNIT(dm_crtc_get_scanoutpos);
226 
227 STATIC_IFN_KUNIT int dm_wait_for_idle(struct amdgpu_ip_block *ip_block)
228 {
229 	/* XXX todo */
230 	return 0;
231 }
232 EXPORT_IF_KUNIT(dm_wait_for_idle);
233 
234 /*
235  * DC will program planes with their z-order determined by their ordering
236  * in the dc_surface_updates array. This comparator is used to sort them
237  * by descending zpos.
238  */
239 STATIC_IFN_KUNIT int dm_plane_layer_index_cmp(const void *a, const void *b)
240 {
241 	const struct dc_surface_update *sa = (struct dc_surface_update *)a;
242 	const struct dc_surface_update *sb = (struct dc_surface_update *)b;
243 
244 	/* Sort by descending dc_plane layer_index (i.e. normalized_zpos) */
245 	return sb->surface->layer_index - sa->surface->layer_index;
246 }
247 EXPORT_IF_KUNIT(dm_plane_layer_index_cmp);
248 
249 #if IS_ENABLED(CONFIG_DRM_AMD_DC_KUNIT_TEST)
250 static const struct amdgpu_dm_kunit_ops *amdgpu_dm_ops;
251 
252 #define dm_post_update_surfaces_to_stream	amdgpu_dm_ops->post_update_surfaces_to_stream
253 #define dm_update_planes_and_stream		amdgpu_dm_ops->update_planes_and_stream
254 #else
255 #define dm_post_update_surfaces_to_stream	dc_post_update_surfaces_to_stream
256 #define dm_update_planes_and_stream		dc_update_planes_and_stream
257 #endif
258 
259 /**
260  * update_planes_and_stream_adapter() - Send planes to be updated in DC
261  *
262  * DC has a generic way to update planes and stream via
263  * dc_update_planes_and_stream function; however, DM might need some
264  * adjustments and preparation before calling it. This function is a wrapper
265  * for the dc_update_planes_and_stream that does any required configuration
266  * before passing control to DC.
267  *
268  * @dc: Display Core control structure
269  * @planes_count: planes count to update
270  * @stream: stream state
271  * @stream_update: stream update
272  * @array_of_surface_update: dc surface update pointer
273  *
274  */
275 STATIC_IFN_KUNIT INLINE_IFN_KUNIT
276 bool update_planes_and_stream_adapter(struct dc *dc,
277 				      int planes_count,
278 				      struct dc_stream_state *stream,
279 				      struct dc_stream_update *stream_update,
280 				      struct dc_surface_update *array_of_surface_update)
281 {
282 	sort(array_of_surface_update, planes_count,
283 	     sizeof(*array_of_surface_update), dm_plane_layer_index_cmp, NULL);
284 
285 	/*
286 	 * Previous frame finished and HW is ready for optimization.
287 	 */
288 	dm_post_update_surfaces_to_stream(dc);
289 
290 	return dm_update_planes_and_stream(dc,
291 					   array_of_surface_update,
292 					   planes_count,
293 					   stream,
294 					   stream_update);
295 }
296 EXPORT_IF_KUNIT(update_planes_and_stream_adapter);
297 
298 STATIC_IFN_KUNIT int dm_set_clockgating_state(struct amdgpu_ip_block *ip_block,
299 					      enum amd_clockgating_state state)
300 {
301 	return 0;
302 }
303 EXPORT_IF_KUNIT(dm_set_clockgating_state);
304 
305 STATIC_IFN_KUNIT int dm_set_powergating_state(struct amdgpu_ip_block *ip_block,
306 					      enum amd_powergating_state state)
307 {
308 	return 0;
309 }
310 EXPORT_IF_KUNIT(dm_set_powergating_state);
311 
312 /* Prototypes of private functions */
313 STATIC_IFN_KUNIT int dm_early_init(struct amdgpu_ip_block *ip_block);
314 
315 #if IS_ENABLED(CONFIG_DRM_AMD_DC_KUNIT_TEST)
316 static const struct amdgpu_dm_kunit_ops amdgpu_dm_default_ops = {
317 	.gmc_pd_addr = amdgpu_gmc_pd_addr,
318 	.post_update_surfaces_to_stream = dc_post_update_surfaces_to_stream,
319 	.update_planes_and_stream = dc_update_planes_and_stream,
320 	.atomic_helper_suspend = drm_atomic_helper_suspend,
321 };
322 
323 static const struct amdgpu_dm_kunit_ops *amdgpu_dm_ops = &amdgpu_dm_default_ops;
324 
325 void amdgpu_dm_kunit_set_ops(const struct amdgpu_dm_kunit_ops *ops)
326 {
327 	amdgpu_dm_ops = ops ? ops : &amdgpu_dm_default_ops;
328 }
329 EXPORT_IF_KUNIT(amdgpu_dm_kunit_set_ops);
330 
331 #define dm_gmc_pd_addr			amdgpu_dm_ops->gmc_pd_addr
332 #define dm_atomic_helper_suspend	amdgpu_dm_ops->atomic_helper_suspend
333 #else
334 #define dm_gmc_pd_addr			amdgpu_gmc_pd_addr
335 #define dm_atomic_helper_suspend	drm_atomic_helper_suspend
336 #endif
337 
338 /* Allocate memory for FBC compressed data  */
339 STATIC_IFN_KUNIT void mmhub_read_system_context(struct amdgpu_device *adev,
340 						struct dc_phy_addr_space_config *pa_config)
341 {
342 	u64 pt_base;
343 	u32 logical_addr_low;
344 	u32 logical_addr_high;
345 	u32 agp_base, agp_bot, agp_top;
346 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
347 
348 	memset(pa_config, 0, sizeof(*pa_config));
349 
350 	agp_base = 0;
351 	agp_bot = adev->gmc.agp_start >> 24;
352 	agp_top = adev->gmc.agp_end >> 24;
353 
354 	/* AGP aperture is disabled */
355 	if (agp_bot > agp_top) {
356 		logical_addr_low = adev->gmc.fb_start >> 18;
357 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
358 				       AMD_APU_IS_RENOIR |
359 				       AMD_APU_IS_GREEN_SARDINE))
360 			/*
361 			 * Raven2 has a HW issue that it is unable to use the vram which
362 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
363 			 * workaround that increase system aperture high address (add 1)
364 			 * to get rid of the VM fault and hardware hang.
365 			 */
366 			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
367 		else
368 			logical_addr_high = adev->gmc.fb_end >> 18;
369 	} else {
370 		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
371 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
372 				       AMD_APU_IS_RENOIR |
373 				       AMD_APU_IS_GREEN_SARDINE))
374 			/*
375 			 * Raven2 has a HW issue that it is unable to use the vram which
376 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
377 			 * workaround that increase system aperture high address (add 1)
378 			 * to get rid of the VM fault and hardware hang.
379 			 */
380 			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
381 		else
382 			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
383 	}
384 
385 	pt_base = dm_gmc_pd_addr(adev->gart.bo);
386 
387 	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
388 						   AMDGPU_GPU_PAGE_SHIFT);
389 	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
390 						  AMDGPU_GPU_PAGE_SHIFT);
391 	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
392 						 AMDGPU_GPU_PAGE_SHIFT);
393 	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
394 						AMDGPU_GPU_PAGE_SHIFT);
395 	page_table_base.high_part = upper_32_bits(pt_base);
396 	page_table_base.low_part = lower_32_bits(pt_base);
397 
398 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
399 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
400 
401 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
402 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
403 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
404 
405 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
406 	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
407 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
408 
409 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
410 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
411 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
412 
413 	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
414 
415 }
416 EXPORT_IF_KUNIT(mmhub_read_system_context);
417 
418 STATIC_IFN_KUNIT int amdgpu_dm_init_power_module(struct amdgpu_display_manager *dm)
419 {
420 	struct mod_power_init_params init_data[MAX_NUM_EDP];
421 
422 	if (dm->num_of_edps == 0) {
423 		drm_dbg_driver(
424 			dm->ddev,
425 			"amdgpu: No eDP detected, skip initializing power module\n");
426 		return 0;
427 	}
428 
429 	/* Initialize all the power module parameters */
430 	for (int i = 0; i < dm->num_of_edps; i++) {
431 		init_data[i].allow_psr_smu_optimizations =
432 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_SMU_OPT);
433 		init_data[i].allow_psr_multi_disp_optimizations =
434 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_MULTI_DISP_OPT);
435 		/* See dm_late_init */
436 		init_data[i].backlight_ramping_override = false;
437 		init_data[i].backlight_ramping_start = 0xCCCC;
438 		init_data[i].backlight_ramping_reduction = 0xCCCCCCCC;
439 		init_data[i].def_varibright_level = 0;
440 		init_data[i].abm_config_setting = 0;
441 		init_data[i].num_backlight_levels = 101;
442 		init_data[i].use_nits_based_brightness = false;
443 		init_data[i].panel_max_millinits = 0;
444 		init_data[i].panel_min_millinits = 0;
445 		init_data[i].disable_fractional_pwm =
446 			!(amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK);
447 		init_data[i].use_custom_backlight_caps = false;
448 		init_data[i].custom_backlight_caps_config_no = 0;
449 		init_data[i].use_linear_backlight_curve = false;
450 		if (amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)
451 			init_data[i].use_linear_backlight_curve = true;
452 		init_data[i].def_varibright_enable = 0;
453 		init_data[i].varibright_level = 0;
454 		/*
455 		 * Power module uses 16-bit backlight levels (0xFFFF max) rather
456 		 * than 8-bit(0XFF max)
457 		 */
458 		init_data[i].min_backlight_pwm =
459 			dm->backlight_caps[i].min_input_signal * 0x101;
460 		init_data[i].max_backlight_pwm =
461 			dm->backlight_caps[i].max_input_signal * 0x101;
462 		init_data[i].min_abm_backlight =
463 			dm->backlight_caps[i].min_input_signal * 0x101;
464 
465 		/* Min backlight level after ABM reduction,  Don't allow below 1%
466 		 * 0xFFFF x 0.01 = 0x28F
467 		 */
468 		init_data[i].min_abm_backlight = (init_data[i].min_abm_backlight < 0x28F) ?
469 			0x28F : init_data[i].min_abm_backlight;
470 	}
471 
472 	dm->power_module = mod_power_create(dm->dc, init_data, dm->num_of_edps);
473 	if (!dm->power_module) {
474 		drm_err(dm->ddev, "amdgpu: Error allocating memory for power module\n");
475 		return -ENOMEM;
476 	}
477 
478 	mod_power_hw_init(dm->power_module);
479 	drm_dbg_driver(dm->ddev, "amdgpu: Power module init done\n");
480 
481 	return 0;
482 }
483 EXPORT_IF_KUNIT(amdgpu_dm_init_power_module);
484 
485 static int amdgpu_dm_init(struct amdgpu_device *adev)
486 {
487 	struct dc_init_data init_data;
488 	struct dc_callback_init init_params;
489 	int r;
490 
491 	adev->dm.ddev = adev_to_drm(adev);
492 	adev->dm.adev = adev;
493 
494 	/* Zero all the fields */
495 	memset(&init_data, 0, sizeof(init_data));
496 	memset(&init_params, 0, sizeof(init_params));
497 
498 	mutex_init(&adev->dm.dpia_aux_lock);
499 	mutex_init(&adev->dm.dc_lock);
500 	mutex_init(&adev->dm.audio_lock);
501 
502 	spin_lock_init(&adev->dm.dmub_lock);
503 
504 	if (amdgpu_dm_irq_init(adev)) {
505 		drm_err(adev_to_drm(adev), "failed to initialize DM IRQ support.\n");
506 		goto error;
507 	}
508 
509 	/* special handling for early revisions of GC 11.5.4 */
510 	if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(11, 5, 4))
511 		init_data.asic_id.chip_family = AMDGPU_FAMILY_GC_11_5_4;
512 	else
513 		init_data.asic_id.chip_family = adev->family;
514 
515 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
516 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
517 	init_data.asic_id.chip_id = adev->pdev->device;
518 
519 	init_data.asic_id.vram_width = adev->gmc.vram_width;
520 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
521 	init_data.asic_id.atombios_base_address =
522 		adev->mode_info.atom_context->bios;
523 
524 	init_data.driver = adev;
525 
526 	/* cgs_device was created in dm_sw_init() */
527 	init_data.cgs_device = adev->dm.cgs_device;
528 
529 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
530 
531 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
532 	case IP_VERSION(2, 1, 0):
533 		switch (adev->dm.dmcub_fw_version) {
534 		case 0: /* development */
535 		case 0x1: /* linux-firmware.git hash 6d9f399 */
536 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
537 			init_data.flags.disable_dmcu = false;
538 			break;
539 		default:
540 			init_data.flags.disable_dmcu = true;
541 		}
542 		break;
543 	case IP_VERSION(2, 0, 3):
544 		init_data.flags.disable_dmcu = true;
545 		break;
546 	default:
547 		break;
548 	}
549 
550 	/* APU support S/G display by default except:
551 	 * ASICs before Carrizo,
552 	 * RAVEN1 (Users reported stability issue)
553 	 */
554 
555 	if (adev->asic_type < CHIP_CARRIZO) {
556 		init_data.flags.gpu_vm_support = false;
557 	} else if (adev->asic_type == CHIP_RAVEN) {
558 		if (adev->apu_flags & AMD_APU_IS_RAVEN)
559 			init_data.flags.gpu_vm_support = false;
560 		else
561 			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
562 	} else {
563 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(2, 0, 3))
564 			init_data.flags.gpu_vm_support = (amdgpu_sg_display == 1);
565 		else
566 			init_data.flags.gpu_vm_support =
567 				(amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
568 	}
569 
570 	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
571 
572 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
573 		init_data.flags.fbc_support = true;
574 
575 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
576 		init_data.flags.multi_mon_pp_mclk_switch = true;
577 
578 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
579 		init_data.flags.disable_fractional_pwm = true;
580 
581 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
582 		init_data.flags.edp_no_power_sequencing = true;
583 
584 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
585 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
586 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
587 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
588 
589 	if (amdgpu_dc_feature_mask & DC_FRL_MASK)
590 		init_data.flags.enable_frl = true;
591 
592 	init_data.flags.seamless_boot_edp_requested = false;
593 
594 	if (amdgpu_device_seamless_boot_supported(adev)) {
595 		init_data.flags.seamless_boot_edp_requested = true;
596 		init_data.flags.allow_seamless_boot_optimization = true;
597 		drm_dbg(adev->dm.ddev, "Seamless boot requested\n");
598 	}
599 
600 	init_data.flags.enable_mipi_converter_optimization = true;
601 
602 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
603 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
604 	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
605 
606 	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
607 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
608 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS_DYNAMIC)
609 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_DYNAMIC;
610 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS2_DYNAMIC)
611 		init_data.flags.disable_ips = DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
612 	else if (amdgpu_dc_debug_mask & DC_FORCE_IPS_ENABLE)
613 		init_data.flags.disable_ips = DMUB_IPS_ENABLE;
614 	else
615 		init_data.flags.disable_ips = dm_get_default_ips_mode(adev);
616 
617 	init_data.flags.disable_ips_in_vpb = 0;
618 
619 	/* DCN35 and above supports dynamic DTBCLK switch */
620 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 5, 0))
621 		init_data.flags.allow_0_dtb_clk = true;
622 
623 	/* Enable DWB for tested platforms only */
624 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
625 		init_data.num_virtual_links = 1;
626 
627 	/* DCN42 and above dpia switch to unified link training path */
628 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 2, 0)) {
629 		init_data.flags.consolidated_dpia_dp_lt = true;
630 		init_data.flags.enable_dpia_pre_training = true;
631 		init_data.flags.unify_link_enc_assignment = true;
632 		init_data.flags.usb4_bw_alloc_support = true;
633 	}
634 
635 	/* DCN201 audio desyncs using DP SS */
636 	if (adev->apu_flags & AMD_APU_IS_CYAN_SKILLFISH2)
637 		init_data.flags.ignore_dpref_ss = true;
638 
639 	retrieve_dmi_info(&adev->dm);
640 	if (adev->dm.edp0_on_dp1_quirk)
641 		init_data.flags.support_edp0_on_dp1 = true;
642 
643 	if (adev->dm.bb_from_dmub)
644 		init_data.bb_from_dmub = adev->dm.bb_from_dmub;
645 	else
646 		init_data.bb_from_dmub = NULL;
647 
648 	/* Display Core create. */
649 	adev->dm.dc = dc_create(&init_data);
650 
651 	if (adev->dm.dc) {
652 		drm_info(adev_to_drm(adev), "Display Core v%s initialized on %s\n", DC_VER,
653 			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
654 	} else {
655 		drm_info(adev_to_drm(adev), "Display Core failed to initialize with v%s!\n", DC_VER);
656 		goto error;
657 	}
658 
659 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
660 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
661 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
662 	}
663 
664 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
665 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
666 	if (dm_should_disable_stutter(adev->pdev))
667 		adev->dm.dc->debug.disable_stutter = true;
668 
669 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
670 		adev->dm.dc->debug.disable_stutter = true;
671 
672 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
673 		adev->dm.dc->debug.disable_dsc = true;
674 
675 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
676 		adev->dm.dc->debug.disable_clock_gate = true;
677 
678 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
679 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
680 
681 	if (amdgpu_dc_debug_mask & DC_DISABLE_SUBVP_FAMS) {
682 		adev->dm.dc->debug.force_disable_subvp = true;
683 		adev->dm.dc->debug.fams2_config.bits.enable = false;
684 	}
685 
686 	if (amdgpu_dc_debug_mask & DC_ENABLE_DML2) {
687 		adev->dm.dc->debug.using_dml2 = true;
688 		adev->dm.dc->debug.using_dml21 = true;
689 	}
690 
691 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_FORCE_FW_ENABLE)
692 		adev->dm.dc->debug.hdcp_lc_force_fw_enable = true;
693 
694 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_ENABLE_SW_FALLBACK)
695 		adev->dm.dc->debug.hdcp_lc_enable_sw_fallback = true;
696 
697 	if (amdgpu_dc_debug_mask & DC_SKIP_DETECTION_LT)
698 		adev->dm.dc->debug.skip_detection_link_training = true;
699 
700 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
701 
702 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
703 	adev->dm.dc->debug.ignore_cable_id = true;
704 
705 	/* temporary enable immediate restore for FAMS2 */
706 	adev->dm.dc->debug.fams2_imm_restore_drr = true;
707 
708 	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
709 		drm_info(adev_to_drm(adev), "DP-HDMI FRL PCON supported\n");
710 
711 	r = dm_dmub_hw_init(adev);
712 	if (r) {
713 		drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
714 		goto error;
715 	}
716 
717 	dc_hardware_init(adev->dm.dc);
718 
719 	/* Enable cursor offload if the ASIC supports it. */
720 	dc_dmub_srv_cursor_offload_init(adev->dm.dc);
721 
722 	/* GOP/vBIOS may leave an OPTC enabled for a display present at power-on
723 	 * but no longer driven (e.g. an external DP unplugged at boot). Such a
724 	 * dangling pipe keeps DCN out of idle and blocks s0i3. Power it down
725 	 * here when nothing needs to be preserved.
726 	 */
727 	if (adev->flags & AMD_IS_APU)
728 		dc_disable_dangling_timing_generators(adev->dm.dc);
729 
730 	adev->dm.hpd_rx_offload_wq = amdgpu_dm_hpd_rx_irq_create_workqueue(adev);
731 	if (!adev->dm.hpd_rx_offload_wq) {
732 		drm_err(adev_to_drm(adev), "failed to create hpd rx offload workqueue.\n");
733 		goto error;
734 	}
735 
736 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
737 		struct dc_phy_addr_space_config pa_config;
738 
739 		mmhub_read_system_context(adev, &pa_config);
740 
741 		// Call the DC init_memory func
742 		dc_setup_system_context(adev->dm.dc, &pa_config);
743 	}
744 
745 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
746 	if (!adev->dm.freesync_module) {
747 		drm_err(adev_to_drm(adev),
748 		"failed to initialize freesync_module.\n");
749 	} else
750 		drm_dbg_driver(adev_to_drm(adev), "freesync_module init done %p.\n",
751 				adev->dm.freesync_module);
752 
753 	amdgpu_dm_init_color_mod();
754 
755 	if (adev->dm.dc->caps.max_links > 0) {
756 		adev->dm.vblank_control_workqueue =
757 			create_singlethread_workqueue("dm_vblank_control_workqueue");
758 		if (!adev->dm.vblank_control_workqueue)
759 			drm_err(adev_to_drm(adev), "failed to initialize vblank_workqueue.\n");
760 	}
761 
762 	if (adev->dm.dc->caps.ips_support &&
763 	    adev->dm.dc->config.disable_ips != DMUB_IPS_DISABLE_ALL)
764 		adev->dm.idle_workqueue = idle_create_workqueue(adev);
765 
766 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
767 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
768 
769 		if (!adev->dm.hdcp_workqueue)
770 			drm_err(adev_to_drm(adev), "failed to initialize hdcp_workqueue.\n");
771 		else
772 			drm_dbg_driver(adev_to_drm(adev),
773 				       "hdcp_workqueue init done %p.\n",
774 				       adev->dm.hdcp_workqueue);
775 
776 		dc_init_callbacks(adev->dm.dc, &init_params);
777 	}
778 	if (adev->dm.dc->caps.max_links > 0) {
779 		adev->dm.hdmi_frl_status_polling_wq =
780 			create_singlethread_workqueue("hdmi_frl_status_polling_wq");
781 		if (!adev->dm.hdmi_frl_status_polling_wq)
782 			drm_err(adev_to_drm(adev), "failed to initialize hdmi_frl_status_polling_wq\n");
783 	}
784 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
785 		init_completion(&adev->dm.dmub_aux_transfer_done);
786 		adev->dm.dmub_notify = kzalloc_obj(struct dmub_notification);
787 		if (!adev->dm.dmub_notify) {
788 			drm_info(adev_to_drm(adev), "fail to allocate adev->dm.dmub_notify");
789 			goto error;
790 		}
791 
792 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
793 		if (!adev->dm.delayed_hpd_wq) {
794 			drm_err(adev_to_drm(adev), "failed to create hpd offload workqueue.\n");
795 			goto error;
796 		}
797 
798 		amdgpu_dm_outbox_init(adev);
799 		if (!dm_register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
800 			dm_dmub_aux_setconfig_callback, false)) {
801 			drm_err(adev_to_drm(adev), "fail to register dmub aux callback");
802 			goto error;
803 		}
804 
805 		for (size_t i = 0; i < ARRAY_SIZE(adev->dm.fused_io); i++)
806 			init_completion(&adev->dm.fused_io[i].replied);
807 
808 		if (!dm_register_dmub_notify_callback(adev, DMUB_NOTIFICATION_FUSED_IO,
809 			dm_dmub_aux_fused_io_callback, false)) {
810 			drm_err(adev_to_drm(adev), "fail to register dmub fused io callback");
811 			goto error;
812 		}
813 		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
814 		 * It is expected that DMUB will resend any pending notifications at this point. Note
815 		 * that hpd and hpd_irq handler registration are deferred to
816 		 * amdgpu_dm_register_hpd_handlers() to align legacy interface initialization
817 		 * sequence. Connection status will be proactivly detected once in the
818 		 * amdgpu_dm_initialize_drm_device.
819 		 */
820 		dc_enable_dmub_outbox(adev->dm.dc);
821 
822 		/* DPIA trace goes to dmesg logs only if outbox is enabled */
823 		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
824 			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
825 	}
826 
827 	if (amdgpu_dm_initialize_drm_device(adev)) {
828 		drm_err(adev_to_drm(adev),
829 		"failed to initialize sw for display support.\n");
830 		goto error;
831 	}
832 
833 	if (amdgpu_dm_init_power_module(&adev->dm))
834 		goto error;
835 
836 	/* create fake encoders for MST */
837 	dm_dp_create_fake_mst_encoders(adev);
838 
839 	/* TODO: Add_display_info? */
840 
841 	/* TODO use dynamic cursor width */
842 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
843 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
844 
845 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
846 		drm_err(adev_to_drm(adev),
847 		"failed to initialize vblank for display support.\n");
848 		goto error;
849 	}
850 
851 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
852 	amdgpu_dm_crtc_secure_display_create_contexts(adev);
853 	if (!adev->dm.secure_display_ctx.crtc_ctx)
854 		drm_err(adev_to_drm(adev), "failed to initialize secure display contexts.\n");
855 
856 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))
857 		adev->dm.secure_display_ctx.support_mul_roi = true;
858 
859 #endif
860 
861 	drm_dbg_driver(adev_to_drm(adev), "KMS initialized.\n");
862 
863 	return 0;
864 error:
865 	amdgpu_dm_fini(adev);
866 
867 	return -EINVAL;
868 }
869 
870 STATIC_IFN_KUNIT int amdgpu_dm_early_fini(struct amdgpu_ip_block *ip_block)
871 {
872 	struct amdgpu_device *adev = ip_block->adev;
873 
874 	amdgpu_dm_audio_fini(adev);
875 
876 	return 0;
877 }
878 EXPORT_IF_KUNIT(amdgpu_dm_early_fini);
879 
880 static void amdgpu_dm_fini(struct amdgpu_device *adev)
881 {
882 	int i;
883 
884 	if (adev->dm.vblank_control_workqueue) {
885 		destroy_workqueue(adev->dm.vblank_control_workqueue);
886 		adev->dm.vblank_control_workqueue = NULL;
887 	}
888 
889 	/* The poll re-queues itself, so stop it before the wq and dc go away. */
890 	if (adev->dm.hdmi_frl_status_polling_wq) {
891 		cancel_delayed_work_sync(&adev->dm.hdmi_frl_status_polling_work);
892 		destroy_workqueue(adev->dm.hdmi_frl_status_polling_wq);
893 		adev->dm.hdmi_frl_status_polling_wq = NULL;
894 	}
895 
896 	if (adev->dm.idle_workqueue) {
897 		if (adev->dm.idle_workqueue->running) {
898 			adev->dm.idle_workqueue->enable = false;
899 			flush_work(&adev->dm.idle_workqueue->work);
900 		}
901 
902 		kfree(adev->dm.idle_workqueue);
903 		adev->dm.idle_workqueue = NULL;
904 	}
905 
906 	/*
907 	 * Disable ISM before dc_destroy() invalidates dm->dc.
908 	 *
909 	 * Quiesce workers first without dc_lock (they take dc_lock
910 	 * themselves, so syncing under it would deadlock), then drive the
911 	 * FSM back to FULL_POWER_RUNNING under dc_lock.
912 	 */
913 	amdgpu_dm_ism_disable(&adev->dm);
914 	scoped_guard(mutex, &adev->dm.dc_lock)
915 		amdgpu_dm_ism_force_full_power(&adev->dm);
916 
917 	amdgpu_dm_destroy_drm_device(&adev->dm);
918 
919 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
920 	if (adev->dm.secure_display_ctx.crtc_ctx) {
921 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
922 			if (adev->dm.secure_display_ctx.crtc_ctx[i].crtc) {
923 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].notify_ta_work);
924 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].forward_roi_work);
925 			}
926 		}
927 		kfree(adev->dm.secure_display_ctx.crtc_ctx);
928 		adev->dm.secure_display_ctx.crtc_ctx = NULL;
929 	}
930 #endif
931 	if (adev->dm.hdcp_workqueue) {
932 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
933 		adev->dm.hdcp_workqueue = NULL;
934 	}
935 
936 	if (adev->dm.dc) {
937 		dc_deinit_callbacks(adev->dm.dc);
938 		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
939 		if (dc_enable_dmub_notifications(adev->dm.dc)) {
940 			kfree(adev->dm.dmub_notify);
941 			adev->dm.dmub_notify = NULL;
942 			destroy_workqueue(adev->dm.delayed_hpd_wq);
943 			adev->dm.delayed_hpd_wq = NULL;
944 		}
945 	}
946 
947 	if (adev->dm.dmub_bo)
948 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
949 				      &adev->dm.dmub_bo_gpu_addr,
950 				      &adev->dm.dmub_bo_cpu_addr);
951 
952 	if (adev->dm.boot_time_crc_info.bo_ptr)
953 		amdgpu_bo_free_kernel(&adev->dm.boot_time_crc_info.bo_ptr,
954 					&adev->dm.boot_time_crc_info.gpu_addr,
955 					&adev->dm.boot_time_crc_info.cpu_addr);
956 
957 	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
958 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
959 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
960 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
961 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
962 			}
963 		}
964 
965 		kfree(adev->dm.hpd_rx_offload_wq);
966 		adev->dm.hpd_rx_offload_wq = NULL;
967 	}
968 
969 	amdgpu_dm_irq_fini(adev);
970 
971 	/* DC Destroy TODO: Replace destroy DAL */
972 	if (adev->dm.dc)
973 		dc_destroy(&adev->dm.dc);
974 
975 	if (adev->dm.cgs_device) {
976 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
977 		adev->dm.cgs_device = NULL;
978 	}
979 	if (adev->dm.freesync_module) {
980 		mod_freesync_destroy(adev->dm.freesync_module);
981 		adev->dm.freesync_module = NULL;
982 	}
983 
984 	if (adev->dm.power_module) {
985 		mod_power_destroy(adev->dm.power_module);
986 		adev->dm.power_module = NULL;
987 	}
988 	mutex_destroy(&adev->dm.audio_lock);
989 	mutex_destroy(&adev->dm.dc_lock);
990 	mutex_destroy(&adev->dm.dpia_aux_lock);
991 }
992 
993 STATIC_IFN_KUNIT int load_dmcu_fw(struct amdgpu_device *adev)
994 {
995 	const char *fw_name_dmcu = NULL;
996 	int r;
997 	const struct dmcu_firmware_header_v1_0 *hdr;
998 
999 	switch (adev->asic_type) {
1000 #if defined(CONFIG_DRM_AMD_DC_SI)
1001 	case CHIP_TAHITI:
1002 	case CHIP_PITCAIRN:
1003 	case CHIP_VERDE:
1004 	case CHIP_OLAND:
1005 #endif
1006 	case CHIP_BONAIRE:
1007 	case CHIP_HAWAII:
1008 	case CHIP_KAVERI:
1009 	case CHIP_KABINI:
1010 	case CHIP_MULLINS:
1011 	case CHIP_TONGA:
1012 	case CHIP_FIJI:
1013 	case CHIP_CARRIZO:
1014 	case CHIP_STONEY:
1015 	case CHIP_POLARIS11:
1016 	case CHIP_POLARIS10:
1017 	case CHIP_POLARIS12:
1018 	case CHIP_VEGAM:
1019 	case CHIP_VEGA10:
1020 	case CHIP_VEGA12:
1021 	case CHIP_VEGA20:
1022 		return 0;
1023 	case CHIP_NAVI12:
1024 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
1025 		break;
1026 	case CHIP_RAVEN:
1027 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
1028 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
1029 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
1030 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
1031 		else
1032 			return 0;
1033 		break;
1034 	default:
1035 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1036 		case IP_VERSION(2, 0, 2):
1037 		case IP_VERSION(2, 0, 3):
1038 		case IP_VERSION(2, 0, 0):
1039 		case IP_VERSION(2, 1, 0):
1040 		case IP_VERSION(3, 0, 0):
1041 		case IP_VERSION(3, 0, 2):
1042 		case IP_VERSION(3, 0, 3):
1043 		case IP_VERSION(3, 0, 1):
1044 		case IP_VERSION(3, 1, 2):
1045 		case IP_VERSION(3, 1, 3):
1046 		case IP_VERSION(3, 1, 4):
1047 		case IP_VERSION(3, 1, 5):
1048 		case IP_VERSION(3, 1, 6):
1049 		case IP_VERSION(3, 2, 0):
1050 		case IP_VERSION(3, 2, 1):
1051 		case IP_VERSION(3, 5, 0):
1052 		case IP_VERSION(3, 5, 1):
1053 		case IP_VERSION(3, 6, 0):
1054 		case IP_VERSION(4, 0, 1):
1055 		case IP_VERSION(4, 2, 0):
1056 		case IP_VERSION(4, 2, 1):
1057 		case IP_VERSION(6, 0, 0):
1058 			return 0;
1059 		default:
1060 			break;
1061 		}
1062 		drm_err(adev_to_drm(adev), "Unsupported ASIC type: 0x%X\n", adev->asic_type);
1063 		return -EINVAL;
1064 	}
1065 
1066 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1067 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not supported on direct or SMU loading\n");
1068 		return 0;
1069 	}
1070 
1071 	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, AMDGPU_UCODE_REQUIRED,
1072 				 "%s", fw_name_dmcu);
1073 	if (r == -ENODEV) {
1074 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
1075 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not found\n");
1076 		adev->dm.fw_dmcu = NULL;
1077 		return 0;
1078 	}
1079 	if (r) {
1080 		drm_err(adev_to_drm(adev), "amdgpu_dm: Can't validate firmware \"%s\"\n",
1081 			fw_name_dmcu);
1082 		amdgpu_ucode_release(&adev->dm.fw_dmcu);
1083 		return r;
1084 	}
1085 
1086 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
1087 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
1088 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
1089 	adev->firmware.fw_size +=
1090 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
1091 
1092 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
1093 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
1094 	adev->firmware.fw_size +=
1095 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
1096 
1097 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
1098 
1099 	drm_dbg_kms(adev_to_drm(adev), "PSP loading DMCU firmware\n");
1100 
1101 	return 0;
1102 }
1103 EXPORT_IF_KUNIT(load_dmcu_fw);
1104 
1105 STATIC_IFN_KUNIT int dm_sw_init(struct amdgpu_ip_block *ip_block)
1106 {
1107 	struct amdgpu_device *adev = ip_block->adev;
1108 	int r;
1109 
1110 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
1111 
1112 	if (!adev->dm.cgs_device) {
1113 		drm_err(adev_to_drm(adev), "failed to create cgs device.\n");
1114 		return -EINVAL;
1115 	}
1116 
1117 	/* Moved from dm init since we need to use allocations for storing bounding box data */
1118 	INIT_LIST_HEAD(&adev->dm.da_list);
1119 
1120 	r = dm_dmub_sw_init(adev);
1121 	if (r)
1122 		return r;
1123 
1124 	return load_dmcu_fw(adev);
1125 }
1126 EXPORT_IF_KUNIT(dm_sw_init);
1127 
1128 STATIC_IFN_KUNIT int dm_sw_fini(struct amdgpu_ip_block *ip_block)
1129 {
1130 	struct amdgpu_device *adev = ip_block->adev;
1131 	struct dal_allocation *da;
1132 
1133 	list_for_each_entry(da, &adev->dm.da_list, list) {
1134 		if (adev->dm.bb_from_dmub == (void *) da->cpu_ptr) {
1135 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
1136 			list_del(&da->list);
1137 			kfree(da);
1138 			adev->dm.bb_from_dmub = NULL;
1139 			break;
1140 		}
1141 	}
1142 
1143 
1144 	kfree(adev->dm.dmub_fb_info);
1145 	adev->dm.dmub_fb_info = NULL;
1146 
1147 	if (adev->dm.dmub_srv) {
1148 		dmub_srv_destroy(adev->dm.dmub_srv);
1149 		kfree(adev->dm.dmub_srv);
1150 		adev->dm.dmub_srv = NULL;
1151 	}
1152 
1153 	amdgpu_ucode_release(&adev->dm.dmub_fw);
1154 	amdgpu_ucode_release(&adev->dm.fw_dmcu);
1155 
1156 	return 0;
1157 }
1158 EXPORT_IF_KUNIT(dm_sw_fini);
1159 
1160 
1161 static void amdgpu_dm_boot_time_crc_init(struct amdgpu_device *adev)
1162 {
1163 	struct dm_boot_time_crc_info *bootcrc_info = NULL;
1164 	struct dmub_srv *dmub = NULL;
1165 	union dmub_fw_boot_options option = {0};
1166 	int ret = 0;
1167 	const uint32_t fb_size = 3 * 1024 * 1024;	/* 3MB for DCC pattern */
1168 
1169 	if (!adev || !adev->dm.dc || !adev->dm.dc->ctx ||
1170 		!adev->dm.dc->ctx->dmub_srv) {
1171 		return;
1172 	}
1173 
1174 	dmub = adev->dm.dc->ctx->dmub_srv->dmub;
1175 	bootcrc_info = &adev->dm.boot_time_crc_info;
1176 
1177 	if (!dmub || !dmub->hw_funcs.get_fw_boot_option) {
1178 		drm_dbg(adev_to_drm(adev), "failed to init boot time crc buffer\n");
1179 		return;
1180 	}
1181 
1182 	option = dmub->hw_funcs.get_fw_boot_option(dmub);
1183 
1184 	/* Return if boot time CRC is not enabled */
1185 	if (option.bits.bootcrc_en_at_S0i3 == 0)
1186 		return;
1187 
1188 	/* Create a buffer for boot time CRC */
1189 	ret = amdgpu_bo_create_kernel(adev, fb_size, PAGE_SIZE,
1190 		AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT,
1191 		&bootcrc_info->bo_ptr,
1192 		&bootcrc_info->gpu_addr,
1193 		&bootcrc_info->cpu_addr);
1194 
1195 	if (ret) {
1196 		drm_dbg(adev_to_drm(adev), "failed to create boot time crc buffer\n");
1197 	} else {
1198 		bootcrc_info->size = fb_size;
1199 
1200 		drm_dbg(adev_to_drm(adev), "boot time crc buffer created addr 0x%llx, size %u\n",
1201 			bootcrc_info->gpu_addr, bootcrc_info->size);
1202 
1203 		/* Send the buffer info to DMUB */
1204 		dc_dmub_srv_boot_time_crc_init(adev->dm.dc,
1205 			bootcrc_info->gpu_addr, bootcrc_info->size);
1206 	}
1207 }
1208 
1209 STATIC_IFN_KUNIT int dm_late_init(struct amdgpu_ip_block *ip_block)
1210 {
1211 	struct amdgpu_device *adev = ip_block->adev;
1212 
1213 	struct dmcu_iram_parameters params;
1214 	unsigned int linear_lut[16];
1215 	int i;
1216 	struct dmcu *dmcu = NULL;
1217 
1218 	dmcu = adev->dm.dc->res_pool->dmcu;
1219 
1220 	/* Init the boot time CRC (skip in resume) */
1221 	if ((adev->in_suspend == 0) &&
1222 		(amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(3, 6, 0)))
1223 		amdgpu_dm_boot_time_crc_init(adev);
1224 
1225 	for (i = 0; i < 16; i++)
1226 		linear_lut[i] = 0xFFFF * i / 15;
1227 
1228 	params.set = 0;
1229 	params.backlight_ramping_override = false;
1230 	params.backlight_ramping_start = 0xCCCC;
1231 	params.backlight_ramping_reduction = 0xCCCCCCCC;
1232 	params.backlight_lut_array_size = 16;
1233 	params.backlight_lut_array = linear_lut;
1234 
1235 	/* Min backlight level after ABM reduction,  Don't allow below 1%
1236 	 * 0xFFFF x 0.01 = 0x28F
1237 	 */
1238 	params.min_abm_backlight = 0x28F;
1239 	/* In the case where abm is implemented on dmcub,
1240 	 * dmcu object will be null.
1241 	 * ABM 2.4 and up are implemented on dmcub.
1242 	 */
1243 	if (dmcu) {
1244 		if (!dmcu_load_iram(dmcu, params))
1245 			return -EINVAL;
1246 	} else if (adev->dm.dc->ctx->dmub_srv) {
1247 		struct dc_link *edp_links[MAX_NUM_EDP];
1248 		int edp_num;
1249 
1250 		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
1251 		for (i = 0; i < edp_num; i++) {
1252 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
1253 				return -EINVAL;
1254 		}
1255 	}
1256 
1257 	return amdgpu_dm_detect_mst_link_for_all_connectors(adev_to_drm(adev));
1258 }
1259 EXPORT_IF_KUNIT(dm_late_init);
1260 
1261 STATIC_IFN_KUNIT void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
1262 {
1263 	u8 buf[UUID_SIZE];
1264 	guid_t guid;
1265 	int ret;
1266 
1267 	mutex_lock(&mgr->lock);
1268 	if (!mgr->mst_primary)
1269 		goto out_fail;
1270 
1271 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
1272 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
1273 		goto out_fail;
1274 	}
1275 
1276 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
1277 				 DP_MST_EN |
1278 				 DP_UP_REQ_EN |
1279 				 DP_UPSTREAM_IS_SRC);
1280 	if (ret < 0) {
1281 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
1282 		goto out_fail;
1283 	}
1284 
1285 	/* Some hubs forget their guids after they resume */
1286 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, buf, sizeof(buf));
1287 	if (ret != sizeof(buf)) {
1288 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
1289 		goto out_fail;
1290 	}
1291 
1292 	import_guid(&guid, buf);
1293 
1294 	if (guid_is_null(&guid)) {
1295 		guid_gen(&guid);
1296 		export_guid(buf, &guid);
1297 
1298 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, buf, sizeof(buf));
1299 
1300 		if (ret != sizeof(buf)) {
1301 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
1302 			goto out_fail;
1303 		}
1304 	}
1305 
1306 	guid_copy(&mgr->mst_primary->guid, &guid);
1307 
1308 out_fail:
1309 	mutex_unlock(&mgr->lock);
1310 }
1311 EXPORT_IF_KUNIT(resume_mst_branch_status);
1312 
1313 STATIC_IFN_KUNIT void s3_handle_mst(struct drm_device *dev, bool suspend)
1314 {
1315 	struct amdgpu_dm_connector *aconnector;
1316 	struct drm_connector *connector;
1317 	struct drm_connector_list_iter iter;
1318 	struct drm_dp_mst_topology_mgr *mgr;
1319 
1320 	drm_connector_list_iter_begin(dev, &iter);
1321 	drm_for_each_connector_iter(connector, &iter) {
1322 
1323 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1324 			continue;
1325 
1326 		aconnector = to_amdgpu_dm_connector(connector);
1327 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
1328 		    aconnector->mst_root)
1329 			continue;
1330 
1331 		mgr = &aconnector->mst_mgr;
1332 
1333 		if (suspend) {
1334 			drm_dp_mst_topology_mgr_suspend(mgr);
1335 		} else {
1336 			/* if extended timeout is supported in hardware,
1337 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
1338 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
1339 			 */
1340 			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
1341 			if (!dp_is_lttpr_present(aconnector->dc_link))
1342 				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
1343 
1344 			/* TODO: move resume_mst_branch_status() into drm mst resume again
1345 			 * once topology probing work is pulled out from mst resume into mst
1346 			 * resume 2nd step. mst resume 2nd step should be called after old
1347 			 * state getting restored (i.e. drm_atomic_helper_resume()).
1348 			 */
1349 			resume_mst_branch_status(mgr);
1350 		}
1351 	}
1352 	drm_connector_list_iter_end(&iter);
1353 }
1354 EXPORT_IF_KUNIT(s3_handle_mst);
1355 
1356 STATIC_IFN_KUNIT int dm_oem_i2c_hw_init(struct amdgpu_device *adev)
1357 {
1358 	struct amdgpu_display_manager *dm = &adev->dm;
1359 	struct amdgpu_i2c_adapter *oem_i2c;
1360 	struct ddc_service *oem_ddc_service;
1361 	int r;
1362 
1363 	oem_ddc_service = dc_get_oem_i2c_device(adev->dm.dc);
1364 	if (oem_ddc_service) {
1365 		oem_i2c = amdgpu_dm_create_i2c(oem_ddc_service, true);
1366 		if (!oem_i2c) {
1367 			drm_info(adev_to_drm(adev), "Failed to create oem i2c adapter data\n");
1368 			return -ENOMEM;
1369 		}
1370 
1371 		r = devm_i2c_add_adapter(adev->dev, &oem_i2c->base);
1372 		if (r) {
1373 			drm_info(adev_to_drm(adev), "Failed to register oem i2c\n");
1374 			kfree(oem_i2c);
1375 			return r;
1376 		}
1377 		dm->oem_i2c = oem_i2c;
1378 	}
1379 
1380 	return 0;
1381 }
1382 EXPORT_IF_KUNIT(dm_oem_i2c_hw_init);
1383 
1384 /**
1385  * dm_hw_init() - Initialize DC device
1386  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
1387  *
1388  * Initialize the &struct amdgpu_display_manager device. This involves calling
1389  * the initializers of each DM component, then populating the struct with them.
1390  *
1391  * Although the function implies hardware initialization, both hardware and
1392  * software are initialized here. Splitting them out to their relevant init
1393  * hooks is a future TODO item.
1394  *
1395  * Some notable things that are initialized here:
1396  *
1397  * - Display Core, both software and hardware
1398  * - DC modules that we need (freesync and color management)
1399  * - DRM software states
1400  * - Interrupt sources and handlers
1401  * - Vblank support
1402  * - Debug FS entries, if enabled
1403  */
1404 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
1405 {
1406 	struct amdgpu_device *adev = ip_block->adev;
1407 	int r;
1408 
1409 	adev->dm.i2c_devres_group = devres_open_group(adev->dev, NULL, GFP_KERNEL);
1410 	if (!adev->dm.i2c_devres_group)
1411 		return -ENOMEM;
1412 
1413 	/* Create DAL display manager */
1414 	r = amdgpu_dm_init(adev);
1415 	if (r)
1416 		goto err_release_i2c;
1417 	amdgpu_dm_hpd_init(adev);
1418 
1419 	r = dm_oem_i2c_hw_init(adev);
1420 	if (r)
1421 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
1422 
1423 	devres_close_group(adev->dev, adev->dm.i2c_devres_group);
1424 	return 0;
1425 
1426 err_release_i2c:
1427 	devres_release_group(adev->dev, adev->dm.i2c_devres_group);
1428 	return r;
1429 }
1430 
1431 /**
1432  * dm_hw_fini() - Teardown DC device
1433  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
1434  *
1435  * Teardown components within &struct amdgpu_display_manager that require
1436  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
1437  * were loaded. Also flush IRQ workqueues and disable them.
1438  */
1439 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
1440 {
1441 	struct amdgpu_device *adev = ip_block->adev;
1442 
1443 	if (adev->dm.i2c_devres_group)
1444 		devres_release_group(adev->dev, adev->dm.i2c_devres_group);
1445 
1446 	amdgpu_dm_hpd_fini(adev);
1447 
1448 	amdgpu_dm_fini(adev);
1449 	return 0;
1450 }
1451 
1452 
1453 STATIC_IFN_KUNIT void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
1454 						    struct dc_state *state, bool enable)
1455 {
1456 	enum dc_irq_source irq_source;
1457 	struct amdgpu_crtc *acrtc;
1458 	int rc = -EBUSY;
1459 	int i = 0;
1460 
1461 	for (i = 0; i < state->stream_count; i++) {
1462 		acrtc = amdgpu_dm_get_crtc_by_otg_inst(
1463 				adev, state->stream_status[i].primary_otg_inst);
1464 
1465 		if (acrtc && state->stream_status[i].plane_count != 0 &&
1466 		    amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
1467 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
1468 			rc = amdgpu_dm_irq_set(adev, irq_source, enable) ? 0 : -EBUSY;
1469 			if (rc)
1470 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
1471 					 enable ? "enable" : "disable");
1472 
1473 			if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
1474 				if (enable) {
1475 					if (amdgpu_dm_crtc_vrr_active(
1476 							to_dm_crtc_state(acrtc->base.state)))
1477 						rc = amdgpu_dm_crtc_set_vupdate_irq(
1478 							&acrtc->base, true);
1479 				} else
1480 					rc = amdgpu_dm_crtc_set_vupdate_irq(
1481 							&acrtc->base, false);
1482 
1483 				if (rc)
1484 					drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
1485 						enable ? "en" : "dis");
1486 			}
1487 
1488 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
1489 			/* During gpu-reset we disable and then enable vblank irq, so
1490 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
1491 			 */
1492 			if (!amdgpu_dm_irq_set(adev, irq_source, enable))
1493 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
1494 
1495 		} else if (acrtc && state->stream_status[i].plane_count != 0) {
1496 			/* DCN only needs to toggle VUPDATE_NO_LOCK */
1497 			rc = amdgpu_dm_crtc_set_vupdate_irq(&acrtc->base, enable);
1498 			if (rc)
1499 				drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
1500 					 enable ? "en" : "dis");
1501 		}
1502 	}
1503 
1504 }
1505 EXPORT_IF_KUNIT(dm_gpureset_toggle_interrupts);
1506 
1507 DEFINE_FREE(state_release, struct dc_state *, dc_state_release(_T))
1508 
1509 STATIC_IFN_KUNIT enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
1510 {
1511 	struct dc_state *context __free(state_release) = NULL;
1512 	int i;
1513 	struct dc_stream_state *del_streams[MAX_PIPES];
1514 	int del_streams_count = 0;
1515 	struct dc_commit_streams_params params = {};
1516 
1517 	memset(del_streams, 0, sizeof(del_streams));
1518 
1519 	context = dc_state_create_current_copy(dc);
1520 	if (context == NULL)
1521 		return DC_ERROR_UNEXPECTED;
1522 
1523 	/* First remove from context all streams */
1524 	for (i = 0; i < context->stream_count; i++) {
1525 		struct dc_stream_state *stream = context->streams[i];
1526 
1527 		del_streams[del_streams_count++] = stream;
1528 	}
1529 
1530 	/* Remove all planes for removed streams and then remove the streams */
1531 	for (i = 0; i < del_streams_count; i++) {
1532 		enum dc_status res;
1533 
1534 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
1535 			return DC_FAIL_DETACH_SURFACES;
1536 
1537 		res = dc_state_remove_stream(dc, context, del_streams[i]);
1538 		if (res != DC_OK)
1539 			return res;
1540 	}
1541 
1542 	params.streams = context->streams;
1543 	params.stream_count = context->stream_count;
1544 
1545 	return dc_commit_streams(dc, &params);
1546 }
1547 EXPORT_IF_KUNIT(amdgpu_dm_commit_zero_streams);
1548 
1549 STATIC_IFN_KUNIT int dm_cache_state(struct amdgpu_device *adev)
1550 {
1551 	int r;
1552 
1553 	adev->dm.cached_state = dm_atomic_helper_suspend(adev_to_drm(adev));
1554 	if (IS_ERR(adev->dm.cached_state)) {
1555 		r = PTR_ERR(adev->dm.cached_state);
1556 		adev->dm.cached_state = NULL;
1557 	}
1558 
1559 	return adev->dm.cached_state ? 0 : r;
1560 }
1561 EXPORT_IF_KUNIT(dm_cache_state);
1562 
1563 STATIC_IFN_KUNIT void dm_destroy_cached_state(struct amdgpu_device *adev)
1564 {
1565 	struct amdgpu_display_manager *dm = &adev->dm;
1566 	struct drm_device *ddev = adev_to_drm(adev);
1567 	struct dm_plane_state *dm_new_plane_state;
1568 	struct drm_plane_state *new_plane_state;
1569 	struct dm_crtc_state *dm_new_crtc_state;
1570 	struct drm_crtc_state *new_crtc_state;
1571 	struct drm_plane *plane;
1572 	struct drm_crtc *crtc;
1573 	int i;
1574 
1575 	if (!dm->cached_state)
1576 		return;
1577 
1578 	/* Force mode set in atomic commit */
1579 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
1580 		new_crtc_state->active_changed = true;
1581 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
1582 		amdgpu_dm_reset_freesync_config_for_crtc(dm_new_crtc_state);
1583 	}
1584 
1585 	/*
1586 	 * atomic_check is expected to create the dc states. We need to release
1587 	 * them here, since they were duplicated as part of the suspend
1588 	 * procedure.
1589 	 */
1590 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
1591 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
1592 		if (dm_new_crtc_state->stream) {
1593 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
1594 			dc_stream_release(dm_new_crtc_state->stream);
1595 			dm_new_crtc_state->stream = NULL;
1596 		}
1597 		dm_new_crtc_state->base.color_mgmt_changed = true;
1598 	}
1599 
1600 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
1601 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
1602 		if (dm_new_plane_state->dc_state) {
1603 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
1604 			dc_plane_state_release(dm_new_plane_state->dc_state);
1605 			dm_new_plane_state->dc_state = NULL;
1606 		}
1607 	}
1608 
1609 	drm_atomic_helper_resume(ddev, dm->cached_state);
1610 
1611 	dm->cached_state = NULL;
1612 }
1613 EXPORT_IF_KUNIT(dm_destroy_cached_state);
1614 
1615 static int dm_suspend(struct amdgpu_ip_block *ip_block)
1616 {
1617 	struct amdgpu_device *adev = ip_block->adev;
1618 	struct amdgpu_display_manager *dm = &adev->dm;
1619 
1620 	if (amdgpu_in_reset(adev)) {
1621 		enum dc_status res;
1622 
1623 		/* Quiesce ISM workers before taking dc_lock (workers take
1624 		 * dc_lock themselves; syncing under it would deadlock).
1625 		 */
1626 		amdgpu_dm_ism_disable(dm);
1627 
1628 		mutex_lock(&dm->dc_lock);
1629 
1630 		amdgpu_dm_ism_force_full_power(dm);
1631 		dc_allow_idle_optimizations(adev->dm.dc, false);
1632 
1633 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
1634 		if (!dm->cached_dc_state) {
1635 			drm_err(adev_to_drm(adev),
1636 				"Failed to allocate cached DC state during suspend\n");
1637 			mutex_unlock(&dm->dc_lock);
1638 			return -ENOMEM;
1639 		}
1640 
1641 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
1642 
1643 		res = amdgpu_dm_commit_zero_streams(dm->dc);
1644 		if (res != DC_OK) {
1645 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
1646 			dc_state_release(dm->cached_dc_state);
1647 			dm->cached_dc_state = NULL;
1648 			mutex_unlock(&dm->dc_lock);
1649 			return -EINVAL;
1650 		}
1651 
1652 		amdgpu_dm_irq_suspend(adev);
1653 
1654 		amdgpu_dm_hpd_rx_irq_work_suspend(dm);
1655 
1656 		return 0;
1657 	}
1658 
1659 	if (!adev->dm.cached_state) {
1660 		int r = dm_cache_state(adev);
1661 
1662 		if (r)
1663 			return r;
1664 	}
1665 
1666 	amdgpu_dm_s3_handle_hdmi_cec(adev_to_drm(adev), true);
1667 
1668 	s3_handle_mst(adev_to_drm(adev), true);
1669 
1670 	amdgpu_dm_irq_suspend(adev);
1671 
1672 	/*
1673 	 * Quiesce ISM workers before taking dc_lock (workers take dc_lock
1674 	 * themselves; syncing under it would deadlock).
1675 	 */
1676 	amdgpu_dm_ism_disable(dm);
1677 	scoped_guard(mutex, &dm->dc_lock)
1678 		amdgpu_dm_ism_force_full_power(dm);
1679 
1680 	amdgpu_dm_hpd_rx_irq_work_suspend(dm);
1681 
1682 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
1683 
1684 	if (dm->dc->caps.ips_support && adev->in_s0ix)
1685 		dc_allow_idle_optimizations(dm->dc, true);
1686 
1687 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
1688 
1689 	return 0;
1690 }
1691 
1692 void amdgpu_dm_emulated_link_detect(struct dc_link *link)
1693 {
1694 	struct dc_sink_init_data sink_init_data = { 0 };
1695 	struct display_sink_capability sink_caps = { 0 };
1696 	enum dc_edid_status edid_status;
1697 	struct dc_context *dc_ctx = link->ctx;
1698 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
1699 	struct dc_sink *sink = NULL;
1700 	struct dc_sink *prev_sink = NULL;
1701 
1702 	link->type = dc_connection_none;
1703 	prev_sink = link->local_sink;
1704 
1705 	if (prev_sink)
1706 		dc_sink_release(prev_sink);
1707 
1708 	switch (link->connector_signal) {
1709 	case SIGNAL_TYPE_HDMI_TYPE_A: {
1710 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1711 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
1712 		break;
1713 	}
1714 
1715 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
1716 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1717 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
1718 		break;
1719 	}
1720 
1721 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
1722 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1723 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
1724 		break;
1725 	}
1726 
1727 	case SIGNAL_TYPE_LVDS: {
1728 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
1729 		sink_caps.signal = SIGNAL_TYPE_LVDS;
1730 		break;
1731 	}
1732 
1733 	case SIGNAL_TYPE_EDP: {
1734 		sink_caps.transaction_type =
1735 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
1736 		sink_caps.signal = SIGNAL_TYPE_EDP;
1737 		break;
1738 	}
1739 
1740 	case SIGNAL_TYPE_DISPLAY_PORT: {
1741 		sink_caps.transaction_type =
1742 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
1743 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
1744 		break;
1745 	}
1746 
1747 	default:
1748 		drm_err(dev, "Invalid connector type! signal:%d\n",
1749 			link->connector_signal);
1750 		return;
1751 	}
1752 
1753 	sink_init_data.link = link;
1754 	sink_init_data.sink_signal = sink_caps.signal;
1755 
1756 	sink = dc_sink_create(&sink_init_data);
1757 	if (!sink) {
1758 		drm_err(dev, "Failed to create sink!\n");
1759 		return;
1760 	}
1761 
1762 	/* dc_sink_create returns a new reference */
1763 	link->local_sink = sink;
1764 
1765 	edid_status = dm_helpers_read_local_edid(
1766 			link->ctx,
1767 			link,
1768 			sink);
1769 
1770 	if (edid_status != EDID_OK)
1771 		drm_err(dev, "Failed to read EDID\n");
1772 
1773 }
1774 EXPORT_IF_KUNIT(amdgpu_dm_emulated_link_detect);
1775 
1776 STATIC_IFN_KUNIT void dm_gpureset_commit_state(struct dc_state *dc_state,
1777 					       struct amdgpu_display_manager *dm)
1778 {
1779 	struct {
1780 		struct dc_surface_update surface_updates[MAX_SURFACES];
1781 		struct dc_plane_info plane_infos[MAX_SURFACES];
1782 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
1783 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
1784 		struct dc_stream_update stream_update;
1785 	} *bundle __free(kfree);
1786 	int k, m;
1787 
1788 	bundle = kzalloc_obj(*bundle);
1789 
1790 	if (!bundle) {
1791 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
1792 		return;
1793 	}
1794 
1795 	for (k = 0; k < dc_state->stream_count; k++) {
1796 		bundle->stream_update.stream = dc_state->streams[k];
1797 
1798 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
1799 			bundle->surface_updates[m].surface =
1800 				dc_state->stream_status[k].plane_states[m];
1801 			bundle->surface_updates[m].surface->force_full_update =
1802 				true;
1803 		}
1804 
1805 		update_planes_and_stream_adapter(dm->dc,
1806 					 dc_state->stream_status[k].plane_count,
1807 					 dc_state->streams[k],
1808 					 &bundle->stream_update,
1809 					 bundle->surface_updates);
1810 	}
1811 }
1812 EXPORT_IF_KUNIT(dm_gpureset_commit_state);
1813 
1814 void amdgpu_dm_apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
1815 											   struct dc_sink *sink)
1816 {
1817 	struct dc_panel_patch *ppatch = NULL;
1818 
1819 	if (!sink)
1820 		return;
1821 
1822 	ppatch = &sink->edid_caps.panel_patch;
1823 	if (ppatch->wait_after_dpcd_poweroff_ms) {
1824 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
1825 		drm_dbg_driver(adev_to_drm(adev),
1826 			       "%s: adding a %ds delay as w/a for panel\n",
1827 			       __func__,
1828 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
1829 	}
1830 }
1831 EXPORT_IF_KUNIT(amdgpu_dm_apply_delay_after_dpcd_poweroff);
1832 
1833 /**
1834  * amdgpu_dm_dump_links_and_sinks - Debug dump of all DC links and their sinks
1835  * @adev: amdgpu device pointer
1836  *
1837  * Iterates through all DC links and dumps information about local and remote
1838  * (MST) sinks. Should be called after connector detection is complete to see
1839  * the final state of all links.
1840  */
1841 STATIC_IFN_KUNIT void amdgpu_dm_dump_links_and_sinks(struct amdgpu_device *adev)
1842 {
1843 	struct dc *dc = adev->dm.dc;
1844 	struct drm_device *dev = adev_to_drm(adev);
1845 	int li;
1846 
1847 	if (!dc)
1848 		return;
1849 
1850 	for (li = 0; li < dc->link_count; li++) {
1851 		struct dc_link *l = dc->links[li];
1852 		const char *name = NULL;
1853 		int rs;
1854 
1855 		if (!l)
1856 			continue;
1857 		if (l->local_sink && l->local_sink->edid_caps.display_name[0])
1858 			name = l->local_sink->edid_caps.display_name;
1859 		else
1860 			name = "n/a";
1861 
1862 		drm_dbg_kms(dev,
1863 			"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",
1864 			li,
1865 			l->local_sink,
1866 			l->type,
1867 			l->local_sink ? l->local_sink->sink_signal : SIGNAL_TYPE_NONE,
1868 			l->sink_count,
1869 			name,
1870 			l->dpcd_caps.is_mst_capable,
1871 			l->mst_stream_alloc_table.stream_count);
1872 
1873 		/* Dump remote (MST) sinks if any */
1874 		for (rs = 0; rs < l->sink_count; rs++) {
1875 			struct dc_sink *rsink = l->remote_sinks[rs];
1876 			const char *rname = NULL;
1877 
1878 			if (!rsink)
1879 				continue;
1880 			if (rsink->edid_caps.display_name[0])
1881 				rname = rsink->edid_caps.display_name;
1882 			else
1883 				rname = "n/a";
1884 			drm_dbg_kms(dev,
1885 				"  REMOTE_SINK[%d:%d]: sink=%p signal=%d edid_name=%s\n",
1886 				li, rs,
1887 				rsink,
1888 				rsink->sink_signal,
1889 				rname);
1890 		}
1891 	}
1892 }
1893 EXPORT_IF_KUNIT(amdgpu_dm_dump_links_and_sinks);
1894 
1895 static int dm_resume(struct amdgpu_ip_block *ip_block)
1896 {
1897 	struct amdgpu_device *adev = ip_block->adev;
1898 	struct drm_device *ddev = adev_to_drm(adev);
1899 	struct amdgpu_display_manager *dm = &adev->dm;
1900 	struct amdgpu_dm_connector *aconnector;
1901 	struct drm_connector *connector;
1902 	struct drm_connector_list_iter iter;
1903 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
1904 	enum dc_connection_type new_connection_type = dc_connection_none;
1905 	struct dc_state *dc_state;
1906 	int i, r, j;
1907 	struct dc_commit_streams_params commit_params = {};
1908 
1909 	if (dm->dc->caps.ips_support) {
1910 		if (!amdgpu_in_reset(adev))
1911 			mutex_lock(&dm->dc_lock);
1912 
1913 		/* Need to set POWER_STATE_D0 first or it will not execute
1914 		 * idle_power_optimizations command to DMUB.
1915 		 */
1916 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
1917 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
1918 
1919 		if (!amdgpu_in_reset(adev))
1920 			mutex_unlock(&dm->dc_lock);
1921 	}
1922 
1923 	if (amdgpu_in_reset(adev)) {
1924 		dc_state = dm->cached_dc_state;
1925 
1926 		/*
1927 		 * The dc->current_state is backed up into dm->cached_dc_state
1928 		 * before we commit 0 streams.
1929 		 *
1930 		 * DC will clear link encoder assignments on the real state
1931 		 * but the changes won't propagate over to the copy we made
1932 		 * before the 0 streams commit.
1933 		 *
1934 		 * DC expects that link encoder assignments are *not* valid
1935 		 * when committing a state, so as a workaround we can copy
1936 		 * off of the current state.
1937 		 *
1938 		 * We lose the previous assignments, but we had already
1939 		 * commit 0 streams anyway.
1940 		 */
1941 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
1942 
1943 		r = dm_dmub_hw_init(adev);
1944 		if (r) {
1945 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
1946 			dc_state_release(dm->cached_dc_state);
1947 			dm->cached_dc_state = NULL;
1948 			mutex_unlock(&dm->dc_lock);
1949 			return r;
1950 		}
1951 
1952 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
1953 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
1954 
1955 		dc_resume(dm->dc);
1956 
1957 		amdgpu_dm_ism_enable(dm);
1958 		amdgpu_dm_irq_resume_early(adev);
1959 
1960 		for (i = 0; i < dc_state->stream_count; i++) {
1961 			dc_state->streams[i]->mode_changed = true;
1962 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
1963 				dc_pipe_update_bits_set_full(&dc_state->stream_status[i].plane_states[j]->update_bits);
1964 			}
1965 		}
1966 
1967 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
1968 			amdgpu_dm_outbox_init(adev);
1969 			dc_enable_dmub_outbox(adev->dm.dc);
1970 		}
1971 
1972 		commit_params.streams = dc_state->streams;
1973 		commit_params.stream_count = dc_state->stream_count;
1974 		dc_exit_ips_for_hw_access(dm->dc);
1975 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
1976 
1977 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
1978 
1979 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
1980 
1981 		dc_state_release(dm->cached_dc_state);
1982 		dm->cached_dc_state = NULL;
1983 
1984 		amdgpu_dm_irq_resume_late(adev);
1985 
1986 		mutex_unlock(&dm->dc_lock);
1987 
1988 		/* set the backlight after a reset */
1989 		for (i = 0; i < dm->num_of_edps; i++) {
1990 			if (dm->backlight_dev[i])
1991 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
1992 		}
1993 
1994 		return 0;
1995 	}
1996 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
1997 	dc_state_release(dm_state->context);
1998 	dm_state->context = dc_state_create(dm->dc, NULL);
1999 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
2000 
2001 	/* Before powering on DC we need to re-initialize DMUB. */
2002 	dm_dmub_hw_resume(adev);
2003 
2004 	/* Re-enable outbox interrupts for DPIA. */
2005 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2006 		amdgpu_dm_outbox_init(adev);
2007 		dc_enable_dmub_outbox(adev->dm.dc);
2008 	}
2009 
2010 	/* power on hardware */
2011 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
2012 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
2013 
2014 	/* program HPD filter */
2015 	dc_resume(dm->dc);
2016 
2017 	scoped_guard(mutex, &dm->dc_lock)
2018 		amdgpu_dm_ism_enable(dm);
2019 
2020 	/*
2021 	 * early enable HPD Rx IRQ, should be done before set mode as short
2022 	 * pulse interrupts are used for MST
2023 	 */
2024 	amdgpu_dm_irq_resume_early(adev);
2025 
2026 	amdgpu_dm_s3_handle_hdmi_cec(ddev, false);
2027 
2028 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
2029 	s3_handle_mst(ddev, false);
2030 
2031 	/* Do detection*/
2032 	drm_connector_list_iter_begin(ddev, &iter);
2033 	drm_for_each_connector_iter(connector, &iter) {
2034 		bool ret;
2035 
2036 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2037 			continue;
2038 
2039 		aconnector = to_amdgpu_dm_connector(connector);
2040 
2041 		if (!aconnector->dc_link)
2042 			continue;
2043 
2044 		/*
2045 		 * this is the case when traversing through already created end sink
2046 		 * MST connectors, should be skipped
2047 		 */
2048 		if (aconnector->mst_root)
2049 			continue;
2050 
2051 		/* Skip eDP detection, when there is no sink present */
2052 		if (aconnector->dc_link->connector_signal == SIGNAL_TYPE_EDP &&
2053 		    !aconnector->dc_link->edp_sink_present)
2054 			continue;
2055 
2056 		guard(mutex)(&aconnector->hpd_lock);
2057 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
2058 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
2059 
2060 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
2061 			amdgpu_dm_emulated_link_detect(aconnector->dc_link);
2062 		} else {
2063 			guard(mutex)(&dm->dc_lock);
2064 			dc_exit_ips_for_hw_access(dm->dc);
2065 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
2066 			if (ret) {
2067 				/* w/a delay for certain panels */
2068 				amdgpu_dm_apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
2069 			}
2070 		}
2071 
2072 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
2073 			aconnector->fake_enable = false;
2074 
2075 		if (aconnector->dc_sink)
2076 			dc_sink_release(aconnector->dc_sink);
2077 		aconnector->dc_sink = NULL;
2078 		amdgpu_dm_update_connector_after_detect(aconnector);
2079 	}
2080 	drm_connector_list_iter_end(&iter);
2081 
2082 	dm_destroy_cached_state(adev);
2083 
2084 	/* Do mst topology probing after resuming cached state*/
2085 	drm_connector_list_iter_begin(ddev, &iter);
2086 	drm_for_each_connector_iter(connector, &iter) {
2087 		bool init = false;
2088 
2089 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2090 			continue;
2091 
2092 		aconnector = to_amdgpu_dm_connector(connector);
2093 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
2094 		    aconnector->mst_root)
2095 			continue;
2096 
2097 		scoped_guard(mutex, &aconnector->mst_mgr.lock) {
2098 			init = !aconnector->mst_mgr.mst_primary;
2099 		}
2100 		if (init)
2101 			dm_helpers_dp_mst_start_top_mgr(aconnector->dc_link->ctx,
2102 				aconnector->dc_link, false);
2103 		else
2104 			drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
2105 	}
2106 	drm_connector_list_iter_end(&iter);
2107 
2108 	/* Debug dump: list all DC links and their associated sinks after detection
2109 	 * is complete for all connectors. This provides a comprehensive view of the
2110 	 * final state without repeating the dump for each connector.
2111 	 */
2112 	amdgpu_dm_dump_links_and_sinks(adev);
2113 
2114 	amdgpu_dm_irq_resume_late(adev);
2115 
2116 	amdgpu_dm_smu_write_watermarks_table(adev);
2117 
2118 	drm_kms_helper_hotplug_event(ddev);
2119 
2120 	return 0;
2121 }
2122 
2123 /**
2124  * DOC: DM Lifecycle
2125  *
2126  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
2127  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
2128  * the base driver's device list to be initialized and torn down accordingly.
2129  *
2130  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
2131  */
2132 
2133 static const struct amd_ip_funcs amdgpu_dm_funcs = {
2134 	.name = "dm",
2135 	.early_init = dm_early_init,
2136 	.late_init = dm_late_init,
2137 	.sw_init = dm_sw_init,
2138 	.sw_fini = dm_sw_fini,
2139 	.early_fini = amdgpu_dm_early_fini,
2140 	.hw_init = dm_hw_init,
2141 	.hw_fini = dm_hw_fini,
2142 	.suspend = dm_suspend,
2143 	.resume = dm_resume,
2144 	.wait_for_idle = dm_wait_for_idle,
2145 	.set_clockgating_state = dm_set_clockgating_state,
2146 	.set_powergating_state = dm_set_powergating_state,
2147 };
2148 
2149 const struct amdgpu_ip_block_version dm_ip_block = {
2150 	.type = AMD_IP_BLOCK_TYPE_DCE,
2151 	.major = 1,
2152 	.minor = 0,
2153 	.rev = 0,
2154 	.funcs = &amdgpu_dm_funcs,
2155 };
2156 
2157 
2158 /**
2159  * DOC: atomic
2160  *
2161  * *WIP*
2162  */
2163 
2164 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
2165 	.fb_create = amdgpu_display_user_framebuffer_create,
2166 	.get_format_info = amdgpu_dm_plane_get_format_info,
2167 	.atomic_check = amdgpu_dm_atomic_check,
2168 	.atomic_commit = drm_atomic_helper_commit,
2169 };
2170 
2171 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
2172 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
2173 	.atomic_commit_setup = amdgpu_dm_atomic_setup_commit,
2174 };
2175 
2176 /*
2177  * Acquires the lock for the atomic state object and returns
2178  * the new atomic state.
2179  *
2180  * This should only be called during atomic check.
2181  */
2182 int dm_atomic_get_state(struct drm_atomic_commit *state,
2183 			struct dm_atomic_state **dm_state)
2184 {
2185 	struct drm_device *dev = state->dev;
2186 	struct amdgpu_device *adev = drm_to_adev(dev);
2187 	struct amdgpu_display_manager *dm = &adev->dm;
2188 	struct drm_private_state *priv_state;
2189 
2190 	if (*dm_state)
2191 		return 0;
2192 
2193 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
2194 	if (IS_ERR(priv_state))
2195 		return PTR_ERR(priv_state);
2196 
2197 	*dm_state = to_dm_atomic_state(priv_state);
2198 
2199 	return 0;
2200 }
2201 EXPORT_IF_KUNIT(dm_atomic_get_state);
2202 
2203 STATIC_IFN_KUNIT struct dm_atomic_state *
2204 dm_atomic_get_new_state(struct drm_atomic_commit *state)
2205 {
2206 	struct drm_device *dev = state->dev;
2207 	struct amdgpu_device *adev = drm_to_adev(dev);
2208 	struct amdgpu_display_manager *dm = &adev->dm;
2209 	struct drm_private_obj *obj;
2210 	struct drm_private_state *new_obj_state;
2211 	int i;
2212 
2213 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
2214 		if (obj->funcs == dm->atomic_obj.funcs)
2215 			return to_dm_atomic_state(new_obj_state);
2216 	}
2217 
2218 	return NULL;
2219 }
2220 EXPORT_IF_KUNIT(dm_atomic_get_new_state);
2221 
2222 STATIC_IFN_KUNIT struct drm_private_state *
2223 dm_atomic_duplicate_state(struct drm_private_obj *obj)
2224 {
2225 	struct dm_atomic_state *old_state, *new_state;
2226 
2227 	new_state = kzalloc_obj(*new_state);
2228 	if (!new_state)
2229 		return NULL;
2230 
2231 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
2232 
2233 	old_state = to_dm_atomic_state(obj->state);
2234 
2235 	if (old_state && old_state->context)
2236 		new_state->context = dc_state_create_copy(old_state->context);
2237 
2238 	if (!new_state->context) {
2239 		kfree(new_state);
2240 		return NULL;
2241 	}
2242 
2243 	return &new_state->base;
2244 }
2245 EXPORT_IF_KUNIT(dm_atomic_duplicate_state);
2246 
2247 STATIC_IFN_KUNIT void dm_atomic_destroy_state(struct drm_private_obj *obj,
2248 					      struct drm_private_state *state)
2249 {
2250 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
2251 
2252 	if (dm_state && dm_state->context)
2253 		dc_state_release(dm_state->context);
2254 
2255 	kfree(dm_state);
2256 }
2257 EXPORT_IF_KUNIT(dm_atomic_destroy_state);
2258 
2259 static struct drm_private_state *
2260 dm_atomic_create_state(struct drm_private_obj *obj)
2261 {
2262 	struct amdgpu_device *adev = drm_to_adev(obj->dev);
2263 	struct dm_atomic_state *dm_state;
2264 	struct dc_state *context;
2265 
2266 	dm_state = kzalloc_obj(*dm_state);
2267 	if (!dm_state)
2268 		return ERR_PTR(-ENOMEM);
2269 
2270 	context = dc_state_create_current_copy(adev->dm.dc);
2271 	if (!context) {
2272 		kfree(dm_state);
2273 		return ERR_PTR(-ENOMEM);
2274 	}
2275 
2276 	__drm_atomic_helper_private_obj_create_state(obj, &dm_state->base);
2277 	dm_state->context = context;
2278 
2279 	return &dm_state->base;
2280 }
2281 
2282 static struct drm_private_state_funcs dm_atomic_state_funcs = {
2283 	.atomic_create_state = dm_atomic_create_state,
2284 	.atomic_duplicate_state = dm_atomic_duplicate_state,
2285 	.atomic_destroy_state = dm_atomic_destroy_state,
2286 };
2287 
2288 STATIC_IFN_KUNIT int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
2289 {
2290 	int r;
2291 
2292 	adev->mode_info.mode_config_initialized = true;
2293 
2294 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
2295 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
2296 
2297 	adev_to_drm(adev)->mode_config.max_width = 16384;
2298 	adev_to_drm(adev)->mode_config.max_height = 16384;
2299 
2300 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
2301 	if (adev->asic_type == CHIP_HAWAII)
2302 		/* disable prefer shadow for now due to hibernation issues */
2303 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
2304 	else
2305 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
2306 	/* indicates support for immediate flip */
2307 	adev_to_drm(adev)->mode_config.async_page_flip = true;
2308 
2309 	drm_atomic_private_obj_init(adev_to_drm(adev),
2310 				    &adev->dm.atomic_obj,
2311 				    &dm_atomic_state_funcs);
2312 
2313 	r = amdgpu_display_modeset_create_props(adev);
2314 	if (r)
2315 		return r;
2316 
2317 #ifdef AMD_PRIVATE_COLOR
2318 	if (amdgpu_dm_create_color_properties(adev))
2319 		return -ENOMEM;
2320 #endif
2321 
2322 	r = amdgpu_dm_audio_init(adev);
2323 	if (r)
2324 		return r;
2325 
2326 	return 0;
2327 }
2328 EXPORT_IF_KUNIT(amdgpu_dm_mode_config_init);
2329 
2330 STATIC_IFN_KUNIT int initialize_plane(struct amdgpu_display_manager *dm,
2331 				      struct amdgpu_mode_info *mode_info, int plane_id,
2332 				      enum drm_plane_type plane_type,
2333 				      const struct dc_plane_cap *plane_cap)
2334 {
2335 	struct drm_plane *plane;
2336 	unsigned long possible_crtcs;
2337 	int ret = 0;
2338 
2339 	plane = kzalloc_obj(struct drm_plane);
2340 	if (!plane) {
2341 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
2342 		return -ENOMEM;
2343 	}
2344 	plane->type = plane_type;
2345 
2346 	/*
2347 	 * HACK: IGT tests expect that the primary plane for a CRTC
2348 	 * can only have one possible CRTC. Only expose support for
2349 	 * any CRTC if they're not going to be used as a primary plane
2350 	 * for a CRTC - like overlay or underlay planes.
2351 	 */
2352 	possible_crtcs = 1 << plane_id;
2353 	if (plane_id >= dm->dc->caps.max_streams)
2354 		possible_crtcs = 0xff;
2355 
2356 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
2357 
2358 	if (ret) {
2359 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
2360 		kfree(plane);
2361 		return ret;
2362 	}
2363 
2364 	if (mode_info)
2365 		mode_info->planes[plane_id] = plane;
2366 
2367 	return ret;
2368 }
2369 EXPORT_IF_KUNIT(initialize_plane);
2370 
2371 
2372 /*
2373  * In this architecture, the association
2374  * connector -> encoder -> crtc
2375  * id not really requried. The crtc and connector will hold the
2376  * display_index as an abstraction to use with DAL component
2377  *
2378  * Returns 0 on success
2379  */
2380 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
2381 {
2382 	struct amdgpu_display_manager *dm = &adev->dm;
2383 	s32 i;
2384 	struct amdgpu_dm_connector *aconnector = NULL;
2385 	struct amdgpu_encoder *aencoder = NULL;
2386 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
2387 	u32 link_cnt;
2388 	s32 primary_planes;
2389 	enum dc_connection_type new_connection_type = dc_connection_none;
2390 	const struct dc_plane_cap *plane;
2391 	bool psr_feature_enabled = false;
2392 	bool replay_feature_enabled = false;
2393 	int max_overlay = dm->dc->caps.max_slave_planes;
2394 
2395 	dm->display_indexes_num = dm->dc->caps.max_streams;
2396 	/* Update the actual used number of crtc */
2397 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
2398 
2399 	amdgpu_dm_set_irq_funcs(adev);
2400 
2401 	link_cnt = dm->dc->caps.max_links;
2402 	if (amdgpu_dm_mode_config_init(dm->adev)) {
2403 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
2404 		return -EINVAL;
2405 	}
2406 
2407 	/* There is one primary plane per CRTC */
2408 	primary_planes = dm->dc->caps.max_streams;
2409 	if (primary_planes > AMDGPU_MAX_PLANES) {
2410 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
2411 		return -EINVAL;
2412 	}
2413 
2414 	/*
2415 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
2416 	 * Order is reversed to match iteration order in atomic check.
2417 	 */
2418 	for (i = (primary_planes - 1); i >= 0; i--) {
2419 		plane = &dm->dc->caps.planes[i];
2420 
2421 		if (initialize_plane(dm, mode_info, i,
2422 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
2423 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
2424 			goto fail;
2425 		}
2426 	}
2427 
2428 	/*
2429 	 * Initialize overlay planes, index starting after primary planes.
2430 	 * These planes have a higher DRM index than the primary planes since
2431 	 * they should be considered as having a higher z-order.
2432 	 * Order is reversed to match iteration order in atomic check.
2433 	 *
2434 	 * Only support DCN for now, and only expose one so we don't encourage
2435 	 * userspace to use up all the pipes.
2436 	 */
2437 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
2438 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
2439 
2440 		/* Do not create overlay if MPO disabled */
2441 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
2442 			break;
2443 
2444 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
2445 			continue;
2446 
2447 		if (!plane->pixel_format_support.argb8888)
2448 			continue;
2449 
2450 		if (max_overlay-- == 0)
2451 			break;
2452 
2453 		if (initialize_plane(dm, NULL, primary_planes + i,
2454 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
2455 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
2456 			goto fail;
2457 		}
2458 	}
2459 
2460 	for (i = 0; i < dm->dc->caps.max_streams; i++)
2461 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
2462 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
2463 			goto fail;
2464 		}
2465 
2466 	/* Use Outbox interrupt */
2467 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2468 	case IP_VERSION(3, 0, 0):
2469 	case IP_VERSION(3, 1, 2):
2470 	case IP_VERSION(3, 1, 3):
2471 	case IP_VERSION(3, 1, 4):
2472 	case IP_VERSION(3, 1, 5):
2473 	case IP_VERSION(3, 1, 6):
2474 	case IP_VERSION(3, 2, 0):
2475 	case IP_VERSION(3, 2, 1):
2476 	case IP_VERSION(2, 1, 0):
2477 	case IP_VERSION(3, 5, 0):
2478 	case IP_VERSION(3, 5, 1):
2479 	case IP_VERSION(3, 6, 0):
2480 	case IP_VERSION(4, 0, 1):
2481 	case IP_VERSION(4, 2, 0):
2482 	case IP_VERSION(4, 2, 1):
2483 	case IP_VERSION(6, 0, 0):
2484 		if (amdgpu_dm_register_outbox_irq_handlers(dm->adev)) {
2485 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
2486 			goto fail;
2487 		}
2488 		break;
2489 	default:
2490 		drm_dbg_kms(adev_to_drm(adev), "Unsupported DCN IP version for outbox: 0x%X\n",
2491 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
2492 	}
2493 
2494 	/* Determine whether to enable PSR support by default. */
2495 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
2496 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2497 		case IP_VERSION(3, 1, 2):
2498 		case IP_VERSION(3, 1, 3):
2499 		case IP_VERSION(3, 1, 4):
2500 		case IP_VERSION(3, 1, 5):
2501 		case IP_VERSION(3, 1, 6):
2502 		case IP_VERSION(3, 2, 0):
2503 		case IP_VERSION(3, 2, 1):
2504 		case IP_VERSION(3, 5, 0):
2505 		case IP_VERSION(3, 5, 1):
2506 		case IP_VERSION(3, 6, 0):
2507 		case IP_VERSION(4, 0, 1):
2508 		case IP_VERSION(4, 2, 0):
2509 		case IP_VERSION(4, 2, 1):
2510 		case IP_VERSION(6, 0, 0):
2511 			psr_feature_enabled = true;
2512 			break;
2513 		default:
2514 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
2515 			break;
2516 		}
2517 	}
2518 
2519 	/* Determine whether to enable Replay support by default. */
2520 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
2521 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2522 		case IP_VERSION(3, 1, 4):
2523 		case IP_VERSION(3, 2, 0):
2524 		case IP_VERSION(3, 2, 1):
2525 		case IP_VERSION(3, 5, 0):
2526 		case IP_VERSION(3, 5, 1):
2527 		case IP_VERSION(3, 6, 0):
2528 		case IP_VERSION(4, 2, 0):
2529 		case IP_VERSION(4, 2, 1):
2530 		case IP_VERSION(6, 0, 0):
2531 			replay_feature_enabled = true;
2532 			break;
2533 
2534 		default:
2535 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
2536 			break;
2537 		}
2538 	}
2539 
2540 	if (link_cnt > MAX_LINKS) {
2541 		drm_err(adev_to_drm(adev),
2542 			"KMS: Cannot support more than %d display indexes\n",
2543 				MAX_LINKS);
2544 		goto fail;
2545 	}
2546 
2547 	/* loops over all connectors on the board */
2548 	for (i = 0; i < link_cnt; i++) {
2549 		struct dc_link *link = NULL;
2550 
2551 		link = dc_get_link_at_index(dm->dc, i);
2552 
2553 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
2554 			struct amdgpu_dm_wb_connector *wbcon = kzalloc_obj(*wbcon);
2555 
2556 			if (!wbcon) {
2557 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
2558 				continue;
2559 			}
2560 
2561 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
2562 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
2563 				kfree(wbcon);
2564 				continue;
2565 			}
2566 
2567 			link->psr_settings.psr_feature_enabled = false;
2568 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
2569 
2570 			continue;
2571 		}
2572 
2573 		aconnector = kzalloc_obj(*aconnector);
2574 		if (!aconnector)
2575 			goto fail;
2576 
2577 		aencoder = kzalloc_obj(*aencoder);
2578 		if (!aencoder)
2579 			goto fail;
2580 
2581 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
2582 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
2583 			goto fail;
2584 		}
2585 
2586 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
2587 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
2588 			goto fail;
2589 		}
2590 
2591 		if (dm->hpd_rx_offload_wq)
2592 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
2593 				aconnector;
2594 
2595 		if (!dc_link_detect_connection_type(link, &new_connection_type))
2596 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
2597 
2598 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
2599 			amdgpu_dm_emulated_link_detect(link);
2600 			amdgpu_dm_update_connector_after_detect(aconnector);
2601 		} else {
2602 			bool ret = false;
2603 
2604 			mutex_lock(&dm->dc_lock);
2605 			dc_exit_ips_for_hw_access(dm->dc);
2606 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
2607 			mutex_unlock(&dm->dc_lock);
2608 
2609 			if (ret) {
2610 				amdgpu_dm_update_connector_after_detect(aconnector);
2611 				amdgpu_dm_setup_backlight_device(dm, aconnector);
2612 
2613 				/* Disable PSR if Replay can be enabled */
2614 				if (replay_feature_enabled)
2615 					if (amdgpu_dm_set_replay_caps(link, aconnector))
2616 						psr_feature_enabled = false;
2617 
2618 				if (psr_feature_enabled) {
2619 					amdgpu_dm_set_psr_caps(link, aconnector);
2620 					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",
2621 						 aconnector->base.name,
2622 						 link->psr_settings.psr_feature_enabled,
2623 						 link->psr_settings.psr_version,
2624 						 link->dpcd_caps.psr_info.psr_version,
2625 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
2626 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
2627 				}
2628 			}
2629 		}
2630 		amdgpu_set_panel_orientation(&aconnector->base);
2631 	}
2632 
2633 	/* Debug dump: list all DC links and their associated sinks after detection
2634 	 * is complete for all connectors. This provides a comprehensive view of the
2635 	 * final state without repeating the dump for each connector.
2636 	 */
2637 	amdgpu_dm_dump_links_and_sinks(adev);
2638 
2639 	/* Software is initialized. Now we can register interrupt handlers. */
2640 	switch (adev->asic_type) {
2641 #if defined(CONFIG_DRM_AMD_DC_SI)
2642 	case CHIP_TAHITI:
2643 	case CHIP_PITCAIRN:
2644 	case CHIP_VERDE:
2645 	case CHIP_OLAND:
2646 #endif
2647 	case CHIP_BONAIRE:
2648 	case CHIP_HAWAII:
2649 	case CHIP_KAVERI:
2650 	case CHIP_KABINI:
2651 	case CHIP_MULLINS:
2652 	case CHIP_TONGA:
2653 	case CHIP_FIJI:
2654 	case CHIP_CARRIZO:
2655 	case CHIP_STONEY:
2656 	case CHIP_POLARIS11:
2657 	case CHIP_POLARIS10:
2658 	case CHIP_POLARIS12:
2659 	case CHIP_VEGAM:
2660 	case CHIP_VEGA10:
2661 	case CHIP_VEGA12:
2662 	case CHIP_VEGA20:
2663 		if (amdgpu_dm_dce110_register_irq_handlers(dm->adev)) {
2664 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
2665 			goto fail;
2666 		}
2667 		break;
2668 	default:
2669 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2670 		case IP_VERSION(1, 0, 0):
2671 		case IP_VERSION(1, 0, 1):
2672 		case IP_VERSION(2, 0, 2):
2673 		case IP_VERSION(2, 0, 3):
2674 		case IP_VERSION(2, 0, 0):
2675 		case IP_VERSION(2, 1, 0):
2676 		case IP_VERSION(3, 0, 0):
2677 		case IP_VERSION(3, 0, 2):
2678 		case IP_VERSION(3, 0, 3):
2679 		case IP_VERSION(3, 0, 1):
2680 		case IP_VERSION(3, 1, 2):
2681 		case IP_VERSION(3, 1, 3):
2682 		case IP_VERSION(3, 1, 4):
2683 		case IP_VERSION(3, 1, 5):
2684 		case IP_VERSION(3, 1, 6):
2685 		case IP_VERSION(3, 2, 0):
2686 		case IP_VERSION(3, 2, 1):
2687 		case IP_VERSION(3, 5, 0):
2688 		case IP_VERSION(3, 5, 1):
2689 		case IP_VERSION(3, 6, 0):
2690 		case IP_VERSION(4, 0, 1):
2691 		case IP_VERSION(4, 2, 0):
2692 		case IP_VERSION(4, 2, 1):
2693 		case IP_VERSION(6, 0, 0):
2694 			if (amdgpu_dm_dcn10_register_irq_handlers(dm->adev)) {
2695 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
2696 				goto fail;
2697 			}
2698 			break;
2699 		default:
2700 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
2701 					amdgpu_ip_version(adev, DCE_HWIP, 0));
2702 			goto fail;
2703 		}
2704 		break;
2705 	}
2706 
2707 	return 0;
2708 fail:
2709 	kfree(aencoder);
2710 	kfree(aconnector);
2711 
2712 	return -EINVAL;
2713 }
2714 
2715 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
2716 {
2717 	if (dm->atomic_obj.state)
2718 		drm_atomic_private_obj_fini(&dm->atomic_obj);
2719 }
2720 
2721 /******************************************************************************
2722  * amdgpu_display_funcs functions
2723  *****************************************************************************/
2724 
2725 /*
2726  * dm_bandwidth_update - program display watermarks
2727  *
2728  * @adev: amdgpu_device pointer
2729  *
2730  * Calculate and program the display watermarks and line buffer allocation.
2731  */
2732 STATIC_IFN_KUNIT void dm_bandwidth_update(struct amdgpu_device *adev)
2733 {
2734 	/* TODO: implement later */
2735 }
2736 EXPORT_IF_KUNIT(dm_bandwidth_update);
2737 
2738 static const struct amdgpu_display_funcs dm_display_funcs = {
2739 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
2740 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
2741 	.backlight_set_level = NULL, /* never called for DC */
2742 	.backlight_get_level = NULL, /* never called for DC */
2743 	.hpd_sense = NULL,/* called unconditionally */
2744 	.hpd_set_polarity = NULL, /* called unconditionally */
2745 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
2746 	.page_flip_get_scanoutpos =
2747 		dm_crtc_get_scanoutpos,/* called unconditionally */
2748 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
2749 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
2750 };
2751 
2752 #if defined(CONFIG_DEBUG_KERNEL_DC)
2753 
2754 static ssize_t s3_debug_store(struct device *device,
2755 			      struct device_attribute *attr,
2756 			      const char *buf,
2757 			      size_t count)
2758 {
2759 	int ret;
2760 	int s3_state;
2761 	struct drm_device *drm_dev = dev_get_drvdata(device);
2762 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
2763 	struct amdgpu_ip_block *ip_block;
2764 
2765 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
2766 	if (!ip_block)
2767 		return -EINVAL;
2768 
2769 	ret = kstrtoint(buf, 0, &s3_state);
2770 
2771 	if (ret == 0) {
2772 		if (s3_state) {
2773 			dm_resume(ip_block);
2774 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
2775 		} else
2776 			dm_suspend(ip_block);
2777 	}
2778 
2779 	return ret == 0 ? count : 0;
2780 }
2781 
2782 DEVICE_ATTR_WO(s3_debug);
2783 
2784 #endif
2785 
2786 STATIC_IFN_KUNIT int dm_early_init(struct amdgpu_ip_block *ip_block)
2787 {
2788 	struct amdgpu_device *adev = ip_block->adev;
2789 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
2790 	struct atom_context *ctx = mode_info->atom_context;
2791 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
2792 	u16 data_offset;
2793 
2794 	/* if there is no object header, skip DM */
2795 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
2796 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
2797 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
2798 		return -ENOENT;
2799 	}
2800 
2801 	switch (adev->asic_type) {
2802 #if defined(CONFIG_DRM_AMD_DC_SI)
2803 	case CHIP_TAHITI:
2804 	case CHIP_PITCAIRN:
2805 	case CHIP_VERDE:
2806 		adev->mode_info.num_crtc = 6;
2807 		adev->mode_info.num_hpd = 6;
2808 		adev->mode_info.num_dig = 6;
2809 		break;
2810 	case CHIP_OLAND:
2811 		adev->mode_info.num_crtc = 2;
2812 		adev->mode_info.num_hpd = 2;
2813 		adev->mode_info.num_dig = 2;
2814 		break;
2815 #endif
2816 	case CHIP_BONAIRE:
2817 	case CHIP_HAWAII:
2818 		adev->mode_info.num_crtc = 6;
2819 		adev->mode_info.num_hpd = 6;
2820 		adev->mode_info.num_dig = 6;
2821 		break;
2822 	case CHIP_KAVERI:
2823 		adev->mode_info.num_crtc = 4;
2824 		adev->mode_info.num_hpd = 6;
2825 		adev->mode_info.num_dig = 7;
2826 		break;
2827 	case CHIP_KABINI:
2828 	case CHIP_MULLINS:
2829 		adev->mode_info.num_crtc = 2;
2830 		adev->mode_info.num_hpd = 6;
2831 		adev->mode_info.num_dig = 6;
2832 		break;
2833 	case CHIP_FIJI:
2834 	case CHIP_TONGA:
2835 		adev->mode_info.num_crtc = 6;
2836 		adev->mode_info.num_hpd = 6;
2837 		adev->mode_info.num_dig = 7;
2838 		break;
2839 	case CHIP_CARRIZO:
2840 		adev->mode_info.num_crtc = 3;
2841 		adev->mode_info.num_hpd = 6;
2842 		adev->mode_info.num_dig = 9;
2843 		break;
2844 	case CHIP_STONEY:
2845 		adev->mode_info.num_crtc = 2;
2846 		adev->mode_info.num_hpd = 6;
2847 		adev->mode_info.num_dig = 9;
2848 		break;
2849 	case CHIP_POLARIS11:
2850 	case CHIP_POLARIS12:
2851 		adev->mode_info.num_crtc = 5;
2852 		adev->mode_info.num_hpd = 5;
2853 		adev->mode_info.num_dig = 5;
2854 		break;
2855 	case CHIP_POLARIS10:
2856 	case CHIP_VEGAM:
2857 		adev->mode_info.num_crtc = 6;
2858 		adev->mode_info.num_hpd = 6;
2859 		adev->mode_info.num_dig = 6;
2860 		break;
2861 	case CHIP_VEGA10:
2862 	case CHIP_VEGA12:
2863 	case CHIP_VEGA20:
2864 		adev->mode_info.num_crtc = 6;
2865 		adev->mode_info.num_hpd = 6;
2866 		adev->mode_info.num_dig = 6;
2867 		break;
2868 	default:
2869 
2870 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2871 		case IP_VERSION(2, 0, 2):
2872 		case IP_VERSION(3, 0, 0):
2873 			adev->mode_info.num_crtc = 6;
2874 			adev->mode_info.num_hpd = 6;
2875 			adev->mode_info.num_dig = 6;
2876 			break;
2877 		case IP_VERSION(2, 0, 0):
2878 		case IP_VERSION(3, 0, 2):
2879 			adev->mode_info.num_crtc = 5;
2880 			adev->mode_info.num_hpd = 5;
2881 			adev->mode_info.num_dig = 5;
2882 			break;
2883 		case IP_VERSION(2, 0, 3):
2884 		case IP_VERSION(3, 0, 3):
2885 			adev->mode_info.num_crtc = 2;
2886 			adev->mode_info.num_hpd = 2;
2887 			adev->mode_info.num_dig = 2;
2888 			break;
2889 		case IP_VERSION(1, 0, 0):
2890 		case IP_VERSION(1, 0, 1):
2891 		case IP_VERSION(3, 0, 1):
2892 		case IP_VERSION(2, 1, 0):
2893 		case IP_VERSION(3, 1, 2):
2894 		case IP_VERSION(3, 1, 3):
2895 		case IP_VERSION(3, 1, 4):
2896 		case IP_VERSION(3, 1, 5):
2897 		case IP_VERSION(3, 1, 6):
2898 		case IP_VERSION(3, 2, 0):
2899 		case IP_VERSION(3, 2, 1):
2900 		case IP_VERSION(3, 5, 0):
2901 		case IP_VERSION(3, 5, 1):
2902 		case IP_VERSION(3, 6, 0):
2903 		case IP_VERSION(4, 0, 1):
2904 		case IP_VERSION(4, 2, 0):
2905 		case IP_VERSION(4, 2, 1):
2906 		case IP_VERSION(6, 0, 0):
2907 			adev->mode_info.num_crtc = 4;
2908 			adev->mode_info.num_hpd = 4;
2909 			adev->mode_info.num_dig = 4;
2910 			break;
2911 		default:
2912 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
2913 					amdgpu_ip_version(adev, DCE_HWIP, 0));
2914 			return -EINVAL;
2915 		}
2916 		break;
2917 	}
2918 
2919 	if (adev->mode_info.funcs == NULL)
2920 		adev->mode_info.funcs = &dm_display_funcs;
2921 
2922 	/*
2923 	 * Note: Do NOT change adev->reg.audio_endpt.rreg and
2924 	 * adev->reg.audio_endpt.wreg because they are initialised in
2925 	 * amdgpu_device_init()
2926 	 */
2927 #if defined(CONFIG_DEBUG_KERNEL_DC)
2928 	device_create_file(
2929 		adev_to_drm(adev)->dev,
2930 		&dev_attr_s3_debug);
2931 #endif
2932 	adev->dc_enabled = true;
2933 
2934 	return dm_init_microcode(adev);
2935 }
2936 EXPORT_IF_KUNIT(dm_early_init);
2937 
2938 STATIC_IFN_KUNIT bool modereset_required(struct drm_crtc_state *crtc_state)
2939 {
2940 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
2941 }
2942 EXPORT_IF_KUNIT(modereset_required);
2943 
2944 STATIC_IFN_KUNIT int
2945 fill_plane_color_attributes(struct drm_atomic_commit *state,
2946 			    const struct drm_plane_state *plane_state,
2947 			    const enum surface_pixel_format format,
2948 			    enum dc_color_space *color_space)
2949 {
2950 	bool full_range;
2951 
2952 	*color_space = COLOR_SPACE_SRGB;
2953 
2954 	/* Ignore properties when DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE is set */
2955 	if (state && state->plane_color_pipeline)
2956 		return 0;
2957 
2958 	/* DRM color properties only affect non-RGB formats. */
2959 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
2960 		return 0;
2961 
2962 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
2963 
2964 	switch (plane_state->color_encoding) {
2965 	case DRM_COLOR_YCBCR_BT601:
2966 		if (full_range)
2967 			*color_space = COLOR_SPACE_YCBCR601;
2968 		else
2969 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
2970 		break;
2971 
2972 	case DRM_COLOR_YCBCR_BT709:
2973 		if (full_range)
2974 			*color_space = COLOR_SPACE_YCBCR709;
2975 		else
2976 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
2977 		break;
2978 
2979 	case DRM_COLOR_YCBCR_BT2020:
2980 		if (full_range)
2981 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
2982 		else
2983 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
2984 		break;
2985 
2986 	default:
2987 		return -EINVAL;
2988 	}
2989 
2990 	return 0;
2991 }
2992 EXPORT_IF_KUNIT(fill_plane_color_attributes);
2993 
2994 STATIC_IFN_KUNIT int
2995 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
2996 			    struct drm_atomic_commit *state,
2997 			    const struct drm_plane_state *plane_state,
2998 			    struct dc_plane_info *plane_info,
2999 			    struct dc_plane_address *address,
3000 			    bool tmz_surface)
3001 {
3002 	const struct drm_framebuffer *fb = plane_state->fb;
3003 	const struct amdgpu_framebuffer *afb =
3004 		to_amdgpu_framebuffer(plane_state->fb);
3005 	int ret;
3006 
3007 	memset(plane_info, 0, sizeof(*plane_info));
3008 
3009 	switch (fb->format->format) {
3010 	case DRM_FORMAT_C8:
3011 		plane_info->format =
3012 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
3013 		break;
3014 	case DRM_FORMAT_RGB565:
3015 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
3016 		break;
3017 	case DRM_FORMAT_XRGB8888:
3018 	case DRM_FORMAT_ARGB8888:
3019 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
3020 		break;
3021 	case DRM_FORMAT_XRGB2101010:
3022 	case DRM_FORMAT_ARGB2101010:
3023 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
3024 		break;
3025 	case DRM_FORMAT_XBGR2101010:
3026 	case DRM_FORMAT_ABGR2101010:
3027 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
3028 		break;
3029 	case DRM_FORMAT_XBGR8888:
3030 	case DRM_FORMAT_ABGR8888:
3031 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
3032 		break;
3033 	case DRM_FORMAT_NV21:
3034 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
3035 		break;
3036 	case DRM_FORMAT_NV12:
3037 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
3038 		break;
3039 	case DRM_FORMAT_P010:
3040 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
3041 		break;
3042 	case DRM_FORMAT_XRGB16161616F:
3043 	case DRM_FORMAT_ARGB16161616F:
3044 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
3045 		break;
3046 	case DRM_FORMAT_XBGR16161616F:
3047 	case DRM_FORMAT_ABGR16161616F:
3048 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
3049 		break;
3050 	case DRM_FORMAT_XRGB16161616:
3051 	case DRM_FORMAT_ARGB16161616:
3052 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
3053 		break;
3054 	case DRM_FORMAT_XBGR16161616:
3055 	case DRM_FORMAT_ABGR16161616:
3056 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
3057 		break;
3058 	default:
3059 		drm_err(adev_to_drm(adev),
3060 			"Unsupported screen format %p4cc\n",
3061 			&fb->format->format);
3062 		return -EINVAL;
3063 	}
3064 
3065 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
3066 	case DRM_MODE_ROTATE_0:
3067 		plane_info->rotation = ROTATION_ANGLE_0;
3068 		break;
3069 	case DRM_MODE_ROTATE_90:
3070 		plane_info->rotation = ROTATION_ANGLE_90;
3071 		break;
3072 	case DRM_MODE_ROTATE_180:
3073 		plane_info->rotation = ROTATION_ANGLE_180;
3074 		break;
3075 	case DRM_MODE_ROTATE_270:
3076 		plane_info->rotation = ROTATION_ANGLE_270;
3077 		break;
3078 	default:
3079 		plane_info->rotation = ROTATION_ANGLE_0;
3080 		break;
3081 	}
3082 
3083 
3084 	plane_info->visible = true;
3085 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
3086 
3087 	plane_info->layer_index = plane_state->normalized_zpos;
3088 
3089 	ret = fill_plane_color_attributes(state, plane_state, plane_info->format,
3090 					  &plane_info->color_space);
3091 	if (ret)
3092 		return ret;
3093 
3094 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
3095 					   plane_info->rotation,
3096 					   &plane_info->tiling_info,
3097 					   &plane_info->plane_size,
3098 					   &plane_info->dcc, address,
3099 					   tmz_surface);
3100 	if (ret)
3101 		return ret;
3102 
3103 	amdgpu_dm_plane_fill_blending_from_plane_state(
3104 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
3105 		&plane_info->global_alpha, &plane_info->global_alpha_value);
3106 
3107 	return 0;
3108 }
3109 EXPORT_IF_KUNIT(fill_dc_plane_info_and_addr);
3110 
3111 STATIC_IFN_KUNIT int fill_dc_plane_attributes(struct amdgpu_device *adev,
3112 					      struct dc_plane_state *dc_plane_state,
3113 					      struct drm_plane_state *plane_state,
3114 					      struct drm_crtc_state *crtc_state)
3115 {
3116 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
3117 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
3118 	struct dc_scaling_info scaling_info;
3119 	struct dc_plane_info plane_info;
3120 	int ret;
3121 
3122 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
3123 	if (ret)
3124 		return ret;
3125 
3126 	dc_plane_state->src_rect = scaling_info.src_rect;
3127 	dc_plane_state->dst_rect = scaling_info.dst_rect;
3128 	dc_plane_state->clip_rect = scaling_info.clip_rect;
3129 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
3130 
3131 	ret = fill_dc_plane_info_and_addr(adev, plane_state->state, plane_state,
3132 					  &plane_info,
3133 					  &dc_plane_state->address,
3134 					  afb->tmz_surface);
3135 	if (ret)
3136 		return ret;
3137 
3138 	dc_plane_state->format = plane_info.format;
3139 	dc_plane_state->color_space = plane_info.color_space;
3140 	dc_plane_state->format = plane_info.format;
3141 	dc_plane_state->plane_size = plane_info.plane_size;
3142 	dc_plane_state->rotation = plane_info.rotation;
3143 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
3144 	dc_plane_state->stereo_format = plane_info.stereo_format;
3145 	dc_plane_state->tiling_info = plane_info.tiling_info;
3146 	dc_plane_state->visible = plane_info.visible;
3147 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
3148 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
3149 	dc_plane_state->global_alpha = plane_info.global_alpha;
3150 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
3151 	dc_plane_state->dcc = plane_info.dcc;
3152 	dc_plane_state->layer_index = plane_info.layer_index;
3153 	dc_plane_state->flip_int_enabled = true;
3154 
3155 	/*
3156 	 * Always set input transfer function, since plane state is refreshed
3157 	 * every time.
3158 	 */
3159 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
3160 						plane_state,
3161 						dc_plane_state);
3162 	if (ret)
3163 		return ret;
3164 
3165 	return 0;
3166 }
3167 EXPORT_IF_KUNIT(fill_dc_plane_attributes);
3168 
3169 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
3170 				      struct rect *dirty_rect, int32_t x,
3171 				      s32 y, s32 width, s32 height,
3172 				      int *i, bool ffu)
3173 {
3174 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
3175 
3176 	dirty_rect->x = x;
3177 	dirty_rect->y = y;
3178 	dirty_rect->width = width;
3179 	dirty_rect->height = height;
3180 
3181 	if (ffu)
3182 		drm_dbg(plane->dev,
3183 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
3184 			plane->base.id, width, height);
3185 	else
3186 		drm_dbg(plane->dev,
3187 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
3188 			plane->base.id, x, y, width, height);
3189 
3190 	(*i)++;
3191 }
3192 
3193 /**
3194  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
3195  *
3196  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
3197  *         remote fb
3198  * @old_plane_state: Old state of @plane
3199  * @new_plane_state: New state of @plane
3200  * @crtc_state: New state of CRTC connected to the @plane
3201  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
3202  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
3203  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
3204  *             that have changed will be updated. If PSR SU is not enabled,
3205  *             or if damage clips are not available, the entire screen will be updated.
3206  * @dirty_regions_changed: dirty regions changed
3207  *
3208  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
3209  * (referred to as "damage clips" in DRM nomenclature) that require updating on
3210  * the eDP remote buffer. The responsibility of specifying the dirty regions is
3211  * amdgpu_dm's.
3212  *
3213  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
3214  * plane with regions that require flushing to the eDP remote buffer. In
3215  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
3216  * implicitly provide damage clips without any client support via the plane
3217  * bounds.
3218  */
3219 STATIC_IFN_KUNIT void fill_dc_dirty_rects(struct drm_plane *plane,
3220 					  struct drm_plane_state *old_plane_state,
3221 					  struct drm_plane_state *new_plane_state,
3222 					  struct drm_crtc_state *crtc_state,
3223 					  struct dc_flip_addrs *flip_addrs,
3224 					  bool is_psr_su,
3225 					  bool *dirty_regions_changed)
3226 {
3227 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
3228 	struct rect *dirty_rects = flip_addrs->dirty_rects;
3229 	u32 num_clips = 0;
3230 	struct drm_mode_rect *clips = NULL;
3231 	bool bb_changed;
3232 	bool fb_changed;
3233 	u32 i = 0;
3234 	*dirty_regions_changed = false;
3235 
3236 	/*
3237 	 * Cursor plane has it's own dirty rect update interface. See
3238 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
3239 	 */
3240 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
3241 		return;
3242 
3243 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
3244 		goto ffu;
3245 
3246 	if (!new_plane_state->ignore_damage_clips) {
3247 		num_clips = drm_plane_get_damage_clips_count(new_plane_state);
3248 		clips = drm_plane_get_damage_clips(new_plane_state);
3249 	}
3250 
3251 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
3252 						   is_psr_su)))
3253 		goto ffu;
3254 
3255 	if (!dm_crtc_state->mpo_requested) {
3256 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
3257 			goto ffu;
3258 
3259 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
3260 			fill_dc_dirty_rect(new_plane_state->plane,
3261 					   &dirty_rects[flip_addrs->dirty_rect_count],
3262 					   clips->x1, clips->y1,
3263 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
3264 					   &flip_addrs->dirty_rect_count,
3265 					   false);
3266 		return;
3267 	}
3268 
3269 	/*
3270 	 * MPO is requested. Add entire plane bounding box to dirty rects if
3271 	 * flipped to or damaged.
3272 	 *
3273 	 * If plane is moved or resized, also add old bounding box to dirty
3274 	 * rects.
3275 	 */
3276 	fb_changed = old_plane_state->fb->base.id !=
3277 		     new_plane_state->fb->base.id;
3278 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
3279 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
3280 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
3281 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
3282 
3283 	drm_dbg(plane->dev,
3284 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
3285 		new_plane_state->plane->base.id,
3286 		bb_changed, fb_changed, num_clips);
3287 
3288 	*dirty_regions_changed = bb_changed;
3289 
3290 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
3291 		goto ffu;
3292 
3293 	if (bb_changed) {
3294 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
3295 				   new_plane_state->crtc_x,
3296 				   new_plane_state->crtc_y,
3297 				   new_plane_state->crtc_w,
3298 				   new_plane_state->crtc_h, &i, false);
3299 
3300 		/* Add old plane bounding-box if plane is moved or resized */
3301 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
3302 				   old_plane_state->crtc_x,
3303 				   old_plane_state->crtc_y,
3304 				   old_plane_state->crtc_w,
3305 				   old_plane_state->crtc_h, &i, false);
3306 	}
3307 
3308 	if (num_clips) {
3309 		for (; i < num_clips; clips++)
3310 			fill_dc_dirty_rect(new_plane_state->plane,
3311 					   &dirty_rects[i], clips->x1,
3312 					   clips->y1, clips->x2 - clips->x1,
3313 					   clips->y2 - clips->y1, &i, false);
3314 	} else if (fb_changed && !bb_changed) {
3315 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
3316 				   new_plane_state->crtc_x,
3317 				   new_plane_state->crtc_y,
3318 				   new_plane_state->crtc_w,
3319 				   new_plane_state->crtc_h, &i, false);
3320 	}
3321 
3322 	flip_addrs->dirty_rect_count = i;
3323 	return;
3324 
3325 ffu:
3326 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
3327 			   dm_crtc_state->base.mode.crtc_hdisplay,
3328 			   dm_crtc_state->base.mode.crtc_vdisplay,
3329 			   &flip_addrs->dirty_rect_count, true);
3330 }
3331 EXPORT_IF_KUNIT(fill_dc_dirty_rects);
3332 
3333 STATIC_IFN_KUNIT int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_commit *state,
3334 						      struct dc_state *dc_state,
3335 						      struct dsc_mst_fairness_vars *vars)
3336 {
3337 	struct dc_stream_state *stream = NULL;
3338 	struct drm_connector *connector;
3339 	struct drm_connector_state *new_con_state;
3340 	struct amdgpu_dm_connector *aconnector;
3341 	struct dm_connector_state *dm_conn_state;
3342 	int i, j, ret;
3343 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
3344 
3345 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3346 
3347 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3348 			continue;
3349 
3350 		aconnector = to_amdgpu_dm_connector(connector);
3351 
3352 		if (!aconnector->mst_output_port)
3353 			continue;
3354 
3355 		if (!new_con_state || !new_con_state->crtc)
3356 			continue;
3357 
3358 		dm_conn_state = to_dm_connector_state(new_con_state);
3359 
3360 		for (j = 0; j < dc_state->stream_count; j++) {
3361 			stream = dc_state->streams[j];
3362 			if (!stream)
3363 				continue;
3364 
3365 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
3366 				break;
3367 
3368 			stream = NULL;
3369 		}
3370 
3371 		if (!stream)
3372 			continue;
3373 
3374 		pbn_div = dm_mst_get_pbn_divider(stream->link);
3375 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
3376 		for (j = 0; j < dc_state->stream_count; j++) {
3377 			if (vars[j].aconnector == aconnector) {
3378 				pbn = vars[j].pbn;
3379 				break;
3380 			}
3381 		}
3382 
3383 		if (j == dc_state->stream_count || pbn_div == 0)
3384 			continue;
3385 
3386 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
3387 
3388 		if (stream->timing.flags.DSC != 1) {
3389 			dm_conn_state->pbn = pbn;
3390 			dm_conn_state->vcpi_slots = slot_num;
3391 
3392 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
3393 							   dm_conn_state->pbn, false);
3394 			if (ret < 0)
3395 				return ret;
3396 
3397 			continue;
3398 		}
3399 
3400 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
3401 		if (vcpi < 0)
3402 			return vcpi;
3403 
3404 		dm_conn_state->pbn = pbn;
3405 		dm_conn_state->vcpi_slots = vcpi;
3406 	}
3407 	return 0;
3408 }
3409 EXPORT_IF_KUNIT(dm_update_mst_vcpi_slots_for_dsc);
3410 
3411 STATIC_IFN_KUNIT void manage_dm_interrupts(struct amdgpu_device *adev,
3412 					   struct amdgpu_crtc *acrtc,
3413 					   struct dm_crtc_state *acrtc_state)
3414 {	/*
3415 	 * We cannot be sure that the frontend index maps to the same
3416 	 * backend index - some even map to more than one.
3417 	 * So we have to go through the CRTC to find the right IRQ.
3418 	 */
3419 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
3420 			adev,
3421 			acrtc->crtc_id);
3422 	struct drm_device *dev = adev_to_drm(adev);
3423 
3424 	struct drm_vblank_crtc_config config = {0};
3425 	struct dc_crtc_timing *timing;
3426 	int offdelay;
3427 
3428 	if (acrtc_state) {
3429 		timing = &acrtc_state->stream->timing;
3430 
3431 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
3432 			   IP_VERSION(3, 5, 0) ||
3433 			   !(adev->flags & AMD_IS_APU)) {
3434 			/*
3435 			 * Older HW and DGPU have issues with instant off;
3436 			 * use a 2 frame offdelay.
3437 			 */
3438 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
3439 						      timing->v_total *
3440 						      timing->h_total,
3441 						      timing->pix_clk_100hz);
3442 
3443 			config.offdelay_ms = offdelay ?: 30;
3444 		} else {
3445 			/* offdelay_ms = 0 will never disable vblank */
3446 			config.offdelay_ms = 1;
3447 			config.disable_immediate = true;
3448 		}
3449 
3450 		drm_crtc_vblank_on_config(&acrtc->base,
3451 					  &config);
3452 		/*
3453 		 * Since pflip_high_irq is no longer registered for DCN, grab an
3454 		 * extra reference to vupdate irq instead to workaround this
3455 		 * issue:
3456 		 * https://gitlab.freedesktop.org/drm/amd/-/work_items/3936
3457 		 *
3458 		 * The callbacks to drm_vblank_on/off should really take care of
3459 		 * this though.
3460 		 */
3461 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
3462 		case IP_VERSION(3, 0, 0):
3463 		case IP_VERSION(3, 0, 2):
3464 		case IP_VERSION(3, 0, 3):
3465 		case IP_VERSION(3, 2, 0):
3466 			if (amdgpu_irq_get(adev, &adev->vupdate_irq, irq_type))
3467 				drm_err(dev, "DM_IRQ: Cannot get vupdate irq!\n");
3468 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
3469 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
3470 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
3471 #endif
3472 		}
3473 
3474 	} else {
3475 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
3476 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
3477 		case IP_VERSION(3, 0, 0):
3478 		case IP_VERSION(3, 0, 2):
3479 		case IP_VERSION(3, 0, 3):
3480 		case IP_VERSION(3, 2, 0):
3481 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
3482 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
3483 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
3484 #endif
3485 			if (amdgpu_irq_put(adev, &adev->vupdate_irq, irq_type))
3486 				drm_err(dev, "DM_IRQ: Cannot put vupdate irq!\n");
3487 		}
3488 
3489 		drm_crtc_vblank_off(&acrtc->base);
3490 	}
3491 }
3492 EXPORT_IF_KUNIT(manage_dm_interrupts);
3493 
3494 STATIC_IFN_KUNIT void dm_update_pflip_irq_state(struct amdgpu_device *adev,
3495 						struct amdgpu_crtc *acrtc)
3496 {
3497 	int irq_type =
3498 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
3499 
3500 	/* GRPH_PFLIP is not used on DCN; nothing to reapply. */
3501 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) != 0)
3502 		return;
3503 
3504 	/**
3505 	 * This reads the current state for the IRQ and force reapplies
3506 	 * the setting to hardware.
3507 	 */
3508 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
3509 }
3510 EXPORT_IF_KUNIT(dm_update_pflip_irq_state);
3511 
3512 STATIC_IFN_KUNIT bool
3513 is_scaling_state_different(const struct dm_connector_state *dm_state,
3514 			   const struct dm_connector_state *old_dm_state)
3515 {
3516 	if (dm_state->scaling != old_dm_state->scaling)
3517 		return true;
3518 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
3519 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
3520 			return true;
3521 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
3522 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
3523 			return true;
3524 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
3525 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
3526 		return true;
3527 	return false;
3528 }
3529 EXPORT_IF_KUNIT(is_scaling_state_different);
3530 
3531 STATIC_IFN_KUNIT bool
3532 is_content_protection_different(struct drm_crtc_state *new_crtc_state,
3533 				struct drm_crtc_state *old_crtc_state,
3534 				struct drm_connector_state *new_conn_state,
3535 				struct drm_connector_state *old_conn_state,
3536 				const struct drm_connector *connector,
3537 				struct hdcp_workqueue *hdcp_w)
3538 {
3539 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
3540 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
3541 
3542 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
3543 		connector->index, connector->status, connector->dpms);
3544 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
3545 		old_conn_state->content_protection, new_conn_state->content_protection);
3546 
3547 	if (old_crtc_state)
3548 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
3549 		old_crtc_state->enable,
3550 		old_crtc_state->active,
3551 		old_crtc_state->mode_changed,
3552 		old_crtc_state->active_changed,
3553 		old_crtc_state->connectors_changed);
3554 
3555 	if (new_crtc_state)
3556 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
3557 		new_crtc_state->enable,
3558 		new_crtc_state->active,
3559 		new_crtc_state->mode_changed,
3560 		new_crtc_state->active_changed,
3561 		new_crtc_state->connectors_changed);
3562 
3563 	/* hdcp content type change */
3564 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
3565 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
3566 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
3567 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
3568 		return true;
3569 	}
3570 
3571 	/* CP is being re enabled, ignore this */
3572 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
3573 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
3574 		if (new_crtc_state && new_crtc_state->mode_changed) {
3575 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
3576 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
3577 			return true;
3578 		}
3579 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
3580 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
3581 		return false;
3582 	}
3583 
3584 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
3585 	 *
3586 	 * Handles:	UNDESIRED -> ENABLED
3587 	 */
3588 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
3589 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
3590 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
3591 
3592 	/* Stream removed and re-enabled
3593 	 *
3594 	 * Can sometimes overlap with the HPD case,
3595 	 * thus set update_hdcp to false to avoid
3596 	 * setting HDCP multiple times.
3597 	 *
3598 	 * Handles:	DESIRED -> DESIRED (Special case)
3599 	 */
3600 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
3601 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
3602 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
3603 		dm_con_state->update_hdcp = false;
3604 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
3605 			__func__);
3606 		return true;
3607 	}
3608 
3609 	/* Hot-plug, headless s3, dpms
3610 	 *
3611 	 * Only start HDCP if the display is connected/enabled.
3612 	 * update_hdcp flag will be set to false until the next
3613 	 * HPD comes in.
3614 	 *
3615 	 * Handles:	DESIRED -> DESIRED (Special case)
3616 	 */
3617 	if (dm_con_state->update_hdcp &&
3618 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
3619 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
3620 		dm_con_state->update_hdcp = false;
3621 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
3622 			__func__);
3623 		return true;
3624 	}
3625 
3626 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
3627 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
3628 			if (new_crtc_state && new_crtc_state->mode_changed) {
3629 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
3630 					__func__);
3631 				return true;
3632 			}
3633 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
3634 				__func__);
3635 			return false;
3636 		}
3637 
3638 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
3639 		return false;
3640 	}
3641 
3642 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
3643 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
3644 			__func__);
3645 		return true;
3646 	}
3647 
3648 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
3649 	return false;
3650 }
3651 EXPORT_IF_KUNIT(is_content_protection_different);
3652 
3653 static void remove_stream(struct amdgpu_device *adev,
3654 			  struct amdgpu_crtc *acrtc,
3655 			  struct dc_stream_state *stream)
3656 {
3657 	/* this is the update mode case */
3658 
3659 	acrtc->otg_inst = -1;
3660 	acrtc->enabled = false;
3661 }
3662 
3663 STATIC_IFN_KUNIT void amdgpu_dm_commit_cursors(struct drm_atomic_commit *state)
3664 {
3665 	struct drm_plane *plane;
3666 	struct drm_plane_state *old_plane_state;
3667 	int i;
3668 
3669 	/*
3670 	 * TODO: Make this per-stream so we don't issue redundant updates for
3671 	 * commits with multiple streams.
3672 	 */
3673 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
3674 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
3675 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
3676 }
3677 EXPORT_IF_KUNIT(amdgpu_dm_commit_cursors);
3678 
3679 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
3680 {
3681 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
3682 
3683 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
3684 }
3685 
3686 STATIC_IFN_KUNIT void amdgpu_dm_update_cursor(struct drm_plane *plane,
3687 					      struct drm_plane_state *old_plane_state,
3688 					      struct dc_stream_update *update)
3689 {
3690 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
3691 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
3692 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
3693 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
3694 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
3695 	uint64_t address = afb ? afb->address : 0;
3696 	struct dc_cursor_position position = {0};
3697 	struct dc_cursor_attributes attributes;
3698 	int ret;
3699 
3700 	if (!plane->state->fb && !old_plane_state->fb)
3701 		return;
3702 
3703 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
3704 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
3705 		       plane->state->crtc_h);
3706 
3707 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
3708 	if (ret)
3709 		return;
3710 
3711 	if (!position.enable) {
3712 		/* turn off cursor */
3713 		if (crtc_state && crtc_state->stream) {
3714 			dc_stream_set_cursor_position(crtc_state->stream,
3715 						      &position);
3716 			update->cursor_position = &crtc_state->stream->cursor_position;
3717 		}
3718 		return;
3719 	}
3720 
3721 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
3722 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
3723 
3724 	memset(&attributes, 0, sizeof(attributes));
3725 	attributes.address.high_part = upper_32_bits(address);
3726 	attributes.address.low_part  = lower_32_bits(address);
3727 	attributes.width             = plane->state->crtc_w;
3728 	attributes.height            = plane->state->crtc_h;
3729 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
3730 	attributes.rotation_angle    = 0;
3731 	attributes.attribute_flags.value = 0;
3732 
3733 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
3734 	 * legacy gamma setup.
3735 	 */
3736 	if (crtc_state->cm_is_degamma_srgb &&
3737 	    adev->dm.dc->caps.color.dpp.gamma_corr)
3738 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
3739 
3740 	if (afb)
3741 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
3742 
3743 	if (crtc_state->stream) {
3744 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
3745 						     &attributes))
3746 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
3747 
3748 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
3749 
3750 		if (!dc_stream_set_cursor_position(crtc_state->stream,
3751 						   &position))
3752 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
3753 
3754 		update->cursor_position = &crtc_state->stream->cursor_position;
3755 	}
3756 }
3757 EXPORT_IF_KUNIT(amdgpu_dm_update_cursor);
3758 
3759 STATIC_IFN_KUNIT void amdgpu_dm_enable_self_refresh(struct amdgpu_display_manager *dm,
3760 						    struct amdgpu_crtc *acrtc_attach,
3761 						    const struct dm_crtc_state *acrtc_state,
3762 						    const u64 current_ts)
3763 {
3764 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
3765 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
3766 	struct amdgpu_dm_connector *aconn =
3767 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
3768 
3769 	if (!acrtc_state->base.async_flip) {
3770 		amdgpu_dm_psr_set_event(dm, acrtc_state->stream, false,
3771 			psr_event_immediate_flip, false);
3772 		amdgpu_dm_replay_set_event(dm, acrtc_state->stream, false,
3773 			replay_event_immediate_flip, false);
3774 	}
3775 
3776 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
3777 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
3778 	    (psr->psr_feature_enabled || pr->replay_feature_enabled)) {
3779 		if (aconn->sr_skip_count > 0)
3780 			aconn->sr_skip_count--;
3781 
3782 		/* Allow SR when skip count is 0. */
3783 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
3784 
3785 		/*
3786 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
3787 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
3788 		 * can be enabled immediately once OS demonstrates an
3789 		 * adequate number of fast atomic commits to notify KMD
3790 		 * of update events.
3791 		 * See `amdgpu_dm_crtc_vblank_control_worker()`.
3792 		 */
3793 		if (acrtc_attach->dm_irq_params.allow_sr_entry &&
3794 			(current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
3795 			amdgpu_dm_psr_set_event(dm, acrtc_state->stream, false,
3796 				psr_event_hw_programming, false);
3797 
3798 			amdgpu_dm_replay_set_event(dm, acrtc_state->stream, false,
3799 				replay_event_hw_programming, false);
3800 		}
3801 	} else {
3802 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
3803 	}
3804 }
3805 EXPORT_IF_KUNIT(amdgpu_dm_enable_self_refresh);
3806 
3807 STATIC_IFN_KUNIT void dm_arm_vblank_event(struct amdgpu_crtc *acrtc,
3808 					  struct dm_crtc_state *acrtc_state,
3809 					  bool pflip_update,
3810 					  bool cursor_update)
3811 {
3812 	assert_spin_locked(&acrtc->base.dev->event_lock);
3813 
3814 	if (!acrtc->base.state->event || acrtc_state->active_planes == 0)
3815 		return;
3816 
3817 	if (pflip_update) {
3818 		WARN_ON(acrtc->pflip_status != AMDGPU_FLIP_NONE);
3819 		WARN_ON(acrtc->event);
3820 
3821 		acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
3822 		acrtc->event = acrtc->base.state->event;
3823 		acrtc->base.state->event = NULL;
3824 
3825 		drm_dbg_state(acrtc->base.dev,
3826 			      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
3827 			      acrtc->crtc_id);
3828 	} else if (cursor_update) {
3829 		acrtc->event = acrtc->base.state->event;
3830 		acrtc->base.state->event = NULL;
3831 	}
3832 }
3833 EXPORT_IF_KUNIT(dm_arm_vblank_event);
3834 
3835 /**
3836  * dm_arm_vblank_event_pre_programming - Prepare for programming
3837  * @acrtc: The amdgpu CRTC to prepare
3838  * @acrtc_state: The new CRTC state
3839  * @pflip_update: Whether a page flip is being programmed
3840  * @cursor_update: Whether a cursor update is being programmed
3841  *
3842  * Grab a reference on the vblank counter if a page flip or cursor update is to
3843  * be programmed. Do this before programming so the HW is not in any
3844  * idle-optimized state (such as PSR).
3845  */
3846 STATIC_IFN_KUNIT void dm_arm_vblank_event_pre_programming(struct amdgpu_crtc *acrtc,
3847 							  struct dm_crtc_state *acrtc_state,
3848 							  bool pflip_update,
3849 							  bool cursor_update)
3850 {
3851 	assert_spin_locked(&acrtc->base.dev->event_lock);
3852 
3853 	if (!acrtc->base.state->event || acrtc_state->active_planes == 0)
3854 		return;
3855 
3856 	if (pflip_update || cursor_update)
3857 		drm_crtc_vblank_get(&acrtc->base);
3858 }
3859 EXPORT_IF_KUNIT(dm_arm_vblank_event_pre_programming);
3860 
3861 /*
3862  * FreeSync times each frame from the plane's previous flip, and a plane
3863  * reset gives the new DC plane zeroed flip timing, so copy it over. Do
3864  * this at commit time, not in atomic check: by then the previous commit
3865  * has finished writing it.
3866  */
3867 static void
3868 dm_plane_inherit_flip_time(struct dc_plane_state *dc_plane_state,
3869 			   struct drm_plane_state *old_plane_state,
3870 			   struct drm_plane_state *new_plane_state)
3871 {
3872 	struct dc_plane_state *old_dc_plane_state =
3873 		to_dm_plane_state(old_plane_state)->dc_state;
3874 
3875 	if (old_dc_plane_state && old_dc_plane_state != dc_plane_state &&
3876 	    old_plane_state->crtc == new_plane_state->crtc)
3877 		dc_plane_state->time = old_dc_plane_state->time;
3878 }
3879 
3880 static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state,
3881 				    struct drm_device *dev,
3882 				    struct amdgpu_display_manager *dm,
3883 				    struct drm_crtc *pcrtc,
3884 				    bool wait_for_vblank)
3885 {
3886 	u32 i;
3887 	u64 timestamp_ns = ktime_get_ns();
3888 	struct drm_plane *plane;
3889 	struct drm_plane_state *old_plane_state, *new_plane_state;
3890 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
3891 	struct drm_crtc_state *new_pcrtc_state =
3892 			drm_atomic_get_new_crtc_state(state, pcrtc);
3893 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
3894 	struct dm_crtc_state *dm_old_crtc_state =
3895 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
3896 	int planes_count = 0, vpos, hpos;
3897 	unsigned long flags;
3898 	u32 target_vblank, last_flip_vblank;
3899 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
3900 	bool cursor_update = false;
3901 	bool pflip_present = false;
3902 	bool immediate_flip = false;
3903 	bool flip_latched_during_prog = false;
3904 	bool dirty_rects_changed = false;
3905 	bool updated_planes_and_streams = false;
3906 	bool stream_update_needed = false;
3907 	struct {
3908 		struct dc_surface_update surface_updates[MAX_SURFACES];
3909 		struct dc_plane_info plane_infos[MAX_SURFACES];
3910 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3911 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3912 		struct dc_stream_update stream_update;
3913 	} *bundle;
3914 
3915 	bundle = kzalloc_obj(*bundle);
3916 
3917 	if (!bundle) {
3918 		drm_err(dev, "Failed to allocate update bundle\n");
3919 		goto cleanup;
3920 	}
3921 
3922 	/*
3923 	 * Disable the cursor first if we're disabling all the planes.
3924 	 * It'll remain on the screen after the planes are re-enabled
3925 	 * if we don't.
3926 	 *
3927 	 * If the cursor is transitioning from native to overlay mode, the
3928 	 * native cursor needs to be disabled first.
3929 	 */
3930 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
3931 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
3932 		struct dc_cursor_position cursor_position = {0};
3933 
3934 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
3935 						   &cursor_position))
3936 			drm_err(dev, "DC failed to disable native cursor\n");
3937 
3938 		bundle->stream_update.cursor_position =
3939 				&acrtc_state->stream->cursor_position;
3940 		stream_update_needed = true;
3941 	}
3942 
3943 	if (acrtc_state->active_planes == 0 &&
3944 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
3945 		amdgpu_dm_commit_cursors(state);
3946 
3947 	/* update planes when needed */
3948 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
3949 		struct drm_crtc *crtc = new_plane_state->crtc;
3950 		struct drm_crtc_state *new_crtc_state;
3951 		struct drm_framebuffer *fb = new_plane_state->fb;
3952 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
3953 		bool plane_needs_flip;
3954 		struct dc_plane_state *dc_plane;
3955 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
3956 		struct dm_plane_state *dm_old_plane_state = to_dm_plane_state(old_plane_state);
3957 
3958 		/* Cursor plane is handled after stream updates */
3959 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
3960 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
3961 			if ((fb && crtc == pcrtc) ||
3962 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
3963 				cursor_update = true;
3964 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0) {
3965 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
3966 					stream_update_needed = true;
3967 				}
3968 			}
3969 
3970 			continue;
3971 		}
3972 
3973 		if (!fb || !crtc || pcrtc != crtc)
3974 			continue;
3975 
3976 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
3977 		if (!new_crtc_state->active)
3978 			continue;
3979 
3980 		dc_plane = dm_new_plane_state->dc_state;
3981 		if (!dc_plane)
3982 			continue;
3983 
3984 		dm_plane_inherit_flip_time(dc_plane, old_plane_state,
3985 					   new_plane_state);
3986 
3987 		bundle->surface_updates[planes_count].surface = dc_plane;
3988 		if (new_pcrtc_state->color_mgmt_changed || new_plane_state->color_mgmt_changed) {
3989 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
3990 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
3991 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
3992 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
3993 			bundle->surface_updates[planes_count].cm = &dc_plane->cm;
3994 		}
3995 
3996 		if (amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
3997 							 &bundle->scaling_infos[planes_count])) {
3998 			planes_count += 1;
3999 			continue;
4000 		}
4001 
4002 		/* Cache the newly computed scaling_info in the plane state */
4003 		*dm_new_plane_state->scaling_info =
4004 			bundle->scaling_infos[planes_count];
4005 
4006 		/* Only send a scaling_info update if it changed vs the old state */
4007 		if (memcmp(dm_old_plane_state->scaling_info,
4008 			   dm_new_plane_state->scaling_info,
4009 			   sizeof(struct dc_scaling_info)))
4010 			bundle->surface_updates[planes_count].scaling_info =
4011 				&bundle->scaling_infos[planes_count];
4012 
4013 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
4014 
4015 		pflip_present = pflip_present || plane_needs_flip;
4016 
4017 		if (!plane_needs_flip) {
4018 			planes_count += 1;
4019 			continue;
4020 		}
4021 
4022 		fill_dc_plane_info_and_addr(
4023 			dm->adev, state, new_plane_state,
4024 			&bundle->plane_infos[planes_count],
4025 			&bundle->flip_addrs[planes_count].address,
4026 			afb->tmz_surface);
4027 
4028 		bundle->plane_infos[planes_count].color_space = dc_plane->color_space;
4029 
4030 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
4031 				 new_plane_state->plane->index,
4032 				 bundle->plane_infos[planes_count].dcc.enable);
4033 
4034 		/* Cache the newly computed plane_info in the plane state */
4035 		*dm_new_plane_state->plane_info =
4036 			bundle->plane_infos[planes_count];
4037 
4038 		/* Only send a plane_info update if it changed vs the old state */
4039 		if (memcmp(dm_old_plane_state->plane_info,
4040 			   dm_new_plane_state->plane_info,
4041 			   sizeof(struct dc_plane_info)))
4042 			bundle->surface_updates[planes_count].plane_info =
4043 				&bundle->plane_infos[planes_count];
4044 
4045 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
4046 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
4047 			fill_dc_dirty_rects(plane, old_plane_state,
4048 					    new_plane_state, new_crtc_state,
4049 					    &bundle->flip_addrs[planes_count],
4050 					    acrtc_state->stream->link->psr_settings.psr_version ==
4051 					    DC_PSR_VERSION_SU_1,
4052 					    &dirty_rects_changed);
4053 
4054 			/*
4055 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
4056 			 * and enabled it again after dirty regions are stable to avoid video glitch.
4057 			 * PSR-SU will be enabled in
4058 			 * amdgpu_dm_crtc_vblank_control_worker() if user
4059 			 * pause the video during the PSR-SU was disabled.
4060 			 */
4061 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
4062 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
4063 			    dirty_rects_changed) {
4064 				mutex_lock(&dm->dc_lock);
4065 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
4066 				timestamp_ns;
4067 				dc_exit_ips_for_hw_access(dm->dc);
4068 				amdgpu_dm_psr_set_event(dm, acrtc_state->stream, true,
4069 					psr_event_hw_programming, true);
4070 				mutex_unlock(&dm->dc_lock);
4071 			}
4072 		}
4073 
4074 		/*
4075 		 * Only allow immediate flips for fast updates that don't
4076 		 * change memory domain, FB pitch, DCC state, rotation or
4077 		 * mirroring.
4078 		 *
4079 		 * dm_crtc_helper_atomic_check() only accepts async flips with
4080 		 * fast updates.
4081 		 */
4082 		if (crtc->state->async_flip &&
4083 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
4084 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
4085 			drm_warn_once(state->dev,
4086 				      "[PLANE:%d:%s] async flip with non-fast update\n",
4087 				      plane->base.id, plane->name);
4088 
4089 		bundle->flip_addrs[planes_count].flip_immediate =
4090 			crtc->state->async_flip &&
4091 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
4092 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
4093 
4094 		immediate_flip |= bundle->flip_addrs[planes_count].flip_immediate;
4095 
4096 		timestamp_ns = ktime_get_ns();
4097 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
4098 		/* Cache the newly computed flip_addr in the plane state */
4099 		*dm_new_plane_state->flip_addr =
4100 			bundle->flip_addrs[planes_count];
4101 
4102 		/* Only send a flip_addr update if it changed vs the old state */
4103 		if (memcmp(dm_old_plane_state->flip_addr,
4104 			   dm_new_plane_state->flip_addr,
4105 			   sizeof(struct dc_flip_addrs)))
4106 			bundle->surface_updates[planes_count].flip_addr =
4107 				&bundle->flip_addrs[planes_count];
4108 		bundle->surface_updates[planes_count].surface = dc_plane;
4109 
4110 		if (!bundle->surface_updates[planes_count].surface) {
4111 			drm_err(dev, "No surface for CRTC: id=%d\n",
4112 					acrtc_attach->crtc_id);
4113 			continue;
4114 		}
4115 
4116 		if (plane == pcrtc->primary)
4117 			amdgpu_dm_update_freesync_state_on_stream(
4118 				dm,
4119 				acrtc_state,
4120 				acrtc_state->stream,
4121 				dc_plane,
4122 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
4123 
4124 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
4125 				 __func__,
4126 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
4127 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
4128 
4129 		planes_count += 1;
4130 
4131 	}
4132 
4133 	if (pflip_present) {
4134 		if (!vrr_active) {
4135 			/* Use old throttling in non-vrr fixed refresh rate mode
4136 			 * to keep flip scheduling based on target vblank counts
4137 			 * working in a backwards compatible way, e.g., for
4138 			 * clients using the GLX_OML_sync_control extension or
4139 			 * DRI3/Present extension with defined target_msc.
4140 			 */
4141 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
4142 		} else {
4143 			/* For variable refresh rate mode only:
4144 			 * Get vblank of last completed flip to avoid > 1 vrr
4145 			 * flips per video frame by use of throttling, but allow
4146 			 * flip programming anywhere in the possibly large
4147 			 * variable vrr vblank interval for fine-grained flip
4148 			 * timing control and more opportunity to avoid stutter
4149 			 * on late submission of flips.
4150 			 */
4151 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
4152 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
4153 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
4154 		}
4155 
4156 		target_vblank = last_flip_vblank + wait_for_vblank;
4157 
4158 		/*
4159 		 * Wait until we're out of the vertical blank period before the one
4160 		 * targeted by the flip
4161 		 */
4162 		while ((acrtc_attach->enabled &&
4163 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
4164 							    0, &vpos, &hpos, NULL,
4165 							    NULL, &pcrtc->hwmode)
4166 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
4167 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
4168 			(int)(target_vblank -
4169 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
4170 			usleep_range(1000, 1100);
4171 		}
4172 
4173 		if (acrtc_state->stream) {
4174 			if (acrtc_state->freesync_vrr_info_changed) {
4175 				bundle->stream_update.vrr_infopacket =
4176 					&acrtc_state->stream->vrr_infopacket;
4177 				bundle->stream_update.vtem_infopacket =
4178 					&acrtc_state->stream->vtem_infopacket;
4179 				bundle->stream_update.vsp_infopacket =
4180 					&acrtc_state->stream->vsp_infopacket;
4181 				stream_update_needed = true;
4182 			}
4183 		}
4184 	}
4185 
4186 	scoped_guard(spinlock_irqsave, &pcrtc->dev->event_lock) {
4187 		dm_arm_vblank_event_pre_programming(acrtc_attach, acrtc_state,
4188 						    pflip_present,
4189 						    cursor_update);
4190 		/*
4191 		 * DCE depends on a combination of GRPH_FLIP, VLINE0, and
4192 		 * VUPDATE for event delivery. Only GRPH_FLIP handler can send
4193 		 * pflip events, and it only fires if HW latched to the flip.
4194 		 * Maintain legacy behavior by arming event before programming.
4195 		 */
4196 		if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) {
4197 			dm_arm_vblank_event(acrtc_attach, acrtc_state,
4198 					    pflip_present, cursor_update);
4199 		}
4200 	}
4201 
4202 	/* Update the planes if changed or disable if we don't have any. */
4203 	if ((planes_count || acrtc_state->active_planes == 0) &&
4204 		acrtc_state->stream) {
4205 		/*
4206 		 * If PSR or idle optimizations are enabled then flush out
4207 		 * any pending work before hardware programming.
4208 		 */
4209 		if (dm->vblank_control_workqueue)
4210 			flush_workqueue(dm->vblank_control_workqueue);
4211 
4212 		bundle->stream_update.stream = acrtc_state->stream;
4213 		if (new_pcrtc_state->mode_changed) {
4214 			bundle->stream_update.src = acrtc_state->stream->src;
4215 			bundle->stream_update.dst = acrtc_state->stream->dst;
4216 			stream_update_needed = true;
4217 		}
4218 
4219 		if (new_pcrtc_state->color_mgmt_changed) {
4220 			/*
4221 			 * TODO: This isn't fully correct since we've actually
4222 			 * already modified the stream in place.
4223 			 */
4224 			bundle->stream_update.gamut_remap =
4225 				&acrtc_state->stream->gamut_remap_matrix;
4226 			bundle->stream_update.output_csc_transform =
4227 				&acrtc_state->stream->csc_color_matrix;
4228 			bundle->stream_update.out_transfer_func =
4229 				&acrtc_state->stream->out_transfer_func;
4230 			bundle->stream_update.lut3d_func =
4231 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
4232 			bundle->stream_update.func_shaper =
4233 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
4234 			stream_update_needed = true;
4235 		}
4236 
4237 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
4238 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level) {
4239 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
4240 			stream_update_needed = true;
4241 		}
4242 
4243 		/*
4244 		 * If FreeSync state on the stream has changed then we need to
4245 		 * re-adjust the min/max bounds now that DC doesn't handle this
4246 		 * as part of commit.
4247 		 */
4248 		if (amdgpu_dm_is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
4249 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
4250 			dc_stream_adjust_vmin_vmax(
4251 				dm->dc, acrtc_state->stream,
4252 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
4253 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
4254 		}
4255 		mutex_lock(&dm->dc_lock);
4256 		/*
4257 		 * Tearing (immediate) flips cannot work with panel self-refresh
4258 		 * features. The event is cleared by
4259 		 * amdgpu_dm_enable_self_refresh() once async flips stop.
4260 		 */
4261 		if (immediate_flip) {
4262 			dc_exit_ips_for_hw_access(dm->dc);
4263 			amdgpu_dm_psr_set_event(dm, acrtc_state->stream, true,
4264 				psr_event_immediate_flip, true);
4265 			amdgpu_dm_replay_set_event(dm, acrtc_state->stream, true,
4266 				replay_event_immediate_flip, true);
4267 		}
4268 		update_planes_and_stream_adapter(dm->dc,
4269 					 planes_count,
4270 					 acrtc_state->stream,
4271 					 stream_update_needed ? &bundle->stream_update : NULL,
4272 					 bundle->surface_updates);
4273 		updated_planes_and_streams = true;
4274 
4275 		/**
4276 		 * Enable or disable the interrupts on the backend.
4277 		 *
4278 		 * Most pipes are put into power gating when unused.
4279 		 *
4280 		 * When power gating is enabled on a pipe we lose the
4281 		 * interrupt enablement state when power gating is disabled.
4282 		 *
4283 		 * So we need to update the IRQ control state in hardware
4284 		 * whenever the pipe turns on (since it could be previously
4285 		 * power gated) or off (since some pipes can't be power gated
4286 		 * on some ASICs).
4287 		 */
4288 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
4289 			dm_update_pflip_irq_state(drm_to_adev(dev),
4290 						  acrtc_attach);
4291 		amdgpu_dm_enable_self_refresh(dm, acrtc_attach, acrtc_state,
4292 					      timestamp_ns);
4293 		mutex_unlock(&dm->dc_lock);
4294 	}
4295 
4296 	/*
4297 	 * Update cursor state *after* programming all the planes.
4298 	 * This avoids redundant programming in the case where we're going
4299 	 * to be disabling a single plane - those pipes are being disabled.
4300 	 */
4301 	if (acrtc_state->active_planes &&
4302 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
4303 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
4304 		amdgpu_dm_commit_cursors(state);
4305 
4306 	/*
4307 	 * DCN specific vblank handling
4308 	 * ============================
4309 	 *
4310 	 * With the event_lock held, arm the vblank event, and determine whether
4311 	 * deliver it immediately, or in VUPDATE_NO_LOCK IRQ (i.e. HW latch
4312 	 * point) handler. Do this *after* programming so that the IRQ handler
4313 	 * will not deliver the event before HW laches onto the programmed
4314 	 * values:
4315 	 *
4316 	 *     Commit thread      IRQ handler                       HW
4317 	 *     -----------------------------------------------------------------
4318 	 *     arm_vblank_event()
4319 	 *                                                          vupdate()
4320 	 *                        vupdate_handler()
4321 	 *                          cook_timestamp()
4322 	 *                          # prev flip already latched,
4323 	 *                          # so flip_latched == true.
4324 	 *                          if event_armed && flip_latched:
4325 	 *                            send_vblank_event()
4326 	 *                            # sent before latch, **BAD!**
4327 	 *     hw_program()
4328 	 *                                                          vupdate()
4329 	 *                                                          **latch**
4330 	 *
4331 	 * There's a consequence of arming after: it's possible for HW to latch
4332 	 * between start of HW programming and acrtc->event/pflip_status arming.
4333 	 * When this happens, the IRQ handler will send the event on the next
4334 	 * immediate latch point, even though HW has already latched. This is
4335 	 * handled by optimistically checking for HW latch after programming,
4336 	 * and if latched, send the event immediately:
4337 	 *
4338 	 *     Commit thread             IRQ handler                HW
4339 	 *     -----------------------------------------------------------------
4340 	 *     hw_program()
4341 	 *                                                          vupdate()
4342 	 *                                                          **latch**
4343 	 *                               vupdate_handler()
4344 	 *                                 cook_timestamp()
4345 	 *                                 # event_armed == false
4346 	 *                                 # **no event sent!**
4347 	 *     arm_vblank_event()
4348 	 *     if flip_latched:
4349 	 *       **send_vblank_event()**
4350 	 *       disarm_vblank_event()
4351 	 *
4352 	 * The IRQ handler is expected to cook the timestamp, but we need to
4353 	 * cook the timestamp before optimistic sending as well. That's because
4354 	 * the following sequence is possible:
4355 	 *
4356 	 *     Commit thread              IRQ handler              HW
4357 	 *     -----------------------------------------------------------------
4358 	 *     hw_program()
4359 	 *     arm_vblank_event()
4360 	 *                                                         vupdate()
4361 	 *                                                         **latch**
4362 	 *     if flip_latched:
4363 	 *       # Need cook before send!
4364 	 *       **cook_timestamp()**
4365 	 *       send_vblank_event()
4366 	 *       disarm_vblank_event()
4367 	 *                                vupdate_handler()
4368 	 *                                  cook_timestamp()
4369 	 *                                  # event_armed == false
4370 	 *                                  # no event sent!
4371 	 *
4372 	 * Cooking twice is OK, since DRM scanout accurate timestamps report A)
4373 	 * the previous vactive start if currently in vactive, or B) the next
4374 	 * vactive start if currently in vblank (see &get_vblank_counter). 'A)'
4375 	 * is what we want for the optimistic send, and for 'B)', we'll cook a
4376 	 * timestamp no later than the next IRQ handler run.
4377 	 *
4378 	 * The more correct fix is to wrap programming and arming with the
4379 	 * event_lock and thus serializing it with the IRQ handler. However,
4380 	 * there are various sleep-waits within
4381 	 * update_planes_and_stream_adapter() that makes spin locking illegal.
4382 	 * And on full updates, it can take 1-2 frame-times to return (see
4383 	 * commit_planes_for_stream).
4384 	 *
4385 	 * On DCE, GRPH_PFLIP IRQ is used and takes care of this.
4386 	 */
4387 	if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0) {
4388 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
4389 
4390 		if (updated_planes_and_streams) {
4391 			flip_latched_during_prog =
4392 				!dc_get_flip_pending_on_otg(dm->dc, acrtc_attach->otg_inst);
4393 		}
4394 
4395 		dm_arm_vblank_event(acrtc_attach, acrtc_state,
4396 				    pflip_present, cursor_update);
4397 
4398 		/*
4399 		 * Deliver the event immediately on immediate flip, or on a
4400 		 * update that has already latched.
4401 		 */
4402 		if ((immediate_flip || flip_latched_during_prog) &&
4403 		    acrtc_attach->pflip_status == AMDGPU_FLIP_SUBMITTED &&
4404 		    acrtc_attach->event) {
4405 			drm_crtc_accurate_vblank_count(&acrtc_attach->base);
4406 			drm_crtc_send_vblank_event(&acrtc_attach->base,
4407 						   acrtc_attach->event);
4408 			acrtc_attach->event = NULL;
4409 			drm_crtc_vblank_put(&acrtc_attach->base);
4410 			acrtc_attach->pflip_status = AMDGPU_FLIP_NONE;
4411 		}
4412 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
4413 	}
4414 
4415 cleanup:
4416 	kfree(bundle);
4417 }
4418 
4419 /*
4420  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
4421  * @crtc_state: the DRM CRTC state
4422  * @stream_state: the DC stream state.
4423  *
4424  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
4425  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
4426  */
4427 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
4428 						struct dc_stream_state *stream_state)
4429 {
4430 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
4431 }
4432 
4433 /**
4434  * amdgpu_dm_crtc_complete_writeback - finish a pending writeback job
4435  * @acrtc: the CRTC whose pending writeback should be completed
4436  *
4437  * Clears the pending state, signals the writeback out fence and releases the
4438  * vblank reference taken in dm_set_writeback() while the writeback was armed.
4439  * The pending flag is tested and cleared under the writeback job lock, so this
4440  * is safe to call concurrently from the completion vblank IRQ
4441  * (dm_crtc_high_irq()) and from the writeback teardown path
4442  * (dm_clear_writeback()); only the caller that observes the pending job
4443  * performs the completion.
4444  *
4445  * Return: true if a pending writeback job was completed by this call.
4446  */
4447 bool amdgpu_dm_crtc_complete_writeback(struct amdgpu_crtc *acrtc)
4448 {
4449 	unsigned long flags;
4450 	bool pending;
4451 
4452 	if (!acrtc->wb_conn)
4453 		return false;
4454 
4455 	spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
4456 	pending = acrtc->wb_pending;
4457 	acrtc->wb_pending = false;
4458 	acrtc->wb_frame_done = false;
4459 	spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
4460 
4461 	if (!pending)
4462 		return false;
4463 
4464 	drm_writeback_signal_completion(acrtc->wb_conn, 0);
4465 	drm_crtc_vblank_put(&acrtc->base);
4466 
4467 	return true;
4468 }
4469 EXPORT_IF_KUNIT(amdgpu_dm_crtc_complete_writeback);
4470 
4471 STATIC_IFN_KUNIT void dm_clear_writeback(struct amdgpu_display_manager *dm,
4472 					 struct amdgpu_crtc *acrtc,
4473 					 struct dm_crtc_state *crtc_state)
4474 {
4475 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
4476 
4477 	/*
4478 	 * If the writeback is still pending when it is torn down (its
4479 	 * completion vblank IRQ never fired), signal the out fence so a
4480 	 * waiting client does not stall and release the vblank reference
4481 	 * taken in dm_set_writeback().
4482 	 */
4483 	amdgpu_dm_crtc_complete_writeback(acrtc);
4484 }
4485 EXPORT_IF_KUNIT(dm_clear_writeback);
4486 
4487 static bool amdgpu_dm_self_refresh_pause_needed(struct drm_atomic_commit *state)
4488 {
4489 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4490 	struct drm_crtc *crtc;
4491 	int i;
4492 
4493 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i)
4494 		if (drm_atomic_crtc_needs_modeset(new_crtc_state) &&
4495 		    (old_crtc_state->active || new_crtc_state->active))
4496 			return true;
4497 
4498 	return false;
4499 }
4500 
4501 static bool amdgpu_dm_is_new_modeset_stream(struct drm_atomic_commit *state,
4502 					    const struct dc_stream_state *stream)
4503 {
4504 	struct drm_crtc_state *new_crtc_state;
4505 	struct drm_crtc *crtc;
4506 	int i;
4507 
4508 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i)
4509 		if (drm_atomic_crtc_needs_modeset(new_crtc_state) &&
4510 		    to_dm_crtc_state(new_crtc_state)->stream == stream)
4511 			return true;
4512 
4513 	return false;
4514 }
4515 
4516 /*
4517  * A modeset CRTC may have no PSR or Replay, such as an HDMI output being
4518  * turned off, while an eDP on another CRTC is still in self-refresh. Pause
4519  * self-refresh on every stream mod_power tracks before
4520  * amdgpu_dm_mod_power_update_streams() changes the set: the old streams of
4521  * the CRTCs in the commit and the unchanged streams of the new state.
4522  * Unlike hw_programming, which a fast update on another CRTC clears, the
4523  * pause holds until amdgpu_dm_resume_self_refresh()
4524  */
4525 static void amdgpu_dm_pause_self_refresh(struct drm_atomic_commit *state,
4526 					 struct amdgpu_display_manager *dm,
4527 					 struct dc_state *dc_state)
4528 {
4529 	struct drm_crtc_state *old_crtc_state;
4530 	struct dc_stream_state *stream;
4531 	struct drm_crtc *crtc;
4532 	int i;
4533 
4534 	if (!amdgpu_dm_self_refresh_pause_needed(state))
4535 		return;
4536 
4537 	guard(mutex)(&dm->dc_lock);
4538 	dc_exit_ips_for_hw_access(dm->dc);
4539 
4540 	for_each_old_crtc_in_state(state, crtc, old_crtc_state, i) {
4541 		stream = to_dm_crtc_state(old_crtc_state)->stream;
4542 		if (!old_crtc_state->active || !stream)
4543 			continue;
4544 
4545 		amdgpu_dm_psr_set_event(dm, stream, true, psr_event_pause, true);
4546 		amdgpu_dm_replay_set_event(dm, stream, true, replay_event_pause, true);
4547 	}
4548 
4549 	for (i = 0; i < dc_state->stream_count; i++) {
4550 		stream = dc_state->streams[i];
4551 		if (amdgpu_dm_is_new_modeset_stream(state, stream))
4552 			continue;
4553 
4554 		amdgpu_dm_psr_set_event(dm, stream, true, psr_event_pause, true);
4555 		amdgpu_dm_replay_set_event(dm, stream, true, replay_event_pause, true);
4556 	}
4557 }
4558 
4559 /*
4560  * Ends amdgpu_dm_pause_self_refresh() on the streams of the commit, which
4561  * mod_power tracks from amdgpu_dm_mod_power_update_streams() on, even if
4562  * dc_commit_streams() failed. mod_power keeps events across
4563  * mod_power_replace_stream(), so the replaced streams carry the pause too.
4564  * Runs after amdgpu_dm_mod_power_setup_streams(), since enabling a stream
4565  * clears psr_feature_enabled and replay_feature_enabled on its link until
4566  * then, and the set_event helpers skip a link without them
4567  */
4568 static void amdgpu_dm_resume_self_refresh(struct drm_atomic_commit *state,
4569 					  struct amdgpu_display_manager *dm,
4570 					  struct dc_state *dc_state)
4571 {
4572 	int i;
4573 
4574 	if (!dc_state || !amdgpu_dm_self_refresh_pause_needed(state))
4575 		return;
4576 
4577 	guard(mutex)(&dm->dc_lock);
4578 	for (i = 0; i < dc_state->stream_count; i++) {
4579 		amdgpu_dm_psr_set_event(dm, dc_state->streams[i], false,
4580 					psr_event_pause, false);
4581 		amdgpu_dm_replay_set_event(dm, dc_state->streams[i], false,
4582 					   replay_event_pause, false);
4583 	}
4584 }
4585 
4586 /**
4587  * amdgpu_dm_mod_power_update_streams - update mod_power stream state on modeset
4588  * @state: the drm atomic state
4589  * @dm: the display manager to update mod_power on
4590  *
4591  * Notify mod_power of stream changes on modeset events, and disable PSR/Replay
4592  * in preparation for hardware programming. See also
4593  * amdgpu_dm_mod_power_setup_streams() for post-modeset mod_power setup.
4594  */
4595 STATIC_IFN_KUNIT void amdgpu_dm_mod_power_update_streams(struct drm_atomic_commit *state,
4596 							struct amdgpu_display_manager *dm)
4597 {
4598 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
4599 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4600 	struct amdgpu_dm_connector *aconnector;
4601 	struct drm_crtc *crtc;
4602 	int i = 0;
4603 
4604 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4605 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4606 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4607 
4608 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
4609 			continue;
4610 
4611 		/*
4612 		 * Update mod_power on modeset event in preparation for hw
4613 		 * programming. Always use the old stream, since it would have
4614 		 * been previously added to mod_power. If old stream is null (on
4615 		 * crtc enable, for example), mod_power will no-op, which is the
4616 		 * desried behavior.
4617 		 */
4618 		if (old_crtc_state->active) {
4619 			scoped_guard(mutex, &dm->dc_lock) {
4620 				dc_exit_ips_for_hw_access(dm->dc);
4621 				amdgpu_dm_psr_set_event(dm, dm_old_crtc_state->stream, true,
4622 					psr_event_hw_programming, true);
4623 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, true,
4624 					replay_event_hw_programming, true);
4625 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, false,
4626 					replay_event_general_ui, false);
4627 			}
4628 		}
4629 
4630 		if (new_crtc_state->active) {
4631 			aconnector = (struct amdgpu_dm_connector *)
4632 				dm_new_crtc_state->stream->dm_stream_context;
4633 			if (old_crtc_state->active) {
4634 				mod_power_replace_stream(dm->power_module,
4635 					dm_old_crtc_state->stream,
4636 					dm_new_crtc_state->stream,
4637 					&aconnector->psr_caps);
4638 			} else {
4639 				mod_power_add_stream(dm->power_module,
4640 					dm_new_crtc_state->stream,
4641 					&aconnector->psr_caps);
4642 			}
4643 		} else if (old_crtc_state->active) {
4644 			mod_power_remove_stream(dm->power_module,
4645 				dm_old_crtc_state->stream);
4646 		}
4647 	}
4648 }
4649 EXPORT_IF_KUNIT(amdgpu_dm_mod_power_update_streams);
4650 
4651 /**
4652  * amdgpu_dm_mod_power_setup_streams - setup mod_power stream state post modeset
4653  * @state: the drm atomic state
4654  * @dm: the display manager to update mod_power on
4655  *
4656  * Notify mod_power of mode_change. This needs to be done after dc_stream
4657  * updates have been committed, and VRR parameters have been updated.
4658  */
4659 STATIC_IFN_KUNIT void amdgpu_dm_mod_power_setup_streams(struct drm_atomic_commit *state,
4660 						       struct amdgpu_display_manager *dm)
4661 {
4662 	struct dm_crtc_state *dm_new_crtc_state;
4663 	struct drm_crtc_state *new_crtc_state;
4664 	struct amdgpu_crtc *acrtc;
4665 	struct drm_crtc *crtc;
4666 	int i = 0;
4667 
4668 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
4669 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4670 		acrtc = to_amdgpu_crtc(crtc);
4671 
4672 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
4673 			continue;
4674 
4675 		if (new_crtc_state->active) {
4676 			amdgpu_dm_link_setup_replay(dm_new_crtc_state->stream,
4677 					&acrtc->dm_irq_params.vrr_params);
4678 			mod_power_notify_mode_change(dm->power_module,
4679 						dm_new_crtc_state->stream,
4680 						false);
4681 
4682 			/*
4683 			 * Block PSR / Replay on the new stream until display settles post-modeset.
4684 			 * These events will be cleared by amdgpu_dm_enable_self_refresh() once
4685 			 * allow_sr_entry becomes true.
4686 			 */
4687 			amdgpu_dm_psr_set_event(dm, dm_new_crtc_state->stream, true,
4688 				psr_event_hw_programming, true);
4689 
4690 			amdgpu_dm_replay_set_event(dm, dm_new_crtc_state->stream, true,
4691 				replay_event_hw_programming | replay_event_general_ui,
4692 				true);
4693 		}
4694 	}
4695 
4696 }
4697 EXPORT_IF_KUNIT(amdgpu_dm_mod_power_setup_streams);
4698 
4699 static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state,
4700 					struct dc_state *dc_state)
4701 {
4702 	struct drm_device *dev = state->dev;
4703 	struct amdgpu_device *adev = drm_to_adev(dev);
4704 	struct amdgpu_display_manager *dm = &adev->dm;
4705 	struct drm_crtc *crtc;
4706 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
4707 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
4708 	struct drm_connector_state *old_con_state;
4709 	struct drm_connector *connector;
4710 	bool mode_set_reset_required = false;
4711 	u32 i;
4712 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
4713 	bool set_backlight_level = false;
4714 
4715 	/* Disable writeback */
4716 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
4717 		struct dm_connector_state *dm_old_con_state;
4718 		struct amdgpu_crtc *acrtc;
4719 
4720 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
4721 			continue;
4722 
4723 		old_crtc_state = NULL;
4724 
4725 		dm_old_con_state = to_dm_connector_state(old_con_state);
4726 		if (!dm_old_con_state->base.crtc)
4727 			continue;
4728 
4729 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
4730 		if (acrtc)
4731 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
4732 
4733 		if (!acrtc || !acrtc->wb_enabled)
4734 			continue;
4735 
4736 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4737 
4738 		dm_clear_writeback(dm, acrtc, dm_old_crtc_state);
4739 		acrtc->wb_enabled = false;
4740 	}
4741 
4742 	amdgpu_dm_pause_self_refresh(state, dm, dc_state);
4743 	amdgpu_dm_mod_power_update_streams(state, dm);
4744 
4745 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
4746 				      new_crtc_state, i) {
4747 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4748 
4749 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4750 
4751 		if (old_crtc_state->active &&
4752 		    (!new_crtc_state->active ||
4753 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
4754 			manage_dm_interrupts(adev, acrtc, NULL);
4755 			/*
4756 			 * ISM hysteresis lives on system_dfl_wq, not the
4757 			 * vblank workqueue. Wait it out so a timer armed while
4758 			 * the stream existed cannot allow idle after the
4759 			 * stream is released.
4760 			 */
4761 			amdgpu_dm_ism_flush(&acrtc->ism);
4762 			dc_stream_release(dm_old_crtc_state->stream);
4763 		}
4764 	}
4765 
4766 	drm_atomic_helper_calc_timestamping_constants(state);
4767 
4768 	/* update changed items */
4769 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
4770 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4771 
4772 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4773 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
4774 
4775 		drm_dbg_state(state->dev,
4776 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
4777 			acrtc->crtc_id,
4778 			new_crtc_state->enable,
4779 			new_crtc_state->active,
4780 			new_crtc_state->planes_changed,
4781 			new_crtc_state->mode_changed,
4782 			new_crtc_state->active_changed,
4783 			new_crtc_state->connectors_changed);
4784 
4785 		/* Disable cursor if disabling crtc */
4786 		if (old_crtc_state->active && !new_crtc_state->active) {
4787 			struct dc_cursor_position position;
4788 
4789 			memset(&position, 0, sizeof(position));
4790 			mutex_lock(&dm->dc_lock);
4791 			dc_exit_ips_for_hw_access(dm->dc);
4792 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
4793 			mutex_unlock(&dm->dc_lock);
4794 		}
4795 
4796 		/* Copy all transient state flags into dc state */
4797 		if (dm_new_crtc_state->stream) {
4798 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
4799 							    dm_new_crtc_state->stream);
4800 		}
4801 
4802 		/* handles headless hotplug case, updating new_state and
4803 		 * aconnector as needed
4804 		 */
4805 
4806 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
4807 
4808 			drm_dbg_atomic(dev,
4809 				       "Atomic commit: SET crtc id %d: [%p]\n",
4810 				       acrtc->crtc_id, acrtc);
4811 
4812 			if (!dm_new_crtc_state->stream) {
4813 				/*
4814 				 * this could happen because of issues with
4815 				 * userspace notifications delivery.
4816 				 * In this case userspace tries to set mode on
4817 				 * display which is disconnected in fact.
4818 				 * dc_sink is NULL in this case on aconnector.
4819 				 * We expect reset mode will come soon.
4820 				 *
4821 				 * This can also happen when unplug is done
4822 				 * during resume sequence ended
4823 				 *
4824 				 * In this case, we want to pretend we still
4825 				 * have a sink to keep the pipe running so that
4826 				 * hw state is consistent with the sw state
4827 				 */
4828 				drm_dbg_atomic(dev,
4829 					       "Failed to create new stream for crtc %d\n",
4830 						acrtc->base.base.id);
4831 				continue;
4832 			}
4833 
4834 			if (dm_old_crtc_state->stream)
4835 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
4836 
4837 			acrtc->enabled = true;
4838 			acrtc->hw_mode = new_crtc_state->mode;
4839 			crtc->hwmode = new_crtc_state->mode;
4840 			mode_set_reset_required = true;
4841 			set_backlight_level = true;
4842 		} else if (modereset_required(new_crtc_state)) {
4843 			drm_dbg_atomic(dev,
4844 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
4845 				       acrtc->crtc_id, acrtc);
4846 			/* i.e. reset mode */
4847 			if (dm_old_crtc_state->stream)
4848 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
4849 
4850 			mode_set_reset_required = true;
4851 		}
4852 	} /* for_each_crtc_in_state() */
4853 
4854 	/* if there mode set or reset, flush vblank work queue */
4855 	if (mode_set_reset_required) {
4856 		if (dm->vblank_control_workqueue)
4857 			flush_workqueue(dm->vblank_control_workqueue);
4858 	}
4859 
4860 	dm_enable_per_frame_crtc_master_sync(dc_state);
4861 	mutex_lock(&dm->dc_lock);
4862 	dc_exit_ips_for_hw_access(dm->dc);
4863 	WARN_ON(!dc_commit_streams(dm->dc, &params));
4864 
4865 	/* Allow idle optimization when vblank count is 0 for display off */
4866 	if (dm->active_vblank_irq_count == 0 && amdgpu_dm_is_headless(dm->adev))
4867 		dc_allow_idle_optimizations(dm->dc, true);
4868 	mutex_unlock(&dm->dc_lock);
4869 
4870 	bool frl_stream_found = false;
4871 
4872 	for (i = 0; i < params.stream_count; i++) {
4873 		struct dc_stream_state *stream = params.streams[i];
4874 
4875 		if (stream->signal == SIGNAL_TYPE_HDMI_FRL) {
4876 			frl_stream_found = true;
4877 			break;
4878 		}
4879 	}
4880 
4881 	if (frl_stream_found) {
4882 		if (queue_delayed_work(dm->hdmi_frl_status_polling_wq,
4883 				       &dm->hdmi_frl_status_polling_work,
4884 				       msecs_to_jiffies(dm->hdmi_frl_status_polling_delay_ms)))
4885 			drm_dbg_kms(dev, "200ms frl status polling starts ...\n");
4886 	} else {
4887 		if (cancel_delayed_work_sync(&dm->hdmi_frl_status_polling_work))
4888 			drm_dbg_kms(dev, "200ms frl status polling stops ...\n");
4889 	}
4890 
4891 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
4892 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
4893 
4894 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
4895 
4896 		if (dm_new_crtc_state->stream != NULL) {
4897 			const struct dc_stream_status *status =
4898 					dc_stream_get_status(dm_new_crtc_state->stream);
4899 
4900 			if (!status)
4901 				status = dc_state_get_stream_status(dc_state,
4902 									 dm_new_crtc_state->stream);
4903 			if (!status)
4904 				drm_err(dev,
4905 					"got no status for stream %p on acrtc%p\n",
4906 					dm_new_crtc_state->stream, acrtc);
4907 			else
4908 				acrtc->otg_inst = status->primary_otg_inst;
4909 		}
4910 	}
4911 
4912 	/* During boot up and resume the DC layer will reset the panel brightness
4913 	 * to fix a flicker issue.
4914 	 * It will cause the dm->actual_brightness is not the current panel brightness
4915 	 * level. (the dm->brightness is the correct panel level)
4916 	 * So we set the backlight level with dm->brightness value after set mode
4917 	 */
4918 	if (set_backlight_level) {
4919 		for (i = 0; i < dm->num_of_edps; i++) {
4920 			if (dm->backlight_dev[i])
4921 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
4922 		}
4923 	}
4924 }
4925 
4926 STATIC_IFN_KUNIT void
4927 dm_set_writeback(struct amdgpu_display_manager *dm,
4928 		 struct dm_crtc_state *crtc_state,
4929 		 struct drm_connector *connector,
4930 		 struct drm_connector_state *new_con_state)
4931 {
4932 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
4933 	struct amdgpu_device *adev = dm->adev;
4934 	struct amdgpu_crtc *acrtc;
4935 	struct dc_writeback_info *wb_info;
4936 	struct pipe_ctx *pipe = NULL;
4937 	struct amdgpu_framebuffer *afb;
4938 	int i = 0;
4939 
4940 	wb_info = kzalloc_obj(*wb_info);
4941 	if (!wb_info) {
4942 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
4943 		goto cleanup;
4944 	}
4945 
4946 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
4947 	if (!acrtc) {
4948 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
4949 		goto cleanup;
4950 	}
4951 
4952 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
4953 	if (!afb) {
4954 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
4955 		goto cleanup;
4956 	}
4957 
4958 	for (i = 0; i < MAX_PIPES; i++) {
4959 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
4960 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
4961 			break;
4962 		}
4963 	}
4964 
4965 	if (!pipe) {
4966 		drm_err(adev_to_drm(adev), "No pipe found for stream\n");
4967 		goto cleanup;
4968 	}
4969 
4970 	/* fill in wb_info */
4971 	wb_info->wb_enabled = true;
4972 
4973 	wb_info->dwb_pipe_inst = 0;
4974 	wb_info->dwb_params.dwbscl_black_color = 0;
4975 	wb_info->dwb_params.hdr_mult = 0x1F000;
4976 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
4977 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
4978 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
4979 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
4980 
4981 	/* width & height from crtc */
4982 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
4983 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
4984 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
4985 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
4986 
4987 	wb_info->dwb_params.cnv_params.crop_en = false;
4988 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
4989 
4990 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
4991 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
4992 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
4993 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
4994 
4995 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
4996 
4997 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
4998 
4999 	wb_info->dwb_params.scaler_taps.h_taps = 1;
5000 	wb_info->dwb_params.scaler_taps.v_taps = 1;
5001 	wb_info->dwb_params.scaler_taps.h_taps_c = 1;
5002 	wb_info->dwb_params.scaler_taps.v_taps_c = 1;
5003 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
5004 
5005 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
5006 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
5007 
5008 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
5009 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
5010 		wb_info->mcif_buf_params.chroma_address[i] = 0;
5011 	}
5012 
5013 	wb_info->mcif_buf_params.p_vmid = 1;
5014 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
5015 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
5016 		wb_info->mcif_warmup_params.region_size =
5017 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
5018 	}
5019 	wb_info->mcif_warmup_params.p_vmid = 1;
5020 	wb_info->writeback_source_plane = pipe->plane_state;
5021 
5022 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
5023 
5024 	acrtc->wb_conn = wb_conn;
5025 	drm_writeback_queue_job(wb_conn, new_con_state);
5026 
5027 	/*
5028 	 * Writeback completion is detected in the CRTC vblank IRQ
5029 	 * (dm_crtc_high_irq()). Take a vblank reference so the vblank interrupt
5030 	 * stays enabled while the writeback is pending; otherwise a
5031 	 * writeback-only commit right after drm_crtc_vblank_on() (e.g.
5032 	 * re-enabling a CRTC that was disabled) has no other vblank reference,
5033 	 * the IRQ never fires and the out fence times out. The matching put
5034 	 * happens once completion is signalled in dm_crtc_high_irq(), or when
5035 	 * the writeback is torn down in dm_clear_writeback().
5036 	 *
5037 	 * Arm wb_pending only after the reference is held so the completion IRQ
5038 	 * cannot run its matching vblank_put before this get.
5039 	 */
5040 	WARN_ON(drm_crtc_vblank_get(&acrtc->base));
5041 	acrtc->wb_frame_done = false;
5042 	acrtc->wb_pending = true;
5043 
5044 cleanup:
5045 	kfree(wb_info);
5046 }
5047 EXPORT_IF_KUNIT(dm_set_writeback);
5048 
5049 STATIC_IFN_KUNIT void amdgpu_dm_update_hdcp(struct drm_atomic_commit *state)
5050 {
5051 	struct drm_connector_state *old_con_state, *new_con_state;
5052 	struct drm_device *dev = state->dev;
5053 	struct drm_connector *connector;
5054 	struct amdgpu_device *adev = drm_to_adev(dev);
5055 	int i;
5056 
5057 	if (!adev->dm.hdcp_workqueue)
5058 		return;
5059 
5060 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
5061 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
5062 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
5063 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5064 		struct dm_crtc_state *dm_new_crtc_state;
5065 		struct amdgpu_dm_connector *aconnector;
5066 
5067 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
5068 			continue;
5069 
5070 		aconnector = to_amdgpu_dm_connector(connector);
5071 
5072 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
5073 
5074 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
5075 			connector->index, connector->status, connector->dpms);
5076 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
5077 			old_con_state->content_protection, new_con_state->content_protection);
5078 
5079 		if (aconnector->dc_sink) {
5080 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
5081 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
5082 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
5083 				aconnector->dc_sink->edid_caps.display_name);
5084 			}
5085 		}
5086 
5087 		new_crtc_state = NULL;
5088 		old_crtc_state = NULL;
5089 
5090 		if (acrtc) {
5091 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
5092 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
5093 		}
5094 
5095 		if (old_crtc_state)
5096 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
5097 			old_crtc_state->enable,
5098 			old_crtc_state->active,
5099 			old_crtc_state->mode_changed,
5100 			old_crtc_state->active_changed,
5101 			old_crtc_state->connectors_changed);
5102 
5103 		if (new_crtc_state)
5104 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
5105 			new_crtc_state->enable,
5106 			new_crtc_state->active,
5107 			new_crtc_state->mode_changed,
5108 			new_crtc_state->active_changed,
5109 			new_crtc_state->connectors_changed);
5110 
5111 
5112 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5113 
5114 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
5115 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
5116 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
5117 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
5118 			dm_new_con_state->update_hdcp = true;
5119 			continue;
5120 		}
5121 
5122 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
5123 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
5124 			/* when display is unplugged from mst hub, connctor will
5125 			 * be destroyed within dm_dp_mst_connector_destroy. connector
5126 			 * hdcp perperties, like type, undesired, desired, enabled,
5127 			 * will be lost. So, save hdcp properties into hdcp_work within
5128 			 * amdgpu_dm_atomic_commit_tail. if the same display is
5129 			 * plugged back with same display index, its hdcp properties
5130 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
5131 			 */
5132 
5133 			bool enable_encryption = false;
5134 
5135 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
5136 				enable_encryption = true;
5137 
5138 			if (aconnector->dc_link && aconnector->dc_sink &&
5139 				aconnector->dc_link->type == dc_connection_mst_branch) {
5140 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
5141 				struct hdcp_workqueue *hdcp_w =
5142 					&hdcp_work[aconnector->dc_link->link_index];
5143 
5144 				hdcp_w->hdcp_content_type[connector->index] =
5145 					new_con_state->hdcp_content_type;
5146 				hdcp_w->content_protection[connector->index] =
5147 					new_con_state->content_protection;
5148 			}
5149 
5150 			if (new_crtc_state && new_crtc_state->mode_changed &&
5151 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
5152 				enable_encryption = true;
5153 
5154 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
5155 
5156 			if (aconnector->dc_link)
5157 				hdcp_update_display(
5158 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
5159 					new_con_state->hdcp_content_type, enable_encryption);
5160 		}
5161 	}
5162 }
5163 EXPORT_IF_KUNIT(amdgpu_dm_update_hdcp);
5164 
5165 STATIC_IFN_KUNIT int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state)
5166 {
5167 	struct drm_crtc *crtc;
5168 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5169 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
5170 	int i, ret;
5171 
5172 	ret = drm_dp_mst_atomic_setup_commit(state);
5173 	if (ret)
5174 		return ret;
5175 
5176 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
5177 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5178 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5179 		/*
5180 		 * Color management settings. We also update color properties
5181 		 * when a modeset is needed, to ensure it gets reprogrammed.
5182 		 */
5183 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
5184 		    (dm_new_crtc_state->base.color_mgmt_changed ||
5185 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
5186 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
5187 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
5188 			if (ret) {
5189 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
5190 				return ret;
5191 			}
5192 		}
5193 	}
5194 
5195 	return 0;
5196 }
5197 EXPORT_IF_KUNIT(amdgpu_dm_atomic_setup_commit);
5198 
5199 STATIC_IFN_KUNIT void set_multisync_trigger_params(
5200 		struct dc_stream_state *stream)
5201 {
5202 	struct dc_stream_state *master = NULL;
5203 
5204 	if (stream->triggered_crtc_reset.enabled) {
5205 		master = stream->triggered_crtc_reset.event_source;
5206 		stream->triggered_crtc_reset.event =
5207 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
5208 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
5209 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
5210 	}
5211 }
5212 EXPORT_IF_KUNIT(set_multisync_trigger_params);
5213 
5214 STATIC_IFN_KUNIT void set_master_stream(struct dc_stream_state *stream_set[],
5215 					int stream_count)
5216 {
5217 	int j, highest_rfr = 0, master_stream = 0;
5218 
5219 	for (j = 0;  j < stream_count; j++) {
5220 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
5221 			int refresh_rate = 0;
5222 
5223 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
5224 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
5225 			if (refresh_rate > highest_rfr) {
5226 				highest_rfr = refresh_rate;
5227 				master_stream = j;
5228 			}
5229 		}
5230 	}
5231 	for (j = 0;  j < stream_count; j++) {
5232 		if (stream_set[j])
5233 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
5234 	}
5235 }
5236 EXPORT_IF_KUNIT(set_master_stream);
5237 
5238 STATIC_IFN_KUNIT void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
5239 {
5240 	int i = 0;
5241 	struct dc_stream_state *stream;
5242 
5243 	if (context->stream_count < 2)
5244 		return;
5245 	for (i = 0; i < context->stream_count ; i++) {
5246 		if (!context->streams[i])
5247 			continue;
5248 		/*
5249 		 * TODO: add a function to read AMD VSDB bits and set
5250 		 * crtc_sync_master.multi_sync_enabled flag
5251 		 * For now it's set to false
5252 		 */
5253 	}
5254 
5255 	set_master_stream(context->streams, context->stream_count);
5256 
5257 	for (i = 0; i < context->stream_count ; i++) {
5258 		stream = context->streams[i];
5259 
5260 		if (!stream)
5261 			continue;
5262 
5263 		set_multisync_trigger_params(stream);
5264 	}
5265 }
5266 EXPORT_IF_KUNIT(dm_enable_per_frame_crtc_master_sync);
5267 
5268 /**
5269  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
5270  * @state: The atomic state to commit
5271  *
5272  * This will tell DC to commit the constructed DC state from atomic_check,
5273  * programming the hardware. Any failures here implies a hardware failure, since
5274  * atomic check should have filtered anything non-kosher.
5275  */
5276 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state)
5277 {
5278 	struct drm_device *dev = state->dev;
5279 	struct amdgpu_device *adev = drm_to_adev(dev);
5280 	struct amdgpu_display_manager *dm = &adev->dm;
5281 	struct dm_atomic_state *dm_state;
5282 	struct dc_state *dc_state = NULL;
5283 	u32 i, j;
5284 	struct drm_crtc *crtc;
5285 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5286 	unsigned long flags;
5287 	bool wait_for_vblank = true;
5288 	struct drm_connector *connector;
5289 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
5290 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
5291 	int crtc_disable_count = 0;
5292 
5293 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
5294 
5295 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
5296 	drm_dp_mst_atomic_wait_for_dependencies(state);
5297 
5298 	dm_state = dm_atomic_get_new_state(state);
5299 	if (dm_state && dm_state->context) {
5300 		dc_state = dm_state->context;
5301 		amdgpu_dm_commit_streams(state, dc_state);
5302 	}
5303 
5304 	amdgpu_dm_update_hdcp(state);
5305 
5306 	/* Handle connector state changes */
5307 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
5308 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
5309 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
5310 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
5311 		struct dc_surface_update *dummy_updates;
5312 		struct dc_stream_update stream_update;
5313 		struct dc_info_packet hdr_packet;
5314 		struct dc_stream_status *status = NULL;
5315 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
5316 
5317 		memset(&stream_update, 0, sizeof(stream_update));
5318 
5319 		if (acrtc) {
5320 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
5321 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
5322 		}
5323 
5324 		/* Skip any modesets/resets */
5325 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
5326 			continue;
5327 
5328 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5329 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5330 
5331 		scaling_changed = is_scaling_state_different(dm_new_con_state,
5332 							     dm_old_con_state);
5333 
5334 		if (new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb &&
5335 		    dm_old_crtc_state->stream->output_color_space !=
5336 		    amdgpu_dm_get_output_color_space(&dm_new_crtc_state->stream->timing,
5337 						     new_con_state,
5338 						     dm_new_crtc_state->stream->signal))
5339 			output_color_space_changed = true;
5340 
5341 		abm_changed = dm_new_crtc_state->abm_level !=
5342 			      dm_old_crtc_state->abm_level;
5343 
5344 		hdr_changed =
5345 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
5346 
5347 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
5348 			continue;
5349 
5350 		stream_update.stream = dm_new_crtc_state->stream;
5351 		if (scaling_changed) {
5352 			amdgpu_dm_update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
5353 					dm_new_con_state, dm_new_crtc_state->stream);
5354 
5355 			stream_update.src = dm_new_crtc_state->stream->src;
5356 			stream_update.dst = dm_new_crtc_state->stream->dst;
5357 		}
5358 
5359 		if (output_color_space_changed) {
5360 			dm_new_crtc_state->stream->output_color_space =
5361 				amdgpu_dm_get_output_color_space(&dm_new_crtc_state->stream->timing,
5362 								 new_con_state,
5363 								 dm_new_crtc_state->stream->signal);
5364 
5365 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
5366 		}
5367 
5368 		if (abm_changed) {
5369 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
5370 
5371 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
5372 		}
5373 
5374 		if (hdr_changed) {
5375 			amdgpu_dm_fill_hdr_info_packet(new_con_state, &hdr_packet);
5376 			stream_update.hdr_static_metadata = &hdr_packet;
5377 		}
5378 
5379 		status = dc_stream_get_status(dm_new_crtc_state->stream);
5380 
5381 		if (WARN_ON(!status))
5382 			continue;
5383 
5384 		WARN_ON(!status->plane_count);
5385 
5386 		/*
5387 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
5388 		 * Here we create an empty update on each plane.
5389 		 * To fix this, DC should permit updating only stream properties.
5390 		 */
5391 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
5392 		if (!dummy_updates) {
5393 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
5394 			continue;
5395 		}
5396 		for (j = 0; j < status->plane_count; j++)
5397 			dummy_updates[j].surface = status->plane_states[j];
5398 
5399 		sort(dummy_updates, status->plane_count,
5400 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
5401 
5402 		mutex_lock(&dm->dc_lock);
5403 		dc_exit_ips_for_hw_access(dm->dc);
5404 		dc_update_planes_and_stream(dm->dc,
5405 					    dummy_updates,
5406 					    status->plane_count,
5407 					    dm_new_crtc_state->stream,
5408 					    &stream_update);
5409 		mutex_unlock(&dm->dc_lock);
5410 		kfree(dummy_updates);
5411 
5412 		drm_connector_update_privacy_screen(new_con_state);
5413 	}
5414 
5415 	/**
5416 	 * Enable interrupts for CRTCs that are newly enabled or went through
5417 	 * a modeset. It was intentionally deferred until after the front end
5418 	 * state was modified to wait until the OTG was on and so the IRQ
5419 	 * handlers didn't access stale or invalid state.
5420 	 */
5421 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
5422 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
5423 #ifdef CONFIG_DEBUG_FS
5424 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
5425 #endif
5426 		/*
5427 		 * One runtime PM reference per active CRTC: take it when the
5428 		 * CRTC turns on, count it when it turns off for dropping later.
5429 		 */
5430 		if (!old_crtc_state->active && new_crtc_state->active)
5431 			pm_runtime_get_noresume(dev->dev);
5432 		else if (old_crtc_state->active && !new_crtc_state->active)
5433 			crtc_disable_count++;
5434 
5435 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5436 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5437 
5438 		/* For freesync config update on crtc state and params for irq */
5439 		amdgpu_dm_update_stream_irq_parameters(dm, dm_new_crtc_state);
5440 
5441 #ifdef CONFIG_DEBUG_FS
5442 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
5443 		cur_crc_src = acrtc->dm_irq_params.crc_src;
5444 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
5445 #endif
5446 
5447 		if (new_crtc_state->active &&
5448 		    (!old_crtc_state->active ||
5449 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
5450 			dc_stream_retain(dm_new_crtc_state->stream);
5451 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
5452 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
5453 		}
5454 		/* Handle vrr on->off / off->on transitions */
5455 		amdgpu_dm_handle_vrr_transition(dm, dm_old_crtc_state, dm_new_crtc_state);
5456 
5457 #ifdef CONFIG_DEBUG_FS
5458 		if (new_crtc_state->active &&
5459 		    (!old_crtc_state->active ||
5460 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
5461 			/**
5462 			 * Frontend may have changed so reapply the CRC capture
5463 			 * settings for the stream.
5464 			 */
5465 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
5466 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
5467 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
5468 					uint8_t cnt;
5469 
5470 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
5471 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
5472 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
5473 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
5474 
5475 							/**
5476 							 * It takes 2 frames for HW to stably generate CRC when
5477 							 * resuming from suspend, so we set skip_frame_cnt 2.
5478 							 */
5479 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
5480 						}
5481 					}
5482 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
5483 				}
5484 #endif
5485 				if (amdgpu_dm_crtc_configure_crc_source(
5486 					crtc, dm_new_crtc_state, cur_crc_src))
5487 					drm_dbg_atomic(dev, "Failed to configure crc source");
5488 			}
5489 		}
5490 #endif
5491 	}
5492 
5493 	amdgpu_dm_mod_power_setup_streams(state, dm);
5494 	amdgpu_dm_resume_self_refresh(state, dm, dc_state);
5495 
5496 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
5497 		if (new_crtc_state->async_flip)
5498 			wait_for_vblank = false;
5499 
5500 	/* update planes when needed per crtc*/
5501 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
5502 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5503 
5504 		if (dm_new_crtc_state->stream)
5505 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
5506 	}
5507 
5508 	/* Enable writeback */
5509 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
5510 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
5511 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
5512 
5513 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
5514 			continue;
5515 
5516 		if (!new_con_state->writeback_job)
5517 			continue;
5518 
5519 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
5520 
5521 		if (!new_crtc_state)
5522 			continue;
5523 
5524 		if (acrtc->wb_enabled)
5525 			continue;
5526 
5527 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5528 
5529 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
5530 		acrtc->wb_enabled = true;
5531 	}
5532 
5533 	/* Update audio instances for each connector. */
5534 	amdgpu_dm_commit_audio(dev, state);
5535 
5536 	/* restore the backlight level */
5537 	for (i = 0; i < dm->num_of_edps; i++) {
5538 		if (dm->backlight_dev[i] &&
5539 		    (dm->actual_brightness[i] != dm->brightness[i]))
5540 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
5541 	}
5542 
5543 	/*
5544 	 * send vblank event on all events not handled in flip and
5545 	 * mark consumed event for drm_atomic_helper_commit_hw_done
5546 	 */
5547 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
5548 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
5549 
5550 		if (new_crtc_state->event)
5551 			drm_send_event_locked(dev, &new_crtc_state->event->base);
5552 
5553 		new_crtc_state->event = NULL;
5554 	}
5555 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
5556 
5557 	/* Signal HW programming completion */
5558 	drm_atomic_helper_commit_hw_done(state);
5559 
5560 	if (wait_for_vblank)
5561 		drm_atomic_helper_wait_for_flip_done(dev, state);
5562 
5563 	drm_atomic_helper_cleanup_planes(dev, state);
5564 
5565 	/* Don't free the memory if we are hitting this as part of suspend.
5566 	 * This way we don't free any memory during suspend; see
5567 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
5568 	 * non-suspend modeset or when the driver is torn down.
5569 	 */
5570 	if (!adev->in_suspend) {
5571 		/* return the stolen vga memory back to VRAM */
5572 		if (!adev->mman.keep_stolen_vga_memory)
5573 			amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_VGA);
5574 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_EXTENDED);
5575 	}
5576 
5577 	/*
5578 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
5579 	 * so we can put the GPU into runtime suspend if we're not driving any
5580 	 * displays anymore
5581 	 */
5582 	for (i = 0; i < crtc_disable_count; i++)
5583 		pm_runtime_put_autosuspend(dev->dev);
5584 	pm_runtime_mark_last_busy(dev->dev);
5585 
5586 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
5587 }
5588 
5589 /*
5590  * Grabs all modesetting locks to serialize against any blocking commits,
5591  * Waits for completion of all non blocking commits.
5592  */
5593 STATIC_IFN_KUNIT int do_aquire_global_lock(struct drm_device *dev,
5594 					   struct drm_atomic_commit *state)
5595 {
5596 	struct drm_crtc *crtc;
5597 	struct drm_crtc_commit *commit;
5598 	long ret;
5599 
5600 	/*
5601 	 * Adding all modeset locks to aquire_ctx will
5602 	 * ensure that when the framework release it the
5603 	 * extra locks we are locking here will get released to
5604 	 */
5605 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
5606 	if (ret)
5607 		return ret;
5608 
5609 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
5610 		spin_lock(&crtc->commit_lock);
5611 		commit = list_first_entry_or_null(&crtc->commit_list,
5612 				struct drm_crtc_commit, commit_entry);
5613 		if (commit)
5614 			drm_crtc_commit_get(commit);
5615 		spin_unlock(&crtc->commit_lock);
5616 
5617 		if (!commit)
5618 			continue;
5619 
5620 		/*
5621 		 * Make sure all pending HW programming completed and
5622 		 * page flips done
5623 		 */
5624 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
5625 
5626 		if (ret > 0)
5627 			ret = wait_for_completion_interruptible_timeout(
5628 					&commit->flip_done, 10*HZ);
5629 
5630 		if (ret == 0)
5631 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
5632 				  crtc->base.id, crtc->name);
5633 
5634 		drm_crtc_commit_put(commit);
5635 	}
5636 
5637 	return ret < 0 ? ret : 0;
5638 }
5639 EXPORT_IF_KUNIT(do_aquire_global_lock);
5640 
5641 STATIC_IFN_KUNIT int dm_update_crtc_state(struct amdgpu_display_manager *dm,
5642 					  struct drm_atomic_commit *state,
5643 					  struct drm_crtc *crtc,
5644 					  struct drm_crtc_state *old_crtc_state,
5645 					  struct drm_crtc_state *new_crtc_state,
5646 					  bool enable,
5647 					  bool *needs_dc_state_realloc)
5648 {
5649 	struct dm_atomic_state *dm_state = NULL;
5650 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
5651 	struct dc_stream_state *new_stream;
5652 	struct amdgpu_device *adev = dm->adev;
5653 	int ret = 0;
5654 
5655 	/*
5656 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
5657 	 * update changed items
5658 	 */
5659 	struct amdgpu_crtc *acrtc = NULL;
5660 	struct drm_connector *connector = NULL;
5661 	struct amdgpu_dm_connector *aconnector = NULL;
5662 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
5663 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
5664 
5665 	new_stream = NULL;
5666 
5667 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
5668 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
5669 	acrtc = to_amdgpu_crtc(crtc);
5670 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
5671 	if (connector)
5672 		aconnector = to_amdgpu_dm_connector(connector);
5673 
5674 	/* TODO This hack should go away */
5675 	if (connector && enable) {
5676 		/* Make sure fake sink is created in plug-in scenario */
5677 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
5678 									connector);
5679 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
5680 									connector);
5681 
5682 		if (WARN_ON(!drm_new_conn_state)) {
5683 			ret = -EINVAL;
5684 			goto fail;
5685 		}
5686 
5687 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
5688 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
5689 
5690 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
5691 			goto skip_modeset;
5692 
5693 		new_stream = amdgpu_dm_create_validate_stream_for_sink(connector,
5694 							     &new_crtc_state->mode,
5695 							     dm_new_conn_state,
5696 							     dm_old_crtc_state->stream);
5697 
5698 		/*
5699 		 * we can have no stream on ACTION_SET if a display
5700 		 * was disconnected during S3, in this case it is not an
5701 		 * error, the OS will be updated after detection, and
5702 		 * will do the right thing on next atomic commit
5703 		 */
5704 
5705 		if (!new_stream) {
5706 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
5707 					__func__, acrtc->base.base.id);
5708 			ret = -ENOMEM;
5709 			goto fail;
5710 		}
5711 
5712 		/*
5713 		 * TODO: Check VSDB bits to decide whether this should
5714 		 * be enabled or not.
5715 		 */
5716 		new_stream->triggered_crtc_reset.enabled =
5717 			dm->force_timing_sync;
5718 
5719 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
5720 
5721 		ret = amdgpu_dm_fill_hdr_info_packet(drm_new_conn_state,
5722 					   &new_stream->hdr_static_metadata);
5723 		if (ret)
5724 			goto fail;
5725 
5726 		/*
5727 		 * If we already removed the old stream from the context
5728 		 * (and set the new stream to NULL) then we can't reuse
5729 		 * the old stream even if the stream and scaling are unchanged.
5730 		 * We'll hit the BUG_ON and black screen.
5731 		 *
5732 		 * TODO: Refactor this function to allow this check to work
5733 		 * in all conditions.
5734 		 */
5735 		if (amdgpu_freesync_vid_mode &&
5736 		    dm_new_crtc_state->stream &&
5737 		    amdgpu_dm_is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
5738 			goto skip_modeset;
5739 
5740 		if (dm_new_crtc_state->stream &&
5741 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
5742 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
5743 			new_crtc_state->mode_changed = false;
5744 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
5745 					 new_crtc_state->mode_changed);
5746 		}
5747 	}
5748 
5749 	/* mode_changed flag may get updated above, need to check again */
5750 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
5751 		goto skip_modeset;
5752 
5753 	drm_dbg_state(state->dev,
5754 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
5755 		acrtc->crtc_id,
5756 		new_crtc_state->enable,
5757 		new_crtc_state->active,
5758 		new_crtc_state->planes_changed,
5759 		new_crtc_state->mode_changed,
5760 		new_crtc_state->active_changed,
5761 		new_crtc_state->connectors_changed);
5762 
5763 	/* Remove stream for any changed/disabled CRTC */
5764 	if (!enable) {
5765 
5766 		if (!dm_old_crtc_state->stream)
5767 			goto skip_modeset;
5768 
5769 		/* Unset freesync video if it was active before */
5770 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
5771 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
5772 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
5773 		}
5774 
5775 		/* Now check if we should set freesync video mode */
5776 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
5777 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
5778 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
5779 		    amdgpu_dm_is_timing_unchanged_for_freesync(new_crtc_state,
5780 						     old_crtc_state)) {
5781 			new_crtc_state->mode_changed = false;
5782 			drm_dbg_driver(adev_to_drm(adev),
5783 				"Mode change not required for front porch change, setting mode_changed to %d",
5784 				new_crtc_state->mode_changed);
5785 
5786 			amdgpu_dm_set_freesync_fixed_config(dm_new_crtc_state);
5787 
5788 			goto skip_modeset;
5789 		} else if (amdgpu_freesync_vid_mode && aconnector &&
5790 			   amdgpu_dm_is_freesync_video_mode(&new_crtc_state->mode,
5791 						  aconnector)) {
5792 			struct drm_display_mode *high_mode;
5793 
5794 			high_mode = amdgpu_dm_get_highest_refresh_rate_mode(aconnector, false);
5795 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
5796 				amdgpu_dm_set_freesync_fixed_config(dm_new_crtc_state);
5797 		}
5798 
5799 		ret = dm_atomic_get_state(state, &dm_state);
5800 		if (ret)
5801 			goto fail;
5802 
5803 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
5804 				crtc->base.id);
5805 
5806 		/* i.e. reset mode */
5807 		if (dc_state_remove_stream(
5808 				dm->dc,
5809 				dm_state->context,
5810 				dm_old_crtc_state->stream) != DC_OK) {
5811 			ret = -EINVAL;
5812 			goto fail;
5813 		}
5814 
5815 		dc_stream_release(dm_old_crtc_state->stream);
5816 		dm_new_crtc_state->stream = NULL;
5817 
5818 		amdgpu_dm_reset_freesync_config_for_crtc(dm_new_crtc_state);
5819 
5820 		*needs_dc_state_realloc = true;
5821 
5822 	} else {/* Add stream for any updated/enabled CRTC */
5823 		/*
5824 		 * Quick fix to prevent NULL pointer on new_stream when
5825 		 * added MST connectors not found in existing crtc_state in the chained mode
5826 		 * TODO: need to dig out the root cause of that
5827 		 */
5828 		if (!connector)
5829 			goto skip_modeset;
5830 
5831 		if (modereset_required(new_crtc_state))
5832 			goto skip_modeset;
5833 
5834 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
5835 				     dm_old_crtc_state->stream)) {
5836 
5837 			WARN_ON(dm_new_crtc_state->stream);
5838 
5839 			ret = dm_atomic_get_state(state, &dm_state);
5840 			if (ret)
5841 				goto fail;
5842 
5843 			dm_new_crtc_state->stream = new_stream;
5844 
5845 			dc_stream_retain(new_stream);
5846 
5847 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
5848 					 crtc->base.id);
5849 
5850 			if (dc_state_add_stream(
5851 					dm->dc,
5852 					dm_state->context,
5853 					dm_new_crtc_state->stream) != DC_OK) {
5854 				ret = -EINVAL;
5855 				goto fail;
5856 			}
5857 
5858 			*needs_dc_state_realloc = true;
5859 		}
5860 	}
5861 
5862 skip_modeset:
5863 	/* Release extra reference */
5864 	if (new_stream) {
5865 		dc_stream_release(new_stream);
5866 		new_stream = NULL;
5867 	}
5868 	new_stream = NULL;
5869 
5870 	/*
5871 	 * We want to do dc stream updates that do not require a
5872 	 * full modeset below.
5873 	 */
5874 	if (!(enable && connector && new_crtc_state->active))
5875 		return 0;
5876 	/*
5877 	 * Given above conditions, the dc state cannot be NULL because:
5878 	 * 1. We're in the process of enabling CRTCs (just been added
5879 	 *    to the dc context, or already is on the context)
5880 	 * 2. Has a valid connector attached, and
5881 	 * 3. Is currently active and enabled.
5882 	 * => The dc stream state currently exists.
5883 	 */
5884 	BUG_ON(dm_new_crtc_state->stream == NULL);
5885 
5886 	/* Scaling or underscan settings */
5887 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
5888 				drm_atomic_crtc_needs_modeset(new_crtc_state))
5889 		amdgpu_dm_update_stream_scaling_settings(adev_to_drm(adev),
5890 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
5891 
5892 	/* ABM settings */
5893 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
5894 
5895 	/*
5896 	 * Color management settings. We also update color properties
5897 	 * when a modeset is needed, to ensure it gets reprogrammed.
5898 	 */
5899 	if (dm_new_crtc_state->base.color_mgmt_changed ||
5900 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
5901 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
5902 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
5903 		if (ret)
5904 			goto fail;
5905 	}
5906 
5907 	/* Update Freesync settings. */
5908 	amdgpu_dm_get_freesync_config_for_crtc(dm_new_crtc_state,
5909 				     dm_new_conn_state);
5910 
5911 	return ret;
5912 
5913 fail:
5914 	if (new_stream)
5915 		dc_stream_release(new_stream);
5916 	return ret;
5917 }
5918 EXPORT_IF_KUNIT(dm_update_crtc_state);
5919 
5920 STATIC_IFN_KUNIT bool should_reset_plane(struct drm_atomic_commit *state,
5921 					 struct drm_plane *plane,
5922 					 struct drm_plane_state *old_plane_state,
5923 					 struct drm_plane_state *new_plane_state)
5924 {
5925 	struct drm_plane *other;
5926 	struct drm_plane_state *old_other_state, *new_other_state;
5927 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
5928 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
5929 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
5930 	struct drm_connector_state *new_con_state;
5931 	struct drm_connector *connector;
5932 	int i;
5933 
5934 	/*
5935 	 * TODO: Remove this hack for all asics once it proves that the
5936 	 * fast updates works fine on DCN3.2+.
5937 	 */
5938 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
5939 	    state->allow_modeset)
5940 		return true;
5941 
5942 	/* Check for writeback commit */
5943 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
5944 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
5945 			continue;
5946 
5947 		if (new_con_state->writeback_job)
5948 			return true;
5949 	}
5950 
5951 	if (amdgpu_in_reset(adev) && state->allow_modeset)
5952 		return true;
5953 
5954 	/* Exit early if we know that we're adding or removing the plane. */
5955 	if (old_plane_state->crtc != new_plane_state->crtc)
5956 		return true;
5957 
5958 	/* old crtc == new_crtc == NULL, plane not in context. */
5959 	if (!new_plane_state->crtc)
5960 		return false;
5961 
5962 	new_crtc_state =
5963 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
5964 	old_crtc_state =
5965 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
5966 
5967 	if (!new_crtc_state)
5968 		return true;
5969 
5970 	/*
5971 	 * A change in cursor mode means a new dc pipe needs to be acquired or
5972 	 * released from the state
5973 	 */
5974 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
5975 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
5976 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
5977 	    old_dm_crtc_state != NULL &&
5978 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
5979 		return true;
5980 	}
5981 
5982 	/* CRTC Degamma changes currently require us to recreate planes. */
5983 	if (new_crtc_state->color_mgmt_changed)
5984 		return true;
5985 
5986 	/* Plane color pipeline or its colorop changes. */
5987 	if (new_plane_state->color_mgmt_changed)
5988 		return true;
5989 
5990 	/*
5991 	 * On zpos change, planes need to be reordered by removing and re-adding
5992 	 * them one by one to the dc state, in order of descending zpos.
5993 	 *
5994 	 * TODO: We can likely skip bandwidth validation if the only thing that
5995 	 * changed about the plane was it'z z-ordering.
5996 	 */
5997 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
5998 		return true;
5999 
6000 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
6001 		return true;
6002 
6003 	/*
6004 	 * If there are any new primary or overlay planes being added or
6005 	 * removed then the z-order can potentially change. To ensure
6006 	 * correct z-order and pipe acquisition the current DC architecture
6007 	 * requires us to remove and recreate all existing planes.
6008 	 *
6009 	 * TODO: Come up with a more elegant solution for this.
6010 	 */
6011 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
6012 		struct amdgpu_framebuffer *old_afb, *new_afb;
6013 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
6014 
6015 		dm_new_other_state = to_dm_plane_state(new_other_state);
6016 		dm_old_other_state = to_dm_plane_state(old_other_state);
6017 
6018 		if (other->type == DRM_PLANE_TYPE_CURSOR)
6019 			continue;
6020 
6021 		if (old_other_state->crtc != new_plane_state->crtc &&
6022 		    new_other_state->crtc != new_plane_state->crtc)
6023 			continue;
6024 
6025 		if (old_other_state->crtc != new_other_state->crtc)
6026 			return true;
6027 
6028 		/* Src/dst size and scaling updates. */
6029 		if (old_other_state->src_w != new_other_state->src_w ||
6030 		    old_other_state->src_h != new_other_state->src_h ||
6031 		    old_other_state->crtc_w != new_other_state->crtc_w ||
6032 		    old_other_state->crtc_h != new_other_state->crtc_h)
6033 			return true;
6034 
6035 		/* Rotation / mirroring updates. */
6036 		if (old_other_state->rotation != new_other_state->rotation)
6037 			return true;
6038 
6039 		/* Blending updates. */
6040 		if (old_other_state->pixel_blend_mode !=
6041 		    new_other_state->pixel_blend_mode)
6042 			return true;
6043 
6044 		/* Alpha updates. */
6045 		if (old_other_state->alpha != new_other_state->alpha)
6046 			return true;
6047 
6048 		/* Colorspace changes. */
6049 		if (old_other_state->color_range != new_other_state->color_range ||
6050 		    old_other_state->color_encoding != new_other_state->color_encoding)
6051 			return true;
6052 
6053 		/* HDR/Transfer Function changes. */
6054 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
6055 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
6056 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
6057 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
6058 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
6059 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
6060 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
6061 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
6062 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
6063 			return true;
6064 
6065 		/* Framebuffer checks fall at the end. */
6066 		if (!old_other_state->fb || !new_other_state->fb)
6067 			continue;
6068 
6069 		/* Pixel format changes can require bandwidth updates. */
6070 		if (old_other_state->fb->format != new_other_state->fb->format)
6071 			return true;
6072 
6073 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
6074 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
6075 
6076 		/* Tiling and DCC changes also require bandwidth updates. */
6077 		if (old_afb->base.modifier != new_afb->base.modifier)
6078 			return true;
6079 	}
6080 
6081 	return false;
6082 }
6083 EXPORT_IF_KUNIT(should_reset_plane);
6084 
6085 STATIC_IFN_KUNIT int
6086 dm_update_plane_state(struct dc *dc,
6087 		      struct drm_atomic_commit *state,
6088 		      struct drm_plane *plane,
6089 		      struct drm_plane_state *old_plane_state,
6090 		      struct drm_plane_state *new_plane_state,
6091 		      bool enable,
6092 		      bool *needs_dc_state_realloc,
6093 		      bool *is_top_most_overlay)
6094 {
6095 
6096 	struct dm_atomic_state *dm_state = NULL;
6097 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
6098 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
6099 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
6100 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
6101 	bool needs_reset, update_native_cursor;
6102 	int ret = 0;
6103 
6104 
6105 	new_plane_crtc = new_plane_state->crtc;
6106 	old_plane_crtc = old_plane_state->crtc;
6107 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
6108 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
6109 
6110 	update_native_cursor = amdgpu_dm_should_update_native_cursor(state,
6111 								     old_plane_crtc,
6112 								     new_plane_crtc,
6113 								     enable);
6114 
6115 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
6116 		ret = amdgpu_dm_check_native_cursor_state(new_plane_crtc, plane,
6117 							  new_plane_state, enable);
6118 		if (ret)
6119 			return ret;
6120 
6121 		return 0;
6122 	}
6123 
6124 	needs_reset = should_reset_plane(state, plane, old_plane_state,
6125 					 new_plane_state);
6126 
6127 	/* Remove any changed/removed planes */
6128 	if (!enable) {
6129 		if (!needs_reset)
6130 			return 0;
6131 
6132 		if (!old_plane_crtc)
6133 			return 0;
6134 
6135 		old_crtc_state = drm_atomic_get_old_crtc_state(
6136 				state, old_plane_crtc);
6137 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6138 
6139 		if (!dm_old_crtc_state->stream)
6140 			return 0;
6141 
6142 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
6143 				plane->base.id, old_plane_crtc->base.id);
6144 
6145 		ret = dm_atomic_get_state(state, &dm_state);
6146 		if (ret)
6147 			return ret;
6148 
6149 		if (!dc_state_remove_plane(
6150 				dc,
6151 				dm_old_crtc_state->stream,
6152 				dm_old_plane_state->dc_state,
6153 				dm_state->context)) {
6154 
6155 			return -EINVAL;
6156 		}
6157 
6158 		if (dm_old_plane_state->dc_state)
6159 			dc_plane_state_release(dm_old_plane_state->dc_state);
6160 
6161 		dm_new_plane_state->dc_state = NULL;
6162 
6163 		*needs_dc_state_realloc = true;
6164 
6165 	} else { /* Add new planes */
6166 		struct dc_plane_state *dc_new_plane_state;
6167 
6168 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
6169 			return 0;
6170 
6171 		if (!new_plane_crtc)
6172 			return 0;
6173 
6174 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
6175 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6176 
6177 		if (!dm_new_crtc_state->stream)
6178 			return 0;
6179 
6180 		if (!needs_reset)
6181 			return 0;
6182 
6183 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
6184 		if (ret)
6185 			goto out;
6186 
6187 		/*
6188 		 * Recreating the plane re-derives its DC color pipeline from the
6189 		 * colorop states in this commit. Pull the plane's colorops in so
6190 		 * the derivation sees the current pipeline; otherwise every stage
6191 		 * silently defaults to bypass (dropping YUV->RGB, shaper, 3D LUT
6192 		 * and regamma) when userspace didn't touch color in this commit.
6193 		 */
6194 		if (new_plane_state->color_pipeline) {
6195 			ret = drm_atomic_add_affected_colorops(state, plane);
6196 			if (ret)
6197 				goto out;
6198 		}
6199 
6200 		WARN_ON(dm_new_plane_state->dc_state);
6201 
6202 		dc_new_plane_state = dc_create_plane_state(dc);
6203 		if (!dc_new_plane_state) {
6204 			ret = -ENOMEM;
6205 			goto out;
6206 		}
6207 
6208 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
6209 				 plane->base.id, new_plane_crtc->base.id);
6210 
6211 		ret = fill_dc_plane_attributes(
6212 			drm_to_adev(new_plane_crtc->dev),
6213 			dc_new_plane_state,
6214 			new_plane_state,
6215 			new_crtc_state);
6216 		if (ret) {
6217 			dc_plane_state_release(dc_new_plane_state);
6218 			goto out;
6219 		}
6220 
6221 		ret = dm_atomic_get_state(state, &dm_state);
6222 		if (ret) {
6223 			dc_plane_state_release(dc_new_plane_state);
6224 			goto out;
6225 		}
6226 
6227 		/*
6228 		 * Any atomic check errors that occur after this will
6229 		 * not need a release. The plane state will be attached
6230 		 * to the stream, and therefore part of the atomic
6231 		 * state. It'll be released when the atomic state is
6232 		 * cleaned.
6233 		 */
6234 		if (!dc_state_add_plane(
6235 				dc,
6236 				dm_new_crtc_state->stream,
6237 				dc_new_plane_state,
6238 				dm_state->context)) {
6239 
6240 			dc_plane_state_release(dc_new_plane_state);
6241 			ret = -EINVAL;
6242 			goto out;
6243 		}
6244 
6245 		dm_new_plane_state->dc_state = dc_new_plane_state;
6246 
6247 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
6248 
6249 		/* Tell DC to do a full surface update every time there
6250 		 * is a plane change. Inefficient, but works for now.
6251 		 */
6252 		dm_new_plane_state->dc_state->update_bits.full_update = 1;
6253 
6254 		*needs_dc_state_realloc = true;
6255 	}
6256 
6257 out:
6258 	/* If enabling cursor overlay failed, attempt fallback to native mode */
6259 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
6260 		ret = amdgpu_dm_check_native_cursor_state(new_plane_crtc, plane,
6261 							  new_plane_state, enable);
6262 		if (ret)
6263 			return ret;
6264 
6265 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
6266 	}
6267 
6268 	return ret;
6269 }
6270 EXPORT_IF_KUNIT(dm_update_plane_state);
6271 
6272 /*
6273  * The normalized_zpos value cannot be used by this iterator directly. It's only
6274  * calculated for enabled planes, potentially causing normalized_zpos collisions
6275  * between enabled/disabled planes in the atomic state. We need a unique value
6276  * so that the iterator will not generate the same object twice, or loop
6277  * indefinitely.
6278  */
6279 struct __drm_planes_state *amdgpu_dm_get_next_zpos(
6280 	struct drm_atomic_commit *state,
6281 	struct __drm_planes_state *prev)
6282 {
6283 	unsigned int highest_zpos = 0, prev_zpos = 256;
6284 	uint32_t highest_id = 0, prev_id = UINT_MAX;
6285 	struct drm_plane_state *new_plane_state;
6286 	struct drm_plane *plane;
6287 	int i, highest_i = -1;
6288 
6289 	if (prev != NULL) {
6290 		prev_zpos = prev->new_state->zpos;
6291 		prev_id = prev->ptr->base.id;
6292 	}
6293 
6294 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
6295 		/* Skip planes with higher zpos than the previously returned */
6296 		if (new_plane_state->zpos > prev_zpos ||
6297 		    (new_plane_state->zpos == prev_zpos &&
6298 		     plane->base.id >= prev_id))
6299 			continue;
6300 
6301 		/* Save the index of the plane with highest zpos */
6302 		if (new_plane_state->zpos > highest_zpos ||
6303 		    (new_plane_state->zpos == highest_zpos &&
6304 		     plane->base.id > highest_id)) {
6305 			highest_zpos = new_plane_state->zpos;
6306 			highest_id = plane->base.id;
6307 			highest_i = i;
6308 		}
6309 	}
6310 
6311 	if (highest_i < 0)
6312 		return NULL;
6313 
6314 	return &state->planes[highest_i];
6315 }
6316 
6317 STATIC_IFN_KUNIT int add_affected_mst_dsc_crtcs(struct drm_atomic_commit *state,
6318 						struct drm_crtc *crtc)
6319 {
6320 	struct drm_connector *connector;
6321 	struct drm_connector_state *conn_state, *old_conn_state;
6322 	struct amdgpu_dm_connector *aconnector = NULL;
6323 	int i;
6324 
6325 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
6326 		if (!conn_state->crtc)
6327 			conn_state = old_conn_state;
6328 
6329 		if (conn_state->crtc != crtc)
6330 			continue;
6331 
6332 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
6333 			continue;
6334 
6335 		aconnector = to_amdgpu_dm_connector(connector);
6336 		if (!aconnector->mst_output_port || !aconnector->mst_root)
6337 			aconnector = NULL;
6338 		else
6339 			break;
6340 	}
6341 
6342 	if (!aconnector)
6343 		return 0;
6344 
6345 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
6346 }
6347 EXPORT_IF_KUNIT(add_affected_mst_dsc_crtcs);
6348 
6349 STATIC_IFN_KUNIT bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
6350 						      struct drm_atomic_commit *state,
6351 						      struct drm_crtc_state *crtc_state)
6352 {
6353 	struct drm_plane *plane;
6354 	struct drm_plane_state *new_plane_state, *old_plane_state;
6355 
6356 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
6357 		new_plane_state = drm_atomic_get_new_plane_state(state, plane);
6358 		old_plane_state = drm_atomic_get_old_plane_state(state, plane);
6359 
6360 		if (!old_plane_state || !new_plane_state)
6361 			continue;
6362 
6363 		if (old_plane_state->fb && new_plane_state->fb &&
6364 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
6365 			return true;
6366 	}
6367 
6368 	return false;
6369 }
6370 EXPORT_IF_KUNIT(amdgpu_dm_crtc_mem_type_changed);
6371 
6372 /**
6373  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
6374  *
6375  * @dev: The DRM device
6376  * @state: The atomic state to commit
6377  *
6378  * Validate that the given atomic state is programmable by DC into hardware.
6379  * This involves constructing a &struct dc_state reflecting the new hardware
6380  * state we wish to commit, then querying DC to see if it is programmable. It's
6381  * important not to modify the existing DC state. Otherwise, atomic_check
6382  * may unexpectedly commit hardware changes.
6383  *
6384  * When validating the DC state, it's important that the right locks are
6385  * acquired. For full updates case which removes/adds/updates streams on one
6386  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
6387  * that any such full update commit will wait for completion of any outstanding
6388  * flip using DRMs synchronization events.
6389  *
6390  * Note that DM adds the affected connectors for all CRTCs in state, when that
6391  * might not seem necessary. This is because DC stream creation requires the
6392  * DC sink, which is tied to the DRM connector state. Cleaning this up should
6393  * be possible but non-trivial - a possible TODO item.
6394  *
6395  * Return: -Error code if validation failed.
6396  */
6397 STATIC_IFN_KUNIT int amdgpu_dm_atomic_check(struct drm_device *dev,
6398 					    struct drm_atomic_commit *state)
6399 {
6400 	struct amdgpu_device *adev = drm_to_adev(dev);
6401 	struct dm_atomic_state *dm_state = NULL;
6402 	struct dc *dc = adev->dm.dc;
6403 	struct drm_connector *connector;
6404 	struct drm_connector_state *old_con_state, *new_con_state;
6405 	struct drm_crtc *crtc;
6406 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
6407 	struct drm_plane *plane;
6408 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
6409 	enum dc_status status;
6410 	int ret, i;
6411 	bool needs_dc_state_realloc = false;
6412 	bool is_top_most_overlay = true;
6413 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
6414 	struct drm_dp_mst_topology_mgr *mgr;
6415 	struct drm_dp_mst_topology_state *mst_state;
6416 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
6417 
6418 	trace_amdgpu_dm_atomic_check_begin(state);
6419 
6420 	ret = drm_atomic_helper_check_modeset(dev, state);
6421 	if (ret) {
6422 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed: %pe\n", ERR_PTR(ret));
6423 		goto fail;
6424 	}
6425 
6426 	/* Check connector changes */
6427 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
6428 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
6429 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
6430 
6431 		/* Skip connectors that are disabled or part of modeset already. */
6432 		if (!new_con_state->crtc)
6433 			continue;
6434 
6435 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
6436 		if (IS_ERR(new_crtc_state)) {
6437 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed: %pe\n", new_crtc_state);
6438 			ret = PTR_ERR(new_crtc_state);
6439 			goto fail;
6440 		}
6441 
6442 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
6443 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
6444 			new_crtc_state->connectors_changed = true;
6445 	}
6446 
6447 	if (dc_resource_is_dsc_encoding_supported(dc)) {
6448 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6449 			dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6450 			dm_new_crtc_state->mode_changed_independent_from_dsc = new_crtc_state->mode_changed;
6451 		}
6452 
6453 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6454 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
6455 				ret = add_affected_mst_dsc_crtcs(state, crtc);
6456 				if (ret) {
6457 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed: %pe\n", ERR_PTR(ret));
6458 					goto fail;
6459 				}
6460 			}
6461 		}
6462 	}
6463 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6464 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
6465 
6466 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
6467 		    !new_crtc_state->color_mgmt_changed &&
6468 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
6469 			dm_old_crtc_state->dsc_force_changed == false)
6470 			continue;
6471 
6472 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
6473 		if (ret) {
6474 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed: %pe\n", ERR_PTR(ret));
6475 			goto fail;
6476 		}
6477 
6478 		if (!new_crtc_state->enable)
6479 			continue;
6480 
6481 		ret = drm_atomic_add_affected_connectors(state, crtc);
6482 		if (ret) {
6483 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed: %pe\n", ERR_PTR(ret));
6484 			goto fail;
6485 		}
6486 
6487 		ret = drm_atomic_add_affected_planes(state, crtc);
6488 		if (ret) {
6489 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed: %pe\n", ERR_PTR(ret));
6490 			goto fail;
6491 		}
6492 
6493 		if (dm_old_crtc_state->dsc_force_changed)
6494 			new_crtc_state->mode_changed = true;
6495 	}
6496 
6497 	/*
6498 	 * Add all primary and overlay planes on the CRTC to the state
6499 	 * whenever a plane is enabled to maintain correct z-ordering
6500 	 * and to enable fast surface updates.
6501 	 */
6502 	drm_for_each_crtc(crtc, dev) {
6503 		bool modified = false;
6504 
6505 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
6506 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
6507 				continue;
6508 
6509 			if (new_plane_state->crtc == crtc ||
6510 			    old_plane_state->crtc == crtc) {
6511 				modified = true;
6512 				break;
6513 			}
6514 		}
6515 
6516 		if (!modified)
6517 			continue;
6518 
6519 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
6520 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
6521 				continue;
6522 
6523 			new_plane_state =
6524 				drm_atomic_get_plane_state(state, plane);
6525 
6526 			if (IS_ERR(new_plane_state)) {
6527 				ret = PTR_ERR(new_plane_state);
6528 				drm_dbg_atomic(dev, "new_plane_state is BAD: %pe\n", new_plane_state);
6529 				goto fail;
6530 			}
6531 		}
6532 	}
6533 
6534 	/*
6535 	 * DC consults the zpos (layer_index in DC terminology) to determine the
6536 	 * hw plane on which to enable the hw cursor (see
6537 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
6538 	 * atomic state, so call drm helper to normalize zpos.
6539 	 */
6540 	ret = drm_atomic_normalize_zpos(dev, state);
6541 	if (ret) {
6542 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed: %pe\n", ERR_PTR(ret));
6543 		goto fail;
6544 	}
6545 
6546 	/*
6547 	 * Determine whether cursors on each CRTC should be enabled in native or
6548 	 * overlay mode.
6549 	 */
6550 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
6551 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6552 
6553 		ret = amdgpu_dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
6554 						     &dm_new_crtc_state->cursor_mode);
6555 		if (ret) {
6556 			drm_dbg(dev, "Failed to determine cursor mode: %pe\n", ERR_PTR(ret));
6557 			goto fail;
6558 		}
6559 
6560 		/*
6561 		 * If overlay cursor is needed, DC cannot go through the
6562 		 * native cursor update path. All enabled planes on the CRTC
6563 		 * need to be added for DC to not disable a plane by mistake
6564 		 */
6565 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
6566 			if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
6567 				drm_dbg(dev, "Overlay cursor not supported on DCE\n");
6568 				ret = -EINVAL;
6569 				goto fail;
6570 			}
6571 
6572 			ret = drm_atomic_add_affected_planes(state, crtc);
6573 			if (ret)
6574 				goto fail;
6575 		}
6576 	}
6577 
6578 	/* Remove exiting planes if they are modified */
6579 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
6580 
6581 		ret = dm_update_plane_state(dc, state, plane,
6582 					    old_plane_state,
6583 					    new_plane_state,
6584 					    false,
6585 					    &needs_dc_state_realloc,
6586 					    &is_top_most_overlay);
6587 		if (ret) {
6588 			drm_dbg_atomic(dev, "dm_update_plane_state() failed: %pe\n", ERR_PTR(ret));
6589 			goto fail;
6590 		}
6591 	}
6592 
6593 	/* Disable all crtcs which require disable */
6594 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6595 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
6596 					   old_crtc_state,
6597 					   new_crtc_state,
6598 					   false,
6599 					   &needs_dc_state_realloc);
6600 		if (ret) {
6601 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed: %pe\n", ERR_PTR(ret));
6602 			goto fail;
6603 		}
6604 	}
6605 
6606 	/* Enable all crtcs which require enable */
6607 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
6608 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
6609 					   old_crtc_state,
6610 					   new_crtc_state,
6611 					   true,
6612 					   &needs_dc_state_realloc);
6613 		if (ret) {
6614 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed: %pe\n", ERR_PTR(ret));
6615 			goto fail;
6616 		}
6617 	}
6618 
6619 	/* Add new/modified planes */
6620 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
6621 		ret = dm_update_plane_state(dc, state, plane,
6622 					    old_plane_state,
6623 					    new_plane_state,
6624 					    true,
6625 					    &needs_dc_state_realloc,
6626 					    &is_top_most_overlay);
6627 		if (ret) {
6628 			drm_dbg_atomic(dev, "dm_update_plane_state() failed: %pe\n", ERR_PTR(ret));
6629 			goto fail;
6630 		}
6631 	}
6632 
6633 #if defined(CONFIG_DRM_AMD_DC_FP)
6634 	if (dc_resource_is_dsc_encoding_supported(dc)) {
6635 		ret = pre_validate_dsc(state, &dm_state, vars);
6636 		if (ret != 0)
6637 			goto fail;
6638 	}
6639 #endif
6640 
6641 	/* Run this here since we want to validate the streams we created */
6642 	ret = drm_atomic_helper_check_planes(dev, state);
6643 	if (ret) {
6644 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed: %pe\n", ERR_PTR(ret));
6645 		goto fail;
6646 	}
6647 
6648 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
6649 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6650 		if (dm_new_crtc_state->mpo_requested)
6651 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
6652 	}
6653 
6654 	/* Check cursor restrictions */
6655 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
6656 		enum amdgpu_dm_cursor_mode required_cursor_mode;
6657 		int is_rotated, is_scaled;
6658 
6659 		/* Overlay cusor not subject to native cursor restrictions */
6660 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
6661 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
6662 			continue;
6663 
6664 		/* Check if rotation or scaling is enabled on DCN 4x and above */
6665 		if ((drm_plane_mask(crtc->cursor) & new_crtc_state->plane_mask) &&
6666 		    (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))) {
6667 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
6668 
6669 			is_rotated = new_cursor_state &&
6670 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
6671 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
6672 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
6673 
6674 			if (is_rotated || is_scaled) {
6675 				drm_dbg_driver(
6676 					crtc->dev,
6677 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
6678 					crtc->base.id, crtc->name);
6679 				ret = -EINVAL;
6680 				goto fail;
6681 			}
6682 		}
6683 
6684 		/* If HW can only do native cursor, check restrictions again */
6685 		ret = amdgpu_dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
6686 						     &required_cursor_mode);
6687 		if (ret) {
6688 			drm_dbg_driver(crtc->dev,
6689 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
6690 				       crtc->base.id, crtc->name);
6691 			goto fail;
6692 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
6693 			drm_dbg_driver(crtc->dev,
6694 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling, YUV, or color pipeline restrictions\n",
6695 				       crtc->base.id, crtc->name);
6696 			ret = -EINVAL;
6697 			goto fail;
6698 		}
6699 	}
6700 
6701 	if (state->legacy_cursor_update) {
6702 		/*
6703 		 * This is a fast cursor update coming from the plane update
6704 		 * helper, check if it can be done asynchronously for better
6705 		 * performance.
6706 		 */
6707 		state->async_update =
6708 			!drm_atomic_helper_async_check(dev, state);
6709 
6710 		/*
6711 		 * Skip the remaining global validation if this is an async
6712 		 * update. Cursor updates can be done without affecting
6713 		 * state or bandwidth calcs and this avoids the performance
6714 		 * penalty of locking the private state object and
6715 		 * allocating a new dc_state.
6716 		 */
6717 		if (state->async_update)
6718 			return 0;
6719 	}
6720 
6721 	/* Check scaling and underscan changes*/
6722 	/* TODO Removed scaling changes validation due to inability to commit
6723 	 * new stream into context w\o causing full reset. Need to
6724 	 * decide how to handle.
6725 	 */
6726 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
6727 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
6728 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
6729 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
6730 
6731 		/* Skip any modesets/resets */
6732 		if (!acrtc || drm_atomic_crtc_needs_modeset(
6733 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
6734 			continue;
6735 
6736 		/* Skip any thing not scale or underscan changes */
6737 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
6738 			continue;
6739 
6740 		needs_dc_state_realloc = true;
6741 	}
6742 
6743 	/* set the slot info for each mst_state based on the link encoding format */
6744 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
6745 		struct amdgpu_dm_connector *aconnector;
6746 		struct drm_connector *connector;
6747 		struct drm_connector_list_iter iter;
6748 		u8 link_coding_cap;
6749 
6750 		drm_connector_list_iter_begin(dev, &iter);
6751 		drm_for_each_connector_iter(connector, &iter) {
6752 			if (connector->index == mst_state->mgr->conn_base_id) {
6753 				aconnector = to_amdgpu_dm_connector(connector);
6754 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
6755 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
6756 
6757 				break;
6758 			}
6759 		}
6760 		drm_connector_list_iter_end(&iter);
6761 	}
6762 
6763 	/**
6764 	 * Streams and planes are reset when there are changes that affect
6765 	 * bandwidth. Anything that affects bandwidth needs to go through
6766 	 * DC global validation to ensure that the configuration can be applied
6767 	 * to hardware.
6768 	 *
6769 	 * We have to currently stall out here in atomic_check for outstanding
6770 	 * commits to finish in this case because our IRQ handlers reference
6771 	 * DRM state directly - we can end up disabling interrupts too early
6772 	 * if we don't.
6773 	 *
6774 	 * TODO: Remove this stall and drop DM state private objects.
6775 	 */
6776 	if (needs_dc_state_realloc) {
6777 		ret = dm_atomic_get_state(state, &dm_state);
6778 		if (ret) {
6779 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed: %pe\n", ERR_PTR(ret));
6780 			goto fail;
6781 		}
6782 
6783 		ret = do_aquire_global_lock(dev, state);
6784 		if (ret) {
6785 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed: %pe\n", ERR_PTR(ret));
6786 			goto fail;
6787 		}
6788 
6789 #if defined(CONFIG_DRM_AMD_DC_FP)
6790 		if (dc_resource_is_dsc_encoding_supported(dc)) {
6791 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
6792 			if (ret) {
6793 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed: %pe\n", ERR_PTR(ret));
6794 				ret = -EINVAL;
6795 				goto fail;
6796 			}
6797 		}
6798 #endif
6799 
6800 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
6801 		if (ret) {
6802 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed: %pe\n", ERR_PTR(ret));
6803 			goto fail;
6804 		}
6805 
6806 		/*
6807 		 * Perform validation of MST topology in the state:
6808 		 * We need to perform MST atomic check before calling
6809 		 * dc_validate_global_state(), or there is a chance
6810 		 * to get stuck in an infinite loop and hang eventually.
6811 		 */
6812 		ret = drm_dp_mst_atomic_check(state);
6813 		if (ret) {
6814 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed: %pe\n", ERR_PTR(ret));
6815 			goto fail;
6816 		}
6817 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
6818 		if (status != DC_OK) {
6819 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
6820 				       dc_status_to_str(status), status);
6821 			ret = -EINVAL;
6822 			goto fail;
6823 		}
6824 	} else {
6825 		/*
6826 		 * The commit is a fast update. Fast updates shouldn't change
6827 		 * the DC context, affect global validation, and can have their
6828 		 * commit work done in parallel with other commits not touching
6829 		 * the same resource. If we have a new DC context as part of
6830 		 * the DM atomic state from validation we need to free it and
6831 		 * retain the existing one instead.
6832 		 *
6833 		 * Furthermore, since the DM atomic state only contains the DC
6834 		 * context and can safely be annulled, we can free the state
6835 		 * and clear the associated private object now to free
6836 		 * some memory and avoid a possible use-after-free later.
6837 		 */
6838 
6839 		for (i = 0; i < state->num_private_objs; i++) {
6840 			struct drm_private_obj *obj = state->private_objs[i].ptr;
6841 
6842 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
6843 				int j = state->num_private_objs-1;
6844 
6845 				dm_atomic_destroy_state(obj,
6846 						state->private_objs[i].state_to_destroy);
6847 
6848 				/* If i is not at the end of the array then the
6849 				 * last element needs to be moved to where i was
6850 				 * before the array can safely be truncated.
6851 				 */
6852 				if (i != j)
6853 					state->private_objs[i] =
6854 						state->private_objs[j];
6855 
6856 				state->private_objs[j].ptr = NULL;
6857 				state->private_objs[j].state_to_destroy = NULL;
6858 				state->private_objs[j].old_state = NULL;
6859 				state->private_objs[j].new_state = NULL;
6860 
6861 				state->num_private_objs = j;
6862 				break;
6863 			}
6864 		}
6865 	}
6866 
6867 	/* Store the overall update type for use later in atomic check. */
6868 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
6869 		struct dm_crtc_state *dm_new_crtc_state =
6870 			to_dm_crtc_state(new_crtc_state);
6871 
6872 		/*
6873 		 * Only allow async flips for fast updates that don't change
6874 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
6875 		 */
6876 		if (new_crtc_state->async_flip &&
6877 		    (needs_dc_state_realloc ||
6878 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
6879 			drm_dbg_atomic(crtc->dev,
6880 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
6881 				       crtc->base.id, crtc->name);
6882 			ret = -EINVAL;
6883 			goto fail;
6884 		}
6885 
6886 		dm_new_crtc_state->update_type = needs_dc_state_realloc ?
6887 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
6888 	}
6889 
6890 	/* Must be success */
6891 	WARN_ON(ret);
6892 
6893 	trace_amdgpu_dm_atomic_check_finish(state, ret);
6894 
6895 	return ret;
6896 
6897 fail:
6898 	if (ret == -EDEADLK)
6899 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
6900 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
6901 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
6902 	else
6903 		drm_dbg_atomic(dev, "Atomic check failed: %pe\n", ERR_PTR(ret));
6904 
6905 	trace_amdgpu_dm_atomic_check_finish(state, ret);
6906 
6907 	return ret;
6908 }
6909 EXPORT_IF_KUNIT(amdgpu_dm_atomic_check);
6910 
6911 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
6912 {
6913 	struct amdgpu_device *adev = drm_to_adev(dev);
6914 	struct dc *dc = adev->dm.dc;
6915 	int i;
6916 
6917 	mutex_lock(&adev->dm.dc_lock);
6918 	if (dc->current_state) {
6919 		for (i = 0; i < dc->current_state->stream_count; ++i)
6920 			dc->current_state->streams[i]
6921 				->triggered_crtc_reset.enabled =
6922 				adev->dm.force_timing_sync;
6923 
6924 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
6925 		dc_trigger_sync(dc, dc->current_state);
6926 	}
6927 	mutex_unlock(&adev->dm.dc_lock);
6928 }
6929 EXPORT_IF_KUNIT(amdgpu_dm_trigger_timing_sync);
6930 
6931 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
6932 		       u32 value, const char *func_name)
6933 {
6934 #ifdef DM_CHECK_ADDR_0
6935 	if (address == 0) {
6936 		drm_err(adev_to_drm(ctx->driver_context),
6937 			"invalid register write. address = 0");
6938 		return;
6939 	}
6940 #endif
6941 
6942 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
6943 	cgs_write_register(ctx->cgs_device, address, value);
6944 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
6945 }
6946 
6947 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
6948 			  const char *func_name)
6949 {
6950 	u32 value;
6951 #ifdef DM_CHECK_ADDR_0
6952 	if (address == 0) {
6953 		drm_err(adev_to_drm(ctx->driver_context),
6954 			"invalid register read; address = 0\n");
6955 		return 0;
6956 	}
6957 #endif
6958 
6959 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
6960 
6961 	value = cgs_read_register(ctx->cgs_device, address);
6962 
6963 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
6964 
6965 	return value;
6966 }
6967 
6968 void dm_acpi_process_phy_transition_interlock(
6969 	const struct dc_context *ctx,
6970 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
6971 {
6972 	// Not yet implemented
6973 }
6974 EXPORT_IF_KUNIT(dm_acpi_process_phy_transition_interlock);
6975