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