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