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