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