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