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