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