xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision ea7da3116015de801840f3e011dee907fb118f0c)
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 
70 #include "ivsrcid/ivsrcid_vislands30.h"
71 
72 #include <linux/backlight.h>
73 #include <linux/module.h>
74 #include <linux/moduleparam.h>
75 #include <linux/types.h>
76 #include <linux/pm_runtime.h>
77 #include <linux/pci.h>
78 #include <linux/power_supply.h>
79 #include <linux/firmware.h>
80 #include <linux/component.h>
81 #include <linux/sort.h>
82 
83 #include <drm/drm_privacy_screen_consumer.h>
84 #include <drm/display/drm_dp_mst_helper.h>
85 #include <drm/display/drm_hdmi_helper.h>
86 #include <drm/drm_atomic.h>
87 #include <drm/drm_atomic_uapi.h>
88 #include <drm/drm_atomic_helper.h>
89 #include <drm/drm_blend.h>
90 #include <drm/drm_fixed.h>
91 #include <drm/drm_fourcc.h>
92 #include <drm/drm_edid.h>
93 #include <drm/drm_eld.h>
94 #include <drm/drm_mode.h>
95 #include <drm/drm_utils.h>
96 #include <drm/drm_vblank.h>
97 #include <drm/drm_audio_component.h>
98 #include <drm/drm_colorop.h>
99 #include <drm/drm_gem_atomic_helper.h>
100 
101 #include <media/cec-notifier.h>
102 #include <acpi/video.h>
103 
104 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
105 
106 #include "modules/inc/mod_freesync.h"
107 #include "modules/inc/mod_power.h"
108 #include "modules/power/power_helpers.h"
109 
110 static_assert(AMDGPU_DMUB_NOTIFICATION_MAX == DMUB_NOTIFICATION_MAX, "AMDGPU_DMUB_NOTIFICATION_MAX mismatch");
111 
112 #define FIRMWARE_RENOIR_DMUB "amdgpu/renoir_dmcub.bin"
113 MODULE_FIRMWARE(FIRMWARE_RENOIR_DMUB);
114 #define FIRMWARE_SIENNA_CICHLID_DMUB "amdgpu/sienna_cichlid_dmcub.bin"
115 MODULE_FIRMWARE(FIRMWARE_SIENNA_CICHLID_DMUB);
116 #define FIRMWARE_NAVY_FLOUNDER_DMUB "amdgpu/navy_flounder_dmcub.bin"
117 MODULE_FIRMWARE(FIRMWARE_NAVY_FLOUNDER_DMUB);
118 #define FIRMWARE_GREEN_SARDINE_DMUB "amdgpu/green_sardine_dmcub.bin"
119 MODULE_FIRMWARE(FIRMWARE_GREEN_SARDINE_DMUB);
120 #define FIRMWARE_VANGOGH_DMUB "amdgpu/vangogh_dmcub.bin"
121 MODULE_FIRMWARE(FIRMWARE_VANGOGH_DMUB);
122 #define FIRMWARE_DIMGREY_CAVEFISH_DMUB "amdgpu/dimgrey_cavefish_dmcub.bin"
123 MODULE_FIRMWARE(FIRMWARE_DIMGREY_CAVEFISH_DMUB);
124 #define FIRMWARE_BEIGE_GOBY_DMUB "amdgpu/beige_goby_dmcub.bin"
125 MODULE_FIRMWARE(FIRMWARE_BEIGE_GOBY_DMUB);
126 #define FIRMWARE_YELLOW_CARP_DMUB "amdgpu/yellow_carp_dmcub.bin"
127 MODULE_FIRMWARE(FIRMWARE_YELLOW_CARP_DMUB);
128 #define FIRMWARE_DCN_314_DMUB "amdgpu/dcn_3_1_4_dmcub.bin"
129 MODULE_FIRMWARE(FIRMWARE_DCN_314_DMUB);
130 #define FIRMWARE_DCN_315_DMUB "amdgpu/dcn_3_1_5_dmcub.bin"
131 MODULE_FIRMWARE(FIRMWARE_DCN_315_DMUB);
132 #define FIRMWARE_DCN316_DMUB "amdgpu/dcn_3_1_6_dmcub.bin"
133 MODULE_FIRMWARE(FIRMWARE_DCN316_DMUB);
134 
135 #define FIRMWARE_DCN_V3_2_0_DMCUB "amdgpu/dcn_3_2_0_dmcub.bin"
136 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_0_DMCUB);
137 #define FIRMWARE_DCN_V3_2_1_DMCUB "amdgpu/dcn_3_2_1_dmcub.bin"
138 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_1_DMCUB);
139 
140 #define FIRMWARE_RAVEN_DMCU		"amdgpu/raven_dmcu.bin"
141 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
142 
143 #define FIRMWARE_NAVI12_DMCU            "amdgpu/navi12_dmcu.bin"
144 MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
145 
146 #define FIRMWARE_DCN_35_DMUB "amdgpu/dcn_3_5_dmcub.bin"
147 MODULE_FIRMWARE(FIRMWARE_DCN_35_DMUB);
148 
149 #define FIRMWARE_DCN_351_DMUB "amdgpu/dcn_3_5_1_dmcub.bin"
150 MODULE_FIRMWARE(FIRMWARE_DCN_351_DMUB);
151 
152 #define FIRMWARE_DCN_36_DMUB "amdgpu/dcn_3_6_dmcub.bin"
153 MODULE_FIRMWARE(FIRMWARE_DCN_36_DMUB);
154 
155 #define FIRMWARE_DCN_401_DMUB "amdgpu/dcn_4_0_1_dmcub.bin"
156 MODULE_FIRMWARE(FIRMWARE_DCN_401_DMUB);
157 
158 #define FIRMWARE_DCN_42_DMUB "amdgpu/dcn_4_2_dmcub.bin"
159 MODULE_FIRMWARE(FIRMWARE_DCN_42_DMUB);
160 
161 #define FIRMWARE_DCN_42B_DMUB "amdgpu/dcn_4_2_1_dmcub.bin"
162 MODULE_FIRMWARE(FIRMWARE_DCN_42B_DMUB);
163 
164 /**
165  * DOC: overview
166  *
167  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
168  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
169  * requests into DC requests, and DC responses into DRM responses.
170  *
171  * The root control structure is &struct amdgpu_display_manager.
172  */
173 
174 /* basic init/fini API */
175 static int amdgpu_dm_init(struct amdgpu_device *adev);
176 static void amdgpu_dm_fini(struct amdgpu_device *adev);
177 static bool is_freesync_video_mode(const struct drm_display_mode *mode, struct amdgpu_dm_connector *aconnector);
178 static void reset_freesync_config_for_crtc(struct dm_crtc_state *new_crtc_state);
179 static struct amdgpu_i2c_adapter *
180 create_i2c(struct ddc_service *ddc_service, bool oem);
181 
182 static enum drm_mode_subconnector get_subconnector_type(struct dc_link *link)
183 {
184 	switch (link->dpcd_caps.dongle_type) {
185 	case DISPLAY_DONGLE_NONE:
186 		return DRM_MODE_SUBCONNECTOR_Native;
187 	case DISPLAY_DONGLE_DP_VGA_CONVERTER:
188 		return DRM_MODE_SUBCONNECTOR_VGA;
189 	case DISPLAY_DONGLE_DP_DVI_CONVERTER:
190 	case DISPLAY_DONGLE_DP_DVI_DONGLE:
191 		return DRM_MODE_SUBCONNECTOR_DVID;
192 	case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
193 	case DISPLAY_DONGLE_DP_HDMI_DONGLE:
194 		return DRM_MODE_SUBCONNECTOR_HDMIA;
195 	case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
196 	default:
197 		return DRM_MODE_SUBCONNECTOR_Unknown;
198 	}
199 }
200 
201 static void update_subconnector_property(struct amdgpu_dm_connector *aconnector)
202 {
203 	struct dc_link *link = aconnector->dc_link;
204 	struct drm_connector *connector = &aconnector->base;
205 	enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
206 
207 	if (connector->connector_type != DRM_MODE_CONNECTOR_DisplayPort)
208 		return;
209 
210 	if (aconnector->dc_sink)
211 		subconnector = get_subconnector_type(link);
212 
213 	drm_object_property_set_value(&connector->base,
214 			connector->dev->mode_config.dp_subconnector_property,
215 			subconnector);
216 }
217 
218 /*
219  * initializes drm_device display related structures, based on the information
220  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
221  * drm_encoder, drm_mode_config
222  *
223  * Returns 0 on success
224  */
225 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
226 /* removes and deallocates the drm structures, created by the above function */
227 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
228 
229 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
230 				    struct amdgpu_dm_connector *amdgpu_dm_connector,
231 				    u32 link_index,
232 				    struct amdgpu_encoder *amdgpu_encoder);
233 static int amdgpu_dm_encoder_init(struct drm_device *dev,
234 				  struct amdgpu_encoder *aencoder,
235 				  uint32_t link_index);
236 
237 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
238 
239 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state);
240 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state);
241 
242 static int amdgpu_dm_atomic_check(struct drm_device *dev,
243 				  struct drm_atomic_commit *state);
244 
245 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector);
246 static void handle_hpd_rx_irq(void *param);
247 
248 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
249 					 int bl_idx,
250 					 u32 user_brightness);
251 
252 static bool
253 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
254 				 struct drm_crtc_state *new_crtc_state);
255 /*
256  * dm_vblank_get_counter
257  *
258  * @brief
259  * Get counter for number of vertical blanks
260  *
261  * @param
262  * struct amdgpu_device *adev - [in] desired amdgpu device
263  * int disp_idx - [in] which CRTC to get the counter from
264  *
265  * @return
266  * Counter for vertical blanks
267  */
268 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
269 {
270 	struct amdgpu_crtc *acrtc = NULL;
271 
272 	if (crtc >= adev->mode_info.num_crtc)
273 		return 0;
274 
275 	acrtc = adev->mode_info.crtcs[crtc];
276 
277 	if (!acrtc->dm_irq_params.stream) {
278 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
279 			  crtc);
280 		return 0;
281 	}
282 
283 	return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
284 }
285 
286 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
287 				  u32 *vbl, u32 *position)
288 {
289 	u32 v_blank_start = 0, v_blank_end = 0, h_position = 0, v_position = 0;
290 	struct amdgpu_crtc *acrtc = NULL;
291 	struct dc *dc = adev->dm.dc;
292 
293 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
294 		return -EINVAL;
295 
296 	acrtc = adev->mode_info.crtcs[crtc];
297 
298 	if (!acrtc->dm_irq_params.stream) {
299 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
300 			  crtc);
301 		return 0;
302 	}
303 
304 	if (dc && dc->caps.ips_support && dc->idle_optimizations_allowed)
305 		dc_allow_idle_optimizations(dc, false);
306 
307 	/*
308 	 * TODO rework base driver to use values directly.
309 	 * for now parse it back into reg-format
310 	 */
311 	dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
312 				 &v_blank_start,
313 				 &v_blank_end,
314 				 &h_position,
315 				 &v_position);
316 
317 	*position = v_position | (h_position << 16);
318 	*vbl = v_blank_start | (v_blank_end << 16);
319 
320 	return 0;
321 }
322 
323 static bool dm_is_idle(struct amdgpu_ip_block *ip_block)
324 {
325 	/* XXX todo */
326 	return true;
327 }
328 
329 static int dm_wait_for_idle(struct amdgpu_ip_block *ip_block)
330 {
331 	/* XXX todo */
332 	return 0;
333 }
334 
335 static bool dm_check_soft_reset(struct amdgpu_ip_block *ip_block)
336 {
337 	return false;
338 }
339 
340 static int dm_soft_reset(struct amdgpu_ip_block *ip_block)
341 {
342 	/* XXX todo */
343 	return 0;
344 }
345 
346 static struct amdgpu_crtc *
347 get_crtc_by_otg_inst(struct amdgpu_device *adev,
348 		     int otg_inst)
349 {
350 	struct drm_device *dev = adev_to_drm(adev);
351 	struct drm_crtc *crtc;
352 	struct amdgpu_crtc *amdgpu_crtc;
353 
354 	if (WARN_ON(otg_inst == -1))
355 		return adev->mode_info.crtcs[0];
356 
357 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
358 		amdgpu_crtc = to_amdgpu_crtc(crtc);
359 
360 		if (amdgpu_crtc->otg_inst == otg_inst)
361 			return amdgpu_crtc;
362 	}
363 
364 	return NULL;
365 }
366 
367 static inline bool is_dc_timing_adjust_needed(struct dm_crtc_state *old_state,
368 					      struct dm_crtc_state *new_state)
369 {
370 	if (new_state->stream->adjust.timing_adjust_pending)
371 		return true;
372 	if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
373 		return true;
374 	else if (amdgpu_dm_crtc_vrr_active(old_state) != amdgpu_dm_crtc_vrr_active(new_state))
375 		return true;
376 	else
377 		return false;
378 }
379 
380 /*
381  * DC will program planes with their z-order determined by their ordering
382  * in the dc_surface_updates array. This comparator is used to sort them
383  * by descending zpos.
384  */
385 static int dm_plane_layer_index_cmp(const void *a, const void *b)
386 {
387 	const struct dc_surface_update *sa = (struct dc_surface_update *)a;
388 	const struct dc_surface_update *sb = (struct dc_surface_update *)b;
389 
390 	/* Sort by descending dc_plane layer_index (i.e. normalized_zpos) */
391 	return sb->surface->layer_index - sa->surface->layer_index;
392 }
393 
394 /**
395  * update_planes_and_stream_adapter() - Send planes to be updated in DC
396  *
397  * DC has a generic way to update planes and stream via
398  * dc_update_planes_and_stream function; however, DM might need some
399  * adjustments and preparation before calling it. This function is a wrapper
400  * for the dc_update_planes_and_stream that does any required configuration
401  * before passing control to DC.
402  *
403  * @dc: Display Core control structure
404  * @update_type: specify whether it is FULL/MEDIUM/FAST update
405  * @planes_count: planes count to update
406  * @stream: stream state
407  * @stream_update: stream update
408  * @array_of_surface_update: dc surface update pointer
409  *
410  */
411 static inline bool update_planes_and_stream_adapter(struct dc *dc,
412 						    int update_type,
413 						    int planes_count,
414 						    struct dc_stream_state *stream,
415 						    struct dc_stream_update *stream_update,
416 						    struct dc_surface_update *array_of_surface_update)
417 {
418 	sort(array_of_surface_update, planes_count,
419 	     sizeof(*array_of_surface_update), dm_plane_layer_index_cmp, NULL);
420 
421 	/*
422 	 * Previous frame finished and HW is ready for optimization.
423 	 */
424 	dc_post_update_surfaces_to_stream(dc);
425 
426 	return dc_update_planes_and_stream(dc,
427 					   array_of_surface_update,
428 					   planes_count,
429 					   stream,
430 					   stream_update);
431 }
432 
433 /**
434  * dm_pflip_high_irq() - Handle pageflip interrupt
435  * @interrupt_params: ignored
436  *
437  * Handles the pageflip interrupt by notifying all interested parties
438  * that the pageflip has been completed.
439  */
440 static void dm_pflip_high_irq(void *interrupt_params)
441 {
442 	struct amdgpu_crtc *amdgpu_crtc;
443 	struct common_irq_params *irq_params = interrupt_params;
444 	struct amdgpu_device *adev = irq_params->adev;
445 	struct drm_device *dev = adev_to_drm(adev);
446 	unsigned long flags;
447 	struct drm_pending_vblank_event *e;
448 	u32 vpos, hpos, v_blank_start, v_blank_end;
449 	bool vrr_active;
450 
451 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
452 
453 	/* IRQ could occur when in initial stage */
454 	/* TODO work and BO cleanup */
455 	if (amdgpu_crtc == NULL) {
456 		drm_dbg_state(dev, "CRTC is null, returning.\n");
457 		return;
458 	}
459 
460 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
461 
462 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED) {
463 		drm_dbg_state(dev,
464 			      "amdgpu_crtc->pflip_status = %d != AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p]\n",
465 			      amdgpu_crtc->pflip_status, AMDGPU_FLIP_SUBMITTED,
466 			      amdgpu_crtc->crtc_id, amdgpu_crtc);
467 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
468 		return;
469 	}
470 
471 	/* page flip completed. */
472 	e = amdgpu_crtc->event;
473 	amdgpu_crtc->event = NULL;
474 
475 	WARN_ON(!e);
476 
477 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(amdgpu_crtc);
478 
479 	/* Fixed refresh rate, or VRR scanout position outside front-porch? */
480 	if (!vrr_active ||
481 	    !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
482 				      &v_blank_end, &hpos, &vpos) ||
483 	    (vpos < v_blank_start)) {
484 		/* Update to correct count and vblank timestamp if racing with
485 		 * vblank irq. This also updates to the correct vblank timestamp
486 		 * even in VRR mode, as scanout is past the front-porch atm.
487 		 */
488 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
489 
490 		/* Wake up userspace by sending the pageflip event with proper
491 		 * count and timestamp of vblank of flip completion.
492 		 */
493 		if (e) {
494 			drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
495 
496 			/* Event sent, so done with vblank for this flip */
497 			drm_crtc_vblank_put(&amdgpu_crtc->base);
498 		}
499 	} else if (e) {
500 		/* VRR active and inside front-porch: vblank count and
501 		 * timestamp for pageflip event will only be up to date after
502 		 * drm_crtc_handle_vblank() has been executed from late vblank
503 		 * irq handler after start of back-porch (vline 0). We queue the
504 		 * pageflip event for send-out by drm_crtc_handle_vblank() with
505 		 * updated timestamp and count, once it runs after us.
506 		 *
507 		 * We need to open-code this instead of using the helper
508 		 * drm_crtc_arm_vblank_event(), as that helper would
509 		 * call drm_crtc_accurate_vblank_count(), which we must
510 		 * not call in VRR mode while we are in front-porch!
511 		 */
512 
513 		/* sequence will be replaced by real count during send-out. */
514 		e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
515 		e->pipe = amdgpu_crtc->crtc_id;
516 
517 		list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
518 		e = NULL;
519 	}
520 
521 	/* Keep track of vblank of this flip for flip throttling. We use the
522 	 * cooked hw counter, as that one incremented at start of this vblank
523 	 * of pageflip completion, so last_flip_vblank is the forbidden count
524 	 * for queueing new pageflips if vsync + VRR is enabled.
525 	 */
526 	amdgpu_crtc->dm_irq_params.last_flip_vblank =
527 		amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
528 
529 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
530 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
531 
532 	drm_dbg_state(dev,
533 		      "crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
534 		      amdgpu_crtc->crtc_id, amdgpu_crtc, vrr_active, (int)!e);
535 }
536 
537 static void dm_handle_vmin_vmax_update(struct work_struct *offload_work)
538 {
539 	struct vupdate_offload_work *work = container_of(offload_work, struct vupdate_offload_work, work);
540 	struct amdgpu_device *adev = work->adev;
541 	struct dc_stream_state *stream = work->stream;
542 	struct dc_crtc_timing_adjust *adjust = work->adjust;
543 
544 	mutex_lock(&adev->dm.dc_lock);
545 	dc_stream_adjust_vmin_vmax(adev->dm.dc, stream, adjust);
546 	mutex_unlock(&adev->dm.dc_lock);
547 
548 	dc_stream_release(stream);
549 	kfree(work->adjust);
550 	kfree(work);
551 }
552 
553 static void schedule_dc_vmin_vmax(struct amdgpu_device *adev,
554 	struct dc_stream_state *stream,
555 	struct dc_crtc_timing_adjust *adjust)
556 {
557 	struct vupdate_offload_work *offload_work = kzalloc_obj(*offload_work,
558 								GFP_NOWAIT);
559 	if (!offload_work) {
560 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate vupdate_offload_work\n");
561 		return;
562 	}
563 
564 	struct dc_crtc_timing_adjust *adjust_copy = kzalloc_obj(*adjust_copy,
565 								GFP_NOWAIT);
566 	if (!adjust_copy) {
567 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate adjust_copy\n");
568 		kfree(offload_work);
569 		return;
570 	}
571 
572 	dc_stream_retain(stream);
573 	memcpy(adjust_copy, adjust, sizeof(*adjust_copy));
574 
575 	INIT_WORK(&offload_work->work, dm_handle_vmin_vmax_update);
576 	offload_work->adev = adev;
577 	offload_work->stream = stream;
578 	offload_work->adjust = adjust_copy;
579 
580 	queue_work(system_percpu_wq, &offload_work->work);
581 }
582 
583 static void dm_vupdate_high_irq(void *interrupt_params)
584 {
585 	struct common_irq_params *irq_params = interrupt_params;
586 	struct amdgpu_device *adev = irq_params->adev;
587 	struct amdgpu_crtc *acrtc;
588 	struct drm_device *drm_dev;
589 	struct drm_vblank_crtc *vblank;
590 	ktime_t frame_duration_ns, previous_timestamp;
591 	unsigned long flags;
592 	int vrr_active;
593 
594 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
595 
596 	if (acrtc) {
597 		vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
598 		drm_dev = acrtc->base.dev;
599 		vblank = drm_crtc_vblank_crtc(&acrtc->base);
600 		previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
601 		frame_duration_ns = vblank->time - previous_timestamp;
602 
603 		if (frame_duration_ns > 0) {
604 			trace_amdgpu_refresh_rate_track(acrtc->base.index,
605 						frame_duration_ns,
606 						ktime_divns(NSEC_PER_SEC, frame_duration_ns));
607 			atomic64_set(&irq_params->previous_timestamp, vblank->time);
608 		}
609 
610 		drm_dbg_vbl(drm_dev,
611 			    "crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
612 			    vrr_active);
613 
614 		/* Core vblank handling is done here after end of front-porch in
615 		 * vrr mode, as vblank timestamping will give valid results
616 		 * while now done after front-porch. This will also deliver
617 		 * page-flip completion events that have been queued to us
618 		 * if a pageflip happened inside front-porch.
619 		 */
620 		if (vrr_active && acrtc->dm_irq_params.stream) {
621 			bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
622 			bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
623 			bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state
624 				== VRR_STATE_ACTIVE_VARIABLE;
625 
626 			amdgpu_dm_crtc_handle_vblank(acrtc);
627 
628 			/* BTR processing for pre-DCE12 ASICs */
629 			if (adev->family < AMDGPU_FAMILY_AI) {
630 				spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
631 				mod_freesync_handle_v_update(
632 				    adev->dm.freesync_module,
633 				    acrtc->dm_irq_params.stream,
634 				    &acrtc->dm_irq_params.vrr_params);
635 
636 				if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
637 					schedule_dc_vmin_vmax(adev,
638 						acrtc->dm_irq_params.stream,
639 						&acrtc->dm_irq_params.vrr_params.adjust);
640 				}
641 				spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
642 			}
643 		}
644 	}
645 }
646 
647 /**
648  * dm_crtc_high_irq() - Handles CRTC interrupt
649  * @interrupt_params: used for determining the CRTC instance
650  *
651  * Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
652  * event handler.
653  */
654 static void dm_crtc_high_irq(void *interrupt_params)
655 {
656 	struct common_irq_params *irq_params = interrupt_params;
657 	struct amdgpu_device *adev = irq_params->adev;
658 	struct drm_writeback_job *job;
659 	struct amdgpu_crtc *acrtc;
660 	unsigned long flags;
661 	int vrr_active;
662 
663 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
664 	if (!acrtc)
665 		return;
666 
667 	if (acrtc->wb_conn) {
668 		spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
669 
670 		if (acrtc->wb_pending) {
671 			job = list_first_entry_or_null(&acrtc->wb_conn->job_queue,
672 						       struct drm_writeback_job,
673 						       list_entry);
674 			acrtc->wb_pending = false;
675 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
676 
677 			if (job) {
678 				unsigned int v_total, refresh_hz;
679 				struct dc_stream_state *stream = acrtc->dm_irq_params.stream;
680 
681 				v_total = stream->adjust.v_total_max ?
682 					  stream->adjust.v_total_max : stream->timing.v_total;
683 				refresh_hz = div_u64((uint64_t) stream->timing.pix_clk_100hz *
684 					     100LL, (v_total * stream->timing.h_total));
685 				mdelay(1000 / refresh_hz);
686 
687 				drm_writeback_signal_completion(acrtc->wb_conn, 0);
688 				dc_stream_fc_disable_writeback(adev->dm.dc,
689 							       acrtc->dm_irq_params.stream, 0);
690 			}
691 		} else
692 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
693 	}
694 
695 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
696 
697 	drm_dbg_vbl(adev_to_drm(adev),
698 		    "crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
699 		    vrr_active, acrtc->dm_irq_params.active_planes);
700 
701 	/**
702 	 * Core vblank handling at start of front-porch is only possible
703 	 * in non-vrr mode, as only there vblank timestamping will give
704 	 * valid results while done in front-porch. Otherwise defer it
705 	 * to dm_vupdate_high_irq after end of front-porch.
706 	 */
707 	if (!vrr_active)
708 		amdgpu_dm_crtc_handle_vblank(acrtc);
709 
710 	/**
711 	 * Following stuff must happen at start of vblank, for crc
712 	 * computation and below-the-range btr support in vrr mode.
713 	 */
714 	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
715 
716 	/* BTR updates need to happen before VUPDATE on Vega and above. */
717 	if (adev->family < AMDGPU_FAMILY_AI)
718 		return;
719 
720 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
721 
722 	if (acrtc->dm_irq_params.stream &&
723 		acrtc->dm_irq_params.vrr_params.supported) {
724 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
725 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
726 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state == VRR_STATE_ACTIVE_VARIABLE;
727 
728 		mod_freesync_handle_v_update(adev->dm.freesync_module,
729 					     acrtc->dm_irq_params.stream,
730 					     &acrtc->dm_irq_params.vrr_params);
731 
732 		/* update vmin_vmax only if freesync is enabled, or only if PSR and REPLAY are disabled */
733 		if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
734 			schedule_dc_vmin_vmax(adev, acrtc->dm_irq_params.stream,
735 					&acrtc->dm_irq_params.vrr_params.adjust);
736 		}
737 	}
738 
739 	/*
740 	 * If there aren't any active_planes then DCH HUBP may be clock-gated.
741 	 * In that case, pageflip completion interrupts won't fire and pageflip
742 	 * completion events won't get delivered. Prevent this by sending
743 	 * pending pageflip events from here if a flip is still pending.
744 	 *
745 	 * If any planes are enabled, use dm_pflip_high_irq() instead, to
746 	 * avoid race conditions between flip programming and completion,
747 	 * which could cause too early flip completion events.
748 	 */
749 	if (adev->family >= AMDGPU_FAMILY_RV &&
750 	    acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
751 	    acrtc->dm_irq_params.active_planes == 0) {
752 		if (acrtc->event) {
753 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
754 			acrtc->event = NULL;
755 			drm_crtc_vblank_put(&acrtc->base);
756 		}
757 		acrtc->pflip_status = AMDGPU_FLIP_NONE;
758 	}
759 
760 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
761 }
762 
763 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
764 /**
765  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
766  * DCN generation ASICs
767  * @interrupt_params: interrupt parameters
768  *
769  * Used to set crc window/read out crc value at vertical line 0 position
770  */
771 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
772 {
773 	struct common_irq_params *irq_params = interrupt_params;
774 	struct amdgpu_device *adev = irq_params->adev;
775 	struct amdgpu_crtc *acrtc;
776 
777 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
778 
779 	if (!acrtc)
780 		return;
781 
782 	amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
783 }
784 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
785 
786 /**
787  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
788  * @adev: amdgpu_device pointer
789  * @notify: dmub notification structure
790  *
791  * Dmub AUX or SET_CONFIG command completion processing callback
792  * Copies dmub notification to DM which is to be read by AUX command.
793  * issuing thread and also signals the event to wake up the thread.
794  */
795 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
796 					struct dmub_notification *notify)
797 {
798 	if (adev->dm.dmub_notify)
799 		memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
800 	if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
801 		complete(&adev->dm.dmub_aux_transfer_done);
802 }
803 
804 static void dmub_aux_fused_io_callback(struct amdgpu_device *adev,
805 					struct dmub_notification *notify)
806 {
807 	if (!adev || !notify) {
808 		ASSERT(false);
809 		return;
810 	}
811 
812 	const struct dmub_cmd_fused_request *req = &notify->fused_request;
813 	const uint8_t ddc_line = req->u.aux.ddc_line;
814 
815 	if (ddc_line >= ARRAY_SIZE(adev->dm.fused_io)) {
816 		ASSERT(false);
817 		return;
818 	}
819 
820 	struct fused_io_sync *sync = &adev->dm.fused_io[ddc_line];
821 
822 	static_assert(sizeof(*req) <= sizeof(sync->reply_data), "Size mismatch");
823 	memcpy(sync->reply_data, req, sizeof(*req));
824 	complete(&sync->replied);
825 }
826 
827 /**
828  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
829  * @adev: amdgpu_device pointer
830  * @notify: dmub notification structure
831  *
832  * Dmub Hpd interrupt processing callback. Gets displayindex through the
833  * ink index and calls helper to do the processing.
834  */
835 static void dmub_hpd_callback(struct amdgpu_device *adev,
836 			      struct dmub_notification *notify)
837 {
838 	struct amdgpu_dm_connector *aconnector;
839 	struct amdgpu_dm_connector *hpd_aconnector = NULL;
840 	struct drm_connector *connector;
841 	struct drm_connector_list_iter iter;
842 	struct dc_link *link;
843 	u8 link_index = 0;
844 	struct drm_device *dev;
845 
846 	if (adev == NULL)
847 		return;
848 
849 	if (notify == NULL) {
850 		drm_err(adev_to_drm(adev), "DMUB HPD callback notification was NULL");
851 		return;
852 	}
853 
854 	if (notify->link_index > adev->dm.dc->link_count) {
855 		drm_err(adev_to_drm(adev), "DMUB HPD index (%u)is abnormal", notify->link_index);
856 		return;
857 	}
858 
859 	/* Skip DMUB HPD IRQ in suspend/resume. We will probe them later. */
860 	if (notify->type == DMUB_NOTIFICATION_HPD && adev->in_suspend) {
861 		drm_info(adev_to_drm(adev), "Skip DMUB HPD IRQ callback in suspend/resume\n");
862 		return;
863 	}
864 
865 	link_index = notify->link_index;
866 	link = adev->dm.dc->links[link_index];
867 	dev = adev->dm.ddev;
868 
869 	drm_connector_list_iter_begin(dev, &iter);
870 	drm_for_each_connector_iter(connector, &iter) {
871 
872 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
873 			continue;
874 
875 		aconnector = to_amdgpu_dm_connector(connector);
876 		if (link && aconnector->dc_link == link) {
877 			if (notify->type == DMUB_NOTIFICATION_HPD)
878 				drm_info(adev_to_drm(adev), "DMUB HPD IRQ callback: link_index=%u\n", link_index);
879 			else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
880 				drm_info(adev_to_drm(adev), "DMUB HPD RX IRQ callback: link_index=%u\n", link_index);
881 			else
882 				drm_warn(adev_to_drm(adev), "DMUB Unknown HPD callback type %d, link_index=%u\n",
883 						notify->type, link_index);
884 
885 			hpd_aconnector = aconnector;
886 			break;
887 		}
888 	}
889 	drm_connector_list_iter_end(&iter);
890 
891 	if (hpd_aconnector) {
892 		if (notify->type == DMUB_NOTIFICATION_HPD) {
893 			if (hpd_aconnector->dc_link->hpd_status == (notify->hpd_status == DP_HPD_PLUG))
894 				drm_warn(adev_to_drm(adev), "DMUB reported hpd status unchanged. link_index=%u\n", link_index);
895 			handle_hpd_irq_helper(hpd_aconnector);
896 		} else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ) {
897 			handle_hpd_rx_irq(hpd_aconnector);
898 		}
899 	}
900 }
901 
902 /**
903  * dmub_hpd_sense_callback - DMUB HPD sense processing callback.
904  * @adev: amdgpu_device pointer
905  * @notify: dmub notification structure
906  *
907  * HPD sense changes can occur during low power states and need to be
908  * notified from firmware to driver.
909  */
910 static void dmub_hpd_sense_callback(struct amdgpu_device *adev,
911 			      struct dmub_notification *notify)
912 {
913 	drm_dbg_driver(adev_to_drm(adev), "DMUB HPD SENSE callback.\n");
914 }
915 
916 /**
917  * register_dmub_notify_callback - Sets callback for DMUB notify
918  * @adev: amdgpu_device pointer
919  * @type: Type of dmub notification
920  * @callback: Dmub interrupt callback function
921  * @dmub_int_thread_offload: offload indicator
922  *
923  * API to register a dmub callback handler for a dmub notification
924  * Also sets indicator whether callback processing to be offloaded.
925  * to dmub interrupt handling thread
926  * Return: true if successfully registered, false if there is existing registration
927  */
928 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
929 					  enum dmub_notification_type type,
930 					  dmub_notify_interrupt_callback_t callback,
931 					  bool dmub_int_thread_offload)
932 {
933 	if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
934 		adev->dm.dmub_callback[type] = callback;
935 		adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
936 	} else
937 		return false;
938 
939 	return true;
940 }
941 
942 static void dm_handle_hpd_work(struct work_struct *work)
943 {
944 	struct dmub_hpd_work *dmub_hpd_wrk;
945 
946 	dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
947 
948 	if (!dmub_hpd_wrk->dmub_notify) {
949 		drm_err(adev_to_drm(dmub_hpd_wrk->adev), "dmub_hpd_wrk dmub_notify is NULL");
950 		return;
951 	}
952 
953 	if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
954 		dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
955 		dmub_hpd_wrk->dmub_notify);
956 	}
957 
958 	kfree(dmub_hpd_wrk->dmub_notify);
959 	kfree(dmub_hpd_wrk);
960 
961 }
962 
963 static const char *dmub_notification_type_str(enum dmub_notification_type e)
964 {
965 	switch (e) {
966 	case DMUB_NOTIFICATION_NO_DATA:
967 		return "NO_DATA";
968 	case DMUB_NOTIFICATION_AUX_REPLY:
969 		return "AUX_REPLY";
970 	case DMUB_NOTIFICATION_HPD:
971 		return "HPD";
972 	case DMUB_NOTIFICATION_HPD_IRQ:
973 		return "HPD_IRQ";
974 	case DMUB_NOTIFICATION_SET_CONFIG_REPLY:
975 		return "SET_CONFIG_REPLY";
976 	case DMUB_NOTIFICATION_DPIA_NOTIFICATION:
977 		return "DPIA_NOTIFICATION";
978 	case DMUB_NOTIFICATION_HPD_SENSE_NOTIFY:
979 		return "HPD_SENSE_NOTIFY";
980 	case DMUB_NOTIFICATION_FUSED_IO:
981 		return "FUSED_IO";
982 	default:
983 		return "<unknown>";
984 	}
985 }
986 
987 #define DMUB_TRACE_MAX_READ 64
988 /**
989  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
990  * @interrupt_params: used for determining the Outbox instance
991  *
992  * Handles the Outbox Interrupt
993  * event handler.
994  */
995 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
996 {
997 	struct dmub_notification notify = {0};
998 	struct common_irq_params *irq_params = interrupt_params;
999 	struct amdgpu_device *adev = irq_params->adev;
1000 	struct amdgpu_display_manager *dm = &adev->dm;
1001 	struct dmcub_trace_buf_entry entry = { 0 };
1002 	u32 count = 0;
1003 	struct dmub_hpd_work *dmub_hpd_wrk;
1004 
1005 	do {
1006 		if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
1007 			trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
1008 							entry.param0, entry.param1);
1009 
1010 			drm_dbg_driver(adev_to_drm(adev), "trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
1011 				 entry.trace_code, entry.tick_count, entry.param0, entry.param1);
1012 		} else
1013 			break;
1014 
1015 		count++;
1016 
1017 	} while (count <= DMUB_TRACE_MAX_READ);
1018 
1019 	if (count > DMUB_TRACE_MAX_READ)
1020 		drm_dbg_driver(adev_to_drm(adev), "Warning : count > DMUB_TRACE_MAX_READ");
1021 
1022 	if (dc_enable_dmub_notifications(adev->dm.dc) &&
1023 		irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
1024 
1025 		do {
1026 			dc_stat_get_dmub_notification(adev->dm.dc, &notify);
1027 			if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
1028 				drm_err(adev_to_drm(adev), "DM: notify type %d invalid!", notify.type);
1029 				continue;
1030 			}
1031 			if (!dm->dmub_callback[notify.type]) {
1032 				drm_warn(adev_to_drm(adev), "DMUB notification skipped due to no handler: type=%s\n",
1033 					dmub_notification_type_str(notify.type));
1034 				continue;
1035 			}
1036 			if (dm->dmub_thread_offload[notify.type] == true) {
1037 				dmub_hpd_wrk = kzalloc_obj(*dmub_hpd_wrk,
1038 							   GFP_ATOMIC);
1039 				if (!dmub_hpd_wrk) {
1040 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk");
1041 					return;
1042 				}
1043 				dmub_hpd_wrk->dmub_notify = kmemdup(&notify, sizeof(struct dmub_notification),
1044 								    GFP_ATOMIC);
1045 				if (!dmub_hpd_wrk->dmub_notify) {
1046 					kfree(dmub_hpd_wrk);
1047 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk->dmub_notify");
1048 					return;
1049 				}
1050 				INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
1051 				dmub_hpd_wrk->adev = adev;
1052 				queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
1053 			} else {
1054 				dm->dmub_callback[notify.type](adev, &notify);
1055 			}
1056 		} while (notify.pending_notification);
1057 	}
1058 }
1059 
1060 static int dm_set_clockgating_state(struct amdgpu_ip_block *ip_block,
1061 		  enum amd_clockgating_state state)
1062 {
1063 	return 0;
1064 }
1065 
1066 static int dm_set_powergating_state(struct amdgpu_ip_block *ip_block,
1067 		  enum amd_powergating_state state)
1068 {
1069 	return 0;
1070 }
1071 
1072 /* Prototypes of private functions */
1073 static int dm_early_init(struct amdgpu_ip_block *ip_block);
1074 
1075 /* Allocate memory for FBC compressed data  */
1076 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
1077 {
1078 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
1079 	struct dm_compressor_info *compressor = &adev->dm.compressor;
1080 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
1081 	struct drm_display_mode *mode;
1082 	unsigned long max_size = 0;
1083 
1084 	if (adev->dm.dc->fbc_compressor == NULL)
1085 		return;
1086 
1087 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
1088 		return;
1089 
1090 	if (compressor->bo_ptr)
1091 		return;
1092 
1093 
1094 	list_for_each_entry(mode, &connector->modes, head) {
1095 		if (max_size < (unsigned long) mode->htotal * mode->vtotal)
1096 			max_size = (unsigned long) mode->htotal * mode->vtotal;
1097 	}
1098 
1099 	if (max_size) {
1100 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
1101 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
1102 			    &compressor->gpu_addr, &compressor->cpu_addr);
1103 
1104 		if (r)
1105 			drm_err(adev_to_drm(adev), "DM: Failed to initialize FBC\n");
1106 		else {
1107 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
1108 			drm_info(adev_to_drm(adev), "DM: FBC alloc %lu\n", max_size*4);
1109 		}
1110 
1111 	}
1112 
1113 }
1114 
1115 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
1116 					  int pipe, bool *enabled,
1117 					  unsigned char *buf, int max_bytes)
1118 {
1119 	struct drm_device *dev = dev_get_drvdata(kdev);
1120 	struct amdgpu_device *adev = drm_to_adev(dev);
1121 	struct drm_connector *connector;
1122 	struct drm_connector_list_iter conn_iter;
1123 	struct amdgpu_dm_connector *aconnector;
1124 	int ret = 0;
1125 
1126 	*enabled = false;
1127 
1128 	mutex_lock(&adev->dm.audio_lock);
1129 
1130 	drm_connector_list_iter_begin(dev, &conn_iter);
1131 	drm_for_each_connector_iter(connector, &conn_iter) {
1132 
1133 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1134 			continue;
1135 
1136 		aconnector = to_amdgpu_dm_connector(connector);
1137 		if (aconnector->audio_inst != port)
1138 			continue;
1139 
1140 		*enabled = true;
1141 		mutex_lock(&connector->eld_mutex);
1142 		ret = drm_eld_size(connector->eld);
1143 		memcpy(buf, connector->eld, min(max_bytes, ret));
1144 		mutex_unlock(&connector->eld_mutex);
1145 
1146 		break;
1147 	}
1148 	drm_connector_list_iter_end(&conn_iter);
1149 
1150 	mutex_unlock(&adev->dm.audio_lock);
1151 
1152 	drm_dbg_kms(adev_to_drm(adev), "Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
1153 
1154 	return ret;
1155 }
1156 
1157 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
1158 	.get_eld = amdgpu_dm_audio_component_get_eld,
1159 };
1160 
1161 static int amdgpu_dm_audio_component_bind(struct device *kdev,
1162 				       struct device *hda_kdev, void *data)
1163 {
1164 	struct drm_device *dev = dev_get_drvdata(kdev);
1165 	struct amdgpu_device *adev = drm_to_adev(dev);
1166 	struct drm_audio_component *acomp = data;
1167 
1168 	acomp->ops = &amdgpu_dm_audio_component_ops;
1169 	acomp->dev = kdev;
1170 	adev->dm.audio_component = acomp;
1171 
1172 	return 0;
1173 }
1174 
1175 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
1176 					  struct device *hda_kdev, void *data)
1177 {
1178 	struct amdgpu_device *adev = drm_to_adev(dev_get_drvdata(kdev));
1179 	struct drm_audio_component *acomp = data;
1180 
1181 	acomp->ops = NULL;
1182 	acomp->dev = NULL;
1183 	adev->dm.audio_component = NULL;
1184 }
1185 
1186 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
1187 	.bind	= amdgpu_dm_audio_component_bind,
1188 	.unbind	= amdgpu_dm_audio_component_unbind,
1189 };
1190 
1191 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
1192 {
1193 	int i, ret;
1194 
1195 	if (!amdgpu_audio)
1196 		return 0;
1197 
1198 	adev->mode_info.audio.enabled = true;
1199 
1200 	adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
1201 
1202 	for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
1203 		adev->mode_info.audio.pin[i].channels = -1;
1204 		adev->mode_info.audio.pin[i].rate = -1;
1205 		adev->mode_info.audio.pin[i].bits_per_sample = -1;
1206 		adev->mode_info.audio.pin[i].status_bits = 0;
1207 		adev->mode_info.audio.pin[i].category_code = 0;
1208 		adev->mode_info.audio.pin[i].connected = false;
1209 		adev->mode_info.audio.pin[i].id =
1210 			adev->dm.dc->res_pool->audios[i]->inst;
1211 		adev->mode_info.audio.pin[i].offset = 0;
1212 	}
1213 
1214 	ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1215 	if (ret < 0)
1216 		return ret;
1217 
1218 	adev->dm.audio_registered = true;
1219 
1220 	return 0;
1221 }
1222 
1223 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
1224 {
1225 	if (!amdgpu_audio)
1226 		return;
1227 
1228 	if (!adev->mode_info.audio.enabled)
1229 		return;
1230 
1231 	if (adev->dm.audio_registered) {
1232 		component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1233 		adev->dm.audio_registered = false;
1234 	}
1235 
1236 	/* TODO: Disable audio? */
1237 
1238 	adev->mode_info.audio.enabled = false;
1239 }
1240 
1241 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
1242 {
1243 	struct drm_audio_component *acomp = adev->dm.audio_component;
1244 
1245 	if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
1246 		drm_dbg_kms(adev_to_drm(adev), "Notify ELD: %d\n", pin);
1247 
1248 		acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1249 						 pin, -1);
1250 	}
1251 }
1252 
1253 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1254 {
1255 	const struct dmcub_firmware_header_v1_0 *hdr;
1256 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1257 	struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1258 	const struct firmware *dmub_fw = adev->dm.dmub_fw;
1259 	struct dc *dc = adev->dm.dc;
1260 	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1261 	struct abm *abm = adev->dm.dc->res_pool->abm;
1262 	struct dc_context *ctx = adev->dm.dc->ctx;
1263 	struct dmub_srv_hw_params hw_params;
1264 	enum dmub_status status;
1265 	const unsigned char *fw_inst_const, *fw_bss_data;
1266 	u32 i, fw_inst_const_size, fw_bss_data_size;
1267 	bool has_hw_support;
1268 
1269 	if (!dmub_srv)
1270 		/* DMUB isn't supported on the ASIC. */
1271 		return 0;
1272 
1273 	if (!fb_info) {
1274 		drm_err(adev_to_drm(adev), "No framebuffer info for DMUB service.\n");
1275 		return -EINVAL;
1276 	}
1277 
1278 	if (!dmub_fw) {
1279 		/* Firmware required for DMUB support. */
1280 		drm_err(adev_to_drm(adev), "No firmware provided for DMUB.\n");
1281 		return -EINVAL;
1282 	}
1283 
1284 	/* initialize register offsets for ASICs with runtime initialization available */
1285 	if (dmub_srv->hw_funcs.init_reg_offsets)
1286 		dmub_srv->hw_funcs.init_reg_offsets(dmub_srv, ctx);
1287 
1288 	status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1289 	if (status != DMUB_STATUS_OK) {
1290 		drm_err(adev_to_drm(adev), "Error checking HW support for DMUB: %d\n", status);
1291 		return -EINVAL;
1292 	}
1293 
1294 	if (!has_hw_support) {
1295 		drm_info(adev_to_drm(adev), "DMUB unsupported on ASIC\n");
1296 		return 0;
1297 	}
1298 
1299 	/* Reset DMCUB if it was previously running - before we overwrite its memory. */
1300 	status = dmub_srv_hw_reset(dmub_srv);
1301 	if (status != DMUB_STATUS_OK)
1302 		drm_warn(adev_to_drm(adev), "Error resetting DMUB HW: %d\n", status);
1303 
1304 	hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1305 
1306 	fw_inst_const = dmub_fw->data +
1307 			le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1308 			PSP_HEADER_BYTES_256;
1309 
1310 	fw_bss_data = dmub_fw->data +
1311 		      le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1312 		      le32_to_cpu(hdr->inst_const_bytes);
1313 
1314 	/* Copy firmware and bios info into FB memory. */
1315 	fw_inst_const_size = adev->dm.fw_inst_size;
1316 
1317 	fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1318 
1319 	/* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1320 	 * amdgpu_ucode_init_single_fw will load dmub firmware
1321 	 * fw_inst_const part to cw0; otherwise, the firmware back door load
1322 	 * will be done by dm_dmub_hw_init
1323 	 */
1324 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1325 		memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1326 				fw_inst_const_size);
1327 	}
1328 
1329 	if (fw_bss_data_size)
1330 		memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1331 		       fw_bss_data, fw_bss_data_size);
1332 
1333 	/* Copy firmware bios info into FB memory. */
1334 	memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1335 	       adev->bios_size);
1336 
1337 	/* Reset regions that need to be reset. */
1338 	memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1339 	fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1340 
1341 	memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1342 	       fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1343 
1344 	memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1345 	       fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1346 
1347 	memset(fb_info->fb[DMUB_WINDOW_SHARED_STATE].cpu_addr, 0,
1348 	       fb_info->fb[DMUB_WINDOW_SHARED_STATE].size);
1349 
1350 	/* Initialize hardware. */
1351 	memset(&hw_params, 0, sizeof(hw_params));
1352 	hw_params.soc_fb_info.fb_base = adev->gmc.fb_start;
1353 	hw_params.soc_fb_info.fb_offset = adev->vm_manager.vram_base_offset;
1354 
1355 	/* backdoor load firmware and trigger dmub running */
1356 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1357 		hw_params.load_inst_const = true;
1358 
1359 	if (dmcu)
1360 		hw_params.psp_version = dmcu->psp_version;
1361 
1362 	for (i = 0; i < fb_info->num_fb; ++i)
1363 		hw_params.fb[i] = &fb_info->fb[i];
1364 
1365 	/* Enable usb4 dpia in the FW APU */
1366 	if (dc->caps.is_apu &&
1367 		dc->res_pool->usb4_dpia_count != 0 &&
1368 		!dc->debug.dpia_debug.bits.disable_dpia) {
1369 		hw_params.dpia_supported = true;
1370 		hw_params.disable_dpia = dc->debug.dpia_debug.bits.disable_dpia;
1371 		hw_params.dpia_hpd_int_enable_supported = false;
1372 		hw_params.enable_non_transparent_setconfig = dc->config.consolidated_dpia_dp_lt;
1373 		hw_params.disable_dpia_bw_allocation = !dc->config.usb4_bw_alloc_support;
1374 	}
1375 
1376 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1377 	case IP_VERSION(3, 5, 0):
1378 	case IP_VERSION(3, 5, 1):
1379 	case IP_VERSION(3, 6, 0):
1380 	case IP_VERSION(4, 2, 0):
1381 	case IP_VERSION(4, 2, 1):
1382 		hw_params.ips_sequential_ono = adev->external_rev_id > 0x10;
1383 		hw_params.lower_hbr3_phy_ssc = true;
1384 		break;
1385 	default:
1386 		break;
1387 	}
1388 
1389 	status = dmub_srv_hw_init(dmub_srv, &hw_params);
1390 	if (status != DMUB_STATUS_OK) {
1391 		drm_err(adev_to_drm(adev), "Error initializing DMUB HW: %d\n", status);
1392 		return -EINVAL;
1393 	}
1394 
1395 	/* Wait for firmware load to finish. */
1396 	status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1397 	if (status != DMUB_STATUS_OK)
1398 		drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1399 
1400 	/* Init DMCU and ABM if available. */
1401 	if (dmcu && abm) {
1402 		dmcu->funcs->dmcu_init(dmcu);
1403 		abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1404 	}
1405 
1406 	if (!adev->dm.dc->ctx->dmub_srv)
1407 		adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1408 	if (!adev->dm.dc->ctx->dmub_srv) {
1409 		drm_err(adev_to_drm(adev), "Couldn't allocate DC DMUB server!\n");
1410 		return -ENOMEM;
1411 	}
1412 
1413 	drm_info(adev_to_drm(adev), "DMUB hardware initialized: version=0x%08X\n",
1414 		 adev->dm.dmcub_fw_version);
1415 
1416 	/* Keeping sanity checks off if
1417 	 * DCN31 >= 4.0.59.0
1418 	 * DCN314 >= 8.0.16.0
1419 	 * Otherwise, turn on sanity checks
1420 	 */
1421 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1422 	case IP_VERSION(3, 1, 2):
1423 	case IP_VERSION(3, 1, 3):
1424 		if (adev->dm.dmcub_fw_version &&
1425 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1426 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(4, 0, 59))
1427 				adev->dm.dc->debug.sanity_checks = true;
1428 		break;
1429 	case IP_VERSION(3, 1, 4):
1430 		if (adev->dm.dmcub_fw_version &&
1431 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1432 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(8, 0, 16))
1433 				adev->dm.dc->debug.sanity_checks = true;
1434 		break;
1435 	default:
1436 		break;
1437 	}
1438 
1439 	return 0;
1440 }
1441 
1442 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1443 {
1444 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1445 	enum dmub_status status;
1446 	bool init;
1447 	int r;
1448 
1449 	if (!dmub_srv) {
1450 		/* DMUB isn't supported on the ASIC. */
1451 		return;
1452 	}
1453 
1454 	status = dmub_srv_is_hw_init(dmub_srv, &init);
1455 	if (status != DMUB_STATUS_OK)
1456 		drm_warn(adev_to_drm(adev), "DMUB hardware init check failed: %d\n", status);
1457 
1458 	if (status == DMUB_STATUS_OK && init) {
1459 		/* Wait for firmware load to finish. */
1460 		status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1461 		if (status != DMUB_STATUS_OK)
1462 			drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1463 	} else {
1464 		/* Perform the full hardware initialization. */
1465 		r = dm_dmub_hw_init(adev);
1466 		if (r)
1467 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
1468 	}
1469 }
1470 
1471 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1472 {
1473 	u64 pt_base;
1474 	u32 logical_addr_low;
1475 	u32 logical_addr_high;
1476 	u32 agp_base, agp_bot, agp_top;
1477 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1478 
1479 	memset(pa_config, 0, sizeof(*pa_config));
1480 
1481 	agp_base = 0;
1482 	agp_bot = adev->gmc.agp_start >> 24;
1483 	agp_top = adev->gmc.agp_end >> 24;
1484 
1485 	/* AGP aperture is disabled */
1486 	if (agp_bot > agp_top) {
1487 		logical_addr_low = adev->gmc.fb_start >> 18;
1488 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1489 				       AMD_APU_IS_RENOIR |
1490 				       AMD_APU_IS_GREEN_SARDINE))
1491 			/*
1492 			 * Raven2 has a HW issue that it is unable to use the vram which
1493 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1494 			 * workaround that increase system aperture high address (add 1)
1495 			 * to get rid of the VM fault and hardware hang.
1496 			 */
1497 			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
1498 		else
1499 			logical_addr_high = adev->gmc.fb_end >> 18;
1500 	} else {
1501 		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1502 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1503 				       AMD_APU_IS_RENOIR |
1504 				       AMD_APU_IS_GREEN_SARDINE))
1505 			/*
1506 			 * Raven2 has a HW issue that it is unable to use the vram which
1507 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1508 			 * workaround that increase system aperture high address (add 1)
1509 			 * to get rid of the VM fault and hardware hang.
1510 			 */
1511 			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1512 		else
1513 			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1514 	}
1515 
1516 	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1517 
1518 	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
1519 						   AMDGPU_GPU_PAGE_SHIFT);
1520 	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
1521 						  AMDGPU_GPU_PAGE_SHIFT);
1522 	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
1523 						 AMDGPU_GPU_PAGE_SHIFT);
1524 	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
1525 						AMDGPU_GPU_PAGE_SHIFT);
1526 	page_table_base.high_part = upper_32_bits(pt_base);
1527 	page_table_base.low_part = lower_32_bits(pt_base);
1528 
1529 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1530 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1531 
1532 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
1533 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1534 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1535 
1536 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1537 	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
1538 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1539 
1540 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1541 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1542 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1543 
1544 	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
1545 
1546 }
1547 
1548 static void force_connector_state(
1549 	struct amdgpu_dm_connector *aconnector,
1550 	enum drm_connector_force force_state)
1551 {
1552 	struct drm_connector *connector = &aconnector->base;
1553 
1554 	mutex_lock(&connector->dev->mode_config.mutex);
1555 	aconnector->base.force = force_state;
1556 	mutex_unlock(&connector->dev->mode_config.mutex);
1557 
1558 	mutex_lock(&aconnector->hpd_lock);
1559 	drm_kms_helper_connector_hotplug_event(connector);
1560 	mutex_unlock(&aconnector->hpd_lock);
1561 }
1562 
1563 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1564 {
1565 	struct hpd_rx_irq_offload_work *offload_work;
1566 	struct amdgpu_dm_connector *aconnector;
1567 	struct dc_link *dc_link;
1568 	struct amdgpu_device *adev;
1569 	enum dc_connection_type new_connection_type = dc_connection_none;
1570 	unsigned long flags;
1571 	union test_response test_response;
1572 
1573 	memset(&test_response, 0, sizeof(test_response));
1574 
1575 	offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1576 	aconnector = offload_work->offload_wq->aconnector;
1577 	adev = offload_work->adev;
1578 
1579 	if (!aconnector) {
1580 		drm_err(adev_to_drm(adev), "Can't retrieve aconnector in hpd_rx_irq_offload_work");
1581 		goto skip;
1582 	}
1583 
1584 	dc_link = aconnector->dc_link;
1585 
1586 	mutex_lock(&aconnector->hpd_lock);
1587 	if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
1588 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
1589 	mutex_unlock(&aconnector->hpd_lock);
1590 
1591 	if (new_connection_type == dc_connection_none)
1592 		goto skip;
1593 
1594 	if (amdgpu_in_reset(adev))
1595 		goto skip;
1596 
1597 	if (offload_work->data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
1598 		offload_work->data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
1599 		dm_handle_mst_sideband_msg_ready_event(&aconnector->mst_mgr, DOWN_OR_UP_MSG_RDY_EVENT);
1600 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1601 		offload_work->offload_wq->is_handling_mst_msg_rdy_event = false;
1602 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1603 		goto skip;
1604 	}
1605 
1606 	mutex_lock(&adev->dm.dc_lock);
1607 	if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
1608 		dc_link_dp_handle_automated_test(dc_link);
1609 
1610 		if (aconnector->timing_changed) {
1611 			/* force connector disconnect and reconnect */
1612 			force_connector_state(aconnector, DRM_FORCE_OFF);
1613 			msleep(100);
1614 			force_connector_state(aconnector, DRM_FORCE_UNSPECIFIED);
1615 		}
1616 
1617 		test_response.bits.ACK = 1;
1618 
1619 		core_link_write_dpcd(
1620 		dc_link,
1621 		DP_TEST_RESPONSE,
1622 		&test_response.raw,
1623 		sizeof(test_response));
1624 	} else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1625 			dc_link_check_link_loss_status(dc_link, &offload_work->data) &&
1626 			dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1627 		/* offload_work->data is from handle_hpd_rx_irq->
1628 		 * schedule_hpd_rx_offload_work.this is defer handle
1629 		 * for hpd short pulse. upon here, link status may be
1630 		 * changed, need get latest link status from dpcd
1631 		 * registers. if link status is good, skip run link
1632 		 * training again.
1633 		 */
1634 		union hpd_irq_data irq_data;
1635 
1636 		memset(&irq_data, 0, sizeof(irq_data));
1637 
1638 		/* before dc_link_dp_handle_link_loss, allow new link lost handle
1639 		 * request be added to work queue if link lost at end of dc_link_
1640 		 * dp_handle_link_loss
1641 		 */
1642 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1643 		offload_work->offload_wq->is_handling_link_loss = false;
1644 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1645 
1646 		if ((dc_link_dp_read_hpd_rx_irq_data(dc_link, &irq_data) == DC_OK) &&
1647 			dc_link_check_link_loss_status(dc_link, &irq_data))
1648 			dc_link_dp_handle_link_loss(dc_link);
1649 	}
1650 	mutex_unlock(&adev->dm.dc_lock);
1651 
1652 skip:
1653 	kfree(offload_work);
1654 
1655 }
1656 
1657 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct amdgpu_device *adev)
1658 {
1659 	struct dc *dc = adev->dm.dc;
1660 	int max_caps = dc->caps.max_links;
1661 	int i = 0;
1662 	struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1663 
1664 	hpd_rx_offload_wq = kzalloc_objs(*hpd_rx_offload_wq, max_caps);
1665 
1666 	if (!hpd_rx_offload_wq)
1667 		return NULL;
1668 
1669 
1670 	for (i = 0; i < max_caps; i++) {
1671 		hpd_rx_offload_wq[i].wq =
1672 				    create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1673 
1674 		if (hpd_rx_offload_wq[i].wq == NULL) {
1675 			drm_err(adev_to_drm(adev), "create amdgpu_dm_hpd_rx_offload_wq fail!");
1676 			goto out_err;
1677 		}
1678 
1679 		spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
1680 	}
1681 
1682 	return hpd_rx_offload_wq;
1683 
1684 out_err:
1685 	for (i = 0; i < max_caps; i++) {
1686 		if (hpd_rx_offload_wq[i].wq)
1687 			destroy_workqueue(hpd_rx_offload_wq[i].wq);
1688 	}
1689 	kfree(hpd_rx_offload_wq);
1690 	return NULL;
1691 }
1692 
1693 struct amdgpu_stutter_quirk {
1694 	u16 chip_vendor;
1695 	u16 chip_device;
1696 	u16 subsys_vendor;
1697 	u16 subsys_device;
1698 	u8 revision;
1699 };
1700 
1701 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1702 	/* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1703 	{ 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1704 	{ 0, 0, 0, 0, 0 },
1705 };
1706 
1707 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1708 {
1709 	const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1710 
1711 	while (p && p->chip_device != 0) {
1712 		if (pdev->vendor == p->chip_vendor &&
1713 		    pdev->device == p->chip_device &&
1714 		    pdev->subsystem_vendor == p->subsys_vendor &&
1715 		    pdev->subsystem_device == p->subsys_device &&
1716 		    pdev->revision == p->revision) {
1717 			return true;
1718 		}
1719 		++p;
1720 	}
1721 	return false;
1722 }
1723 
1724 
1725 void*
1726 dm_allocate_gpu_mem(
1727 		struct amdgpu_device *adev,
1728 		enum dc_gpu_mem_alloc_type type,
1729 		size_t size,
1730 		long long *addr)
1731 {
1732 	struct dal_allocation *da;
1733 	u32 domain = (type == DC_MEM_ALLOC_TYPE_GART) ?
1734 		AMDGPU_GEM_DOMAIN_GTT : AMDGPU_GEM_DOMAIN_VRAM;
1735 	int ret;
1736 
1737 	da = kzalloc_obj(struct dal_allocation);
1738 	if (!da)
1739 		return NULL;
1740 
1741 	ret = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
1742 				      domain, &da->bo,
1743 				      &da->gpu_addr, &da->cpu_ptr);
1744 
1745 	*addr = da->gpu_addr;
1746 
1747 	if (ret) {
1748 		kfree(da);
1749 		return NULL;
1750 	}
1751 
1752 	/* add da to list in dm */
1753 	list_add(&da->list, &adev->dm.da_list);
1754 
1755 	return da->cpu_ptr;
1756 }
1757 
1758 void
1759 dm_free_gpu_mem(
1760 		struct amdgpu_device *adev,
1761 		enum dc_gpu_mem_alloc_type type,
1762 		void *pvMem)
1763 {
1764 	struct dal_allocation *da;
1765 
1766 	/* walk the da list in DM */
1767 	list_for_each_entry(da, &adev->dm.da_list, list) {
1768 		if (pvMem == da->cpu_ptr) {
1769 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
1770 			list_del(&da->list);
1771 			kfree(da);
1772 			break;
1773 		}
1774 	}
1775 
1776 }
1777 
1778 static enum dmub_status
1779 dm_dmub_send_vbios_gpint_command(struct amdgpu_device *adev,
1780 				 enum dmub_gpint_command command_code,
1781 				 uint16_t param,
1782 				 uint32_t timeout_us)
1783 {
1784 	union dmub_gpint_data_register reg, test;
1785 	uint32_t i;
1786 
1787 	/* Assume that VBIOS DMUB is ready to take commands */
1788 
1789 	reg.bits.status = 1;
1790 	reg.bits.command_code = command_code;
1791 	reg.bits.param = param;
1792 
1793 	cgs_write_register(adev->dm.cgs_device, 0x34c0 + 0x01f8, reg.all);
1794 
1795 	for (i = 0; i < timeout_us; ++i) {
1796 		udelay(1);
1797 
1798 		/* Check if our GPINT got acked */
1799 		reg.bits.status = 0;
1800 		test = (union dmub_gpint_data_register)
1801 			cgs_read_register(adev->dm.cgs_device, 0x34c0 + 0x01f8);
1802 
1803 		if (test.all == reg.all)
1804 			return DMUB_STATUS_OK;
1805 	}
1806 
1807 	return DMUB_STATUS_TIMEOUT;
1808 }
1809 
1810 static void *dm_dmub_get_vbios_bounding_box(struct amdgpu_device *adev)
1811 {
1812 	void *bb;
1813 	long long addr;
1814 	unsigned int bb_size;
1815 	int i = 0;
1816 	uint16_t chunk;
1817 	enum dmub_gpint_command send_addrs[] = {
1818 		DMUB_GPINT__SET_BB_ADDR_WORD0,
1819 		DMUB_GPINT__SET_BB_ADDR_WORD1,
1820 		DMUB_GPINT__SET_BB_ADDR_WORD2,
1821 		DMUB_GPINT__SET_BB_ADDR_WORD3,
1822 	};
1823 	enum dmub_status ret;
1824 
1825 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1826 	case IP_VERSION(4, 0, 1):
1827 		bb_size = sizeof(struct dml2_soc_bb);
1828 		break;
1829 	case IP_VERSION(4, 2, 0):
1830 	case IP_VERSION(4, 2, 1):
1831 		bb_size = sizeof(struct dml2_soc_bb);
1832 		break;
1833 	default:
1834 		return NULL;
1835 	}
1836 
1837 	bb =  dm_allocate_gpu_mem(adev,
1838 				  DC_MEM_ALLOC_TYPE_GART,
1839 				  bb_size,
1840 				  &addr);
1841 	if (!bb)
1842 		return NULL;
1843 
1844 	for (i = 0; i < 4; i++) {
1845 		/* Extract 16-bit chunk */
1846 		chunk = ((uint64_t) addr >> (i * 16)) & 0xFFFF;
1847 		/* Send the chunk */
1848 		ret = dm_dmub_send_vbios_gpint_command(adev, send_addrs[i], chunk, 30000);
1849 		if (ret != DMUB_STATUS_OK)
1850 			goto free_bb;
1851 	}
1852 
1853 	/* Now ask DMUB to copy the bb */
1854 	ret = dm_dmub_send_vbios_gpint_command(adev, DMUB_GPINT__BB_COPY, 1, 200000);
1855 	if (ret != DMUB_STATUS_OK)
1856 		goto free_bb;
1857 
1858 	return bb;
1859 
1860 free_bb:
1861 	dm_free_gpu_mem(adev, DC_MEM_ALLOC_TYPE_GART, (void *) bb);
1862 	return NULL;
1863 
1864 }
1865 
1866 static enum dmub_ips_disable_type dm_get_default_ips_mode(
1867 	struct amdgpu_device *adev)
1868 {
1869 	enum dmub_ips_disable_type ret = DMUB_IPS_ENABLE;
1870 
1871 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1872 	case IP_VERSION(3, 5, 0):
1873 	case IP_VERSION(3, 6, 0):
1874 	case IP_VERSION(3, 5, 1):
1875 		ret =  DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
1876 		break;
1877 	case IP_VERSION(4, 2, 0):
1878 	case IP_VERSION(4, 2, 1):
1879 		ret =  DMUB_IPS_ENABLE;
1880 		break;
1881 	default:
1882 		/* ASICs older than DCN35 do not have IPSs */
1883 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 5, 0))
1884 			ret = DMUB_IPS_DISABLE_ALL;
1885 		break;
1886 	}
1887 
1888 	return ret;
1889 }
1890 
1891 static int amdgpu_dm_init_power_module(struct amdgpu_display_manager *dm)
1892 {
1893 	struct mod_power_init_params init_data[MAX_NUM_EDP];
1894 
1895 	if (dm->num_of_edps == 0) {
1896 		drm_dbg_driver(
1897 			dm->ddev,
1898 			"amdgpu: No eDP detected, skip initializing power module\n");
1899 		return 0;
1900 	}
1901 
1902 	/* Initialize all the power module parameters */
1903 	for (int i = 0; i < dm->num_of_edps; i++) {
1904 		init_data[i].allow_psr_smu_optimizations =
1905 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_SMU_OPT);
1906 		init_data[i].allow_psr_multi_disp_optimizations =
1907 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_MULTI_DISP_OPT);
1908 		/* See dm_late_init */
1909 		init_data[i].backlight_ramping_override = false;
1910 		init_data[i].backlight_ramping_start = 0xCCCC;
1911 		init_data[i].backlight_ramping_reduction = 0xCCCCCCCC;
1912 		init_data[i].def_varibright_level = 0;
1913 		init_data[i].abm_config_setting = 0;
1914 		init_data[i].num_backlight_levels = 101;
1915 		init_data[i].use_nits_based_brightness = false;
1916 		init_data[i].panel_max_millinits = 0;
1917 		init_data[i].panel_min_millinits = 0;
1918 		init_data[i].disable_fractional_pwm =
1919 			!(amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK);
1920 		init_data[i].use_custom_backlight_caps = false;
1921 		init_data[i].custom_backlight_caps_config_no = 0;
1922 		init_data[i].use_linear_backlight_curve = false;
1923 		init_data[i].def_varibright_enable = 0;
1924 		init_data[i].varibright_level = 0;
1925 		/*
1926 		 * Power module uses 16-bit backlight levels (0xFFFF max) rather
1927 		 * than 8-bit(0XFF max)
1928 		 */
1929 		init_data[i].min_backlight_pwm =
1930 			dm->backlight_caps[i].min_input_signal * 0x101;
1931 		init_data[i].max_backlight_pwm =
1932 			dm->backlight_caps[i].max_input_signal * 0x101;
1933 		init_data[i].min_abm_backlight =
1934 			dm->backlight_caps[i].min_input_signal * 0x101;
1935 
1936 		/* Min backlight level after ABM reduction,  Don't allow below 1%
1937 		 * 0xFFFF x 0.01 = 0x28F
1938 		 */
1939 		init_data[i].min_abm_backlight = (init_data[i].min_abm_backlight < 0x28F) ?
1940 			0x28F : init_data[i].min_abm_backlight;
1941 	}
1942 
1943 	dm->power_module = mod_power_create(dm->dc, init_data, dm->num_of_edps);
1944 	if (!dm->power_module) {
1945 		drm_err(dm->ddev, "amdgpu: Error allocating memory for power module\n");
1946 		return -ENOMEM;
1947 	}
1948 
1949 	mod_power_hw_init(dm->power_module);
1950 	drm_dbg_driver(dm->ddev, "amdgpu: Power module init done\n");
1951 
1952 	return 0;
1953 }
1954 
1955 static void hdmi_frl_status_polling_work(struct work_struct *work)
1956 {
1957 	struct amdgpu_display_manager *dm =
1958 		container_of(to_delayed_work(work), struct amdgpu_display_manager,
1959 				hdmi_frl_status_polling_work);
1960 	struct dc *dc = dm->dc;
1961 	struct dc_link *dc_link;
1962 	bool link_update = false;
1963 
1964 	for (int i = 0; i < MAX_LINKS; i++) {
1965 		dc_link = dc->links[i];
1966 
1967 		if (!dc_link || !dc_link->local_sink)
1968 			continue;
1969 
1970 		if (!dc_is_hdmi_signal(dc_link->connector_signal))
1971 			continue;
1972 
1973 		if (dc_link->connector_signal != SIGNAL_TYPE_HDMI_FRL)
1974 			continue;
1975 
1976 		link_update = dc_link_frl_poll_status_flag(dc_link);
1977 		if (link_update) {
1978 			mutex_lock(&dm->dc_lock);
1979 			dc_link_detect(dc_link, DETECT_REASON_RETRAIN);
1980 			mutex_unlock(&dm->dc_lock);
1981 		}
1982 	}
1983 
1984 	queue_delayed_work(dm->hdmi_frl_status_polling_wq,
1985 			   &dm->hdmi_frl_status_polling_work,
1986 			   msecs_to_jiffies(dm->hdmi_frl_status_polling_delay_ms));
1987 }
1988 
1989 static int amdgpu_dm_init(struct amdgpu_device *adev)
1990 {
1991 	struct dc_init_data init_data;
1992 	struct dc_callback_init init_params;
1993 	int r;
1994 
1995 	adev->dm.ddev = adev_to_drm(adev);
1996 	adev->dm.adev = adev;
1997 
1998 	/* Zero all the fields */
1999 	memset(&init_data, 0, sizeof(init_data));
2000 	memset(&init_params, 0, sizeof(init_params));
2001 
2002 	mutex_init(&adev->dm.dpia_aux_lock);
2003 	mutex_init(&adev->dm.dc_lock);
2004 	mutex_init(&adev->dm.audio_lock);
2005 
2006 	spin_lock_init(&adev->dm.dmub_lock);
2007 
2008 	if (amdgpu_dm_irq_init(adev)) {
2009 		drm_err(adev_to_drm(adev), "failed to initialize DM IRQ support.\n");
2010 		goto error;
2011 	}
2012 
2013 	/* special handling for early revisions of GC 11.5.4 */
2014 	if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(11, 5, 4))
2015 		init_data.asic_id.chip_family = AMDGPU_FAMILY_GC_11_5_4;
2016 	else
2017 		init_data.asic_id.chip_family = adev->family;
2018 
2019 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
2020 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
2021 	init_data.asic_id.chip_id = adev->pdev->device;
2022 
2023 	init_data.asic_id.vram_width = adev->gmc.vram_width;
2024 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
2025 	init_data.asic_id.atombios_base_address =
2026 		adev->mode_info.atom_context->bios;
2027 
2028 	init_data.driver = adev;
2029 
2030 	/* cgs_device was created in dm_sw_init() */
2031 	init_data.cgs_device = adev->dm.cgs_device;
2032 
2033 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
2034 
2035 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2036 	case IP_VERSION(2, 1, 0):
2037 		switch (adev->dm.dmcub_fw_version) {
2038 		case 0: /* development */
2039 		case 0x1: /* linux-firmware.git hash 6d9f399 */
2040 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
2041 			init_data.flags.disable_dmcu = false;
2042 			break;
2043 		default:
2044 			init_data.flags.disable_dmcu = true;
2045 		}
2046 		break;
2047 	case IP_VERSION(2, 0, 3):
2048 		init_data.flags.disable_dmcu = true;
2049 		break;
2050 	default:
2051 		break;
2052 	}
2053 
2054 	/* APU support S/G display by default except:
2055 	 * ASICs before Carrizo,
2056 	 * RAVEN1 (Users reported stability issue)
2057 	 */
2058 
2059 	if (adev->asic_type < CHIP_CARRIZO) {
2060 		init_data.flags.gpu_vm_support = false;
2061 	} else if (adev->asic_type == CHIP_RAVEN) {
2062 		if (adev->apu_flags & AMD_APU_IS_RAVEN)
2063 			init_data.flags.gpu_vm_support = false;
2064 		else
2065 			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
2066 	} else {
2067 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(2, 0, 3))
2068 			init_data.flags.gpu_vm_support = (amdgpu_sg_display == 1);
2069 		else
2070 			init_data.flags.gpu_vm_support =
2071 				(amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
2072 	}
2073 
2074 	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
2075 
2076 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
2077 		init_data.flags.fbc_support = true;
2078 
2079 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
2080 		init_data.flags.multi_mon_pp_mclk_switch = true;
2081 
2082 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
2083 		init_data.flags.disable_fractional_pwm = true;
2084 
2085 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
2086 		init_data.flags.edp_no_power_sequencing = true;
2087 
2088 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
2089 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
2090 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
2091 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
2092 
2093 	if (amdgpu_dc_feature_mask & DC_FRL_MASK)
2094 		init_data.flags.enable_frl = true;
2095 
2096 	init_data.flags.seamless_boot_edp_requested = false;
2097 
2098 	if (amdgpu_device_seamless_boot_supported(adev)) {
2099 		init_data.flags.seamless_boot_edp_requested = true;
2100 		init_data.flags.allow_seamless_boot_optimization = true;
2101 		drm_dbg(adev->dm.ddev, "Seamless boot requested\n");
2102 	}
2103 
2104 	init_data.flags.enable_mipi_converter_optimization = true;
2105 
2106 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
2107 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
2108 	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
2109 
2110 	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
2111 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
2112 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS_DYNAMIC)
2113 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_DYNAMIC;
2114 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS2_DYNAMIC)
2115 		init_data.flags.disable_ips = DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
2116 	else if (amdgpu_dc_debug_mask & DC_FORCE_IPS_ENABLE)
2117 		init_data.flags.disable_ips = DMUB_IPS_ENABLE;
2118 	else
2119 		init_data.flags.disable_ips = dm_get_default_ips_mode(adev);
2120 
2121 	init_data.flags.disable_ips_in_vpb = 0;
2122 
2123 	/* DCN35 and above supports dynamic DTBCLK switch */
2124 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 5, 0))
2125 		init_data.flags.allow_0_dtb_clk = true;
2126 
2127 	/* Enable DWB for tested platforms only */
2128 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
2129 		init_data.num_virtual_links = 1;
2130 
2131 	/* DCN42 and above dpia switch to unified link training path */
2132 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 2, 0)) {
2133 		init_data.flags.consolidated_dpia_dp_lt = true;
2134 		init_data.flags.enable_dpia_pre_training = true;
2135 		init_data.flags.unify_link_enc_assignment = true;
2136 		init_data.flags.usb4_bw_alloc_support = true;
2137 	}
2138 	retrieve_dmi_info(&adev->dm);
2139 	if (adev->dm.edp0_on_dp1_quirk)
2140 		init_data.flags.support_edp0_on_dp1 = true;
2141 
2142 	if (adev->dm.bb_from_dmub)
2143 		init_data.bb_from_dmub = adev->dm.bb_from_dmub;
2144 	else
2145 		init_data.bb_from_dmub = NULL;
2146 
2147 	/* Display Core create. */
2148 	adev->dm.dc = dc_create(&init_data);
2149 
2150 	if (adev->dm.dc) {
2151 		drm_info(adev_to_drm(adev), "Display Core v%s initialized on %s\n", DC_VER,
2152 			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
2153 	} else {
2154 		drm_info(adev_to_drm(adev), "Display Core failed to initialize with v%s!\n", DC_VER);
2155 		goto error;
2156 	}
2157 
2158 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
2159 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
2160 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
2161 	}
2162 
2163 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2164 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2165 	if (dm_should_disable_stutter(adev->pdev))
2166 		adev->dm.dc->debug.disable_stutter = true;
2167 
2168 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
2169 		adev->dm.dc->debug.disable_stutter = true;
2170 
2171 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
2172 		adev->dm.dc->debug.disable_dsc = true;
2173 
2174 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
2175 		adev->dm.dc->debug.disable_clock_gate = true;
2176 
2177 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
2178 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
2179 
2180 	if (amdgpu_dc_debug_mask & DC_DISABLE_SUBVP_FAMS) {
2181 		adev->dm.dc->debug.force_disable_subvp = true;
2182 		adev->dm.dc->debug.fams2_config.bits.enable = false;
2183 	}
2184 
2185 	if (amdgpu_dc_debug_mask & DC_ENABLE_DML2) {
2186 		adev->dm.dc->debug.using_dml2 = true;
2187 		adev->dm.dc->debug.using_dml21 = true;
2188 	}
2189 
2190 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_FORCE_FW_ENABLE)
2191 		adev->dm.dc->debug.hdcp_lc_force_fw_enable = true;
2192 
2193 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_ENABLE_SW_FALLBACK)
2194 		adev->dm.dc->debug.hdcp_lc_enable_sw_fallback = true;
2195 
2196 	if (amdgpu_dc_debug_mask & DC_SKIP_DETECTION_LT)
2197 		adev->dm.dc->debug.skip_detection_link_training = true;
2198 
2199 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
2200 
2201 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
2202 	adev->dm.dc->debug.ignore_cable_id = true;
2203 
2204 	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
2205 		drm_info(adev_to_drm(adev), "DP-HDMI FRL PCON supported\n");
2206 
2207 	r = dm_dmub_hw_init(adev);
2208 	if (r) {
2209 		drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
2210 		goto error;
2211 	}
2212 
2213 	dc_hardware_init(adev->dm.dc);
2214 
2215 	adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev);
2216 	if (!adev->dm.hpd_rx_offload_wq) {
2217 		drm_err(adev_to_drm(adev), "failed to create hpd rx offload workqueue.\n");
2218 		goto error;
2219 	}
2220 
2221 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
2222 		struct dc_phy_addr_space_config pa_config;
2223 
2224 		mmhub_read_system_context(adev, &pa_config);
2225 
2226 		// Call the DC init_memory func
2227 		dc_setup_system_context(adev->dm.dc, &pa_config);
2228 	}
2229 
2230 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
2231 	if (!adev->dm.freesync_module) {
2232 		drm_err(adev_to_drm(adev),
2233 		"failed to initialize freesync_module.\n");
2234 	} else
2235 		drm_dbg_driver(adev_to_drm(adev), "freesync_module init done %p.\n",
2236 				adev->dm.freesync_module);
2237 
2238 	amdgpu_dm_init_color_mod();
2239 
2240 	if (adev->dm.dc->caps.max_links > 0) {
2241 		adev->dm.vblank_control_workqueue =
2242 			create_singlethread_workqueue("dm_vblank_control_workqueue");
2243 		if (!adev->dm.vblank_control_workqueue)
2244 			drm_err(adev_to_drm(adev), "failed to initialize vblank_workqueue.\n");
2245 	}
2246 
2247 	if (adev->dm.dc->caps.ips_support &&
2248 	    adev->dm.dc->config.disable_ips != DMUB_IPS_DISABLE_ALL)
2249 		adev->dm.idle_workqueue = idle_create_workqueue(adev);
2250 
2251 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
2252 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
2253 
2254 		if (!adev->dm.hdcp_workqueue)
2255 			drm_err(adev_to_drm(adev), "failed to initialize hdcp_workqueue.\n");
2256 		else
2257 			drm_dbg_driver(adev_to_drm(adev),
2258 				       "hdcp_workqueue init done %p.\n",
2259 				       adev->dm.hdcp_workqueue);
2260 
2261 		dc_init_callbacks(adev->dm.dc, &init_params);
2262 	}
2263 	if (adev->dm.dc->caps.max_links > 0) {
2264 		adev->dm.hdmi_frl_status_polling_wq =
2265 			create_singlethread_workqueue("hdmi_frl_status_polling_workqueue");
2266 		if (!adev->dm.hdmi_frl_status_polling_wq)
2267 			drm_err(adev_to_drm(adev), "failed to initialize hdmi_frl_status_polling_workqueue\n");
2268 		adev->dm.hdmi_frl_status_polling_delay_ms = 200;
2269 		INIT_DELAYED_WORK(&adev->dm.hdmi_frl_status_polling_work, hdmi_frl_status_polling_work);
2270 	}
2271 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2272 		init_completion(&adev->dm.dmub_aux_transfer_done);
2273 		adev->dm.dmub_notify = kzalloc_obj(struct dmub_notification);
2274 		if (!adev->dm.dmub_notify) {
2275 			drm_info(adev_to_drm(adev), "fail to allocate adev->dm.dmub_notify");
2276 			goto error;
2277 		}
2278 
2279 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
2280 		if (!adev->dm.delayed_hpd_wq) {
2281 			drm_err(adev_to_drm(adev), "failed to create hpd offload workqueue.\n");
2282 			goto error;
2283 		}
2284 
2285 		amdgpu_dm_outbox_init(adev);
2286 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
2287 			dmub_aux_setconfig_callback, false)) {
2288 			drm_err(adev_to_drm(adev), "fail to register dmub aux callback");
2289 			goto error;
2290 		}
2291 
2292 		for (size_t i = 0; i < ARRAY_SIZE(adev->dm.fused_io); i++)
2293 			init_completion(&adev->dm.fused_io[i].replied);
2294 
2295 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_FUSED_IO,
2296 			dmub_aux_fused_io_callback, false)) {
2297 			drm_err(adev_to_drm(adev), "fail to register dmub fused io callback");
2298 			goto error;
2299 		}
2300 		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
2301 		 * It is expected that DMUB will resend any pending notifications at this point. Note
2302 		 * that hpd and hpd_irq handler registration are deferred to register_hpd_handlers() to
2303 		 * align legacy interface initialization sequence. Connection status will be proactivly
2304 		 * detected once in the amdgpu_dm_initialize_drm_device.
2305 		 */
2306 		dc_enable_dmub_outbox(adev->dm.dc);
2307 
2308 		/* DPIA trace goes to dmesg logs only if outbox is enabled */
2309 		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
2310 			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
2311 	}
2312 
2313 	if (amdgpu_dm_initialize_drm_device(adev)) {
2314 		drm_err(adev_to_drm(adev),
2315 		"failed to initialize sw for display support.\n");
2316 		goto error;
2317 	}
2318 
2319 	if (amdgpu_dm_init_power_module(&adev->dm))
2320 		goto error;
2321 
2322 	/* create fake encoders for MST */
2323 	dm_dp_create_fake_mst_encoders(adev);
2324 
2325 	/* TODO: Add_display_info? */
2326 
2327 	/* TODO use dynamic cursor width */
2328 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
2329 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
2330 
2331 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
2332 		drm_err(adev_to_drm(adev),
2333 		"failed to initialize vblank for display support.\n");
2334 		goto error;
2335 	}
2336 
2337 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2338 	amdgpu_dm_crtc_secure_display_create_contexts(adev);
2339 	if (!adev->dm.secure_display_ctx.crtc_ctx)
2340 		drm_err(adev_to_drm(adev), "failed to initialize secure display contexts.\n");
2341 
2342 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))
2343 		adev->dm.secure_display_ctx.support_mul_roi = true;
2344 
2345 #endif
2346 
2347 	drm_dbg_driver(adev_to_drm(adev), "KMS initialized.\n");
2348 
2349 	return 0;
2350 error:
2351 	amdgpu_dm_fini(adev);
2352 
2353 	return -EINVAL;
2354 }
2355 
2356 static int amdgpu_dm_early_fini(struct amdgpu_ip_block *ip_block)
2357 {
2358 	struct amdgpu_device *adev = ip_block->adev;
2359 
2360 	amdgpu_dm_audio_fini(adev);
2361 
2362 	return 0;
2363 }
2364 
2365 static void amdgpu_dm_fini(struct amdgpu_device *adev)
2366 {
2367 	int i;
2368 
2369 	if (adev->dm.vblank_control_workqueue) {
2370 		destroy_workqueue(adev->dm.vblank_control_workqueue);
2371 		adev->dm.vblank_control_workqueue = NULL;
2372 	}
2373 
2374 	if (adev->dm.idle_workqueue) {
2375 		if (adev->dm.idle_workqueue->running) {
2376 			adev->dm.idle_workqueue->enable = false;
2377 			flush_work(&adev->dm.idle_workqueue->work);
2378 		}
2379 
2380 		kfree(adev->dm.idle_workqueue);
2381 		adev->dm.idle_workqueue = NULL;
2382 	}
2383 
2384 	/*
2385 	 * Disable ISM before dc_destroy() invalidates dm->dc.
2386 	 *
2387 	 * Quiesce workers first without dc_lock (they take dc_lock
2388 	 * themselves, so syncing under it would deadlock), then drive the
2389 	 * FSM back to FULL_POWER_RUNNING under dc_lock.
2390 	 */
2391 	amdgpu_dm_ism_disable(&adev->dm);
2392 	scoped_guard(mutex, &adev->dm.dc_lock)
2393 		amdgpu_dm_ism_force_full_power(&adev->dm);
2394 
2395 	amdgpu_dm_destroy_drm_device(&adev->dm);
2396 
2397 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2398 	if (adev->dm.secure_display_ctx.crtc_ctx) {
2399 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
2400 			if (adev->dm.secure_display_ctx.crtc_ctx[i].crtc) {
2401 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].notify_ta_work);
2402 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].forward_roi_work);
2403 			}
2404 		}
2405 		kfree(adev->dm.secure_display_ctx.crtc_ctx);
2406 		adev->dm.secure_display_ctx.crtc_ctx = NULL;
2407 	}
2408 #endif
2409 	if (adev->dm.hdcp_workqueue) {
2410 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
2411 		adev->dm.hdcp_workqueue = NULL;
2412 	}
2413 
2414 	if (adev->dm.dc) {
2415 		dc_deinit_callbacks(adev->dm.dc);
2416 		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
2417 		if (dc_enable_dmub_notifications(adev->dm.dc)) {
2418 			kfree(adev->dm.dmub_notify);
2419 			adev->dm.dmub_notify = NULL;
2420 			destroy_workqueue(adev->dm.delayed_hpd_wq);
2421 			adev->dm.delayed_hpd_wq = NULL;
2422 		}
2423 	}
2424 
2425 	if (adev->dm.dmub_bo)
2426 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
2427 				      &adev->dm.dmub_bo_gpu_addr,
2428 				      &adev->dm.dmub_bo_cpu_addr);
2429 
2430 	if (adev->dm.boot_time_crc_info.bo_ptr)
2431 		amdgpu_bo_free_kernel(&adev->dm.boot_time_crc_info.bo_ptr,
2432 					&adev->dm.boot_time_crc_info.gpu_addr,
2433 					&adev->dm.boot_time_crc_info.cpu_addr);
2434 
2435 	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
2436 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
2437 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
2438 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
2439 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
2440 			}
2441 		}
2442 
2443 		kfree(adev->dm.hpd_rx_offload_wq);
2444 		adev->dm.hpd_rx_offload_wq = NULL;
2445 	}
2446 
2447 	/* DC Destroy TODO: Replace destroy DAL */
2448 	if (adev->dm.dc)
2449 		dc_destroy(&adev->dm.dc);
2450 	/*
2451 	 * TODO: pageflip, vlank interrupt
2452 	 *
2453 	 * amdgpu_dm_irq_fini(adev);
2454 	 */
2455 
2456 	if (adev->dm.cgs_device) {
2457 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
2458 		adev->dm.cgs_device = NULL;
2459 	}
2460 	if (adev->dm.freesync_module) {
2461 		mod_freesync_destroy(adev->dm.freesync_module);
2462 		adev->dm.freesync_module = NULL;
2463 	}
2464 
2465 	if (adev->dm.power_module) {
2466 		mod_power_destroy(adev->dm.power_module);
2467 		adev->dm.power_module = NULL;
2468 	}
2469 	mutex_destroy(&adev->dm.audio_lock);
2470 	mutex_destroy(&adev->dm.dc_lock);
2471 	mutex_destroy(&adev->dm.dpia_aux_lock);
2472 }
2473 
2474 static int load_dmcu_fw(struct amdgpu_device *adev)
2475 {
2476 	const char *fw_name_dmcu = NULL;
2477 	int r;
2478 	const struct dmcu_firmware_header_v1_0 *hdr;
2479 
2480 	switch (adev->asic_type) {
2481 #if defined(CONFIG_DRM_AMD_DC_SI)
2482 	case CHIP_TAHITI:
2483 	case CHIP_PITCAIRN:
2484 	case CHIP_VERDE:
2485 	case CHIP_OLAND:
2486 #endif
2487 	case CHIP_BONAIRE:
2488 	case CHIP_HAWAII:
2489 	case CHIP_KAVERI:
2490 	case CHIP_KABINI:
2491 	case CHIP_MULLINS:
2492 	case CHIP_TONGA:
2493 	case CHIP_FIJI:
2494 	case CHIP_CARRIZO:
2495 	case CHIP_STONEY:
2496 	case CHIP_POLARIS11:
2497 	case CHIP_POLARIS10:
2498 	case CHIP_POLARIS12:
2499 	case CHIP_VEGAM:
2500 	case CHIP_VEGA10:
2501 	case CHIP_VEGA12:
2502 	case CHIP_VEGA20:
2503 		return 0;
2504 	case CHIP_NAVI12:
2505 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
2506 		break;
2507 	case CHIP_RAVEN:
2508 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
2509 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2510 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
2511 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2512 		else
2513 			return 0;
2514 		break;
2515 	default:
2516 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2517 		case IP_VERSION(2, 0, 2):
2518 		case IP_VERSION(2, 0, 3):
2519 		case IP_VERSION(2, 0, 0):
2520 		case IP_VERSION(2, 1, 0):
2521 		case IP_VERSION(3, 0, 0):
2522 		case IP_VERSION(3, 0, 2):
2523 		case IP_VERSION(3, 0, 3):
2524 		case IP_VERSION(3, 0, 1):
2525 		case IP_VERSION(3, 1, 2):
2526 		case IP_VERSION(3, 1, 3):
2527 		case IP_VERSION(3, 1, 4):
2528 		case IP_VERSION(3, 1, 5):
2529 		case IP_VERSION(3, 1, 6):
2530 		case IP_VERSION(3, 2, 0):
2531 		case IP_VERSION(3, 2, 1):
2532 		case IP_VERSION(3, 5, 0):
2533 		case IP_VERSION(3, 5, 1):
2534 		case IP_VERSION(3, 6, 0):
2535 		case IP_VERSION(4, 0, 1):
2536 		case IP_VERSION(4, 2, 0):
2537 		case IP_VERSION(4, 2, 1):
2538 			return 0;
2539 		default:
2540 			break;
2541 		}
2542 		drm_err(adev_to_drm(adev), "Unsupported ASIC type: 0x%X\n", adev->asic_type);
2543 		return -EINVAL;
2544 	}
2545 
2546 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
2547 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not supported on direct or SMU loading\n");
2548 		return 0;
2549 	}
2550 
2551 	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, AMDGPU_UCODE_REQUIRED,
2552 				 "%s", fw_name_dmcu);
2553 	if (r == -ENODEV) {
2554 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
2555 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not found\n");
2556 		adev->dm.fw_dmcu = NULL;
2557 		return 0;
2558 	}
2559 	if (r) {
2560 		drm_err(adev_to_drm(adev), "amdgpu_dm: Can't validate firmware \"%s\"\n",
2561 			fw_name_dmcu);
2562 		amdgpu_ucode_release(&adev->dm.fw_dmcu);
2563 		return r;
2564 	}
2565 
2566 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
2567 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
2568 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
2569 	adev->firmware.fw_size +=
2570 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2571 
2572 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
2573 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
2574 	adev->firmware.fw_size +=
2575 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2576 
2577 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
2578 
2579 	drm_dbg_kms(adev_to_drm(adev), "PSP loading DMCU firmware\n");
2580 
2581 	return 0;
2582 }
2583 
2584 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
2585 {
2586 	struct amdgpu_device *adev = ctx;
2587 
2588 	return dm_read_reg(adev->dm.dc->ctx, address);
2589 }
2590 
2591 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
2592 				     uint32_t value)
2593 {
2594 	struct amdgpu_device *adev = ctx;
2595 
2596 	return dm_write_reg(adev->dm.dc->ctx, address, value);
2597 }
2598 
2599 static int dm_dmub_sw_init(struct amdgpu_device *adev)
2600 {
2601 	struct dmub_srv_create_params create_params;
2602 	struct dmub_srv_fw_meta_info_params fw_meta_info_params;
2603 	struct dmub_srv_region_params region_params;
2604 	struct dmub_srv_region_info region_info;
2605 	struct dmub_srv_memory_params memory_params;
2606 	struct dmub_fw_meta_info fw_info;
2607 	struct dmub_srv_fb_info *fb_info;
2608 	struct dmub_srv *dmub_srv;
2609 	const struct dmcub_firmware_header_v1_0 *hdr;
2610 	enum dmub_asic dmub_asic;
2611 	enum dmub_status status;
2612 	static enum dmub_window_memory_type window_memory_type[DMUB_WINDOW_TOTAL] = {
2613 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_0_INST_CONST
2614 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_1_STACK
2615 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_2_BSS_DATA
2616 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_3_VBIOS
2617 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_4_MAILBOX
2618 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_5_TRACEBUFF
2619 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_6_FW_STATE
2620 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_7_SCRATCH_MEM
2621 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_IB_MEM
2622 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_SHARED_STATE
2623 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_LSDMA_BUFFER
2624 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_CURSOR_OFFLOAD
2625 	};
2626 	int r;
2627 
2628 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2629 	case IP_VERSION(2, 1, 0):
2630 		dmub_asic = DMUB_ASIC_DCN21;
2631 		break;
2632 	case IP_VERSION(3, 0, 0):
2633 		dmub_asic = DMUB_ASIC_DCN30;
2634 		break;
2635 	case IP_VERSION(3, 0, 1):
2636 		dmub_asic = DMUB_ASIC_DCN301;
2637 		break;
2638 	case IP_VERSION(3, 0, 2):
2639 		dmub_asic = DMUB_ASIC_DCN302;
2640 		break;
2641 	case IP_VERSION(3, 0, 3):
2642 		dmub_asic = DMUB_ASIC_DCN303;
2643 		break;
2644 	case IP_VERSION(3, 1, 2):
2645 	case IP_VERSION(3, 1, 3):
2646 		dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
2647 		break;
2648 	case IP_VERSION(3, 1, 4):
2649 		dmub_asic = DMUB_ASIC_DCN314;
2650 		break;
2651 	case IP_VERSION(3, 1, 5):
2652 		dmub_asic = DMUB_ASIC_DCN315;
2653 		break;
2654 	case IP_VERSION(3, 1, 6):
2655 		dmub_asic = DMUB_ASIC_DCN316;
2656 		break;
2657 	case IP_VERSION(3, 2, 0):
2658 		dmub_asic = DMUB_ASIC_DCN32;
2659 		break;
2660 	case IP_VERSION(3, 2, 1):
2661 		dmub_asic = DMUB_ASIC_DCN321;
2662 		break;
2663 	case IP_VERSION(3, 5, 0):
2664 	case IP_VERSION(3, 5, 1):
2665 		dmub_asic = DMUB_ASIC_DCN35;
2666 		break;
2667 	case IP_VERSION(3, 6, 0):
2668 		dmub_asic = DMUB_ASIC_DCN36;
2669 		break;
2670 	case IP_VERSION(4, 0, 1):
2671 		dmub_asic = DMUB_ASIC_DCN401;
2672 		break;
2673 	case IP_VERSION(4, 2, 0):
2674 		dmub_asic = DMUB_ASIC_DCN42;
2675 		break;
2676 	case IP_VERSION(4, 2, 1):
2677 		dmub_asic = DMUB_ASIC_DCN42B;
2678 		break;
2679 	default:
2680 		/* ASIC doesn't support DMUB. */
2681 		return 0;
2682 	}
2683 
2684 	hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
2685 	adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
2686 
2687 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
2688 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
2689 			AMDGPU_UCODE_ID_DMCUB;
2690 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
2691 			adev->dm.dmub_fw;
2692 		adev->firmware.fw_size +=
2693 			ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
2694 
2695 		drm_info(adev_to_drm(adev), "Loading DMUB firmware via PSP: version=0x%08X\n",
2696 			 adev->dm.dmcub_fw_version);
2697 	}
2698 
2699 
2700 	adev->dm.dmub_srv = kzalloc_obj(*adev->dm.dmub_srv);
2701 	dmub_srv = adev->dm.dmub_srv;
2702 
2703 	if (!dmub_srv) {
2704 		drm_err(adev_to_drm(adev), "Failed to allocate DMUB service!\n");
2705 		return -ENOMEM;
2706 	}
2707 
2708 	memset(&create_params, 0, sizeof(create_params));
2709 	create_params.user_ctx = adev;
2710 	create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2711 	create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2712 	create_params.asic = dmub_asic;
2713 
2714 	/* Create the DMUB service. */
2715 	status = dmub_srv_create(dmub_srv, &create_params);
2716 	if (status != DMUB_STATUS_OK) {
2717 		drm_err(adev_to_drm(adev), "Error creating DMUB service: %d\n", status);
2718 		return -EINVAL;
2719 	}
2720 
2721 	/* Extract the FW meta info. */
2722 	memset(&fw_meta_info_params, 0, sizeof(fw_meta_info_params));
2723 
2724 	fw_meta_info_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2725 					      PSP_HEADER_BYTES_256;
2726 	fw_meta_info_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2727 	fw_meta_info_params.fw_inst_const = adev->dm.dmub_fw->data +
2728 					    le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2729 					    PSP_HEADER_BYTES_256;
2730 	fw_meta_info_params.fw_bss_data = fw_meta_info_params.bss_data_size ? adev->dm.dmub_fw->data +
2731 					  le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2732 					  le32_to_cpu(hdr->inst_const_bytes) : NULL;
2733 	fw_meta_info_params.custom_psp_footer_size = 0;
2734 
2735 	status = dmub_srv_get_fw_meta_info_from_raw_fw(&fw_meta_info_params, &fw_info);
2736 	if (status != DMUB_STATUS_OK) {
2737 		/* Skip returning early, just log the error. */
2738 		drm_err(adev_to_drm(adev), "Error getting DMUB FW meta info: %d\n", status);
2739 		// return -EINVAL;
2740 	}
2741 
2742 	/* Calculate the size of all the regions for the DMUB service. */
2743 	memset(&region_params, 0, sizeof(region_params));
2744 
2745 	region_params.inst_const_size = fw_meta_info_params.inst_const_size;
2746 	region_params.bss_data_size = fw_meta_info_params.bss_data_size;
2747 	region_params.vbios_size = adev->bios_size;
2748 	region_params.fw_bss_data = fw_meta_info_params.fw_bss_data;
2749 	region_params.fw_inst_const = fw_meta_info_params.fw_inst_const;
2750 	region_params.window_memory_type = window_memory_type;
2751 	region_params.fw_info = (status == DMUB_STATUS_OK) ? &fw_info : NULL;
2752 
2753 	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2754 					   &region_info);
2755 
2756 	if (status != DMUB_STATUS_OK) {
2757 		drm_err(adev_to_drm(adev), "Error calculating DMUB region info: %d\n", status);
2758 		return -EINVAL;
2759 	}
2760 
2761 	/*
2762 	 * Allocate a framebuffer based on the total size of all the regions.
2763 	 * TODO: Move this into GART.
2764 	 */
2765 	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2766 				    AMDGPU_GEM_DOMAIN_VRAM |
2767 				    AMDGPU_GEM_DOMAIN_GTT,
2768 				    &adev->dm.dmub_bo,
2769 				    &adev->dm.dmub_bo_gpu_addr,
2770 				    &adev->dm.dmub_bo_cpu_addr);
2771 	if (r)
2772 		return r;
2773 
2774 	/* Rebase the regions on the framebuffer address. */
2775 	memset(&memory_params, 0, sizeof(memory_params));
2776 	memory_params.cpu_fb_addr = adev->dm.dmub_bo_cpu_addr;
2777 	memory_params.gpu_fb_addr = adev->dm.dmub_bo_gpu_addr;
2778 	memory_params.region_info = &region_info;
2779 	memory_params.window_memory_type = window_memory_type;
2780 
2781 	adev->dm.dmub_fb_info = kzalloc_obj(*adev->dm.dmub_fb_info);
2782 	fb_info = adev->dm.dmub_fb_info;
2783 
2784 	if (!fb_info) {
2785 		drm_err(adev_to_drm(adev),
2786 			"Failed to allocate framebuffer info for DMUB service!\n");
2787 		return -ENOMEM;
2788 	}
2789 
2790 	status = dmub_srv_calc_mem_info(dmub_srv, &memory_params, fb_info);
2791 	if (status != DMUB_STATUS_OK) {
2792 		drm_err(adev_to_drm(adev), "Error calculating DMUB FB info: %d\n", status);
2793 		return -EINVAL;
2794 	}
2795 
2796 	adev->dm.bb_from_dmub = dm_dmub_get_vbios_bounding_box(adev);
2797 	adev->dm.fw_inst_size = fw_meta_info_params.inst_const_size;
2798 
2799 	return 0;
2800 }
2801 
2802 static int dm_sw_init(struct amdgpu_ip_block *ip_block)
2803 {
2804 	struct amdgpu_device *adev = ip_block->adev;
2805 	int r;
2806 
2807 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
2808 
2809 	if (!adev->dm.cgs_device) {
2810 		drm_err(adev_to_drm(adev), "failed to create cgs device.\n");
2811 		return -EINVAL;
2812 	}
2813 
2814 	/* Moved from dm init since we need to use allocations for storing bounding box data */
2815 	INIT_LIST_HEAD(&adev->dm.da_list);
2816 
2817 	r = dm_dmub_sw_init(adev);
2818 	if (r)
2819 		return r;
2820 
2821 	return load_dmcu_fw(adev);
2822 }
2823 
2824 static int dm_sw_fini(struct amdgpu_ip_block *ip_block)
2825 {
2826 	struct amdgpu_device *adev = ip_block->adev;
2827 	struct dal_allocation *da;
2828 
2829 	list_for_each_entry(da, &adev->dm.da_list, list) {
2830 		if (adev->dm.bb_from_dmub == (void *) da->cpu_ptr) {
2831 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
2832 			list_del(&da->list);
2833 			kfree(da);
2834 			adev->dm.bb_from_dmub = NULL;
2835 			break;
2836 		}
2837 	}
2838 
2839 
2840 	kfree(adev->dm.dmub_fb_info);
2841 	adev->dm.dmub_fb_info = NULL;
2842 
2843 	if (adev->dm.dmub_srv) {
2844 		dmub_srv_destroy(adev->dm.dmub_srv);
2845 		kfree(adev->dm.dmub_srv);
2846 		adev->dm.dmub_srv = NULL;
2847 	}
2848 
2849 	amdgpu_ucode_release(&adev->dm.dmub_fw);
2850 	amdgpu_ucode_release(&adev->dm.fw_dmcu);
2851 
2852 	return 0;
2853 }
2854 
2855 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2856 {
2857 	struct amdgpu_dm_connector *aconnector;
2858 	struct drm_connector *connector;
2859 	struct drm_connector_list_iter iter;
2860 	int ret = 0;
2861 
2862 	drm_connector_list_iter_begin(dev, &iter);
2863 	drm_for_each_connector_iter(connector, &iter) {
2864 
2865 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2866 			continue;
2867 
2868 		aconnector = to_amdgpu_dm_connector(connector);
2869 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
2870 		    aconnector->mst_mgr.aux) {
2871 			drm_dbg_kms(dev, "DM_MST: starting TM on aconnector: %p [id: %d]\n",
2872 					 aconnector,
2873 					 aconnector->base.base.id);
2874 
2875 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2876 			if (ret < 0) {
2877 				drm_err(dev, "DM_MST: Failed to start MST\n");
2878 				aconnector->dc_link->type =
2879 					dc_connection_single;
2880 				ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2881 								     aconnector->dc_link);
2882 				break;
2883 			}
2884 		}
2885 	}
2886 	drm_connector_list_iter_end(&iter);
2887 
2888 	return ret;
2889 }
2890 
2891 static void amdgpu_dm_boot_time_crc_init(struct amdgpu_device *adev)
2892 {
2893 	struct dm_boot_time_crc_info *bootcrc_info = NULL;
2894 	struct dmub_srv *dmub = NULL;
2895 	union dmub_fw_boot_options option = {0};
2896 	int ret = 0;
2897 	const uint32_t fb_size = 3 * 1024 * 1024;	/* 3MB for DCC pattern */
2898 
2899 	if (!adev || !adev->dm.dc || !adev->dm.dc->ctx ||
2900 		!adev->dm.dc->ctx->dmub_srv) {
2901 		return;
2902 	}
2903 
2904 	dmub = adev->dm.dc->ctx->dmub_srv->dmub;
2905 	bootcrc_info = &adev->dm.boot_time_crc_info;
2906 
2907 	if (!dmub || !dmub->hw_funcs.get_fw_boot_option) {
2908 		drm_dbg(adev_to_drm(adev), "failed to init boot time crc buffer\n");
2909 		return;
2910 	}
2911 
2912 	option = dmub->hw_funcs.get_fw_boot_option(dmub);
2913 
2914 	/* Return if boot time CRC is not enabled */
2915 	if (option.bits.bootcrc_en_at_S0i3 == 0)
2916 		return;
2917 
2918 	/* Create a buffer for boot time CRC */
2919 	ret = amdgpu_bo_create_kernel(adev, fb_size, PAGE_SIZE,
2920 		AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT,
2921 		&bootcrc_info->bo_ptr,
2922 		&bootcrc_info->gpu_addr,
2923 		&bootcrc_info->cpu_addr);
2924 
2925 	if (ret) {
2926 		drm_dbg(adev_to_drm(adev), "failed to create boot time crc buffer\n");
2927 	} else {
2928 		bootcrc_info->size = fb_size;
2929 
2930 		drm_dbg(adev_to_drm(adev), "boot time crc buffer created addr 0x%llx, size %u\n",
2931 			bootcrc_info->gpu_addr, bootcrc_info->size);
2932 
2933 		/* Send the buffer info to DMUB */
2934 		dc_dmub_srv_boot_time_crc_init(adev->dm.dc,
2935 			bootcrc_info->gpu_addr, bootcrc_info->size);
2936 	}
2937 }
2938 
2939 static int dm_late_init(struct amdgpu_ip_block *ip_block)
2940 {
2941 	struct amdgpu_device *adev = ip_block->adev;
2942 
2943 	struct dmcu_iram_parameters params;
2944 	unsigned int linear_lut[16];
2945 	int i;
2946 	struct dmcu *dmcu = NULL;
2947 
2948 	dmcu = adev->dm.dc->res_pool->dmcu;
2949 
2950 	/* Init the boot time CRC (skip in resume) */
2951 	if ((adev->in_suspend == 0) &&
2952 		(amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(3, 6, 0)))
2953 		amdgpu_dm_boot_time_crc_init(adev);
2954 
2955 	for (i = 0; i < 16; i++)
2956 		linear_lut[i] = 0xFFFF * i / 15;
2957 
2958 	params.set = 0;
2959 	params.backlight_ramping_override = false;
2960 	params.backlight_ramping_start = 0xCCCC;
2961 	params.backlight_ramping_reduction = 0xCCCCCCCC;
2962 	params.backlight_lut_array_size = 16;
2963 	params.backlight_lut_array = linear_lut;
2964 
2965 	/* Min backlight level after ABM reduction,  Don't allow below 1%
2966 	 * 0xFFFF x 0.01 = 0x28F
2967 	 */
2968 	params.min_abm_backlight = 0x28F;
2969 	/* In the case where abm is implemented on dmcub,
2970 	 * dmcu object will be null.
2971 	 * ABM 2.4 and up are implemented on dmcub.
2972 	 */
2973 	if (dmcu) {
2974 		if (!dmcu_load_iram(dmcu, params))
2975 			return -EINVAL;
2976 	} else if (adev->dm.dc->ctx->dmub_srv) {
2977 		struct dc_link *edp_links[MAX_NUM_EDP];
2978 		int edp_num;
2979 
2980 		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
2981 		for (i = 0; i < edp_num; i++) {
2982 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
2983 				return -EINVAL;
2984 		}
2985 	}
2986 
2987 	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
2988 }
2989 
2990 static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
2991 {
2992 	u8 buf[UUID_SIZE];
2993 	guid_t guid;
2994 	int ret;
2995 
2996 	mutex_lock(&mgr->lock);
2997 	if (!mgr->mst_primary)
2998 		goto out_fail;
2999 
3000 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
3001 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
3002 		goto out_fail;
3003 	}
3004 
3005 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
3006 				 DP_MST_EN |
3007 				 DP_UP_REQ_EN |
3008 				 DP_UPSTREAM_IS_SRC);
3009 	if (ret < 0) {
3010 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
3011 		goto out_fail;
3012 	}
3013 
3014 	/* Some hubs forget their guids after they resume */
3015 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, buf, sizeof(buf));
3016 	if (ret != sizeof(buf)) {
3017 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
3018 		goto out_fail;
3019 	}
3020 
3021 	import_guid(&guid, buf);
3022 
3023 	if (guid_is_null(&guid)) {
3024 		guid_gen(&guid);
3025 		export_guid(buf, &guid);
3026 
3027 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, buf, sizeof(buf));
3028 
3029 		if (ret != sizeof(buf)) {
3030 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
3031 			goto out_fail;
3032 		}
3033 	}
3034 
3035 	guid_copy(&mgr->mst_primary->guid, &guid);
3036 
3037 out_fail:
3038 	mutex_unlock(&mgr->lock);
3039 }
3040 
3041 void hdmi_cec_unset_edid(struct amdgpu_dm_connector *aconnector)
3042 {
3043 	struct cec_notifier *n = aconnector->notifier;
3044 
3045 	if (!n)
3046 		return;
3047 
3048 	cec_notifier_phys_addr_invalidate(n);
3049 }
3050 
3051 void hdmi_cec_set_edid(struct amdgpu_dm_connector *aconnector)
3052 {
3053 	struct drm_connector *connector = &aconnector->base;
3054 	struct cec_notifier *n = aconnector->notifier;
3055 
3056 	if (!n)
3057 		return;
3058 
3059 	cec_notifier_set_phys_addr(n,
3060 				   connector->display_info.source_physical_address);
3061 }
3062 
3063 static void s3_handle_hdmi_cec(struct drm_device *ddev, bool suspend)
3064 {
3065 	struct amdgpu_dm_connector *aconnector;
3066 	struct drm_connector *connector;
3067 	struct drm_connector_list_iter conn_iter;
3068 
3069 	drm_connector_list_iter_begin(ddev, &conn_iter);
3070 	drm_for_each_connector_iter(connector, &conn_iter) {
3071 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3072 			continue;
3073 
3074 		aconnector = to_amdgpu_dm_connector(connector);
3075 		if (suspend)
3076 			hdmi_cec_unset_edid(aconnector);
3077 		else
3078 			hdmi_cec_set_edid(aconnector);
3079 	}
3080 	drm_connector_list_iter_end(&conn_iter);
3081 }
3082 
3083 static void s3_handle_mst(struct drm_device *dev, bool suspend)
3084 {
3085 	struct amdgpu_dm_connector *aconnector;
3086 	struct drm_connector *connector;
3087 	struct drm_connector_list_iter iter;
3088 	struct drm_dp_mst_topology_mgr *mgr;
3089 
3090 	drm_connector_list_iter_begin(dev, &iter);
3091 	drm_for_each_connector_iter(connector, &iter) {
3092 
3093 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3094 			continue;
3095 
3096 		aconnector = to_amdgpu_dm_connector(connector);
3097 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3098 		    aconnector->mst_root)
3099 			continue;
3100 
3101 		mgr = &aconnector->mst_mgr;
3102 
3103 		if (suspend) {
3104 			drm_dp_mst_topology_mgr_suspend(mgr);
3105 		} else {
3106 			/* if extended timeout is supported in hardware,
3107 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
3108 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
3109 			 */
3110 			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
3111 			if (!dp_is_lttpr_present(aconnector->dc_link))
3112 				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
3113 
3114 			/* TODO: move resume_mst_branch_status() into drm mst resume again
3115 			 * once topology probing work is pulled out from mst resume into mst
3116 			 * resume 2nd step. mst resume 2nd step should be called after old
3117 			 * state getting restored (i.e. drm_atomic_helper_resume()).
3118 			 */
3119 			resume_mst_branch_status(mgr);
3120 		}
3121 	}
3122 	drm_connector_list_iter_end(&iter);
3123 }
3124 
3125 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
3126 {
3127 	int ret = 0;
3128 
3129 	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
3130 	 * on window driver dc implementation.
3131 	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
3132 	 * should be passed to smu during boot up and resume from s3.
3133 	 * boot up: dc calculate dcn watermark clock settings within dc_create,
3134 	 * dcn20_resource_construct
3135 	 * then call pplib functions below to pass the settings to smu:
3136 	 * smu_set_watermarks_for_clock_ranges
3137 	 * smu_set_watermarks_table
3138 	 * navi10_set_watermarks_table
3139 	 * smu_write_watermarks_table
3140 	 *
3141 	 * For Renoir, clock settings of dcn watermark are also fixed values.
3142 	 * dc has implemented different flow for window driver:
3143 	 * dc_hardware_init / dc_set_power_state
3144 	 * dcn10_init_hw
3145 	 * notify_wm_ranges
3146 	 * set_wm_ranges
3147 	 * -- Linux
3148 	 * smu_set_watermarks_for_clock_ranges
3149 	 * renoir_set_watermarks_table
3150 	 * smu_write_watermarks_table
3151 	 *
3152 	 * For Linux,
3153 	 * dc_hardware_init -> amdgpu_dm_init
3154 	 * dc_set_power_state --> dm_resume
3155 	 *
3156 	 * therefore, this function apply to navi10/12/14 but not Renoir
3157 	 * *
3158 	 */
3159 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
3160 	case IP_VERSION(2, 0, 2):
3161 	case IP_VERSION(2, 0, 0):
3162 		break;
3163 	default:
3164 		return 0;
3165 	}
3166 
3167 	ret = amdgpu_dpm_write_watermarks_table(adev);
3168 	if (ret) {
3169 		drm_err(adev_to_drm(adev), "Failed to update WMTABLE!\n");
3170 		return ret;
3171 	}
3172 
3173 	return 0;
3174 }
3175 
3176 static int dm_oem_i2c_hw_init(struct amdgpu_device *adev)
3177 {
3178 	struct amdgpu_display_manager *dm = &adev->dm;
3179 	struct amdgpu_i2c_adapter *oem_i2c;
3180 	struct ddc_service *oem_ddc_service;
3181 	int r;
3182 
3183 	oem_ddc_service = dc_get_oem_i2c_device(adev->dm.dc);
3184 	if (oem_ddc_service) {
3185 		oem_i2c = create_i2c(oem_ddc_service, true);
3186 		if (!oem_i2c) {
3187 			drm_info(adev_to_drm(adev), "Failed to create oem i2c adapter data\n");
3188 			return -ENOMEM;
3189 		}
3190 
3191 		r = devm_i2c_add_adapter(adev->dev, &oem_i2c->base);
3192 		if (r) {
3193 			drm_info(adev_to_drm(adev), "Failed to register oem i2c\n");
3194 			kfree(oem_i2c);
3195 			return r;
3196 		}
3197 		dm->oem_i2c = oem_i2c;
3198 	}
3199 
3200 	return 0;
3201 }
3202 
3203 /**
3204  * dm_hw_init() - Initialize DC device
3205  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3206  *
3207  * Initialize the &struct amdgpu_display_manager device. This involves calling
3208  * the initializers of each DM component, then populating the struct with them.
3209  *
3210  * Although the function implies hardware initialization, both hardware and
3211  * software are initialized here. Splitting them out to their relevant init
3212  * hooks is a future TODO item.
3213  *
3214  * Some notable things that are initialized here:
3215  *
3216  * - Display Core, both software and hardware
3217  * - DC modules that we need (freesync and color management)
3218  * - DRM software states
3219  * - Interrupt sources and handlers
3220  * - Vblank support
3221  * - Debug FS entries, if enabled
3222  */
3223 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
3224 {
3225 	struct amdgpu_device *adev = ip_block->adev;
3226 	int r;
3227 
3228 	/* Create DAL display manager */
3229 	r = amdgpu_dm_init(adev);
3230 	if (r)
3231 		return r;
3232 	amdgpu_dm_hpd_init(adev);
3233 
3234 	r = dm_oem_i2c_hw_init(adev);
3235 	if (r)
3236 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
3237 
3238 	return 0;
3239 }
3240 
3241 /**
3242  * dm_hw_fini() - Teardown DC device
3243  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3244  *
3245  * Teardown components within &struct amdgpu_display_manager that require
3246  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
3247  * were loaded. Also flush IRQ workqueues and disable them.
3248  */
3249 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
3250 {
3251 	struct amdgpu_device *adev = ip_block->adev;
3252 
3253 	amdgpu_dm_hpd_fini(adev);
3254 
3255 	amdgpu_dm_irq_fini(adev);
3256 	amdgpu_dm_fini(adev);
3257 	return 0;
3258 }
3259 
3260 
3261 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
3262 				 struct dc_state *state, bool enable)
3263 {
3264 	enum dc_irq_source irq_source;
3265 	struct amdgpu_crtc *acrtc;
3266 	int rc = -EBUSY;
3267 	int i = 0;
3268 
3269 	for (i = 0; i < state->stream_count; i++) {
3270 		acrtc = get_crtc_by_otg_inst(
3271 				adev, state->stream_status[i].primary_otg_inst);
3272 
3273 		if (acrtc && state->stream_status[i].plane_count != 0) {
3274 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
3275 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3276 			if (rc)
3277 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
3278 					 enable ? "enable" : "disable");
3279 
3280 			if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
3281 				if (enable) {
3282 					if (amdgpu_dm_crtc_vrr_active(
3283 							to_dm_crtc_state(acrtc->base.state)))
3284 						rc = amdgpu_dm_crtc_set_vupdate_irq(
3285 							&acrtc->base, true);
3286 				} else
3287 					rc = amdgpu_dm_crtc_set_vupdate_irq(
3288 							&acrtc->base, false);
3289 
3290 				if (rc)
3291 					drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
3292 						enable ? "en" : "dis");
3293 			}
3294 
3295 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3296 			/* During gpu-reset we disable and then enable vblank irq, so
3297 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
3298 			 */
3299 			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
3300 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
3301 		}
3302 	}
3303 
3304 }
3305 
3306 DEFINE_FREE(state_release, struct dc_state *, if (_T) dc_state_release(_T))
3307 
3308 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
3309 {
3310 	struct dc_state *context __free(state_release) = NULL;
3311 	int i;
3312 	struct dc_stream_state *del_streams[MAX_PIPES];
3313 	int del_streams_count = 0;
3314 	struct dc_commit_streams_params params = {};
3315 
3316 	memset(del_streams, 0, sizeof(del_streams));
3317 
3318 	context = dc_state_create_current_copy(dc);
3319 	if (context == NULL)
3320 		return DC_ERROR_UNEXPECTED;
3321 
3322 	/* First remove from context all streams */
3323 	for (i = 0; i < context->stream_count; i++) {
3324 		struct dc_stream_state *stream = context->streams[i];
3325 
3326 		del_streams[del_streams_count++] = stream;
3327 	}
3328 
3329 	/* Remove all planes for removed streams and then remove the streams */
3330 	for (i = 0; i < del_streams_count; i++) {
3331 		enum dc_status res;
3332 
3333 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
3334 			return DC_FAIL_DETACH_SURFACES;
3335 
3336 		res = dc_state_remove_stream(dc, context, del_streams[i]);
3337 		if (res != DC_OK)
3338 			return res;
3339 	}
3340 
3341 	params.streams = context->streams;
3342 	params.stream_count = context->stream_count;
3343 
3344 	return dc_commit_streams(dc, &params);
3345 }
3346 
3347 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
3348 {
3349 	int i;
3350 
3351 	if (dm->hpd_rx_offload_wq) {
3352 		for (i = 0; i < dm->dc->caps.max_links; i++)
3353 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
3354 	}
3355 }
3356 
3357 static int dm_cache_state(struct amdgpu_device *adev)
3358 {
3359 	int r;
3360 
3361 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
3362 	if (IS_ERR(adev->dm.cached_state)) {
3363 		r = PTR_ERR(adev->dm.cached_state);
3364 		adev->dm.cached_state = NULL;
3365 	}
3366 
3367 	return adev->dm.cached_state ? 0 : r;
3368 }
3369 
3370 static void dm_destroy_cached_state(struct amdgpu_device *adev)
3371 {
3372 	struct amdgpu_display_manager *dm = &adev->dm;
3373 	struct drm_device *ddev = adev_to_drm(adev);
3374 	struct dm_plane_state *dm_new_plane_state;
3375 	struct drm_plane_state *new_plane_state;
3376 	struct dm_crtc_state *dm_new_crtc_state;
3377 	struct drm_crtc_state *new_crtc_state;
3378 	struct drm_plane *plane;
3379 	struct drm_crtc *crtc;
3380 	int i;
3381 
3382 	if (!dm->cached_state)
3383 		return;
3384 
3385 	/* Force mode set in atomic commit */
3386 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3387 		new_crtc_state->active_changed = true;
3388 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3389 		reset_freesync_config_for_crtc(dm_new_crtc_state);
3390 	}
3391 
3392 	/*
3393 	 * atomic_check is expected to create the dc states. We need to release
3394 	 * them here, since they were duplicated as part of the suspend
3395 	 * procedure.
3396 	 */
3397 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3398 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3399 		if (dm_new_crtc_state->stream) {
3400 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
3401 			dc_stream_release(dm_new_crtc_state->stream);
3402 			dm_new_crtc_state->stream = NULL;
3403 		}
3404 		dm_new_crtc_state->base.color_mgmt_changed = true;
3405 	}
3406 
3407 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
3408 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
3409 		if (dm_new_plane_state->dc_state) {
3410 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
3411 			dc_plane_state_release(dm_new_plane_state->dc_state);
3412 			dm_new_plane_state->dc_state = NULL;
3413 		}
3414 	}
3415 
3416 	drm_atomic_helper_resume(ddev, dm->cached_state);
3417 
3418 	dm->cached_state = NULL;
3419 }
3420 
3421 static int dm_suspend(struct amdgpu_ip_block *ip_block)
3422 {
3423 	struct amdgpu_device *adev = ip_block->adev;
3424 	struct amdgpu_display_manager *dm = &adev->dm;
3425 
3426 	if (amdgpu_in_reset(adev)) {
3427 		enum dc_status res;
3428 
3429 		/* Quiesce ISM workers before taking dc_lock (workers take
3430 		 * dc_lock themselves; syncing under it would deadlock).
3431 		 */
3432 		amdgpu_dm_ism_disable(dm);
3433 
3434 		mutex_lock(&dm->dc_lock);
3435 
3436 		amdgpu_dm_ism_force_full_power(dm);
3437 		dc_allow_idle_optimizations(adev->dm.dc, false);
3438 
3439 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
3440 
3441 		if (dm->cached_dc_state)
3442 			dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
3443 
3444 		res = amdgpu_dm_commit_zero_streams(dm->dc);
3445 		if (res != DC_OK) {
3446 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
3447 			return -EINVAL;
3448 		}
3449 
3450 		amdgpu_dm_irq_suspend(adev);
3451 
3452 		hpd_rx_irq_work_suspend(dm);
3453 
3454 		return 0;
3455 	}
3456 
3457 	if (!adev->dm.cached_state) {
3458 		int r = dm_cache_state(adev);
3459 
3460 		if (r)
3461 			return r;
3462 	}
3463 
3464 	s3_handle_hdmi_cec(adev_to_drm(adev), true);
3465 
3466 	s3_handle_mst(adev_to_drm(adev), true);
3467 
3468 	amdgpu_dm_irq_suspend(adev);
3469 
3470 	/*
3471 	 * Quiesce ISM workers before taking dc_lock (workers take dc_lock
3472 	 * themselves; syncing under it would deadlock).
3473 	 */
3474 	amdgpu_dm_ism_disable(dm);
3475 	scoped_guard(mutex, &dm->dc_lock)
3476 		amdgpu_dm_ism_force_full_power(dm);
3477 
3478 	hpd_rx_irq_work_suspend(dm);
3479 
3480 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
3481 
3482 	if (dm->dc->caps.ips_support && adev->in_s0ix)
3483 		dc_allow_idle_optimizations(dm->dc, true);
3484 
3485 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
3486 
3487 	return 0;
3488 }
3489 
3490 struct drm_connector *
3491 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_commit *state,
3492 					     struct drm_crtc *crtc)
3493 {
3494 	u32 i;
3495 	struct drm_connector_state *new_con_state;
3496 	struct drm_connector *connector;
3497 	struct drm_crtc *crtc_from_state;
3498 
3499 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3500 		crtc_from_state = new_con_state->crtc;
3501 
3502 		if (crtc_from_state == crtc)
3503 			return connector;
3504 	}
3505 
3506 	return NULL;
3507 }
3508 
3509 static void emulated_link_detect(struct dc_link *link)
3510 {
3511 	struct dc_sink_init_data sink_init_data = { 0 };
3512 	struct display_sink_capability sink_caps = { 0 };
3513 	enum dc_edid_status edid_status;
3514 	struct dc_context *dc_ctx = link->ctx;
3515 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
3516 	struct dc_sink *sink = NULL;
3517 	struct dc_sink *prev_sink = NULL;
3518 
3519 	link->type = dc_connection_none;
3520 	prev_sink = link->local_sink;
3521 
3522 	if (prev_sink)
3523 		dc_sink_release(prev_sink);
3524 
3525 	switch (link->connector_signal) {
3526 	case SIGNAL_TYPE_HDMI_TYPE_A: {
3527 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3528 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
3529 		break;
3530 	}
3531 
3532 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
3533 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3534 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
3535 		break;
3536 	}
3537 
3538 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
3539 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3540 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
3541 		break;
3542 	}
3543 
3544 	case SIGNAL_TYPE_LVDS: {
3545 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3546 		sink_caps.signal = SIGNAL_TYPE_LVDS;
3547 		break;
3548 	}
3549 
3550 	case SIGNAL_TYPE_EDP: {
3551 		sink_caps.transaction_type =
3552 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3553 		sink_caps.signal = SIGNAL_TYPE_EDP;
3554 		break;
3555 	}
3556 
3557 	case SIGNAL_TYPE_DISPLAY_PORT: {
3558 		sink_caps.transaction_type =
3559 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3560 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
3561 		break;
3562 	}
3563 
3564 	default:
3565 		drm_err(dev, "Invalid connector type! signal:%d\n",
3566 			link->connector_signal);
3567 		return;
3568 	}
3569 
3570 	sink_init_data.link = link;
3571 	sink_init_data.sink_signal = sink_caps.signal;
3572 
3573 	sink = dc_sink_create(&sink_init_data);
3574 	if (!sink) {
3575 		drm_err(dev, "Failed to create sink!\n");
3576 		return;
3577 	}
3578 
3579 	/* dc_sink_create returns a new reference */
3580 	link->local_sink = sink;
3581 
3582 	edid_status = dm_helpers_read_local_edid(
3583 			link->ctx,
3584 			link,
3585 			sink);
3586 
3587 	if (edid_status != EDID_OK)
3588 		drm_err(dev, "Failed to read EDID\n");
3589 
3590 }
3591 
3592 static void dm_gpureset_commit_state(struct dc_state *dc_state,
3593 				     struct amdgpu_display_manager *dm)
3594 {
3595 	struct {
3596 		struct dc_surface_update surface_updates[MAX_SURFACES];
3597 		struct dc_plane_info plane_infos[MAX_SURFACES];
3598 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3599 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3600 		struct dc_stream_update stream_update;
3601 	} *bundle __free(kfree);
3602 	int k, m;
3603 
3604 	bundle = kzalloc_obj(*bundle);
3605 
3606 	if (!bundle) {
3607 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
3608 		return;
3609 	}
3610 
3611 	for (k = 0; k < dc_state->stream_count; k++) {
3612 		bundle->stream_update.stream = dc_state->streams[k];
3613 
3614 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
3615 			bundle->surface_updates[m].surface =
3616 				dc_state->stream_status[k].plane_states[m];
3617 			bundle->surface_updates[m].surface->force_full_update =
3618 				true;
3619 		}
3620 
3621 		update_planes_and_stream_adapter(dm->dc,
3622 					 UPDATE_TYPE_FULL,
3623 					 dc_state->stream_status[k].plane_count,
3624 					 dc_state->streams[k],
3625 					 &bundle->stream_update,
3626 					 bundle->surface_updates);
3627 	}
3628 }
3629 
3630 static void apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
3631 					    struct dc_sink *sink)
3632 {
3633 	struct dc_panel_patch *ppatch = NULL;
3634 
3635 	if (!sink)
3636 		return;
3637 
3638 	ppatch = &sink->edid_caps.panel_patch;
3639 	if (ppatch->wait_after_dpcd_poweroff_ms) {
3640 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
3641 		drm_dbg_driver(adev_to_drm(adev),
3642 			       "%s: adding a %ds delay as w/a for panel\n",
3643 			       __func__,
3644 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
3645 	}
3646 }
3647 
3648 /**
3649  * amdgpu_dm_dump_links_and_sinks - Debug dump of all DC links and their sinks
3650  * @adev: amdgpu device pointer
3651  *
3652  * Iterates through all DC links and dumps information about local and remote
3653  * (MST) sinks. Should be called after connector detection is complete to see
3654  * the final state of all links.
3655  */
3656 static void amdgpu_dm_dump_links_and_sinks(struct amdgpu_device *adev)
3657 {
3658 	struct dc *dc = adev->dm.dc;
3659 	struct drm_device *dev = adev_to_drm(adev);
3660 	int li;
3661 
3662 	if (!dc)
3663 		return;
3664 
3665 	for (li = 0; li < dc->link_count; li++) {
3666 		struct dc_link *l = dc->links[li];
3667 		const char *name = NULL;
3668 		int rs;
3669 
3670 		if (!l)
3671 			continue;
3672 		if (l->local_sink && l->local_sink->edid_caps.display_name[0])
3673 			name = l->local_sink->edid_caps.display_name;
3674 		else
3675 			name = "n/a";
3676 
3677 		drm_dbg_kms(dev,
3678 			"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",
3679 			li,
3680 			l->local_sink,
3681 			l->type,
3682 			l->local_sink ? l->local_sink->sink_signal : SIGNAL_TYPE_NONE,
3683 			l->sink_count,
3684 			name,
3685 			l->dpcd_caps.is_mst_capable,
3686 			l->mst_stream_alloc_table.stream_count);
3687 
3688 		/* Dump remote (MST) sinks if any */
3689 		for (rs = 0; rs < l->sink_count; rs++) {
3690 			struct dc_sink *rsink = l->remote_sinks[rs];
3691 			const char *rname = NULL;
3692 
3693 			if (!rsink)
3694 				continue;
3695 			if (rsink->edid_caps.display_name[0])
3696 				rname = rsink->edid_caps.display_name;
3697 			else
3698 				rname = "n/a";
3699 			drm_dbg_kms(dev,
3700 				"  REMOTE_SINK[%d:%d]: sink=%p signal=%d edid_name=%s\n",
3701 				li, rs,
3702 				rsink,
3703 				rsink->sink_signal,
3704 				rname);
3705 		}
3706 	}
3707 }
3708 
3709 static int dm_resume(struct amdgpu_ip_block *ip_block)
3710 {
3711 	struct amdgpu_device *adev = ip_block->adev;
3712 	struct drm_device *ddev = adev_to_drm(adev);
3713 	struct amdgpu_display_manager *dm = &adev->dm;
3714 	struct amdgpu_dm_connector *aconnector;
3715 	struct drm_connector *connector;
3716 	struct drm_connector_list_iter iter;
3717 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
3718 	enum dc_connection_type new_connection_type = dc_connection_none;
3719 	struct dc_state *dc_state;
3720 	int i, r, j;
3721 	struct dc_commit_streams_params commit_params = {};
3722 
3723 	if (dm->dc->caps.ips_support) {
3724 		if (!amdgpu_in_reset(adev))
3725 			mutex_lock(&dm->dc_lock);
3726 
3727 		/* Need to set POWER_STATE_D0 first or it will not execute
3728 		 * idle_power_optimizations command to DMUB.
3729 		 */
3730 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3731 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
3732 
3733 		if (!amdgpu_in_reset(adev))
3734 			mutex_unlock(&dm->dc_lock);
3735 	}
3736 
3737 	if (amdgpu_in_reset(adev)) {
3738 		dc_state = dm->cached_dc_state;
3739 
3740 		/*
3741 		 * The dc->current_state is backed up into dm->cached_dc_state
3742 		 * before we commit 0 streams.
3743 		 *
3744 		 * DC will clear link encoder assignments on the real state
3745 		 * but the changes won't propagate over to the copy we made
3746 		 * before the 0 streams commit.
3747 		 *
3748 		 * DC expects that link encoder assignments are *not* valid
3749 		 * when committing a state, so as a workaround we can copy
3750 		 * off of the current state.
3751 		 *
3752 		 * We lose the previous assignments, but we had already
3753 		 * commit 0 streams anyway.
3754 		 */
3755 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
3756 
3757 		r = dm_dmub_hw_init(adev);
3758 		if (r) {
3759 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
3760 			return r;
3761 		}
3762 
3763 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3764 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3765 
3766 		dc_resume(dm->dc);
3767 
3768 		amdgpu_dm_ism_enable(dm);
3769 		amdgpu_dm_irq_resume_early(adev);
3770 
3771 		for (i = 0; i < dc_state->stream_count; i++) {
3772 			dc_state->streams[i]->mode_changed = true;
3773 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
3774 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
3775 					= 0xffffffff;
3776 			}
3777 		}
3778 
3779 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3780 			amdgpu_dm_outbox_init(adev);
3781 			dc_enable_dmub_outbox(adev->dm.dc);
3782 		}
3783 
3784 		commit_params.streams = dc_state->streams;
3785 		commit_params.stream_count = dc_state->stream_count;
3786 		dc_exit_ips_for_hw_access(dm->dc);
3787 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
3788 
3789 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
3790 
3791 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
3792 
3793 		dc_state_release(dm->cached_dc_state);
3794 		dm->cached_dc_state = NULL;
3795 
3796 		amdgpu_dm_irq_resume_late(adev);
3797 
3798 		mutex_unlock(&dm->dc_lock);
3799 
3800 		/* set the backlight after a reset */
3801 		for (i = 0; i < dm->num_of_edps; i++) {
3802 			if (dm->backlight_dev[i])
3803 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
3804 		}
3805 
3806 		return 0;
3807 	}
3808 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
3809 	dc_state_release(dm_state->context);
3810 	dm_state->context = dc_state_create(dm->dc, NULL);
3811 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
3812 
3813 	/* Before powering on DC we need to re-initialize DMUB. */
3814 	dm_dmub_hw_resume(adev);
3815 
3816 	/* Re-enable outbox interrupts for DPIA. */
3817 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3818 		amdgpu_dm_outbox_init(adev);
3819 		dc_enable_dmub_outbox(adev->dm.dc);
3820 	}
3821 
3822 	/* power on hardware */
3823 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3824 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3825 
3826 	/* program HPD filter */
3827 	dc_resume(dm->dc);
3828 
3829 	scoped_guard(mutex, &dm->dc_lock)
3830 		amdgpu_dm_ism_enable(dm);
3831 
3832 	/*
3833 	 * early enable HPD Rx IRQ, should be done before set mode as short
3834 	 * pulse interrupts are used for MST
3835 	 */
3836 	amdgpu_dm_irq_resume_early(adev);
3837 
3838 	s3_handle_hdmi_cec(ddev, false);
3839 
3840 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
3841 	s3_handle_mst(ddev, false);
3842 
3843 	/* Do detection*/
3844 	drm_connector_list_iter_begin(ddev, &iter);
3845 	drm_for_each_connector_iter(connector, &iter) {
3846 		bool ret;
3847 
3848 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3849 			continue;
3850 
3851 		aconnector = to_amdgpu_dm_connector(connector);
3852 
3853 		if (!aconnector->dc_link)
3854 			continue;
3855 
3856 		/*
3857 		 * this is the case when traversing through already created end sink
3858 		 * MST connectors, should be skipped
3859 		 */
3860 		if (aconnector->mst_root)
3861 			continue;
3862 
3863 		/* Skip eDP detection, when there is no sink present */
3864 		if (aconnector->dc_link->connector_signal == SIGNAL_TYPE_EDP &&
3865 		    !aconnector->dc_link->edp_sink_present)
3866 			continue;
3867 
3868 		guard(mutex)(&aconnector->hpd_lock);
3869 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3870 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3871 
3872 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3873 			emulated_link_detect(aconnector->dc_link);
3874 		} else {
3875 			guard(mutex)(&dm->dc_lock);
3876 			dc_exit_ips_for_hw_access(dm->dc);
3877 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
3878 			if (ret) {
3879 				/* w/a delay for certain panels */
3880 				apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3881 			}
3882 		}
3883 
3884 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
3885 			aconnector->fake_enable = false;
3886 
3887 		if (aconnector->dc_sink)
3888 			dc_sink_release(aconnector->dc_sink);
3889 		aconnector->dc_sink = NULL;
3890 		amdgpu_dm_update_connector_after_detect(aconnector);
3891 	}
3892 	drm_connector_list_iter_end(&iter);
3893 
3894 	dm_destroy_cached_state(adev);
3895 
3896 	/* Do mst topology probing after resuming cached state*/
3897 	drm_connector_list_iter_begin(ddev, &iter);
3898 	drm_for_each_connector_iter(connector, &iter) {
3899 		bool init = false;
3900 
3901 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3902 			continue;
3903 
3904 		aconnector = to_amdgpu_dm_connector(connector);
3905 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3906 		    aconnector->mst_root)
3907 			continue;
3908 
3909 		scoped_guard(mutex, &aconnector->mst_mgr.lock) {
3910 			init = !aconnector->mst_mgr.mst_primary;
3911 		}
3912 		if (init)
3913 			dm_helpers_dp_mst_start_top_mgr(aconnector->dc_link->ctx,
3914 				aconnector->dc_link, false);
3915 		else
3916 			drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
3917 	}
3918 	drm_connector_list_iter_end(&iter);
3919 
3920 	/* Debug dump: list all DC links and their associated sinks after detection
3921 	 * is complete for all connectors. This provides a comprehensive view of the
3922 	 * final state without repeating the dump for each connector.
3923 	 */
3924 	amdgpu_dm_dump_links_and_sinks(adev);
3925 
3926 	amdgpu_dm_irq_resume_late(adev);
3927 
3928 	amdgpu_dm_smu_write_watermarks_table(adev);
3929 
3930 	drm_kms_helper_hotplug_event(ddev);
3931 
3932 	return 0;
3933 }
3934 
3935 /**
3936  * DOC: DM Lifecycle
3937  *
3938  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
3939  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
3940  * the base driver's device list to be initialized and torn down accordingly.
3941  *
3942  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
3943  */
3944 
3945 static const struct amd_ip_funcs amdgpu_dm_funcs = {
3946 	.name = "dm",
3947 	.early_init = dm_early_init,
3948 	.late_init = dm_late_init,
3949 	.sw_init = dm_sw_init,
3950 	.sw_fini = dm_sw_fini,
3951 	.early_fini = amdgpu_dm_early_fini,
3952 	.hw_init = dm_hw_init,
3953 	.hw_fini = dm_hw_fini,
3954 	.suspend = dm_suspend,
3955 	.resume = dm_resume,
3956 	.is_idle = dm_is_idle,
3957 	.wait_for_idle = dm_wait_for_idle,
3958 	.check_soft_reset = dm_check_soft_reset,
3959 	.soft_reset = dm_soft_reset,
3960 	.set_clockgating_state = dm_set_clockgating_state,
3961 	.set_powergating_state = dm_set_powergating_state,
3962 };
3963 
3964 const struct amdgpu_ip_block_version dm_ip_block = {
3965 	.type = AMD_IP_BLOCK_TYPE_DCE,
3966 	.major = 1,
3967 	.minor = 0,
3968 	.rev = 0,
3969 	.funcs = &amdgpu_dm_funcs,
3970 };
3971 
3972 
3973 /**
3974  * DOC: atomic
3975  *
3976  * *WIP*
3977  */
3978 
3979 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
3980 	.fb_create = amdgpu_display_user_framebuffer_create,
3981 	.get_format_info = amdgpu_dm_plane_get_format_info,
3982 	.atomic_check = amdgpu_dm_atomic_check,
3983 	.atomic_commit = drm_atomic_helper_commit,
3984 };
3985 
3986 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
3987 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
3988 	.atomic_commit_setup = amdgpu_dm_atomic_setup_commit,
3989 };
3990 
3991 #define DDC_MANUFACTURERNAME_SAMSUNG 0x2D4C
3992 
3993 static void dm_set_panel_type(struct amdgpu_dm_connector *aconnector)
3994 {
3995 	struct drm_connector *connector = &aconnector->base;
3996 	struct drm_display_info *display_info = &connector->display_info;
3997 	struct dc_link *link = aconnector->dc_link;
3998 	struct amdgpu_device *adev;
3999 
4000 	adev = drm_to_adev(connector->dev);
4001 
4002 	link->panel_type = PANEL_TYPE_NONE;
4003 
4004 	switch (display_info->amd_vsdb.panel_type) {
4005 	case AMD_VSDB_PANEL_TYPE_OLED:
4006 		link->panel_type = PANEL_TYPE_OLED;
4007 		break;
4008 	case AMD_VSDB_PANEL_TYPE_MINILED:
4009 		link->panel_type = PANEL_TYPE_MINILED;
4010 		break;
4011 	}
4012 
4013 	/* If VSDB didn't determine panel type, check DPCD ext caps */
4014 	if (link->panel_type == PANEL_TYPE_NONE) {
4015 		if (link->dpcd_sink_ext_caps.bits.miniled == 1)
4016 			link->panel_type = PANEL_TYPE_MINILED;
4017 		if (link->dpcd_sink_ext_caps.bits.oled == 1)
4018 			link->panel_type = PANEL_TYPE_OLED;
4019 	}
4020 
4021 	/*
4022 	 * TODO: get panel type from DID2 that has device technology field
4023 	 * to specify if it's OLED or not. But we need to wait for DID2
4024 	 * support in DC and EDID parser to be able to use it here.
4025 	 */
4026 
4027 	if (link->panel_type == PANEL_TYPE_NONE) {
4028 		struct drm_amd_vsdb_info *vsdb = &display_info->amd_vsdb;
4029 		u32 lum1_max = vsdb->luminance_range1.max_luminance;
4030 		u32 lum2_max = vsdb->luminance_range2.max_luminance;
4031 
4032 		if (vsdb->version && link->local_sink &&
4033 		    link->local_sink->edid_caps.manufacturer_id ==
4034 		    DDC_MANUFACTURERNAME_SAMSUNG &&
4035 		    lum1_max >= ((lum2_max * 3) / 2))
4036 			link->panel_type = PANEL_TYPE_MINILED;
4037 	}
4038 
4039 	if (link->panel_type == PANEL_TYPE_OLED)
4040 		drm_object_property_set_value(&connector->base,
4041 		    adev_to_drm(adev)->mode_config.panel_type_property,
4042 		    DRM_MODE_PANEL_TYPE_OLED);
4043 	else
4044 		drm_object_property_set_value(&connector->base,
4045 		    adev_to_drm(adev)->mode_config.panel_type_property,
4046 		    DRM_MODE_PANEL_TYPE_UNKNOWN);
4047 
4048 	drm_dbg_kms(aconnector->base.dev, "Panel type: %d\n", link->panel_type);
4049 }
4050 
4051 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
4052 {
4053 	const struct drm_panel_backlight_quirk *panel_backlight_quirk;
4054 	struct amdgpu_dm_backlight_caps *caps;
4055 	struct drm_connector *conn_base;
4056 	struct amdgpu_device *adev;
4057 	struct drm_luminance_range_info *luminance_range;
4058 	struct drm_device *drm;
4059 
4060 	if (aconnector->bl_idx == -1 ||
4061 	    aconnector->dc_link->connector_signal != SIGNAL_TYPE_EDP)
4062 		return;
4063 
4064 	conn_base = &aconnector->base;
4065 	drm = conn_base->dev;
4066 	adev = drm_to_adev(drm);
4067 
4068 	caps = &adev->dm.backlight_caps[aconnector->bl_idx];
4069 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
4070 	caps->aux_support = false;
4071 
4072 	if (caps->ext_caps->bits.oled == 1
4073 	    /*
4074 	     * ||
4075 	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
4076 	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
4077 	     */)
4078 		caps->aux_support = true;
4079 
4080 	if (amdgpu_backlight == 0)
4081 		caps->aux_support = false;
4082 	else if (amdgpu_backlight == 1)
4083 		caps->aux_support = true;
4084 	if (caps->aux_support)
4085 		aconnector->dc_link->backlight_control_type = BACKLIGHT_CONTROL_AMD_AUX;
4086 
4087 	luminance_range = &conn_base->display_info.luminance_range;
4088 
4089 	if (luminance_range->max_luminance)
4090 		caps->aux_max_input_signal = luminance_range->max_luminance;
4091 	else
4092 		caps->aux_max_input_signal = 512;
4093 
4094 	if (luminance_range->min_luminance)
4095 		caps->aux_min_input_signal = luminance_range->min_luminance;
4096 	else
4097 		caps->aux_min_input_signal = 1;
4098 
4099 	panel_backlight_quirk =
4100 		drm_get_panel_backlight_quirk(aconnector->drm_edid);
4101 	if (!IS_ERR_OR_NULL(panel_backlight_quirk)) {
4102 		if (panel_backlight_quirk->min_brightness) {
4103 			caps->min_input_signal =
4104 				panel_backlight_quirk->min_brightness - 1;
4105 			drm_info(drm,
4106 				 "Applying panel backlight quirk, min_brightness: %d\n",
4107 				 caps->min_input_signal);
4108 		}
4109 		if (panel_backlight_quirk->brightness_mask) {
4110 			drm_info(drm,
4111 				 "Applying panel backlight quirk, brightness_mask: 0x%X\n",
4112 				 panel_backlight_quirk->brightness_mask);
4113 			caps->brightness_mask =
4114 				panel_backlight_quirk->brightness_mask;
4115 		}
4116 	}
4117 }
4118 
4119 DEFINE_FREE(sink_release, struct dc_sink *, if (_T) dc_sink_release(_T))
4120 
4121 void amdgpu_dm_update_connector_after_detect(
4122 		struct amdgpu_dm_connector *aconnector)
4123 {
4124 	struct drm_connector *connector = &aconnector->base;
4125 	struct dc_sink *sink __free(sink_release) = NULL;
4126 	struct drm_device *dev = connector->dev;
4127 
4128 	/* MST handled by drm_mst framework */
4129 	if (aconnector->mst_mgr.mst_state == true)
4130 		return;
4131 
4132 	sink = aconnector->dc_link->local_sink;
4133 	if (sink)
4134 		dc_sink_retain(sink);
4135 
4136 	/*
4137 	 * Edid mgmt connector gets first update only in mode_valid hook and then
4138 	 * the connector sink is set to either fake or physical sink depends on link status.
4139 	 * Skip if already done during boot.
4140 	 */
4141 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
4142 			&& aconnector->dc_em_sink) {
4143 
4144 		/*
4145 		 * For S3 resume with headless use eml_sink to fake stream
4146 		 * because on resume connector->sink is set to NULL
4147 		 */
4148 		guard(mutex)(&dev->mode_config.mutex);
4149 
4150 		if (sink) {
4151 			if (aconnector->dc_sink) {
4152 				amdgpu_dm_update_freesync_caps(connector, NULL, true);
4153 				/*
4154 				 * retain and release below are used to
4155 				 * bump up refcount for sink because the link doesn't point
4156 				 * to it anymore after disconnect, so on next crtc to connector
4157 				 * reshuffle by UMD we will get into unwanted dc_sink release
4158 				 */
4159 				dc_sink_release(aconnector->dc_sink);
4160 			}
4161 			aconnector->dc_sink = sink;
4162 			dc_sink_retain(aconnector->dc_sink);
4163 			amdgpu_dm_update_freesync_caps(connector,
4164 					aconnector->drm_edid, true);
4165 		} else {
4166 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4167 			if (!aconnector->dc_sink) {
4168 				aconnector->dc_sink = aconnector->dc_em_sink;
4169 				dc_sink_retain(aconnector->dc_sink);
4170 			}
4171 		}
4172 
4173 		return;
4174 	}
4175 
4176 	/*
4177 	 * TODO: temporary guard to look for proper fix
4178 	 * if this sink is MST sink, we should not do anything
4179 	 */
4180 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
4181 		return;
4182 
4183 	if (aconnector->dc_sink == sink) {
4184 		/*
4185 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
4186 		 * Do nothing!!
4187 		 */
4188 		drm_dbg_kms(dev, "DCHPD: connector_id=%d: dc_sink didn't change.\n",
4189 				 aconnector->connector_id);
4190 		return;
4191 	}
4192 
4193 	drm_dbg_kms(dev, "DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
4194 		    aconnector->connector_id, aconnector->dc_sink, sink);
4195 
4196 	/* When polling, DRM has already locked the mutex for us. */
4197 	if (!drm_kms_helper_is_poll_worker())
4198 		mutex_lock(&dev->mode_config.mutex);
4199 
4200 	/*
4201 	 * 1. Update status of the drm connector
4202 	 * 2. Send an event and let userspace tell us what to do
4203 	 */
4204 	if (sink) {
4205 		/*
4206 		 * TODO: check if we still need the S3 mode update workaround.
4207 		 * If yes, put it here.
4208 		 */
4209 		if (aconnector->dc_sink) {
4210 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4211 			dc_sink_release(aconnector->dc_sink);
4212 		}
4213 
4214 		aconnector->dc_sink = sink;
4215 		dc_sink_retain(aconnector->dc_sink);
4216 		drm_edid_free(aconnector->drm_edid);
4217 		aconnector->drm_edid = NULL;
4218 		if (sink->dc_edid.length == 0) {
4219 			hdmi_cec_unset_edid(aconnector);
4220 			if (aconnector->dc_link->aux_mode) {
4221 				drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4222 			}
4223 		} else {
4224 			const struct edid *edid = (const struct edid *)sink->dc_edid.raw_edid;
4225 
4226 			aconnector->drm_edid = drm_edid_alloc(edid, sink->dc_edid.length);
4227 			drm_edid_connector_update(connector, aconnector->drm_edid);
4228 
4229 			hdmi_cec_set_edid(aconnector);
4230 			if (aconnector->dc_link->aux_mode)
4231 				drm_dp_cec_attach(&aconnector->dm_dp_aux.aux,
4232 						  connector->display_info.source_physical_address);
4233 		}
4234 
4235 		if (!aconnector->timing_requested) {
4236 			aconnector->timing_requested =
4237 				kzalloc_obj(struct dc_crtc_timing);
4238 			if (!aconnector->timing_requested)
4239 				drm_err(dev,
4240 					"failed to create aconnector->requested_timing\n");
4241 		}
4242 
4243 		amdgpu_dm_update_freesync_caps(connector, aconnector->drm_edid, true);
4244 		update_connector_ext_caps(aconnector);
4245 		dm_set_panel_type(aconnector);
4246 	} else {
4247 		hdmi_cec_unset_edid(aconnector);
4248 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4249 		amdgpu_dm_update_freesync_caps(connector, NULL, true);
4250 		aconnector->num_modes = 0;
4251 		dc_sink_release(aconnector->dc_sink);
4252 		aconnector->dc_sink = NULL;
4253 		drm_edid_free(aconnector->drm_edid);
4254 		aconnector->drm_edid = NULL;
4255 		kfree(aconnector->timing_requested);
4256 		aconnector->timing_requested = NULL;
4257 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
4258 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
4259 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
4260 	}
4261 
4262 	update_subconnector_property(aconnector);
4263 
4264 	/* When polling, the mutex will be unlocked for us by DRM. */
4265 	if (!drm_kms_helper_is_poll_worker())
4266 		mutex_unlock(&dev->mode_config.mutex);
4267 }
4268 
4269 static bool are_sinks_equal(const struct dc_sink *sink1, const struct dc_sink *sink2)
4270 {
4271 	if (!sink1 || !sink2)
4272 		return false;
4273 	if (sink1->sink_signal != sink2->sink_signal)
4274 		return false;
4275 
4276 	if (sink1->dc_edid.length != sink2->dc_edid.length)
4277 		return false;
4278 
4279 	if (memcmp(sink1->dc_edid.raw_edid, sink2->dc_edid.raw_edid,
4280 		   sink1->dc_edid.length) != 0)
4281 		return false;
4282 	return true;
4283 }
4284 
4285 
4286 /**
4287  * DOC: hdmi_hpd_debounce_work
4288  *
4289  * HDMI HPD debounce delay in milliseconds. When an HDMI display toggles HPD
4290  * (such as during power save transitions), this delay determines how long to
4291  * wait before processing the HPD event. This allows distinguishing between a
4292  * physical unplug (>hdmi_hpd_debounce_delay)
4293  * and a spontaneous RX HPD toggle (<hdmi_hpd_debounce_delay).
4294  *
4295  * If the toggle is less than this delay, the driver compares sink capabilities
4296  * and permits a hotplug event if they changed.
4297  *
4298  * The default value of 1500ms was chosen based on experimental testing with
4299  * various monitors that exhibit spontaneous HPD toggling behavior.
4300  */
4301 static void hdmi_hpd_debounce_work(struct work_struct *work)
4302 {
4303 	struct amdgpu_dm_connector *aconnector =
4304 		container_of(to_delayed_work(work), struct amdgpu_dm_connector,
4305 			     hdmi_hpd_debounce_work);
4306 	struct drm_connector *connector = &aconnector->base;
4307 	struct drm_device *dev = connector->dev;
4308 	struct amdgpu_device *adev = drm_to_adev(dev);
4309 	struct dc *dc = aconnector->dc_link->ctx->dc;
4310 	bool fake_reconnect = false;
4311 	bool reallow_idle = false;
4312 	bool ret = false;
4313 	guard(mutex)(&aconnector->hpd_lock);
4314 
4315 	/* Re-detect the display */
4316 	scoped_guard(mutex, &adev->dm.dc_lock) {
4317 		if (dc->caps.ips_support && dc->ctx->dmub_srv->idle_allowed) {
4318 			dc_allow_idle_optimizations(dc, false);
4319 			reallow_idle = true;
4320 		}
4321 		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4322 	}
4323 
4324 	if (ret) {
4325 		/* Apply workaround delay for certain panels */
4326 		apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4327 		/* Compare sinks to determine if this was a spontaneous HPD toggle */
4328 		if (are_sinks_equal(aconnector->dc_link->local_sink, aconnector->hdmi_prev_sink)) {
4329 			/*
4330 			* Sinks match - this was a spontaneous HDMI HPD toggle.
4331 			*/
4332 			drm_dbg_kms(dev, "HDMI HPD: Sink unchanged after debounce, internal re-enable\n");
4333 			fake_reconnect = true;
4334 		}
4335 
4336 		/* Update connector state */
4337 		amdgpu_dm_update_connector_after_detect(aconnector);
4338 
4339 		drm_modeset_lock_all(dev);
4340 		dm_restore_drm_connector_state(dev, connector);
4341 		drm_modeset_unlock_all(dev);
4342 
4343 		/* Only notify OS if sink actually changed */
4344 		if (!fake_reconnect && aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4345 			drm_kms_helper_hotplug_event(dev);
4346 	}
4347 
4348 	/* Release the cached sink reference */
4349 	if (aconnector->hdmi_prev_sink) {
4350 		dc_sink_release(aconnector->hdmi_prev_sink);
4351 		aconnector->hdmi_prev_sink = NULL;
4352 	}
4353 
4354 	scoped_guard(mutex, &adev->dm.dc_lock) {
4355 		if (reallow_idle && dc->caps.ips_support)
4356 			dc_allow_idle_optimizations(dc, true);
4357 	}
4358 }
4359 
4360 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
4361 {
4362 	struct drm_connector *connector = &aconnector->base;
4363 	struct drm_device *dev = connector->dev;
4364 	enum dc_connection_type new_connection_type = dc_connection_none;
4365 	struct amdgpu_device *adev = drm_to_adev(dev);
4366 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
4367 	struct dc *dc = aconnector->dc_link->ctx->dc;
4368 	bool ret = false;
4369 	bool debounce_required = false;
4370 
4371 	if (adev->dm.disable_hpd_irq)
4372 		return;
4373 
4374 	/*
4375 	 * In case of failure or MST no need to update connector status or notify the OS
4376 	 * since (for MST case) MST does this in its own context.
4377 	 */
4378 	guard(mutex)(&aconnector->hpd_lock);
4379 
4380 	if (adev->dm.hdcp_workqueue) {
4381 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
4382 		dm_con_state->update_hdcp = true;
4383 	}
4384 	if (aconnector->fake_enable)
4385 		aconnector->fake_enable = false;
4386 
4387 	aconnector->timing_changed = false;
4388 
4389 	if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
4390 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4391 
4392 	/*
4393 	 * Check for HDMI disconnect with debounce enabled.
4394 	 */
4395 	debounce_required = (aconnector->hdmi_hpd_debounce_delay_ms > 0 &&
4396 			      dc_is_hdmi_signal(aconnector->dc_link->connector_signal) &&
4397 			      new_connection_type == dc_connection_none &&
4398 			      aconnector->dc_link->local_sink != NULL);
4399 
4400 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
4401 		emulated_link_detect(aconnector->dc_link);
4402 
4403 		drm_modeset_lock_all(dev);
4404 		dm_restore_drm_connector_state(dev, connector);
4405 		drm_modeset_unlock_all(dev);
4406 
4407 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4408 			drm_kms_helper_connector_hotplug_event(connector);
4409 	} else if (debounce_required) {
4410 		/*
4411 		 * HDMI disconnect detected - schedule delayed work instead of
4412 		 * processing immediately. This allows us to coalesce spurious
4413 		 * HDMI signals from physical unplugs.
4414 		 */
4415 		drm_dbg_kms(dev, "HDMI HPD: Disconnect detected, scheduling debounce work (%u ms)\n",
4416 			    aconnector->hdmi_hpd_debounce_delay_ms);
4417 
4418 		/* Cache the current sink for later comparison */
4419 		if (aconnector->hdmi_prev_sink)
4420 			dc_sink_release(aconnector->hdmi_prev_sink);
4421 		aconnector->hdmi_prev_sink = aconnector->dc_link->local_sink;
4422 		if (aconnector->hdmi_prev_sink)
4423 			dc_sink_retain(aconnector->hdmi_prev_sink);
4424 
4425 		/* Schedule delayed detection. */
4426 		if (mod_delayed_work(system_percpu_wq,
4427 				 &aconnector->hdmi_hpd_debounce_work,
4428 				 msecs_to_jiffies(aconnector->hdmi_hpd_debounce_delay_ms)))
4429 			drm_dbg_kms(dev, "HDMI HPD: Re-scheduled debounce work\n");
4430 
4431 	} else {
4432 
4433 		/* If the aconnector->hdmi_hpd_debounce_work is scheduled, exit early */
4434 		if (delayed_work_pending(&aconnector->hdmi_hpd_debounce_work))
4435 			return;
4436 
4437 		scoped_guard(mutex, &adev->dm.dc_lock) {
4438 			dc_exit_ips_for_hw_access(dc);
4439 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4440 		}
4441 		if (ret) {
4442 			/* w/a delay for certain panels */
4443 			apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4444 			amdgpu_dm_update_connector_after_detect(aconnector);
4445 
4446 			drm_modeset_lock_all(dev);
4447 			dm_restore_drm_connector_state(dev, connector);
4448 			drm_modeset_unlock_all(dev);
4449 
4450 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4451 				drm_kms_helper_connector_hotplug_event(connector);
4452 		}
4453 	}
4454 }
4455 
4456 static void handle_hpd_irq(void *param)
4457 {
4458 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4459 
4460 	handle_hpd_irq_helper(aconnector);
4461 
4462 }
4463 
4464 static void schedule_hpd_rx_offload_work(struct amdgpu_device *adev, struct hpd_rx_irq_offload_work_queue *offload_wq,
4465 							union hpd_irq_data hpd_irq_data)
4466 {
4467 	struct hpd_rx_irq_offload_work *offload_work = kzalloc_obj(*offload_work);
4468 
4469 	if (!offload_work) {
4470 		drm_err(adev_to_drm(adev), "Failed to allocate hpd_rx_irq_offload_work.\n");
4471 		return;
4472 	}
4473 
4474 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
4475 	offload_work->data = hpd_irq_data;
4476 	offload_work->offload_wq = offload_wq;
4477 	offload_work->adev = adev;
4478 
4479 	queue_work(offload_wq->wq, &offload_work->work);
4480 	drm_dbg_kms(adev_to_drm(adev), "queue work to handle hpd_rx offload work");
4481 }
4482 
4483 static void handle_hpd_rx_irq(void *param)
4484 {
4485 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4486 	struct drm_connector *connector = &aconnector->base;
4487 	struct drm_device *dev = connector->dev;
4488 	struct dc_link *dc_link = aconnector->dc_link;
4489 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
4490 	bool result = false;
4491 	enum dc_connection_type new_connection_type = dc_connection_none;
4492 	struct amdgpu_device *adev = drm_to_adev(dev);
4493 	union hpd_irq_data hpd_irq_data;
4494 	bool link_loss = false;
4495 	bool has_left_work = false;
4496 	int idx = dc_link->link_index;
4497 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
4498 	struct dc *dc = aconnector->dc_link->ctx->dc;
4499 
4500 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
4501 
4502 	if (adev->dm.disable_hpd_irq)
4503 		return;
4504 
4505 	/*
4506 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
4507 	 * conflict, after implement i2c helper, this mutex should be
4508 	 * retired.
4509 	 */
4510 	mutex_lock(&aconnector->hpd_lock);
4511 
4512 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
4513 						&link_loss, true, &has_left_work);
4514 
4515 	if (!has_left_work)
4516 		goto out;
4517 
4518 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
4519 		schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4520 		goto out;
4521 	}
4522 
4523 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
4524 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
4525 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
4526 			bool skip = false;
4527 
4528 			/*
4529 			 * DOWN_REP_MSG_RDY is also handled by polling method
4530 			 * mgr->cbs->poll_hpd_irq()
4531 			 */
4532 			spin_lock(&offload_wq->offload_lock);
4533 			skip = offload_wq->is_handling_mst_msg_rdy_event;
4534 
4535 			if (!skip)
4536 				offload_wq->is_handling_mst_msg_rdy_event = true;
4537 
4538 			spin_unlock(&offload_wq->offload_lock);
4539 
4540 			if (!skip)
4541 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4542 
4543 			goto out;
4544 		}
4545 
4546 		if (link_loss) {
4547 			bool skip = false;
4548 
4549 			spin_lock(&offload_wq->offload_lock);
4550 			skip = offload_wq->is_handling_link_loss;
4551 
4552 			if (!skip)
4553 				offload_wq->is_handling_link_loss = true;
4554 
4555 			spin_unlock(&offload_wq->offload_lock);
4556 
4557 			if (!skip)
4558 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4559 
4560 			goto out;
4561 		}
4562 	}
4563 
4564 out:
4565 	if (result && !is_mst_root_connector) {
4566 		/* Downstream Port status changed. */
4567 		if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
4568 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4569 
4570 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4571 			emulated_link_detect(dc_link);
4572 
4573 			if (aconnector->fake_enable)
4574 				aconnector->fake_enable = false;
4575 
4576 			amdgpu_dm_update_connector_after_detect(aconnector);
4577 
4578 
4579 			drm_modeset_lock_all(dev);
4580 			dm_restore_drm_connector_state(dev, connector);
4581 			drm_modeset_unlock_all(dev);
4582 
4583 			drm_kms_helper_connector_hotplug_event(connector);
4584 		} else {
4585 			bool ret = false;
4586 
4587 			mutex_lock(&adev->dm.dc_lock);
4588 			dc_exit_ips_for_hw_access(dc);
4589 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
4590 			mutex_unlock(&adev->dm.dc_lock);
4591 
4592 			if (ret) {
4593 				if (aconnector->fake_enable)
4594 					aconnector->fake_enable = false;
4595 
4596 				amdgpu_dm_update_connector_after_detect(aconnector);
4597 
4598 				drm_modeset_lock_all(dev);
4599 				dm_restore_drm_connector_state(dev, connector);
4600 				drm_modeset_unlock_all(dev);
4601 
4602 				drm_kms_helper_connector_hotplug_event(connector);
4603 			}
4604 		}
4605 	}
4606 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
4607 		if (adev->dm.hdcp_workqueue)
4608 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
4609 	}
4610 
4611 	if (dc_link->type != dc_connection_mst_branch)
4612 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
4613 
4614 	mutex_unlock(&aconnector->hpd_lock);
4615 }
4616 
4617 static int register_hpd_handlers(struct amdgpu_device *adev)
4618 {
4619 	struct drm_device *dev = adev_to_drm(adev);
4620 	struct drm_connector *connector;
4621 	struct amdgpu_dm_connector *aconnector;
4622 	const struct dc_link *dc_link;
4623 	struct dc_interrupt_params int_params = {0};
4624 
4625 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4626 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4627 
4628 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
4629 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD,
4630 			dmub_hpd_callback, true)) {
4631 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4632 			return -EINVAL;
4633 		}
4634 
4635 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ,
4636 			dmub_hpd_callback, true)) {
4637 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4638 			return -EINVAL;
4639 		}
4640 
4641 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_SENSE_NOTIFY,
4642 			dmub_hpd_sense_callback, true)) {
4643 			drm_err(adev_to_drm(adev), "fail to register dmub hpd sense callback");
4644 			return -EINVAL;
4645 		}
4646 	}
4647 
4648 	list_for_each_entry(connector,
4649 			&dev->mode_config.connector_list, head)	{
4650 
4651 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
4652 			continue;
4653 
4654 		aconnector = to_amdgpu_dm_connector(connector);
4655 		dc_link = aconnector->dc_link;
4656 
4657 		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
4658 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4659 			int_params.irq_source = dc_link->irq_source_hpd;
4660 
4661 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4662 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1 ||
4663 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6) {
4664 				drm_err(adev_to_drm(adev), "Failed to register hpd irq!\n");
4665 				return -EINVAL;
4666 			}
4667 
4668 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4669 				handle_hpd_irq, (void *) aconnector))
4670 				return -ENOMEM;
4671 		}
4672 
4673 		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
4674 
4675 			/* Also register for DP short pulse (hpd_rx). */
4676 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4677 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
4678 
4679 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4680 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1RX ||
4681 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6RX) {
4682 				drm_err(adev_to_drm(adev), "Failed to register hpd rx irq!\n");
4683 				return -EINVAL;
4684 			}
4685 
4686 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4687 				handle_hpd_rx_irq, (void *) aconnector))
4688 				return -ENOMEM;
4689 		}
4690 	}
4691 	return 0;
4692 }
4693 
4694 /* Register IRQ sources and initialize IRQ callbacks */
4695 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
4696 {
4697 	struct dc *dc = adev->dm.dc;
4698 	struct common_irq_params *c_irq_params;
4699 	struct dc_interrupt_params int_params = {0};
4700 	int r;
4701 	int i;
4702 	unsigned int src_id;
4703 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4704 	/* Use different interrupts for VBLANK on DCE 6 vs. newer. */
4705 	const unsigned int vblank_d1 =
4706 		adev->dm.dc->ctx->dce_version >= DCE_VERSION_8_0
4707 		? VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0 : 1;
4708 
4709 	if (adev->family >= AMDGPU_FAMILY_AI)
4710 		client_id = SOC15_IH_CLIENTID_DCE;
4711 
4712 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4713 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4714 
4715 	/*
4716 	 * Actions of amdgpu_irq_add_id():
4717 	 * 1. Register a set() function with base driver.
4718 	 *    Base driver will call set() function to enable/disable an
4719 	 *    interrupt in DC hardware.
4720 	 * 2. Register amdgpu_dm_irq_handler().
4721 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4722 	 *    coming from DC hardware.
4723 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4724 	 *    for acknowledging and handling.
4725 	 */
4726 
4727 	/* Use VBLANK interrupt */
4728 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
4729 		src_id = vblank_d1 + i;
4730 		r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->crtc_irq);
4731 		if (r) {
4732 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4733 			return r;
4734 		}
4735 
4736 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4737 		int_params.irq_source =
4738 			dc_interrupt_to_irq_source(dc, src_id, 0);
4739 
4740 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4741 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4742 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4743 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4744 			return -EINVAL;
4745 		}
4746 
4747 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4748 
4749 		c_irq_params->adev = adev;
4750 		c_irq_params->irq_src = int_params.irq_source;
4751 
4752 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4753 			dm_crtc_high_irq, c_irq_params))
4754 			return -ENOMEM;
4755 	}
4756 
4757 	if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
4758 		/* Use VUPDATE interrupt */
4759 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
4760 			src_id = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT + i * 2;
4761 			r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->vupdate_irq);
4762 			if (r) {
4763 				drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4764 				return r;
4765 			}
4766 
4767 			int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4768 			int_params.irq_source =
4769 				dc_interrupt_to_irq_source(dc, src_id, 0);
4770 
4771 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4772 				int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4773 				int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4774 				drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4775 				return -EINVAL;
4776 			}
4777 
4778 			c_irq_params = &adev->dm.vupdate_params[
4779 				int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4780 			c_irq_params->adev = adev;
4781 			c_irq_params->irq_src = int_params.irq_source;
4782 
4783 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4784 				dm_vupdate_high_irq, c_irq_params))
4785 				return -ENOMEM;
4786 		}
4787 	}
4788 
4789 	/* Use GRPH_PFLIP interrupt */
4790 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4791 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4792 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4793 		if (r) {
4794 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4795 			return r;
4796 		}
4797 
4798 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4799 		int_params.irq_source =
4800 			dc_interrupt_to_irq_source(dc, i, 0);
4801 
4802 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4803 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4804 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4805 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4806 			return -EINVAL;
4807 		}
4808 
4809 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4810 
4811 		c_irq_params->adev = adev;
4812 		c_irq_params->irq_src = int_params.irq_source;
4813 
4814 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4815 			dm_pflip_high_irq, c_irq_params))
4816 			return -ENOMEM;
4817 	}
4818 
4819 	/* HPD */
4820 	r = amdgpu_irq_add_id(adev, client_id,
4821 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4822 	if (r) {
4823 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4824 		return r;
4825 	}
4826 
4827 	r = register_hpd_handlers(adev);
4828 
4829 	return r;
4830 }
4831 
4832 /* Register IRQ sources and initialize IRQ callbacks */
4833 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
4834 {
4835 	struct dc *dc = adev->dm.dc;
4836 	struct common_irq_params *c_irq_params;
4837 	struct dc_interrupt_params int_params = {0};
4838 	int r;
4839 	int i;
4840 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4841 	static const unsigned int vrtl_int_srcid[] = {
4842 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
4843 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
4844 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
4845 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
4846 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
4847 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
4848 	};
4849 #endif
4850 
4851 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4852 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4853 
4854 	/*
4855 	 * Actions of amdgpu_irq_add_id():
4856 	 * 1. Register a set() function with base driver.
4857 	 *    Base driver will call set() function to enable/disable an
4858 	 *    interrupt in DC hardware.
4859 	 * 2. Register amdgpu_dm_irq_handler().
4860 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4861 	 *    coming from DC hardware.
4862 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4863 	 *    for acknowledging and handling.
4864 	 */
4865 
4866 	/* Use VSTARTUP interrupt */
4867 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
4868 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
4869 			i++) {
4870 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
4871 
4872 		if (r) {
4873 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4874 			return r;
4875 		}
4876 
4877 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4878 		int_params.irq_source =
4879 			dc_interrupt_to_irq_source(dc, i, 0);
4880 
4881 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4882 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4883 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4884 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4885 			return -EINVAL;
4886 		}
4887 
4888 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4889 
4890 		c_irq_params->adev = adev;
4891 		c_irq_params->irq_src = int_params.irq_source;
4892 
4893 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4894 			dm_crtc_high_irq, c_irq_params))
4895 			return -ENOMEM;
4896 	}
4897 
4898 	/* Use otg vertical line interrupt */
4899 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4900 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
4901 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
4902 				vrtl_int_srcid[i], &adev->vline0_irq);
4903 
4904 		if (r) {
4905 			drm_err(adev_to_drm(adev), "Failed to add vline0 irq id!\n");
4906 			return r;
4907 		}
4908 
4909 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4910 		int_params.irq_source =
4911 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
4912 
4913 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4914 			int_params.irq_source < DC_IRQ_SOURCE_DC1_VLINE0 ||
4915 			int_params.irq_source > DC_IRQ_SOURCE_DC6_VLINE0) {
4916 			drm_err(adev_to_drm(adev), "Failed to register vline0 irq!\n");
4917 			return -EINVAL;
4918 		}
4919 
4920 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
4921 					- DC_IRQ_SOURCE_DC1_VLINE0];
4922 
4923 		c_irq_params->adev = adev;
4924 		c_irq_params->irq_src = int_params.irq_source;
4925 
4926 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4927 			dm_dcn_vertical_interrupt0_high_irq,
4928 			c_irq_params))
4929 			return -ENOMEM;
4930 	}
4931 #endif
4932 
4933 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
4934 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
4935 	 * to trigger at end of each vblank, regardless of state of the lock,
4936 	 * matching DCE behaviour.
4937 	 */
4938 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
4939 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
4940 	     i++) {
4941 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
4942 
4943 		if (r) {
4944 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4945 			return r;
4946 		}
4947 
4948 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4949 		int_params.irq_source =
4950 			dc_interrupt_to_irq_source(dc, i, 0);
4951 
4952 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4953 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4954 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4955 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4956 			return -EINVAL;
4957 		}
4958 
4959 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4960 
4961 		c_irq_params->adev = adev;
4962 		c_irq_params->irq_src = int_params.irq_source;
4963 
4964 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4965 			dm_vupdate_high_irq, c_irq_params))
4966 			return -ENOMEM;
4967 	}
4968 
4969 	/* Use GRPH_PFLIP interrupt */
4970 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
4971 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
4972 			i++) {
4973 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
4974 		if (r) {
4975 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4976 			return r;
4977 		}
4978 
4979 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4980 		int_params.irq_source =
4981 			dc_interrupt_to_irq_source(dc, i, 0);
4982 
4983 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4984 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4985 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4986 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4987 			return -EINVAL;
4988 		}
4989 
4990 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4991 
4992 		c_irq_params->adev = adev;
4993 		c_irq_params->irq_src = int_params.irq_source;
4994 
4995 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4996 			dm_pflip_high_irq, c_irq_params))
4997 			return -ENOMEM;
4998 	}
4999 
5000 	/* HPD */
5001 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
5002 			&adev->hpd_irq);
5003 	if (r) {
5004 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
5005 		return r;
5006 	}
5007 
5008 	r = register_hpd_handlers(adev);
5009 
5010 	return r;
5011 }
5012 /* Register Outbox IRQ sources and initialize IRQ callbacks */
5013 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
5014 {
5015 	struct dc *dc = adev->dm.dc;
5016 	struct common_irq_params *c_irq_params;
5017 	struct dc_interrupt_params int_params = {0};
5018 	int r, i;
5019 
5020 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
5021 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
5022 
5023 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
5024 			&adev->dmub_outbox_irq);
5025 	if (r) {
5026 		drm_err(adev_to_drm(adev), "Failed to add outbox irq id!\n");
5027 		return r;
5028 	}
5029 
5030 	if (dc->ctx->dmub_srv) {
5031 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
5032 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
5033 		int_params.irq_source =
5034 		dc_interrupt_to_irq_source(dc, i, 0);
5035 
5036 		c_irq_params = &adev->dm.dmub_outbox_params[0];
5037 
5038 		c_irq_params->adev = adev;
5039 		c_irq_params->irq_src = int_params.irq_source;
5040 
5041 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
5042 			dm_dmub_outbox1_low_irq, c_irq_params))
5043 			return -ENOMEM;
5044 	}
5045 
5046 	return 0;
5047 }
5048 
5049 /*
5050  * Acquires the lock for the atomic state object and returns
5051  * the new atomic state.
5052  *
5053  * This should only be called during atomic check.
5054  */
5055 int dm_atomic_get_state(struct drm_atomic_commit *state,
5056 			struct dm_atomic_state **dm_state)
5057 {
5058 	struct drm_device *dev = state->dev;
5059 	struct amdgpu_device *adev = drm_to_adev(dev);
5060 	struct amdgpu_display_manager *dm = &adev->dm;
5061 	struct drm_private_state *priv_state;
5062 
5063 	if (*dm_state)
5064 		return 0;
5065 
5066 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
5067 	if (IS_ERR(priv_state))
5068 		return PTR_ERR(priv_state);
5069 
5070 	*dm_state = to_dm_atomic_state(priv_state);
5071 
5072 	return 0;
5073 }
5074 
5075 static struct dm_atomic_state *
5076 dm_atomic_get_new_state(struct drm_atomic_commit *state)
5077 {
5078 	struct drm_device *dev = state->dev;
5079 	struct amdgpu_device *adev = drm_to_adev(dev);
5080 	struct amdgpu_display_manager *dm = &adev->dm;
5081 	struct drm_private_obj *obj;
5082 	struct drm_private_state *new_obj_state;
5083 	int i;
5084 
5085 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
5086 		if (obj->funcs == dm->atomic_obj.funcs)
5087 			return to_dm_atomic_state(new_obj_state);
5088 	}
5089 
5090 	return NULL;
5091 }
5092 
5093 static struct drm_private_state *
5094 dm_atomic_duplicate_state(struct drm_private_obj *obj)
5095 {
5096 	struct dm_atomic_state *old_state, *new_state;
5097 
5098 	new_state = kzalloc_obj(*new_state);
5099 	if (!new_state)
5100 		return NULL;
5101 
5102 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
5103 
5104 	old_state = to_dm_atomic_state(obj->state);
5105 
5106 	if (old_state && old_state->context)
5107 		new_state->context = dc_state_create_copy(old_state->context);
5108 
5109 	if (!new_state->context) {
5110 		kfree(new_state);
5111 		return NULL;
5112 	}
5113 
5114 	return &new_state->base;
5115 }
5116 
5117 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
5118 				    struct drm_private_state *state)
5119 {
5120 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
5121 
5122 	if (dm_state && dm_state->context)
5123 		dc_state_release(dm_state->context);
5124 
5125 	kfree(dm_state);
5126 }
5127 
5128 static struct drm_private_state *
5129 dm_atomic_create_state(struct drm_private_obj *obj)
5130 {
5131 	struct amdgpu_device *adev = drm_to_adev(obj->dev);
5132 	struct dm_atomic_state *dm_state;
5133 	struct dc_state *context;
5134 
5135 	dm_state = kzalloc_obj(*dm_state);
5136 	if (!dm_state)
5137 		return ERR_PTR(-ENOMEM);
5138 
5139 	context = dc_state_create_current_copy(adev->dm.dc);
5140 	if (!context) {
5141 		kfree(dm_state);
5142 		return ERR_PTR(-ENOMEM);
5143 	}
5144 
5145 	__drm_atomic_helper_private_obj_create_state(obj, &dm_state->base);
5146 	dm_state->context = context;
5147 
5148 	return &dm_state->base;
5149 }
5150 
5151 static struct drm_private_state_funcs dm_atomic_state_funcs = {
5152 	.atomic_create_state = dm_atomic_create_state,
5153 	.atomic_duplicate_state = dm_atomic_duplicate_state,
5154 	.atomic_destroy_state = dm_atomic_destroy_state,
5155 };
5156 
5157 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
5158 {
5159 	int r;
5160 
5161 	adev->mode_info.mode_config_initialized = true;
5162 
5163 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
5164 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
5165 
5166 	adev_to_drm(adev)->mode_config.max_width = 16384;
5167 	adev_to_drm(adev)->mode_config.max_height = 16384;
5168 
5169 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
5170 	if (adev->asic_type == CHIP_HAWAII)
5171 		/* disable prefer shadow for now due to hibernation issues */
5172 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
5173 	else
5174 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
5175 	/* indicates support for immediate flip */
5176 	adev_to_drm(adev)->mode_config.async_page_flip = true;
5177 
5178 	drm_atomic_private_obj_init(adev_to_drm(adev),
5179 				    &adev->dm.atomic_obj,
5180 				    &dm_atomic_state_funcs);
5181 
5182 	r = amdgpu_display_modeset_create_props(adev);
5183 	if (r)
5184 		return r;
5185 
5186 #ifdef AMD_PRIVATE_COLOR
5187 	if (amdgpu_dm_create_color_properties(adev))
5188 		return -ENOMEM;
5189 #endif
5190 
5191 	r = amdgpu_dm_audio_init(adev);
5192 	if (r)
5193 		return r;
5194 
5195 	return 0;
5196 }
5197 
5198 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
5199 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
5200 #define AMDGPU_DM_MIN_SPREAD ((AMDGPU_DM_DEFAULT_MAX_BACKLIGHT - AMDGPU_DM_DEFAULT_MIN_BACKLIGHT) / 2)
5201 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
5202 
5203 void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
5204 				     int bl_idx)
5205 {
5206 	struct amdgpu_dm_backlight_caps *caps = &dm->backlight_caps[bl_idx];
5207 
5208 	if (caps->caps_valid)
5209 		return;
5210 
5211 #if defined(CONFIG_ACPI)
5212 	amdgpu_acpi_get_backlight_caps(caps);
5213 
5214 	/* validate the firmware value is sane */
5215 	if (caps->caps_valid) {
5216 		int spread = caps->max_input_signal - caps->min_input_signal;
5217 
5218 		if (caps->max_input_signal > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5219 		    caps->min_input_signal < 0 ||
5220 		    spread > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5221 		    spread < AMDGPU_DM_MIN_SPREAD) {
5222 			drm_dbg_kms(adev_to_drm(dm->adev), "DM: Invalid backlight caps: min=%d, max=%d\n",
5223 				      caps->min_input_signal, caps->max_input_signal);
5224 			caps->caps_valid = false;
5225 		}
5226 	}
5227 
5228 	if (!caps->caps_valid) {
5229 		caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5230 		caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5231 		caps->caps_valid = true;
5232 	}
5233 #else
5234 	if (caps->aux_support)
5235 		return;
5236 
5237 	caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5238 	caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5239 	caps->caps_valid = true;
5240 #endif
5241 }
5242 
5243 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
5244 				unsigned int *min, unsigned int *max)
5245 {
5246 	if (!caps)
5247 		return 0;
5248 
5249 	if (caps->aux_support) {
5250 		// Firmware limits are in nits, DC API wants millinits.
5251 		*max = 1000 * caps->aux_max_input_signal;
5252 		*min = 1000 * caps->aux_min_input_signal;
5253 	} else {
5254 		// Firmware limits are 8-bit, PWM control is 16-bit.
5255 		*max = 0x101 * caps->max_input_signal;
5256 		*min = 0x101 * caps->min_input_signal;
5257 	}
5258 	return 1;
5259 }
5260 
5261 /* Rescale from [min..max] to [0..AMDGPU_MAX_BL_LEVEL] */
5262 static inline u32 scale_input_to_fw(int min, int max, u64 input)
5263 {
5264 	return DIV_ROUND_CLOSEST_ULL(input * AMDGPU_MAX_BL_LEVEL, max - min);
5265 }
5266 
5267 /* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [min..max] */
5268 static inline u32 scale_fw_to_input(int min, int max, u64 input)
5269 {
5270 	return min + DIV_ROUND_CLOSEST_ULL(input * (max - min), AMDGPU_MAX_BL_LEVEL);
5271 }
5272 
5273 static void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps,
5274 				      unsigned int min, unsigned int max,
5275 				      uint32_t *user_brightness)
5276 {
5277 	u32 brightness = scale_input_to_fw(min, max, *user_brightness);
5278 	u8 lower_signal, upper_signal, upper_lum, lower_lum, lum;
5279 	int left, right;
5280 
5281 	if (amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)
5282 		return;
5283 
5284 	if (!caps->data_points)
5285 		return;
5286 
5287 	/*
5288 	 * Handle the case where brightness is below the first data point
5289 	 * Interpolate between (0,0) and (first_signal, first_lum)
5290 	 */
5291 	if (brightness < caps->luminance_data[0].input_signal) {
5292 		lum = DIV_ROUND_CLOSEST(caps->luminance_data[0].luminance * brightness,
5293 					caps->luminance_data[0].input_signal);
5294 		goto scale;
5295 	}
5296 
5297 	left = 0;
5298 	right = caps->data_points - 1;
5299 	while (left <= right) {
5300 		int mid = left + (right - left) / 2;
5301 		u8 signal = caps->luminance_data[mid].input_signal;
5302 
5303 		/* Exact match found */
5304 		if (signal == brightness) {
5305 			lum = caps->luminance_data[mid].luminance;
5306 			goto scale;
5307 		}
5308 
5309 		if (signal < brightness)
5310 			left = mid + 1;
5311 		else
5312 			right = mid - 1;
5313 	}
5314 
5315 	/* verify bound */
5316 	if (left >= caps->data_points)
5317 		left = caps->data_points - 1;
5318 
5319 	/* At this point, left > right */
5320 	lower_signal = caps->luminance_data[right].input_signal;
5321 	upper_signal = caps->luminance_data[left].input_signal;
5322 	lower_lum = caps->luminance_data[right].luminance;
5323 	upper_lum = caps->luminance_data[left].luminance;
5324 
5325 	/* interpolate */
5326 	if (right == left || !lower_lum)
5327 		lum = upper_lum;
5328 	else
5329 		lum = lower_lum + DIV_ROUND_CLOSEST((upper_lum - lower_lum) *
5330 						    (brightness - lower_signal),
5331 						    upper_signal - lower_signal);
5332 scale:
5333 	*user_brightness = scale_fw_to_input(min, max,
5334 					     DIV_ROUND_CLOSEST(lum * brightness, 101));
5335 }
5336 
5337 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
5338 					uint32_t brightness)
5339 {
5340 	unsigned int min, max;
5341 
5342 	if (!get_brightness_range(caps, &min, &max))
5343 		return brightness;
5344 
5345 	convert_custom_brightness(caps, min, max, &brightness);
5346 
5347 	// Rescale 0..max to min..max
5348 	return min + DIV_ROUND_CLOSEST_ULL((u64)(max - min) * brightness, max);
5349 }
5350 
5351 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
5352 				      uint32_t brightness)
5353 {
5354 	unsigned int min, max;
5355 
5356 	if (!get_brightness_range(caps, &min, &max))
5357 		return brightness;
5358 
5359 	if (brightness < min)
5360 		return 0;
5361 	// Rescale min..max to 0..max
5362 	return DIV_ROUND_CLOSEST_ULL((u64)max * (brightness - min),
5363 				 max - min);
5364 }
5365 
5366 static struct dc_stream_state *dm_find_stream_with_link(
5367 	struct amdgpu_display_manager *dm,
5368 	struct dc_link *link)
5369 {
5370 	struct dc_state *cur_dc_state = dm->dc->current_state;
5371 	struct dc_stream_state *stream = NULL;
5372 	int i;
5373 
5374 	for (i = 0; i < cur_dc_state->stream_count; i++) {
5375 		stream = cur_dc_state->streams[i];
5376 		if (stream->link == link)
5377 			return stream;
5378 	}
5379 
5380 	return NULL;
5381 }
5382 
5383 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
5384 					 int bl_idx,
5385 					 u32 user_brightness)
5386 {
5387 	struct amdgpu_dm_backlight_caps *caps;
5388 	struct dc_link *link;
5389 	u32 brightness = 0;
5390 	bool rc = false, reallow_idle = false;
5391 	struct drm_connector *connector;
5392 	struct dc_stream_state *stream;
5393 	unsigned int min, max;
5394 
5395 	list_for_each_entry(connector, &dm->ddev->mode_config.connector_list, head) {
5396 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5397 
5398 		if (aconnector->bl_idx != bl_idx)
5399 			continue;
5400 
5401 		/* if connector is off, save the brightness for next time it's on */
5402 		if (!aconnector->base.encoder) {
5403 			dm->brightness[bl_idx] = user_brightness;
5404 			dm->actual_brightness[bl_idx] = 0;
5405 			return;
5406 		}
5407 	}
5408 
5409 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5410 	caps = &dm->backlight_caps[bl_idx];
5411 
5412 	dm->brightness[bl_idx] = user_brightness;
5413 	/* update scratch register */
5414 	if (bl_idx == 0)
5415 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
5416 	brightness = convert_brightness_from_user(caps, dm->brightness[bl_idx]);
5417 	link = (struct dc_link *)dm->backlight_link[bl_idx];
5418 
5419 	/* Apply brightness quirk */
5420 	if (caps->brightness_mask)
5421 		brightness |= caps->brightness_mask;
5422 
5423 	if (trace_amdgpu_dm_brightness_enabled()) {
5424 		trace_amdgpu_dm_brightness(__builtin_return_address(0),
5425 					   user_brightness,
5426 					   brightness,
5427 					   caps->aux_support,
5428 					   power_supply_is_system_supplied() > 0);
5429 	}
5430 
5431 	stream = dm_find_stream_with_link(dm, link);
5432 	if (!stream)
5433 		return;
5434 
5435 	mutex_lock(&dm->dc_lock);
5436 	if (dm->dc->caps.ips_support && dm->dc->ctx->dmub_srv->idle_allowed) {
5437 		dc_allow_idle_optimizations(dm->dc, false);
5438 		reallow_idle = true;
5439 	}
5440 
5441 	if (caps->aux_support) {
5442 		rc = mod_power_set_backlight_nits(dm->power_module, stream, brightness,
5443 			AUX_BL_DEFAULT_TRANSITION_TIME_MS, false, true);
5444 	} else {
5445 		/* power module uses millipercent */
5446 		get_brightness_range(caps, &min, &max);
5447 		brightness = DIV_ROUND_CLOSEST(brightness * 100, (max - min)) * 1000;
5448 		rc = mod_power_set_backlight_percent(dm->power_module, stream,
5449 						     brightness, 0, false);
5450 	}
5451 
5452 	/*
5453 	 * Some kms clients create a ramped backlight transition effect
5454 	 * by rapidly changing the backlight. Yet we must wait on dmcub
5455 	 * fw to exit psr/replay before programming backlight. To
5456 	 * prevent lag, keep disable psr/replay and let the next atomic
5457 	 * flip clear the event.
5458 	 *
5459 	 * ToDo: use ISM to handle rapidly backlight change
5460 	 *
5461 	 * Rapidly backlight change is similar to rapidly cursor events,
5462 	 * which is now handled by ISM. ISM can delay the event until system
5463 	 * is really idle, so we may use ISM to handle backlight change as well.
5464 	 */
5465 	amdgpu_dm_psr_set_event(dm, stream, true,
5466 		psr_event_hw_programming, true);
5467 	amdgpu_dm_replay_set_event(dm, stream, true,
5468 		replay_event_hw_programming, true);
5469 
5470 	if (dm->dc->caps.ips_support && reallow_idle)
5471 		dc_allow_idle_optimizations(dm->dc, true);
5472 
5473 	mutex_unlock(&dm->dc_lock);
5474 
5475 	if (rc)
5476 		dm->actual_brightness[bl_idx] = user_brightness;
5477 }
5478 
5479 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
5480 {
5481 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5482 	int i;
5483 
5484 	for (i = 0; i < dm->num_of_edps; i++) {
5485 		if (bd == dm->backlight_dev[i])
5486 			break;
5487 	}
5488 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5489 		i = 0;
5490 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
5491 
5492 	return 0;
5493 }
5494 
5495 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
5496 					 int bl_idx)
5497 {
5498 	int ret;
5499 	struct amdgpu_dm_backlight_caps caps;
5500 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
5501 
5502 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5503 	caps = dm->backlight_caps[bl_idx];
5504 
5505 	if (caps.aux_support) {
5506 		u32 avg, peak;
5507 
5508 		if (!dc_link_get_backlight_level_nits(link, &avg, &peak))
5509 			return dm->brightness[bl_idx];
5510 		return convert_brightness_to_user(&caps, avg);
5511 	}
5512 
5513 	ret = dc_link_get_backlight_level(link);
5514 
5515 	if (ret == DC_ERROR_UNEXPECTED)
5516 		return dm->brightness[bl_idx];
5517 
5518 	return convert_brightness_to_user(&caps, ret);
5519 }
5520 
5521 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
5522 {
5523 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5524 	int i;
5525 
5526 	for (i = 0; i < dm->num_of_edps; i++) {
5527 		if (bd == dm->backlight_dev[i])
5528 			break;
5529 	}
5530 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5531 		i = 0;
5532 	return amdgpu_dm_backlight_get_level(dm, i);
5533 }
5534 
5535 static const struct backlight_ops amdgpu_dm_backlight_ops = {
5536 	.options = BL_CORE_SUSPENDRESUME,
5537 	.get_brightness = amdgpu_dm_backlight_get_brightness,
5538 	.update_status	= amdgpu_dm_backlight_update_status,
5539 };
5540 
5541 static void
5542 amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector *aconnector)
5543 {
5544 	struct drm_device *drm = aconnector->base.dev;
5545 	struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
5546 	struct backlight_properties props = { 0 };
5547 	struct amdgpu_dm_backlight_caps *caps;
5548 	char bl_name[16];
5549 	int min, max;
5550 	int real_brightness;
5551 	int init_brightness;
5552 
5553 	if (aconnector->bl_idx == -1)
5554 		return;
5555 
5556 	if (!acpi_video_backlight_use_native()) {
5557 		drm_info(drm, "Skipping amdgpu DM backlight registration\n");
5558 		/* Try registering an ACPI video backlight device instead. */
5559 		acpi_video_register_backlight();
5560 		return;
5561 	}
5562 
5563 	caps = &dm->backlight_caps[aconnector->bl_idx];
5564 	if (get_brightness_range(caps, &min, &max)) {
5565 		if (power_supply_is_system_supplied() > 0)
5566 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->ac_level, 100);
5567 		else
5568 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->dc_level, 100);
5569 		/* min is zero, so max needs to be adjusted */
5570 		props.max_brightness = max - min;
5571 		drm_dbg(drm, "Backlight caps: min: %d, max: %d, ac %d, dc %d\n", min, max,
5572 			caps->ac_level, caps->dc_level);
5573 	} else
5574 		props.brightness = props.max_brightness = MAX_BACKLIGHT_LEVEL;
5575 
5576 	init_brightness = props.brightness;
5577 
5578 	if (caps->data_points && !(amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)) {
5579 		drm_info(drm, "Using custom brightness curve\n");
5580 		props.scale = BACKLIGHT_SCALE_NON_LINEAR;
5581 	} else
5582 		props.scale = BACKLIGHT_SCALE_LINEAR;
5583 	props.type = BACKLIGHT_RAW;
5584 
5585 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
5586 		 drm->primary->index + aconnector->bl_idx);
5587 
5588 	dm->backlight_dev[aconnector->bl_idx] =
5589 		backlight_device_register(bl_name, aconnector->base.kdev, dm,
5590 					  &amdgpu_dm_backlight_ops, &props);
5591 	dm->brightness[aconnector->bl_idx] = props.brightness;
5592 
5593 	if (IS_ERR(dm->backlight_dev[aconnector->bl_idx])) {
5594 		drm_err(drm, "DM: Backlight registration failed!\n");
5595 		dm->backlight_dev[aconnector->bl_idx] = NULL;
5596 	} else {
5597 		/*
5598 		 * dm->brightness[x] can be inconsistent just after startup until
5599 		 * ops.get_brightness is called.
5600 		 */
5601 		real_brightness =
5602 			amdgpu_dm_backlight_ops.get_brightness(dm->backlight_dev[aconnector->bl_idx]);
5603 
5604 		if (real_brightness != init_brightness) {
5605 			dm->actual_brightness[aconnector->bl_idx] = real_brightness;
5606 			dm->brightness[aconnector->bl_idx] = real_brightness;
5607 		}
5608 		drm_dbg_driver(drm, "DM: Registered Backlight device: %s\n", bl_name);
5609 	}
5610 }
5611 
5612 static int initialize_plane(struct amdgpu_display_manager *dm,
5613 			    struct amdgpu_mode_info *mode_info, int plane_id,
5614 			    enum drm_plane_type plane_type,
5615 			    const struct dc_plane_cap *plane_cap)
5616 {
5617 	struct drm_plane *plane;
5618 	unsigned long possible_crtcs;
5619 	int ret = 0;
5620 
5621 	plane = kzalloc_obj(struct drm_plane);
5622 	if (!plane) {
5623 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
5624 		return -ENOMEM;
5625 	}
5626 	plane->type = plane_type;
5627 
5628 	/*
5629 	 * HACK: IGT tests expect that the primary plane for a CRTC
5630 	 * can only have one possible CRTC. Only expose support for
5631 	 * any CRTC if they're not going to be used as a primary plane
5632 	 * for a CRTC - like overlay or underlay planes.
5633 	 */
5634 	possible_crtcs = 1 << plane_id;
5635 	if (plane_id >= dm->dc->caps.max_streams)
5636 		possible_crtcs = 0xff;
5637 
5638 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
5639 
5640 	if (ret) {
5641 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
5642 		kfree(plane);
5643 		return ret;
5644 	}
5645 
5646 	if (mode_info)
5647 		mode_info->planes[plane_id] = plane;
5648 
5649 	return ret;
5650 }
5651 
5652 
5653 static void setup_backlight_device(struct amdgpu_display_manager *dm,
5654 				   struct amdgpu_dm_connector *aconnector)
5655 {
5656 	struct amdgpu_dm_backlight_caps *caps;
5657 	struct dc_link *link = aconnector->dc_link;
5658 	int bl_idx = dm->num_of_edps;
5659 
5660 	if (!(link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) ||
5661 	    link->type == dc_connection_none)
5662 		return;
5663 
5664 	if (dm->num_of_edps >= AMDGPU_DM_MAX_NUM_EDP) {
5665 		drm_warn(adev_to_drm(dm->adev), "Too much eDP connections, skipping backlight setup for additional eDPs\n");
5666 		return;
5667 	}
5668 
5669 	aconnector->bl_idx = bl_idx;
5670 
5671 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5672 	dm->backlight_link[bl_idx] = link;
5673 	dm->num_of_edps++;
5674 
5675 	update_connector_ext_caps(aconnector);
5676 	caps = &dm->backlight_caps[aconnector->bl_idx];
5677 
5678 	/* Only offer ABM property when non-OLED and user didn't turn off by module parameter */
5679 	if (caps->ext_caps && !caps->ext_caps->bits.oled && amdgpu_dm_abm_level < 0)
5680 		drm_object_attach_property(&aconnector->base.base,
5681 					   dm->adev->mode_info.abm_level_property,
5682 					   ABM_SYSFS_CONTROL);
5683 }
5684 
5685 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
5686 
5687 
5688 
5689 /*
5690  * In this architecture, the association
5691  * connector -> encoder -> crtc
5692  * id not really requried. The crtc and connector will hold the
5693  * display_index as an abstraction to use with DAL component
5694  *
5695  * Returns 0 on success
5696  */
5697 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
5698 {
5699 	struct amdgpu_display_manager *dm = &adev->dm;
5700 	s32 i;
5701 	struct amdgpu_dm_connector *aconnector = NULL;
5702 	struct amdgpu_encoder *aencoder = NULL;
5703 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5704 	u32 link_cnt;
5705 	s32 primary_planes;
5706 	enum dc_connection_type new_connection_type = dc_connection_none;
5707 	const struct dc_plane_cap *plane;
5708 	bool psr_feature_enabled = false;
5709 	bool replay_feature_enabled = false;
5710 	int max_overlay = dm->dc->caps.max_slave_planes;
5711 
5712 	dm->display_indexes_num = dm->dc->caps.max_streams;
5713 	/* Update the actual used number of crtc */
5714 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
5715 
5716 	amdgpu_dm_set_irq_funcs(adev);
5717 
5718 	link_cnt = dm->dc->caps.max_links;
5719 	if (amdgpu_dm_mode_config_init(dm->adev)) {
5720 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
5721 		return -EINVAL;
5722 	}
5723 
5724 	/* There is one primary plane per CRTC */
5725 	primary_planes = dm->dc->caps.max_streams;
5726 	if (primary_planes > AMDGPU_MAX_PLANES) {
5727 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
5728 		return -EINVAL;
5729 	}
5730 
5731 	/*
5732 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
5733 	 * Order is reversed to match iteration order in atomic check.
5734 	 */
5735 	for (i = (primary_planes - 1); i >= 0; i--) {
5736 		plane = &dm->dc->caps.planes[i];
5737 
5738 		if (initialize_plane(dm, mode_info, i,
5739 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
5740 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
5741 			goto fail;
5742 		}
5743 	}
5744 
5745 	/*
5746 	 * Initialize overlay planes, index starting after primary planes.
5747 	 * These planes have a higher DRM index than the primary planes since
5748 	 * they should be considered as having a higher z-order.
5749 	 * Order is reversed to match iteration order in atomic check.
5750 	 *
5751 	 * Only support DCN for now, and only expose one so we don't encourage
5752 	 * userspace to use up all the pipes.
5753 	 */
5754 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
5755 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
5756 
5757 		/* Do not create overlay if MPO disabled */
5758 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
5759 			break;
5760 
5761 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
5762 			continue;
5763 
5764 		if (!plane->pixel_format_support.argb8888)
5765 			continue;
5766 
5767 		if (max_overlay-- == 0)
5768 			break;
5769 
5770 		if (initialize_plane(dm, NULL, primary_planes + i,
5771 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
5772 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
5773 			goto fail;
5774 		}
5775 	}
5776 
5777 	for (i = 0; i < dm->dc->caps.max_streams; i++)
5778 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
5779 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
5780 			goto fail;
5781 		}
5782 
5783 	/* Use Outbox interrupt */
5784 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5785 	case IP_VERSION(3, 0, 0):
5786 	case IP_VERSION(3, 1, 2):
5787 	case IP_VERSION(3, 1, 3):
5788 	case IP_VERSION(3, 1, 4):
5789 	case IP_VERSION(3, 1, 5):
5790 	case IP_VERSION(3, 1, 6):
5791 	case IP_VERSION(3, 2, 0):
5792 	case IP_VERSION(3, 2, 1):
5793 	case IP_VERSION(2, 1, 0):
5794 	case IP_VERSION(3, 5, 0):
5795 	case IP_VERSION(3, 5, 1):
5796 	case IP_VERSION(3, 6, 0):
5797 	case IP_VERSION(4, 0, 1):
5798 	case IP_VERSION(4, 2, 0):
5799 	case IP_VERSION(4, 2, 1):
5800 		if (register_outbox_irq_handlers(dm->adev)) {
5801 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5802 			goto fail;
5803 		}
5804 		break;
5805 	default:
5806 		drm_dbg_kms(adev_to_drm(adev), "Unsupported DCN IP version for outbox: 0x%X\n",
5807 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
5808 	}
5809 
5810 	/* Determine whether to enable PSR support by default. */
5811 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
5812 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5813 		case IP_VERSION(3, 1, 2):
5814 		case IP_VERSION(3, 1, 3):
5815 		case IP_VERSION(3, 1, 4):
5816 		case IP_VERSION(3, 1, 5):
5817 		case IP_VERSION(3, 1, 6):
5818 		case IP_VERSION(3, 2, 0):
5819 		case IP_VERSION(3, 2, 1):
5820 		case IP_VERSION(3, 5, 0):
5821 		case IP_VERSION(3, 5, 1):
5822 		case IP_VERSION(3, 6, 0):
5823 		case IP_VERSION(4, 0, 1):
5824 		case IP_VERSION(4, 2, 0):
5825 		case IP_VERSION(4, 2, 1):
5826 			psr_feature_enabled = true;
5827 			break;
5828 		default:
5829 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
5830 			break;
5831 		}
5832 	}
5833 
5834 	/* Determine whether to enable Replay support by default. */
5835 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
5836 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5837 		case IP_VERSION(3, 1, 4):
5838 		case IP_VERSION(3, 2, 0):
5839 		case IP_VERSION(3, 2, 1):
5840 		case IP_VERSION(3, 5, 0):
5841 		case IP_VERSION(3, 5, 1):
5842 		case IP_VERSION(3, 6, 0):
5843 		case IP_VERSION(4, 2, 0):
5844 		case IP_VERSION(4, 2, 1):
5845 			replay_feature_enabled = true;
5846 			break;
5847 
5848 		default:
5849 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
5850 			break;
5851 		}
5852 	}
5853 
5854 	if (link_cnt > MAX_LINKS) {
5855 		drm_err(adev_to_drm(adev),
5856 			"KMS: Cannot support more than %d display indexes\n",
5857 				MAX_LINKS);
5858 		goto fail;
5859 	}
5860 
5861 	/* loops over all connectors on the board */
5862 	for (i = 0; i < link_cnt; i++) {
5863 		struct dc_link *link = NULL;
5864 
5865 		link = dc_get_link_at_index(dm->dc, i);
5866 
5867 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
5868 			struct amdgpu_dm_wb_connector *wbcon = kzalloc_obj(*wbcon);
5869 
5870 			if (!wbcon) {
5871 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
5872 				continue;
5873 			}
5874 
5875 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
5876 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
5877 				kfree(wbcon);
5878 				continue;
5879 			}
5880 
5881 			link->psr_settings.psr_feature_enabled = false;
5882 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
5883 
5884 			continue;
5885 		}
5886 
5887 		aconnector = kzalloc_obj(*aconnector);
5888 		if (!aconnector)
5889 			goto fail;
5890 
5891 		aencoder = kzalloc_obj(*aencoder);
5892 		if (!aencoder)
5893 			goto fail;
5894 
5895 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
5896 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
5897 			goto fail;
5898 		}
5899 
5900 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
5901 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
5902 			goto fail;
5903 		}
5904 
5905 		if (dm->hpd_rx_offload_wq)
5906 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
5907 				aconnector;
5908 
5909 		if (!dc_link_detect_connection_type(link, &new_connection_type))
5910 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
5911 
5912 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
5913 			emulated_link_detect(link);
5914 			amdgpu_dm_update_connector_after_detect(aconnector);
5915 		} else {
5916 			bool ret = false;
5917 
5918 			mutex_lock(&dm->dc_lock);
5919 			dc_exit_ips_for_hw_access(dm->dc);
5920 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
5921 			mutex_unlock(&dm->dc_lock);
5922 
5923 			if (ret) {
5924 				amdgpu_dm_update_connector_after_detect(aconnector);
5925 				setup_backlight_device(dm, aconnector);
5926 
5927 				/* Disable PSR if Replay can be enabled */
5928 				if (replay_feature_enabled)
5929 					if (amdgpu_dm_set_replay_caps(link, aconnector))
5930 						psr_feature_enabled = false;
5931 
5932 				if (psr_feature_enabled) {
5933 					amdgpu_dm_set_psr_caps(link, aconnector);
5934 					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",
5935 						 aconnector->base.name,
5936 						 link->psr_settings.psr_feature_enabled,
5937 						 link->psr_settings.psr_version,
5938 						 link->dpcd_caps.psr_info.psr_version,
5939 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
5940 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
5941 				}
5942 			}
5943 		}
5944 		amdgpu_set_panel_orientation(&aconnector->base);
5945 	}
5946 
5947 	/* Debug dump: list all DC links and their associated sinks after detection
5948 	 * is complete for all connectors. This provides a comprehensive view of the
5949 	 * final state without repeating the dump for each connector.
5950 	 */
5951 	amdgpu_dm_dump_links_and_sinks(adev);
5952 
5953 	/* Software is initialized. Now we can register interrupt handlers. */
5954 	switch (adev->asic_type) {
5955 #if defined(CONFIG_DRM_AMD_DC_SI)
5956 	case CHIP_TAHITI:
5957 	case CHIP_PITCAIRN:
5958 	case CHIP_VERDE:
5959 	case CHIP_OLAND:
5960 #endif
5961 	case CHIP_BONAIRE:
5962 	case CHIP_HAWAII:
5963 	case CHIP_KAVERI:
5964 	case CHIP_KABINI:
5965 	case CHIP_MULLINS:
5966 	case CHIP_TONGA:
5967 	case CHIP_FIJI:
5968 	case CHIP_CARRIZO:
5969 	case CHIP_STONEY:
5970 	case CHIP_POLARIS11:
5971 	case CHIP_POLARIS10:
5972 	case CHIP_POLARIS12:
5973 	case CHIP_VEGAM:
5974 	case CHIP_VEGA10:
5975 	case CHIP_VEGA12:
5976 	case CHIP_VEGA20:
5977 		if (dce110_register_irq_handlers(dm->adev)) {
5978 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5979 			goto fail;
5980 		}
5981 		break;
5982 	default:
5983 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5984 		case IP_VERSION(1, 0, 0):
5985 		case IP_VERSION(1, 0, 1):
5986 		case IP_VERSION(2, 0, 2):
5987 		case IP_VERSION(2, 0, 3):
5988 		case IP_VERSION(2, 0, 0):
5989 		case IP_VERSION(2, 1, 0):
5990 		case IP_VERSION(3, 0, 0):
5991 		case IP_VERSION(3, 0, 2):
5992 		case IP_VERSION(3, 0, 3):
5993 		case IP_VERSION(3, 0, 1):
5994 		case IP_VERSION(3, 1, 2):
5995 		case IP_VERSION(3, 1, 3):
5996 		case IP_VERSION(3, 1, 4):
5997 		case IP_VERSION(3, 1, 5):
5998 		case IP_VERSION(3, 1, 6):
5999 		case IP_VERSION(3, 2, 0):
6000 		case IP_VERSION(3, 2, 1):
6001 		case IP_VERSION(3, 5, 0):
6002 		case IP_VERSION(3, 5, 1):
6003 		case IP_VERSION(3, 6, 0):
6004 		case IP_VERSION(4, 0, 1):
6005 		case IP_VERSION(4, 2, 0):
6006 		case IP_VERSION(4, 2, 1):
6007 			if (dcn10_register_irq_handlers(dm->adev)) {
6008 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
6009 				goto fail;
6010 			}
6011 			break;
6012 		default:
6013 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
6014 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6015 			goto fail;
6016 		}
6017 		break;
6018 	}
6019 
6020 	return 0;
6021 fail:
6022 	kfree(aencoder);
6023 	kfree(aconnector);
6024 
6025 	return -EINVAL;
6026 }
6027 
6028 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
6029 {
6030 	if (dm->atomic_obj.state)
6031 		drm_atomic_private_obj_fini(&dm->atomic_obj);
6032 }
6033 
6034 /******************************************************************************
6035  * amdgpu_display_funcs functions
6036  *****************************************************************************/
6037 
6038 /*
6039  * dm_bandwidth_update - program display watermarks
6040  *
6041  * @adev: amdgpu_device pointer
6042  *
6043  * Calculate and program the display watermarks and line buffer allocation.
6044  */
6045 static void dm_bandwidth_update(struct amdgpu_device *adev)
6046 {
6047 	/* TODO: implement later */
6048 }
6049 
6050 static const struct amdgpu_display_funcs dm_display_funcs = {
6051 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
6052 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
6053 	.backlight_set_level = NULL, /* never called for DC */
6054 	.backlight_get_level = NULL, /* never called for DC */
6055 	.hpd_sense = NULL,/* called unconditionally */
6056 	.hpd_set_polarity = NULL, /* called unconditionally */
6057 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
6058 	.page_flip_get_scanoutpos =
6059 		dm_crtc_get_scanoutpos,/* called unconditionally */
6060 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
6061 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
6062 };
6063 
6064 #if defined(CONFIG_DEBUG_KERNEL_DC)
6065 
6066 static ssize_t s3_debug_store(struct device *device,
6067 			      struct device_attribute *attr,
6068 			      const char *buf,
6069 			      size_t count)
6070 {
6071 	int ret;
6072 	int s3_state;
6073 	struct drm_device *drm_dev = dev_get_drvdata(device);
6074 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
6075 	struct amdgpu_ip_block *ip_block;
6076 
6077 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
6078 	if (!ip_block)
6079 		return -EINVAL;
6080 
6081 	ret = kstrtoint(buf, 0, &s3_state);
6082 
6083 	if (ret == 0) {
6084 		if (s3_state) {
6085 			dm_resume(ip_block);
6086 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
6087 		} else
6088 			dm_suspend(ip_block);
6089 	}
6090 
6091 	return ret == 0 ? count : 0;
6092 }
6093 
6094 DEVICE_ATTR_WO(s3_debug);
6095 
6096 #endif
6097 
6098 static int dm_init_microcode(struct amdgpu_device *adev)
6099 {
6100 	char *fw_name_dmub;
6101 	int r;
6102 
6103 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6104 	case IP_VERSION(2, 1, 0):
6105 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
6106 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
6107 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
6108 		break;
6109 	case IP_VERSION(3, 0, 0):
6110 		if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(10, 3, 0))
6111 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
6112 		else
6113 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
6114 		break;
6115 	case IP_VERSION(3, 0, 1):
6116 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
6117 		break;
6118 	case IP_VERSION(3, 0, 2):
6119 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
6120 		break;
6121 	case IP_VERSION(3, 0, 3):
6122 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
6123 		break;
6124 	case IP_VERSION(3, 1, 2):
6125 	case IP_VERSION(3, 1, 3):
6126 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
6127 		break;
6128 	case IP_VERSION(3, 1, 4):
6129 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
6130 		break;
6131 	case IP_VERSION(3, 1, 5):
6132 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
6133 		break;
6134 	case IP_VERSION(3, 1, 6):
6135 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
6136 		break;
6137 	case IP_VERSION(3, 2, 0):
6138 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
6139 		break;
6140 	case IP_VERSION(3, 2, 1):
6141 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
6142 		break;
6143 	case IP_VERSION(3, 5, 0):
6144 		fw_name_dmub = FIRMWARE_DCN_35_DMUB;
6145 		break;
6146 	case IP_VERSION(3, 5, 1):
6147 		fw_name_dmub = FIRMWARE_DCN_351_DMUB;
6148 		break;
6149 	case IP_VERSION(3, 6, 0):
6150 		fw_name_dmub = FIRMWARE_DCN_36_DMUB;
6151 		break;
6152 	case IP_VERSION(4, 0, 1):
6153 		fw_name_dmub = FIRMWARE_DCN_401_DMUB;
6154 		break;
6155 	case IP_VERSION(4, 2, 0):
6156 		fw_name_dmub = FIRMWARE_DCN_42_DMUB;
6157 		break;
6158 	case IP_VERSION(4, 2, 1):
6159 		fw_name_dmub = FIRMWARE_DCN_42B_DMUB;
6160 		break;
6161 	default:
6162 		/* ASIC doesn't support DMUB. */
6163 		return 0;
6164 	}
6165 	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, AMDGPU_UCODE_REQUIRED,
6166 				 "%s", fw_name_dmub);
6167 	return r;
6168 }
6169 
6170 static int dm_early_init(struct amdgpu_ip_block *ip_block)
6171 {
6172 	struct amdgpu_device *adev = ip_block->adev;
6173 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
6174 	struct atom_context *ctx = mode_info->atom_context;
6175 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
6176 	u16 data_offset;
6177 
6178 	/* if there is no object header, skip DM */
6179 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
6180 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
6181 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
6182 		return -ENOENT;
6183 	}
6184 
6185 	switch (adev->asic_type) {
6186 #if defined(CONFIG_DRM_AMD_DC_SI)
6187 	case CHIP_TAHITI:
6188 	case CHIP_PITCAIRN:
6189 	case CHIP_VERDE:
6190 		adev->mode_info.num_crtc = 6;
6191 		adev->mode_info.num_hpd = 6;
6192 		adev->mode_info.num_dig = 6;
6193 		break;
6194 	case CHIP_OLAND:
6195 		adev->mode_info.num_crtc = 2;
6196 		adev->mode_info.num_hpd = 2;
6197 		adev->mode_info.num_dig = 2;
6198 		break;
6199 #endif
6200 	case CHIP_BONAIRE:
6201 	case CHIP_HAWAII:
6202 		adev->mode_info.num_crtc = 6;
6203 		adev->mode_info.num_hpd = 6;
6204 		adev->mode_info.num_dig = 6;
6205 		break;
6206 	case CHIP_KAVERI:
6207 		adev->mode_info.num_crtc = 4;
6208 		adev->mode_info.num_hpd = 6;
6209 		adev->mode_info.num_dig = 7;
6210 		break;
6211 	case CHIP_KABINI:
6212 	case CHIP_MULLINS:
6213 		adev->mode_info.num_crtc = 2;
6214 		adev->mode_info.num_hpd = 6;
6215 		adev->mode_info.num_dig = 6;
6216 		break;
6217 	case CHIP_FIJI:
6218 	case CHIP_TONGA:
6219 		adev->mode_info.num_crtc = 6;
6220 		adev->mode_info.num_hpd = 6;
6221 		adev->mode_info.num_dig = 7;
6222 		break;
6223 	case CHIP_CARRIZO:
6224 		adev->mode_info.num_crtc = 3;
6225 		adev->mode_info.num_hpd = 6;
6226 		adev->mode_info.num_dig = 9;
6227 		break;
6228 	case CHIP_STONEY:
6229 		adev->mode_info.num_crtc = 2;
6230 		adev->mode_info.num_hpd = 6;
6231 		adev->mode_info.num_dig = 9;
6232 		break;
6233 	case CHIP_POLARIS11:
6234 	case CHIP_POLARIS12:
6235 		adev->mode_info.num_crtc = 5;
6236 		adev->mode_info.num_hpd = 5;
6237 		adev->mode_info.num_dig = 5;
6238 		break;
6239 	case CHIP_POLARIS10:
6240 	case CHIP_VEGAM:
6241 		adev->mode_info.num_crtc = 6;
6242 		adev->mode_info.num_hpd = 6;
6243 		adev->mode_info.num_dig = 6;
6244 		break;
6245 	case CHIP_VEGA10:
6246 	case CHIP_VEGA12:
6247 	case CHIP_VEGA20:
6248 		adev->mode_info.num_crtc = 6;
6249 		adev->mode_info.num_hpd = 6;
6250 		adev->mode_info.num_dig = 6;
6251 		break;
6252 	default:
6253 
6254 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6255 		case IP_VERSION(2, 0, 2):
6256 		case IP_VERSION(3, 0, 0):
6257 			adev->mode_info.num_crtc = 6;
6258 			adev->mode_info.num_hpd = 6;
6259 			adev->mode_info.num_dig = 6;
6260 			break;
6261 		case IP_VERSION(2, 0, 0):
6262 		case IP_VERSION(3, 0, 2):
6263 			adev->mode_info.num_crtc = 5;
6264 			adev->mode_info.num_hpd = 5;
6265 			adev->mode_info.num_dig = 5;
6266 			break;
6267 		case IP_VERSION(2, 0, 3):
6268 		case IP_VERSION(3, 0, 3):
6269 			adev->mode_info.num_crtc = 2;
6270 			adev->mode_info.num_hpd = 2;
6271 			adev->mode_info.num_dig = 2;
6272 			break;
6273 		case IP_VERSION(1, 0, 0):
6274 		case IP_VERSION(1, 0, 1):
6275 		case IP_VERSION(3, 0, 1):
6276 		case IP_VERSION(2, 1, 0):
6277 		case IP_VERSION(3, 1, 2):
6278 		case IP_VERSION(3, 1, 3):
6279 		case IP_VERSION(3, 1, 4):
6280 		case IP_VERSION(3, 1, 5):
6281 		case IP_VERSION(3, 1, 6):
6282 		case IP_VERSION(3, 2, 0):
6283 		case IP_VERSION(3, 2, 1):
6284 		case IP_VERSION(3, 5, 0):
6285 		case IP_VERSION(3, 5, 1):
6286 		case IP_VERSION(3, 6, 0):
6287 		case IP_VERSION(4, 0, 1):
6288 		case IP_VERSION(4, 2, 0):
6289 		case IP_VERSION(4, 2, 1):
6290 			adev->mode_info.num_crtc = 4;
6291 			adev->mode_info.num_hpd = 4;
6292 			adev->mode_info.num_dig = 4;
6293 			break;
6294 		default:
6295 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
6296 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6297 			return -EINVAL;
6298 		}
6299 		break;
6300 	}
6301 
6302 	if (adev->mode_info.funcs == NULL)
6303 		adev->mode_info.funcs = &dm_display_funcs;
6304 
6305 	/*
6306 	 * Note: Do NOT change adev->reg.audio_endpt.rreg and
6307 	 * adev->reg.audio_endpt.wreg because they are initialised in
6308 	 * amdgpu_device_init()
6309 	 */
6310 #if defined(CONFIG_DEBUG_KERNEL_DC)
6311 	device_create_file(
6312 		adev_to_drm(adev)->dev,
6313 		&dev_attr_s3_debug);
6314 #endif
6315 	adev->dc_enabled = true;
6316 
6317 	return dm_init_microcode(adev);
6318 }
6319 
6320 static bool modereset_required(struct drm_crtc_state *crtc_state)
6321 {
6322 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
6323 }
6324 
6325 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
6326 {
6327 	drm_encoder_cleanup(encoder);
6328 	kfree(encoder);
6329 }
6330 
6331 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
6332 	.destroy = amdgpu_dm_encoder_destroy,
6333 };
6334 
6335 static int
6336 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
6337 			    const enum surface_pixel_format format,
6338 			    enum dc_color_space *color_space)
6339 {
6340 	bool full_range;
6341 
6342 	*color_space = COLOR_SPACE_SRGB;
6343 
6344 	/* Ignore properties when DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE is set */
6345 	if (plane_state->state && plane_state->state->plane_color_pipeline)
6346 		return 0;
6347 
6348 	/* DRM color properties only affect non-RGB formats. */
6349 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
6350 		return 0;
6351 
6352 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
6353 
6354 	switch (plane_state->color_encoding) {
6355 	case DRM_COLOR_YCBCR_BT601:
6356 		if (full_range)
6357 			*color_space = COLOR_SPACE_YCBCR601;
6358 		else
6359 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
6360 		break;
6361 
6362 	case DRM_COLOR_YCBCR_BT709:
6363 		if (full_range)
6364 			*color_space = COLOR_SPACE_YCBCR709;
6365 		else
6366 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
6367 		break;
6368 
6369 	case DRM_COLOR_YCBCR_BT2020:
6370 		if (full_range)
6371 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
6372 		else
6373 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6374 		break;
6375 
6376 	default:
6377 		return -EINVAL;
6378 	}
6379 
6380 	return 0;
6381 }
6382 
6383 static int
6384 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
6385 			    const struct drm_plane_state *plane_state,
6386 			    const u64 tiling_flags,
6387 			    struct dc_plane_info *plane_info,
6388 			    struct dc_plane_address *address,
6389 			    bool tmz_surface)
6390 {
6391 	const struct drm_framebuffer *fb = plane_state->fb;
6392 	const struct amdgpu_framebuffer *afb =
6393 		to_amdgpu_framebuffer(plane_state->fb);
6394 	int ret;
6395 
6396 	memset(plane_info, 0, sizeof(*plane_info));
6397 
6398 	switch (fb->format->format) {
6399 	case DRM_FORMAT_C8:
6400 		plane_info->format =
6401 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
6402 		break;
6403 	case DRM_FORMAT_RGB565:
6404 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
6405 		break;
6406 	case DRM_FORMAT_XRGB8888:
6407 	case DRM_FORMAT_ARGB8888:
6408 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6409 		break;
6410 	case DRM_FORMAT_XRGB2101010:
6411 	case DRM_FORMAT_ARGB2101010:
6412 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
6413 		break;
6414 	case DRM_FORMAT_XBGR2101010:
6415 	case DRM_FORMAT_ABGR2101010:
6416 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
6417 		break;
6418 	case DRM_FORMAT_XBGR8888:
6419 	case DRM_FORMAT_ABGR8888:
6420 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
6421 		break;
6422 	case DRM_FORMAT_NV21:
6423 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
6424 		break;
6425 	case DRM_FORMAT_NV12:
6426 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
6427 		break;
6428 	case DRM_FORMAT_P010:
6429 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
6430 		break;
6431 	case DRM_FORMAT_XRGB16161616F:
6432 	case DRM_FORMAT_ARGB16161616F:
6433 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
6434 		break;
6435 	case DRM_FORMAT_XBGR16161616F:
6436 	case DRM_FORMAT_ABGR16161616F:
6437 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
6438 		break;
6439 	case DRM_FORMAT_XRGB16161616:
6440 	case DRM_FORMAT_ARGB16161616:
6441 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
6442 		break;
6443 	case DRM_FORMAT_XBGR16161616:
6444 	case DRM_FORMAT_ABGR16161616:
6445 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
6446 		break;
6447 	default:
6448 		drm_err(adev_to_drm(adev),
6449 			"Unsupported screen format %p4cc\n",
6450 			&fb->format->format);
6451 		return -EINVAL;
6452 	}
6453 
6454 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
6455 	case DRM_MODE_ROTATE_0:
6456 		plane_info->rotation = ROTATION_ANGLE_0;
6457 		break;
6458 	case DRM_MODE_ROTATE_90:
6459 		plane_info->rotation = ROTATION_ANGLE_90;
6460 		break;
6461 	case DRM_MODE_ROTATE_180:
6462 		plane_info->rotation = ROTATION_ANGLE_180;
6463 		break;
6464 	case DRM_MODE_ROTATE_270:
6465 		plane_info->rotation = ROTATION_ANGLE_270;
6466 		break;
6467 	default:
6468 		plane_info->rotation = ROTATION_ANGLE_0;
6469 		break;
6470 	}
6471 
6472 
6473 	plane_info->visible = true;
6474 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
6475 
6476 	plane_info->layer_index = plane_state->normalized_zpos;
6477 
6478 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
6479 					  &plane_info->color_space);
6480 	if (ret)
6481 		return ret;
6482 
6483 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
6484 					   plane_info->rotation, tiling_flags,
6485 					   &plane_info->tiling_info,
6486 					   &plane_info->plane_size,
6487 					   &plane_info->dcc, address,
6488 					   tmz_surface);
6489 	if (ret)
6490 		return ret;
6491 
6492 	amdgpu_dm_plane_fill_blending_from_plane_state(
6493 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
6494 		&plane_info->global_alpha, &plane_info->global_alpha_value);
6495 
6496 	return 0;
6497 }
6498 
6499 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
6500 				    struct dc_plane_state *dc_plane_state,
6501 				    struct drm_plane_state *plane_state,
6502 				    struct drm_crtc_state *crtc_state)
6503 {
6504 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6505 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
6506 	struct dc_scaling_info scaling_info;
6507 	struct dc_plane_info plane_info;
6508 	int ret;
6509 
6510 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
6511 	if (ret)
6512 		return ret;
6513 
6514 	dc_plane_state->src_rect = scaling_info.src_rect;
6515 	dc_plane_state->dst_rect = scaling_info.dst_rect;
6516 	dc_plane_state->clip_rect = scaling_info.clip_rect;
6517 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
6518 
6519 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
6520 					  afb->tiling_flags,
6521 					  &plane_info,
6522 					  &dc_plane_state->address,
6523 					  afb->tmz_surface);
6524 	if (ret)
6525 		return ret;
6526 
6527 	dc_plane_state->format = plane_info.format;
6528 	dc_plane_state->color_space = plane_info.color_space;
6529 	dc_plane_state->format = plane_info.format;
6530 	dc_plane_state->plane_size = plane_info.plane_size;
6531 	dc_plane_state->rotation = plane_info.rotation;
6532 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
6533 	dc_plane_state->stereo_format = plane_info.stereo_format;
6534 	dc_plane_state->tiling_info = plane_info.tiling_info;
6535 	dc_plane_state->visible = plane_info.visible;
6536 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
6537 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
6538 	dc_plane_state->global_alpha = plane_info.global_alpha;
6539 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
6540 	dc_plane_state->dcc = plane_info.dcc;
6541 	dc_plane_state->layer_index = plane_info.layer_index;
6542 	dc_plane_state->flip_int_enabled = true;
6543 
6544 	/*
6545 	 * Always set input transfer function, since plane state is refreshed
6546 	 * every time.
6547 	 */
6548 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
6549 						plane_state,
6550 						dc_plane_state);
6551 	if (ret)
6552 		return ret;
6553 
6554 	return 0;
6555 }
6556 
6557 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
6558 				      struct rect *dirty_rect, int32_t x,
6559 				      s32 y, s32 width, s32 height,
6560 				      int *i, bool ffu)
6561 {
6562 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
6563 
6564 	dirty_rect->x = x;
6565 	dirty_rect->y = y;
6566 	dirty_rect->width = width;
6567 	dirty_rect->height = height;
6568 
6569 	if (ffu)
6570 		drm_dbg(plane->dev,
6571 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
6572 			plane->base.id, width, height);
6573 	else
6574 		drm_dbg(plane->dev,
6575 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
6576 			plane->base.id, x, y, width, height);
6577 
6578 	(*i)++;
6579 }
6580 
6581 /**
6582  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
6583  *
6584  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
6585  *         remote fb
6586  * @old_plane_state: Old state of @plane
6587  * @new_plane_state: New state of @plane
6588  * @crtc_state: New state of CRTC connected to the @plane
6589  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
6590  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
6591  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
6592  *             that have changed will be updated. If PSR SU is not enabled,
6593  *             or if damage clips are not available, the entire screen will be updated.
6594  * @dirty_regions_changed: dirty regions changed
6595  *
6596  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
6597  * (referred to as "damage clips" in DRM nomenclature) that require updating on
6598  * the eDP remote buffer. The responsibility of specifying the dirty regions is
6599  * amdgpu_dm's.
6600  *
6601  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
6602  * plane with regions that require flushing to the eDP remote buffer. In
6603  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
6604  * implicitly provide damage clips without any client support via the plane
6605  * bounds.
6606  */
6607 static void fill_dc_dirty_rects(struct drm_plane *plane,
6608 				struct drm_plane_state *old_plane_state,
6609 				struct drm_plane_state *new_plane_state,
6610 				struct drm_crtc_state *crtc_state,
6611 				struct dc_flip_addrs *flip_addrs,
6612 				bool is_psr_su,
6613 				bool *dirty_regions_changed)
6614 {
6615 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6616 	struct rect *dirty_rects = flip_addrs->dirty_rects;
6617 	u32 num_clips = 0;
6618 	struct drm_mode_rect *clips = NULL;
6619 	bool bb_changed;
6620 	bool fb_changed;
6621 	u32 i = 0;
6622 	*dirty_regions_changed = false;
6623 
6624 	/*
6625 	 * Cursor plane has it's own dirty rect update interface. See
6626 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
6627 	 */
6628 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
6629 		return;
6630 
6631 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
6632 		goto ffu;
6633 
6634 	if (!new_plane_state->ignore_damage_clips) {
6635 		num_clips = drm_plane_get_damage_clips_count(new_plane_state);
6636 		clips = drm_plane_get_damage_clips(new_plane_state);
6637 	}
6638 
6639 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
6640 						   is_psr_su)))
6641 		goto ffu;
6642 
6643 	if (!dm_crtc_state->mpo_requested) {
6644 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
6645 			goto ffu;
6646 
6647 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
6648 			fill_dc_dirty_rect(new_plane_state->plane,
6649 					   &dirty_rects[flip_addrs->dirty_rect_count],
6650 					   clips->x1, clips->y1,
6651 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
6652 					   &flip_addrs->dirty_rect_count,
6653 					   false);
6654 		return;
6655 	}
6656 
6657 	/*
6658 	 * MPO is requested. Add entire plane bounding box to dirty rects if
6659 	 * flipped to or damaged.
6660 	 *
6661 	 * If plane is moved or resized, also add old bounding box to dirty
6662 	 * rects.
6663 	 */
6664 	fb_changed = old_plane_state->fb->base.id !=
6665 		     new_plane_state->fb->base.id;
6666 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
6667 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
6668 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
6669 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
6670 
6671 	drm_dbg(plane->dev,
6672 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
6673 		new_plane_state->plane->base.id,
6674 		bb_changed, fb_changed, num_clips);
6675 
6676 	*dirty_regions_changed = bb_changed;
6677 
6678 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
6679 		goto ffu;
6680 
6681 	if (bb_changed) {
6682 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6683 				   new_plane_state->crtc_x,
6684 				   new_plane_state->crtc_y,
6685 				   new_plane_state->crtc_w,
6686 				   new_plane_state->crtc_h, &i, false);
6687 
6688 		/* Add old plane bounding-box if plane is moved or resized */
6689 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6690 				   old_plane_state->crtc_x,
6691 				   old_plane_state->crtc_y,
6692 				   old_plane_state->crtc_w,
6693 				   old_plane_state->crtc_h, &i, false);
6694 	}
6695 
6696 	if (num_clips) {
6697 		for (; i < num_clips; clips++)
6698 			fill_dc_dirty_rect(new_plane_state->plane,
6699 					   &dirty_rects[i], clips->x1,
6700 					   clips->y1, clips->x2 - clips->x1,
6701 					   clips->y2 - clips->y1, &i, false);
6702 	} else if (fb_changed && !bb_changed) {
6703 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6704 				   new_plane_state->crtc_x,
6705 				   new_plane_state->crtc_y,
6706 				   new_plane_state->crtc_w,
6707 				   new_plane_state->crtc_h, &i, false);
6708 	}
6709 
6710 	flip_addrs->dirty_rect_count = i;
6711 	return;
6712 
6713 ffu:
6714 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
6715 			   dm_crtc_state->base.mode.crtc_hdisplay,
6716 			   dm_crtc_state->base.mode.crtc_vdisplay,
6717 			   &flip_addrs->dirty_rect_count, true);
6718 }
6719 
6720 static void update_stream_scaling_settings(struct drm_device *dev,
6721 					   const struct drm_display_mode *mode,
6722 					   const struct dm_connector_state *dm_state,
6723 					   struct dc_stream_state *stream)
6724 {
6725 	enum amdgpu_rmx_type rmx_type;
6726 
6727 	struct rect src = { 0 }; /* viewport in composition space*/
6728 	struct rect dst = { 0 }; /* stream addressable area */
6729 
6730 	/* no mode. nothing to be done */
6731 	if (!mode)
6732 		return;
6733 
6734 	/* Full screen scaling by default */
6735 	src.width = mode->hdisplay;
6736 	src.height = mode->vdisplay;
6737 	dst.width = stream->timing.h_addressable;
6738 	dst.height = stream->timing.v_addressable;
6739 
6740 	if (dm_state) {
6741 		rmx_type = dm_state->scaling;
6742 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
6743 			if (src.width * dst.height <
6744 					src.height * dst.width) {
6745 				/* height needs less upscaling/more downscaling */
6746 				dst.width = src.width *
6747 						dst.height / src.height;
6748 			} else {
6749 				/* width needs less upscaling/more downscaling */
6750 				dst.height = src.height *
6751 						dst.width / src.width;
6752 			}
6753 		} else if (rmx_type == RMX_CENTER) {
6754 			dst = src;
6755 		}
6756 
6757 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
6758 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
6759 
6760 		if (dm_state->underscan_enable) {
6761 			dst.x += dm_state->underscan_hborder / 2;
6762 			dst.y += dm_state->underscan_vborder / 2;
6763 			dst.width -= dm_state->underscan_hborder;
6764 			dst.height -= dm_state->underscan_vborder;
6765 		}
6766 	}
6767 
6768 	stream->src = src;
6769 	stream->dst = dst;
6770 
6771 	drm_dbg_kms(dev, "Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
6772 		    dst.x, dst.y, dst.width, dst.height);
6773 
6774 }
6775 
6776 static enum dc_color_depth
6777 convert_color_depth_from_display_info(const struct drm_connector *connector,
6778 				      bool is_y420, int requested_bpc)
6779 {
6780 	u8 bpc;
6781 
6782 	if (is_y420) {
6783 		bpc = 8;
6784 
6785 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
6786 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
6787 			bpc = 16;
6788 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
6789 			bpc = 12;
6790 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
6791 			bpc = 10;
6792 	} else {
6793 		bpc = (uint8_t)connector->display_info.bpc;
6794 		/* Assume 8 bpc by default if no bpc is specified. */
6795 		bpc = bpc ? bpc : 8;
6796 	}
6797 
6798 	if (requested_bpc > 0) {
6799 		/*
6800 		 * Cap display bpc based on the user requested value.
6801 		 *
6802 		 * The value for state->max_bpc may not correctly updated
6803 		 * depending on when the connector gets added to the state
6804 		 * or if this was called outside of atomic check, so it
6805 		 * can't be used directly.
6806 		 */
6807 		bpc = min_t(u8, bpc, requested_bpc);
6808 
6809 		/* Round down to the nearest even number. */
6810 		bpc = bpc - (bpc & 1);
6811 	}
6812 
6813 	switch (bpc) {
6814 	case 0:
6815 		/*
6816 		 * Temporary Work around, DRM doesn't parse color depth for
6817 		 * EDID revision before 1.4
6818 		 * TODO: Fix edid parsing
6819 		 */
6820 		return COLOR_DEPTH_888;
6821 	case 6:
6822 		return COLOR_DEPTH_666;
6823 	case 8:
6824 		return COLOR_DEPTH_888;
6825 	case 10:
6826 		return COLOR_DEPTH_101010;
6827 	case 12:
6828 		return COLOR_DEPTH_121212;
6829 	case 14:
6830 		return COLOR_DEPTH_141414;
6831 	case 16:
6832 		return COLOR_DEPTH_161616;
6833 	default:
6834 		return COLOR_DEPTH_UNDEFINED;
6835 	}
6836 }
6837 
6838 static enum dc_aspect_ratio
6839 get_aspect_ratio(const struct drm_display_mode *mode_in)
6840 {
6841 	/* 1-1 mapping, since both enums follow the HDMI spec. */
6842 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
6843 }
6844 
6845 static enum dc_color_space
6846 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
6847 		       const struct drm_connector_state *connector_state)
6848 {
6849 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
6850 
6851 	switch (connector_state->colorspace) {
6852 	case DRM_MODE_COLORIMETRY_BT601_YCC:
6853 		if (dc_crtc_timing->flags.Y_ONLY)
6854 			color_space = COLOR_SPACE_YCBCR601_LIMITED;
6855 		else
6856 			color_space = COLOR_SPACE_YCBCR601;
6857 		break;
6858 	case DRM_MODE_COLORIMETRY_BT709_YCC:
6859 		if (dc_crtc_timing->flags.Y_ONLY)
6860 			color_space = COLOR_SPACE_YCBCR709_LIMITED;
6861 		else
6862 			color_space = COLOR_SPACE_YCBCR709;
6863 		break;
6864 	case DRM_MODE_COLORIMETRY_OPRGB:
6865 		color_space = COLOR_SPACE_ADOBERGB;
6866 		break;
6867 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
6868 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
6869 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
6870 			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
6871 		else
6872 			color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6873 		break;
6874 	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
6875 	default:
6876 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
6877 			color_space = COLOR_SPACE_SRGB;
6878 			if (connector_state->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_LIMITED)
6879 				color_space = COLOR_SPACE_SRGB_LIMITED;
6880 		/*
6881 		 * 27030khz is the separation point between HDTV and SDTV
6882 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
6883 		 * respectively
6884 		 */
6885 		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
6886 			if (dc_crtc_timing->flags.Y_ONLY)
6887 				color_space =
6888 					COLOR_SPACE_YCBCR709_LIMITED;
6889 			else
6890 				color_space = COLOR_SPACE_YCBCR709;
6891 		} else {
6892 			if (dc_crtc_timing->flags.Y_ONLY)
6893 				color_space =
6894 					COLOR_SPACE_YCBCR601_LIMITED;
6895 			else
6896 				color_space = COLOR_SPACE_YCBCR601;
6897 		}
6898 		break;
6899 	}
6900 
6901 	return color_space;
6902 }
6903 
6904 static enum display_content_type
6905 get_output_content_type(const struct drm_connector_state *connector_state)
6906 {
6907 	switch (connector_state->content_type) {
6908 	default:
6909 	case DRM_MODE_CONTENT_TYPE_NO_DATA:
6910 		return DISPLAY_CONTENT_TYPE_NO_DATA;
6911 	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
6912 		return DISPLAY_CONTENT_TYPE_GRAPHICS;
6913 	case DRM_MODE_CONTENT_TYPE_PHOTO:
6914 		return DISPLAY_CONTENT_TYPE_PHOTO;
6915 	case DRM_MODE_CONTENT_TYPE_CINEMA:
6916 		return DISPLAY_CONTENT_TYPE_CINEMA;
6917 	case DRM_MODE_CONTENT_TYPE_GAME:
6918 		return DISPLAY_CONTENT_TYPE_GAME;
6919 	}
6920 }
6921 
6922 static bool adjust_colour_depth_from_display_info(
6923 	struct dc_crtc_timing *timing_out,
6924 	const struct drm_display_info *info)
6925 {
6926 	enum dc_color_depth depth = timing_out->display_color_depth;
6927 	int normalized_clk;
6928 
6929 	do {
6930 		normalized_clk = timing_out->pix_clk_100hz / 10;
6931 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
6932 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
6933 			normalized_clk /= 2;
6934 		/* Adjusting pix clock following on HDMI spec based on colour depth */
6935 		switch (depth) {
6936 		case COLOR_DEPTH_888:
6937 			break;
6938 		case COLOR_DEPTH_101010:
6939 			normalized_clk = (normalized_clk * 30) / 24;
6940 			break;
6941 		case COLOR_DEPTH_121212:
6942 			normalized_clk = (normalized_clk * 36) / 24;
6943 			break;
6944 		case COLOR_DEPTH_161616:
6945 			normalized_clk = (normalized_clk * 48) / 24;
6946 			break;
6947 		default:
6948 			/* The above depths are the only ones valid for HDMI. */
6949 			return false;
6950 		}
6951 		if (normalized_clk <= info->max_tmds_clock) {
6952 			timing_out->display_color_depth = depth;
6953 			return true;
6954 		}
6955 	} while (--depth > COLOR_DEPTH_666);
6956 	return false;
6957 }
6958 
6959 static void fill_stream_properties_from_drm_display_mode(
6960 	struct dc_stream_state *stream,
6961 	const struct drm_display_mode *mode_in,
6962 	const struct drm_connector *connector,
6963 	const struct drm_connector_state *connector_state,
6964 	const struct dc_stream_state *old_stream,
6965 	int requested_bpc)
6966 {
6967 	struct dc_crtc_timing *timing_out = &stream->timing;
6968 	const struct drm_display_info *info = &connector->display_info;
6969 	struct amdgpu_dm_connector *aconnector = NULL;
6970 	struct hdmi_vendor_infoframe hv_frame;
6971 	struct hdmi_avi_infoframe avi_frame;
6972 	ssize_t err;
6973 
6974 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
6975 		aconnector = to_amdgpu_dm_connector(connector);
6976 
6977 	memset(&hv_frame, 0, sizeof(hv_frame));
6978 	memset(&avi_frame, 0, sizeof(avi_frame));
6979 
6980 	timing_out->h_border_left = 0;
6981 	timing_out->h_border_right = 0;
6982 	timing_out->v_border_top = 0;
6983 	timing_out->v_border_bottom = 0;
6984 	/* TODO: un-hardcode */
6985 	if (drm_mode_is_420_only(info, mode_in)
6986 			&& (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
6987 			    stream->signal == SIGNAL_TYPE_HDMI_FRL)
6988 			&& aconnector
6989 			&& aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR420)
6990 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6991 	else if (drm_mode_is_420_also(info, mode_in)
6992 			&& aconnector
6993 			&& (aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR420
6994 			|| aconnector->force_yuv420_output))
6995 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6996 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR422))
6997 			&& aconnector
6998 			&& (aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR422
6999 			|| aconnector->force_yuv422_output))
7000 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR422;
7001 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR444))
7002 			&& (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7003 			    stream->signal == SIGNAL_TYPE_HDMI_FRL)
7004 			&& aconnector
7005 			&& aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR444)
7006 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
7007 	else
7008 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
7009 
7010 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
7011 	timing_out->display_color_depth = convert_color_depth_from_display_info(
7012 		connector,
7013 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
7014 		requested_bpc);
7015 	timing_out->scan_type = SCANNING_TYPE_NODATA;
7016 	timing_out->hdmi_vic = 0;
7017 
7018 	if (old_stream) {
7019 		timing_out->vic = old_stream->timing.vic;
7020 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
7021 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
7022 	} else {
7023 		timing_out->vic = drm_match_cea_mode(mode_in);
7024 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
7025 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
7026 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
7027 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
7028 	}
7029 
7030 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7031 		stream->signal == SIGNAL_TYPE_HDMI_FRL) {
7032 		err = drm_hdmi_avi_infoframe_from_display_mode(&avi_frame,
7033 							       (struct drm_connector *)connector,
7034 							       mode_in);
7035 		if (err < 0)
7036 			drm_warn_once(connector->dev, "Failed to setup avi infoframe on connector %s: %zd\n",
7037 				      connector->name, err);
7038 		timing_out->vic = avi_frame.video_code;
7039 		err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame,
7040 								  (struct drm_connector *)connector,
7041 								  mode_in);
7042 		if (err < 0)
7043 			drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n",
7044 				      connector->name, err);
7045 		timing_out->hdmi_vic = hv_frame.vic;
7046 	}
7047 
7048 	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
7049 		timing_out->h_addressable = mode_in->hdisplay;
7050 		timing_out->h_total = mode_in->htotal;
7051 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
7052 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
7053 		timing_out->v_total = mode_in->vtotal;
7054 		timing_out->v_addressable = mode_in->vdisplay;
7055 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
7056 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
7057 		timing_out->pix_clk_100hz = mode_in->clock * 10;
7058 	} else {
7059 		timing_out->h_addressable = mode_in->crtc_hdisplay;
7060 		timing_out->h_total = mode_in->crtc_htotal;
7061 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
7062 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
7063 		timing_out->v_total = mode_in->crtc_vtotal;
7064 		timing_out->v_addressable = mode_in->crtc_vdisplay;
7065 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
7066 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
7067 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
7068 	}
7069 
7070 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
7071 
7072 	stream->out_transfer_func.type = TF_TYPE_PREDEFINED;
7073 	stream->out_transfer_func.tf = TRANSFER_FUNCTION_SRGB;
7074 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
7075 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
7076 		    drm_mode_is_420_also(info, mode_in) &&
7077 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
7078 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
7079 			adjust_colour_depth_from_display_info(timing_out, info);
7080 		}
7081 	}
7082 
7083 	stream->output_color_space = get_output_color_space(timing_out, connector_state);
7084 	stream->content_type = get_output_content_type(connector_state);
7085 }
7086 
7087 static void fill_audio_info(struct audio_info *audio_info,
7088 			    const struct drm_connector *drm_connector,
7089 			    const struct dc_sink *dc_sink)
7090 {
7091 	int i = 0;
7092 	int cea_revision = 0;
7093 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
7094 
7095 	audio_info->manufacture_id = edid_caps->manufacturer_id;
7096 	audio_info->product_id = edid_caps->product_id;
7097 
7098 	cea_revision = drm_connector->display_info.cea_rev;
7099 
7100 	strscpy(audio_info->display_name,
7101 		edid_caps->display_name,
7102 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
7103 
7104 	if (cea_revision >= 3) {
7105 		audio_info->mode_count = edid_caps->audio_mode_count;
7106 
7107 		for (i = 0; i < audio_info->mode_count; ++i) {
7108 			audio_info->modes[i].format_code =
7109 					(enum audio_format_code)
7110 					(edid_caps->audio_modes[i].format_code);
7111 			audio_info->modes[i].channel_count =
7112 					edid_caps->audio_modes[i].channel_count;
7113 			audio_info->modes[i].sample_rates.all =
7114 					edid_caps->audio_modes[i].sample_rate;
7115 			audio_info->modes[i].sample_size =
7116 					edid_caps->audio_modes[i].sample_size;
7117 		}
7118 	}
7119 
7120 	audio_info->flags.all = edid_caps->speaker_flags;
7121 
7122 	/* TODO: We only check for the progressive mode, check for interlace mode too */
7123 	if (drm_connector->latency_present[0]) {
7124 		audio_info->video_latency = drm_connector->video_latency[0];
7125 		audio_info->audio_latency = drm_connector->audio_latency[0];
7126 	}
7127 
7128 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
7129 
7130 }
7131 
7132 static void
7133 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
7134 				      struct drm_display_mode *dst_mode)
7135 {
7136 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
7137 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
7138 	dst_mode->crtc_clock = src_mode->crtc_clock;
7139 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
7140 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
7141 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
7142 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
7143 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
7144 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
7145 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
7146 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
7147 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
7148 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
7149 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
7150 }
7151 
7152 static void
7153 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
7154 					const struct drm_display_mode *native_mode,
7155 					bool scale_enabled)
7156 {
7157 	if (scale_enabled || (
7158 	    native_mode->clock == drm_mode->clock &&
7159 	    native_mode->htotal == drm_mode->htotal &&
7160 	    native_mode->vtotal == drm_mode->vtotal)) {
7161 		if (native_mode->crtc_clock)
7162 			copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
7163 	} else {
7164 		/* no scaling nor amdgpu inserted, no need to patch */
7165 	}
7166 }
7167 
7168 static struct dc_sink *
7169 create_fake_sink(struct drm_device *dev, struct dc_link *link)
7170 {
7171 	struct dc_sink_init_data sink_init_data = { 0 };
7172 	struct dc_sink *sink = NULL;
7173 
7174 	sink_init_data.link = link;
7175 	sink_init_data.sink_signal = link->connector_signal;
7176 
7177 	sink = dc_sink_create(&sink_init_data);
7178 	if (!sink) {
7179 		drm_err(dev, "Failed to create sink!\n");
7180 		return NULL;
7181 	}
7182 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
7183 
7184 	return sink;
7185 }
7186 
7187 static void set_multisync_trigger_params(
7188 		struct dc_stream_state *stream)
7189 {
7190 	struct dc_stream_state *master = NULL;
7191 
7192 	if (stream->triggered_crtc_reset.enabled) {
7193 		master = stream->triggered_crtc_reset.event_source;
7194 		stream->triggered_crtc_reset.event =
7195 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
7196 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
7197 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
7198 	}
7199 }
7200 
7201 static void set_master_stream(struct dc_stream_state *stream_set[],
7202 			      int stream_count)
7203 {
7204 	int j, highest_rfr = 0, master_stream = 0;
7205 
7206 	for (j = 0;  j < stream_count; j++) {
7207 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
7208 			int refresh_rate = 0;
7209 
7210 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
7211 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
7212 			if (refresh_rate > highest_rfr) {
7213 				highest_rfr = refresh_rate;
7214 				master_stream = j;
7215 			}
7216 		}
7217 	}
7218 	for (j = 0;  j < stream_count; j++) {
7219 		if (stream_set[j])
7220 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
7221 	}
7222 }
7223 
7224 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
7225 {
7226 	int i = 0;
7227 	struct dc_stream_state *stream;
7228 
7229 	if (context->stream_count < 2)
7230 		return;
7231 	for (i = 0; i < context->stream_count ; i++) {
7232 		if (!context->streams[i])
7233 			continue;
7234 		/*
7235 		 * TODO: add a function to read AMD VSDB bits and set
7236 		 * crtc_sync_master.multi_sync_enabled flag
7237 		 * For now it's set to false
7238 		 */
7239 	}
7240 
7241 	set_master_stream(context->streams, context->stream_count);
7242 
7243 	for (i = 0; i < context->stream_count ; i++) {
7244 		stream = context->streams[i];
7245 
7246 		if (!stream)
7247 			continue;
7248 
7249 		set_multisync_trigger_params(stream);
7250 	}
7251 }
7252 
7253 /**
7254  * DOC: FreeSync Video
7255  *
7256  * When a userspace application wants to play a video, the content follows a
7257  * standard format definition that usually specifies the FPS for that format.
7258  * The below list illustrates some video format and the expected FPS,
7259  * respectively:
7260  *
7261  * - TV/NTSC (23.976 FPS)
7262  * - Cinema (24 FPS)
7263  * - TV/PAL (25 FPS)
7264  * - TV/NTSC (29.97 FPS)
7265  * - TV/NTSC (30 FPS)
7266  * - Cinema HFR (48 FPS)
7267  * - TV/PAL (50 FPS)
7268  * - Commonly used (60 FPS)
7269  * - Multiples of 24 (48,72,96 FPS)
7270  *
7271  * The list of standards video format is not huge and can be added to the
7272  * connector modeset list beforehand. With that, userspace can leverage
7273  * FreeSync to extends the front porch in order to attain the target refresh
7274  * rate. Such a switch will happen seamlessly, without screen blanking or
7275  * reprogramming of the output in any other way. If the userspace requests a
7276  * modesetting change compatible with FreeSync modes that only differ in the
7277  * refresh rate, DC will skip the full update and avoid blink during the
7278  * transition. For example, the video player can change the modesetting from
7279  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
7280  * causing any display blink. This same concept can be applied to a mode
7281  * setting change.
7282  */
7283 static struct drm_display_mode *
7284 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
7285 		bool use_probed_modes)
7286 {
7287 	struct drm_display_mode *m, *m_pref = NULL;
7288 	u16 current_refresh, highest_refresh;
7289 	struct list_head *list_head = use_probed_modes ?
7290 		&aconnector->base.probed_modes :
7291 		&aconnector->base.modes;
7292 
7293 	if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
7294 		return NULL;
7295 
7296 	if (aconnector->freesync_vid_base.clock != 0)
7297 		return &aconnector->freesync_vid_base;
7298 
7299 	/* Find the preferred mode */
7300 	list_for_each_entry(m, list_head, head) {
7301 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
7302 			m_pref = m;
7303 			break;
7304 		}
7305 	}
7306 
7307 	if (!m_pref) {
7308 		/* Probably an EDID with no preferred mode. Fallback to first entry */
7309 		m_pref = list_first_entry_or_null(
7310 				&aconnector->base.modes, struct drm_display_mode, head);
7311 		if (!m_pref) {
7312 			drm_dbg_driver(aconnector->base.dev, "No preferred mode found in EDID\n");
7313 			return NULL;
7314 		}
7315 	}
7316 
7317 	highest_refresh = drm_mode_vrefresh(m_pref);
7318 
7319 	/*
7320 	 * Find the mode with highest refresh rate with same resolution.
7321 	 * For some monitors, preferred mode is not the mode with highest
7322 	 * supported refresh rate.
7323 	 */
7324 	list_for_each_entry(m, list_head, head) {
7325 		current_refresh  = drm_mode_vrefresh(m);
7326 
7327 		if (m->hdisplay == m_pref->hdisplay &&
7328 		    m->vdisplay == m_pref->vdisplay &&
7329 		    highest_refresh < current_refresh) {
7330 			highest_refresh = current_refresh;
7331 			m_pref = m;
7332 		}
7333 	}
7334 
7335 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
7336 	return m_pref;
7337 }
7338 
7339 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
7340 		struct amdgpu_dm_connector *aconnector)
7341 {
7342 	struct drm_display_mode *high_mode;
7343 	int timing_diff;
7344 
7345 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
7346 	if (!high_mode || !mode)
7347 		return false;
7348 
7349 	timing_diff = high_mode->vtotal - mode->vtotal;
7350 
7351 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
7352 	    high_mode->hdisplay != mode->hdisplay ||
7353 	    high_mode->vdisplay != mode->vdisplay ||
7354 	    high_mode->hsync_start != mode->hsync_start ||
7355 	    high_mode->hsync_end != mode->hsync_end ||
7356 	    high_mode->htotal != mode->htotal ||
7357 	    high_mode->hskew != mode->hskew ||
7358 	    high_mode->vscan != mode->vscan ||
7359 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
7360 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
7361 		return false;
7362 	else
7363 		return true;
7364 }
7365 
7366 #if defined(CONFIG_DRM_AMD_DC_FP)
7367 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
7368 			    struct dc_sink *sink, struct dc_stream_state *stream,
7369 			    struct dsc_dec_dpcd_caps *dsc_caps)
7370 {
7371 	stream->timing.flags.DSC = 0;
7372 	dsc_caps->is_dsc_supported = false;
7373 
7374 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
7375 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
7376 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE)
7377 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7378 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7379 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7380 				dsc_caps);
7381 		else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7382 			if (aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.fields.dsc_support.DSC_PASSTHROUGH_SUPPORT &&
7383 					!aconnector->dsc_settings.dsc_force_disable_passthrough &&
7384 					aconnector->dc_link->dpcd_caps.dongle_caps.dp_hdmi_frl_max_link_bw_in_kbps > 0 &&
7385 					sink->edid_caps.frl_dsc_support &&
7386 					sink->edid_caps.max_frl_rate > 0 &&
7387 					sink->edid_caps.frl_dsc_max_frl_rate > 0)
7388 				dc_dsc_parse_dsc_edid(aconnector->dc_link->ctx->dc, &sink->edid_caps, dsc_caps);
7389 			else
7390 				dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7391 				      aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7392 				      aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7393 				      dsc_caps);
7394 		}
7395 	} else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_HDMI_FRL) {
7396 		if (sink->edid_caps.frl_dsc_support &&
7397 				sink->edid_caps.max_frl_rate > 0 &&
7398 				sink->edid_caps.frl_dsc_max_frl_rate > 0)
7399 			dc_dsc_parse_dsc_edid(aconnector->dc_link->ctx->dc, &sink->edid_caps, dsc_caps);
7400 	}
7401 }
7402 
7403 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
7404 				    struct dc_sink *sink, struct dc_stream_state *stream,
7405 				    struct dsc_dec_dpcd_caps *dsc_caps,
7406 				    uint32_t max_dsc_target_bpp_limit_override)
7407 {
7408 	const struct dc_link_settings *verified_link_cap = NULL;
7409 	u32 link_bw_in_kbps;
7410 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
7411 	struct dc *dc = sink->ctx->dc;
7412 	struct dc_dsc_bw_range bw_range = {0};
7413 	struct dc_dsc_config dsc_cfg = {0};
7414 	struct dc_dsc_config_options dsc_options = {0};
7415 
7416 	dc_dsc_get_default_config_option(dc, &dsc_options);
7417 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7418 
7419 	verified_link_cap = dc_link_get_link_cap(stream->link);
7420 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
7421 	edp_min_bpp_x16 = 8 * 16;
7422 	edp_max_bpp_x16 = 8 * 16;
7423 
7424 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
7425 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
7426 
7427 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
7428 		edp_min_bpp_x16 = edp_max_bpp_x16;
7429 
7430 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
7431 				dc->debug.dsc_min_slice_height_override,
7432 				edp_min_bpp_x16, edp_max_bpp_x16,
7433 				dsc_caps,
7434 				&stream->timing,
7435 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7436 				&bw_range)) {
7437 
7438 		if (bw_range.max_kbps < link_bw_in_kbps) {
7439 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7440 					dsc_caps,
7441 					&dsc_options,
7442 					0,
7443 					&stream->timing,
7444 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7445 					&dsc_cfg)) {
7446 				stream->timing.dsc_cfg = dsc_cfg;
7447 				stream->timing.flags.DSC = 1;
7448 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
7449 			}
7450 			return;
7451 		}
7452 	}
7453 
7454 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7455 				dsc_caps,
7456 				&dsc_options,
7457 				link_bw_in_kbps,
7458 				&stream->timing,
7459 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7460 				&dsc_cfg)) {
7461 		stream->timing.dsc_cfg = dsc_cfg;
7462 		stream->timing.flags.DSC = 1;
7463 	}
7464 }
7465 
7466 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
7467 					struct dc_sink *sink, struct dc_stream_state *stream,
7468 					struct dsc_dec_dpcd_caps *dsc_caps)
7469 {
7470 	struct drm_connector *drm_connector = &aconnector->base;
7471 	u32 link_bandwidth_kbps;
7472 	struct dc *dc = sink->ctx->dc;
7473 	const struct dc_hdmi_frl_link_settings *frl_verified_link_cap = NULL;
7474 	u32 converter_bw_in_kbps;
7475 	u32 sink_bw_in_kbps;
7476 	u32 dsc_sink_bw_in_kbps;
7477 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
7478 	u32 dsc_max_supported_bw_in_kbps;
7479 	u32 max_dsc_target_bpp_limit_override =
7480 		drm_connector->display_info.max_dsc_bpp;
7481 	struct dc_dsc_config_options dsc_options = {0};
7482 
7483 	dc_dsc_get_default_config_option(dc, &dsc_options);
7484 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7485 
7486 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
7487 							dc_link_get_link_cap(aconnector->dc_link));
7488 
7489 	/* Set DSC policy according to dsc_clock_en */
7490 	dc_dsc_policy_set_enable_dsc_when_not_needed(
7491 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
7492 
7493 	if (sink->sink_signal == SIGNAL_TYPE_EDP &&
7494 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
7495 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
7496 
7497 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
7498 
7499 	} else if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
7500 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
7501 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7502 						dsc_caps,
7503 						&dsc_options,
7504 						link_bandwidth_kbps,
7505 						&stream->timing,
7506 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7507 						&stream->timing.dsc_cfg)) {
7508 				stream->timing.flags.DSC = 1;
7509 				drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from SST RX\n",
7510 							__func__, drm_connector->name);
7511 			}
7512 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7513 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
7514 					dc_link_get_highest_encoding_format(aconnector->dc_link));
7515 			converter_bw_in_kbps = aconnector->dc_link->dpcd_caps.dongle_caps.dp_hdmi_frl_max_link_bw_in_kbps;
7516 			sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.max_frl_rate);
7517 			dsc_sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.frl_dsc_max_frl_rate);
7518 
7519 			if (dsc_caps->is_frl) {
7520 				max_supported_bw_in_kbps = min(link_bandwidth_kbps, converter_bw_in_kbps);
7521 				max_supported_bw_in_kbps = min(max_supported_bw_in_kbps, sink_bw_in_kbps);
7522 				dsc_max_supported_bw_in_kbps = min(max_supported_bw_in_kbps, dsc_sink_bw_in_kbps);
7523 			} else {
7524 				max_supported_bw_in_kbps = link_bandwidth_kbps;
7525 				dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
7526 			}
7527 
7528 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
7529 					max_supported_bw_in_kbps > 0 &&
7530 					dsc_max_supported_bw_in_kbps > 0)
7531 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7532 						dsc_caps,
7533 						&dsc_options,
7534 						dsc_max_supported_bw_in_kbps,
7535 						&stream->timing,
7536 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7537 						&stream->timing.dsc_cfg)) {
7538 					stream->timing.flags.DSC = 1;
7539 					drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from %s\n",
7540 							__func__, drm_connector->name,
7541 							(dsc_caps->is_frl == 1) ? "HDMI FRL RX" : "DP-HDMI PCON");
7542 				}
7543 		}
7544 	}
7545 	else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_HDMI_FRL) {
7546 		struct dc_dsc_policy dsc_policy = {0};
7547 
7548 		frl_verified_link_cap = dc_link_get_frl_link_cap(stream->link);
7549 		if (frl_verified_link_cap->frl_link_rate != HDMI_FRL_LINK_RATE_DISABLE &&
7550 			aconnector->dc_link->frl_flags.force_frl_dsc) {
7551 			dc_dsc_policy_set_enable_dsc_when_not_needed(true);
7552 			dc_dsc_get_policy_for_timing(&stream->timing, 0, &dsc_policy, dc_link_get_highest_encoding_format(stream->link));
7553 		}
7554 
7555 		timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing, DC_LINK_ENCODING_HDMI_FRL);
7556 		link_bandwidth_kbps = dc_link_frl_bandwidth_kbps(stream->link, frl_verified_link_cap->frl_link_rate);
7557 		dsc_sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.frl_dsc_max_frl_rate);
7558 
7559 		if ((timing_bw_in_kbps > link_bandwidth_kbps && dsc_sink_bw_in_kbps > 0) ||
7560 		    (dsc_policy.enable_dsc_when_not_needed || dsc_options.force_dsc_when_not_needed)) {
7561 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7562 					dsc_caps,
7563 					&dsc_options,
7564 					dsc_sink_bw_in_kbps,
7565 					&stream->timing,
7566 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7567 					&stream->timing.dsc_cfg)) {
7568 				stream->timing.flags.DSC = 1;
7569 				drm_dbg_driver(drm_connector->dev, "%s: HDMI_FRL_DSC [%s] DSC is selected from HDMI FRL RX\n",
7570 						__func__, drm_connector->name);
7571 			}
7572 		}
7573 	}
7574 
7575 	/* Overwrite the stream flag if DSC is enabled through debugfs */
7576 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
7577 		stream->timing.flags.DSC = 1;
7578 
7579 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
7580 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
7581 
7582 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
7583 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
7584 
7585 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
7586 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
7587 }
7588 #endif
7589 
7590 static struct dc_stream_state *
7591 create_stream_for_sink(struct drm_connector *connector,
7592 		       const struct drm_display_mode *drm_mode,
7593 		       const struct dm_connector_state *dm_state,
7594 		       const struct dc_stream_state *old_stream,
7595 		       int requested_bpc)
7596 {
7597 	struct drm_device *dev = connector->dev;
7598 	struct amdgpu_dm_connector *aconnector = NULL;
7599 	struct drm_display_mode *preferred_mode = NULL;
7600 	const struct drm_connector_state *con_state = &dm_state->base;
7601 	struct dc_stream_state *stream = NULL;
7602 	struct drm_display_mode mode;
7603 	struct drm_display_mode saved_mode;
7604 	struct drm_display_mode *freesync_mode = NULL;
7605 	bool native_mode_found = false;
7606 	bool recalculate_timing = false;
7607 	bool scale = dm_state->scaling != RMX_OFF;
7608 	int mode_refresh;
7609 	int preferred_refresh = 0;
7610 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
7611 #if defined(CONFIG_DRM_AMD_DC_FP)
7612 	struct dsc_dec_dpcd_caps dsc_caps = {0};
7613 #endif
7614 	struct dc_link *link = NULL;
7615 	struct dc_sink *sink = NULL;
7616 
7617 	drm_mode_init(&mode, drm_mode);
7618 	memset(&saved_mode, 0, sizeof(saved_mode));
7619 
7620 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK) {
7621 		aconnector = NULL;
7622 		aconnector = to_amdgpu_dm_connector(connector);
7623 		link = aconnector->dc_link;
7624 	} else {
7625 		struct drm_writeback_connector *wbcon = NULL;
7626 		struct amdgpu_dm_wb_connector *dm_wbcon = NULL;
7627 
7628 		wbcon = drm_connector_to_writeback(connector);
7629 		dm_wbcon = to_amdgpu_dm_wb_connector(wbcon);
7630 		link = dm_wbcon->link;
7631 	}
7632 
7633 	if (!aconnector || !aconnector->dc_sink) {
7634 		sink = create_fake_sink(dev, link);
7635 		if (!sink)
7636 			return stream;
7637 
7638 	} else {
7639 		sink = aconnector->dc_sink;
7640 		dc_sink_retain(sink);
7641 	}
7642 
7643 	stream = dc_create_stream_for_sink(sink);
7644 
7645 	if (stream == NULL) {
7646 		drm_err(dev, "Failed to create stream for sink!\n");
7647 		goto finish;
7648 	}
7649 
7650 	/* We leave this NULL for writeback connectors */
7651 	stream->dm_stream_context = aconnector;
7652 
7653 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
7654 		connector->display_info.hdmi.scdc.scrambling.low_rates;
7655 
7656 	list_for_each_entry(preferred_mode, &connector->modes, head) {
7657 		/* Search for preferred mode */
7658 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
7659 			native_mode_found = true;
7660 			break;
7661 		}
7662 	}
7663 	if (!native_mode_found)
7664 		preferred_mode = list_first_entry_or_null(
7665 				&connector->modes,
7666 				struct drm_display_mode,
7667 				head);
7668 
7669 	mode_refresh = drm_mode_vrefresh(&mode);
7670 
7671 	if (preferred_mode == NULL) {
7672 		/*
7673 		 * This may not be an error, the use case is when we have no
7674 		 * usermode calls to reset and set mode upon hotplug. In this
7675 		 * case, we call set mode ourselves to restore the previous mode
7676 		 * and the modelist may not be filled in time.
7677 		 */
7678 		drm_dbg_driver(dev, "No preferred mode found\n");
7679 	} else if (aconnector) {
7680 		recalculate_timing = amdgpu_freesync_vid_mode &&
7681 				 is_freesync_video_mode(&mode, aconnector);
7682 		if (recalculate_timing) {
7683 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
7684 			drm_mode_copy(&saved_mode, &mode);
7685 			saved_mode.picture_aspect_ratio = mode.picture_aspect_ratio;
7686 			drm_mode_copy(&mode, freesync_mode);
7687 			mode.picture_aspect_ratio = saved_mode.picture_aspect_ratio;
7688 		} else {
7689 			decide_crtc_timing_for_drm_display_mode(
7690 					&mode, preferred_mode, scale);
7691 
7692 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
7693 		}
7694 	}
7695 
7696 	if (recalculate_timing)
7697 		drm_mode_set_crtcinfo(&saved_mode, 0);
7698 
7699 	/*
7700 	 * If scaling is enabled and refresh rate didn't change
7701 	 * we copy the vic and polarities of the old timings
7702 	 */
7703 	if (!scale || mode_refresh != preferred_refresh)
7704 		fill_stream_properties_from_drm_display_mode(
7705 			stream, &mode, connector, con_state, NULL,
7706 			requested_bpc);
7707 	else
7708 		fill_stream_properties_from_drm_display_mode(
7709 			stream, &mode, connector, con_state, old_stream,
7710 			requested_bpc);
7711 
7712 	/* The rest isn't needed for writeback connectors */
7713 	if (!aconnector)
7714 		goto finish;
7715 
7716 	if (aconnector->timing_changed) {
7717 		drm_dbg(aconnector->base.dev,
7718 			"overriding timing for automated test, bpc %d, changing to %d\n",
7719 			stream->timing.display_color_depth,
7720 			aconnector->timing_requested->display_color_depth);
7721 		stream->timing = *aconnector->timing_requested;
7722 	}
7723 
7724 #if defined(CONFIG_DRM_AMD_DC_FP)
7725 	/* SST DSC determination policy */
7726 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
7727 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
7728 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
7729 #endif
7730 
7731 	update_stream_scaling_settings(dev, &mode, dm_state, stream);
7732 
7733 	fill_audio_info(
7734 		&stream->audio_info,
7735 		connector,
7736 		sink);
7737 
7738 	update_stream_signal(stream, sink);
7739 
7740 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7741 	    stream->signal == SIGNAL_TYPE_HDMI_FRL)
7742 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket, false, false);
7743 
7744 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT ||
7745 	    stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
7746 	    stream->signal == SIGNAL_TYPE_EDP) {
7747 		const struct dc_edid_caps *edid_caps;
7748 		unsigned int disable_colorimetry = 0;
7749 
7750 		if (aconnector->dc_sink) {
7751 			edid_caps = &aconnector->dc_sink->edid_caps;
7752 			disable_colorimetry = edid_caps->panel_patch.disable_colorimetry;
7753 		}
7754 
7755 		//
7756 		// should decide stream support vsc sdp colorimetry capability
7757 		// before building vsc info packet
7758 		//
7759 		stream->use_vsc_sdp_for_colorimetry = stream->link->dpcd_caps.dpcd_rev.raw >= 0x14 &&
7760 						      stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED &&
7761 						      !disable_colorimetry;
7762 
7763 		if (stream->out_transfer_func.tf == TRANSFER_FUNCTION_GAMMA22)
7764 			tf = TRANSFER_FUNC_GAMMA_22;
7765 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
7766 		aconnector->sr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
7767 
7768 	}
7769 finish:
7770 	dc_sink_release(sink);
7771 
7772 	return stream;
7773 }
7774 
7775 /**
7776  * amdgpu_dm_connector_poll - Poll a connector to see if it's connected to a display
7777  * @aconnector: DM connector to poll (owns @base drm_connector and @dc_link)
7778  * @force: if true, force polling even when DAC load detection was used
7779  *
7780  * Used for connectors that don't support HPD (hotplug detection) to
7781  * periodically check whether the connector is connected to a display.
7782  *
7783  * When connection was determined via DAC load detection, we avoid
7784  * re-running it on normal polls to prevent visible glitches, unless
7785  * @force is set.
7786  *
7787  * Return: The probed connector status (connected/disconnected/unknown).
7788  */
7789 static enum drm_connector_status
7790 amdgpu_dm_connector_poll(struct amdgpu_dm_connector *aconnector, bool force)
7791 {
7792 	struct drm_connector *connector = &aconnector->base;
7793 	struct drm_device *dev = connector->dev;
7794 	struct amdgpu_device *adev = drm_to_adev(dev);
7795 	struct dc_link *link = aconnector->dc_link;
7796 	enum dc_connection_type conn_type = dc_connection_none;
7797 	enum drm_connector_status status = connector_status_disconnected;
7798 
7799 	/* When we determined the connection using DAC load detection,
7800 	 * do NOT poll the connector do detect disconnect because
7801 	 * that would run DAC load detection again which can cause
7802 	 * visible visual glitches.
7803 	 *
7804 	 * Only allow to poll such a connector again when forcing.
7805 	 */
7806 	if (!force && link->local_sink && link->type == dc_connection_analog_load)
7807 		return connector->status;
7808 
7809 	mutex_lock(&aconnector->hpd_lock);
7810 
7811 	if (dc_link_detect_connection_type(aconnector->dc_link, &conn_type) &&
7812 	    conn_type != dc_connection_none) {
7813 		mutex_lock(&adev->dm.dc_lock);
7814 
7815 		/* Only call full link detection when a sink isn't created yet,
7816 		 * ie. just when the display is plugged in, otherwise we risk flickering.
7817 		 */
7818 		if (link->local_sink ||
7819 			dc_link_detect(link, DETECT_REASON_HPD))
7820 			status = connector_status_connected;
7821 
7822 		mutex_unlock(&adev->dm.dc_lock);
7823 	}
7824 
7825 	if (connector->status != status) {
7826 		if (status == connector_status_disconnected) {
7827 			if (link->local_sink)
7828 				dc_sink_release(link->local_sink);
7829 
7830 			link->local_sink = NULL;
7831 			link->dpcd_sink_count = 0;
7832 			link->type = dc_connection_none;
7833 		}
7834 
7835 		amdgpu_dm_update_connector_after_detect(aconnector);
7836 	}
7837 
7838 	mutex_unlock(&aconnector->hpd_lock);
7839 	return status;
7840 }
7841 
7842 /**
7843  * amdgpu_dm_connector_detect() - Detect whether a DRM connector is connected to a display
7844  *
7845  * A connector is considered connected when it has a sink that is not NULL.
7846  * For connectors that support HPD (hotplug detection), the connection is
7847  * handled in the HPD interrupt.
7848  * For connectors that may not support HPD, such as analog connectors,
7849  * DRM will call this function repeatedly to poll them.
7850  *
7851  * Notes:
7852  * 1. This interface is NOT called in context of HPD irq.
7853  * 2. This interface *is called* in context of user-mode ioctl. Which
7854  *    makes it a bad place for *any* MST-related activity.
7855  *
7856  * @connector: The DRM connector we are checking. We convert it to
7857  *             amdgpu_dm_connector so we can read the DC link and state.
7858  * @force:     If true, do a full detect again. This is used even when
7859  *             a lighter check would normally be used to avoid flicker.
7860  *
7861  * Return: The connector status (connected, disconnected, or unknown).
7862  *
7863  */
7864 static enum drm_connector_status
7865 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
7866 {
7867 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7868 
7869 	update_subconnector_property(aconnector);
7870 
7871 	if (aconnector->base.force == DRM_FORCE_ON ||
7872 		aconnector->base.force == DRM_FORCE_ON_DIGITAL)
7873 		return connector_status_connected;
7874 	else if (aconnector->base.force == DRM_FORCE_OFF)
7875 		return connector_status_disconnected;
7876 
7877 	/* Poll analog connectors and only when either
7878 	 * disconnected or connected to an analog display.
7879 	 */
7880 	if (drm_kms_helper_is_poll_worker() &&
7881 		dc_connector_supports_analog(aconnector->dc_link->link_id.id) &&
7882 		(!aconnector->dc_sink || aconnector->dc_sink->edid_caps.analog))
7883 		return amdgpu_dm_connector_poll(aconnector, force);
7884 
7885 	return (aconnector->dc_sink ? connector_status_connected :
7886 			connector_status_disconnected);
7887 }
7888 
7889 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
7890 					    struct drm_connector_state *connector_state,
7891 					    struct drm_property *property,
7892 					    uint64_t val)
7893 {
7894 	struct drm_device *dev = connector->dev;
7895 	struct amdgpu_device *adev = drm_to_adev(dev);
7896 	struct dm_connector_state *dm_old_state =
7897 		to_dm_connector_state(connector->state);
7898 	struct dm_connector_state *dm_new_state =
7899 		to_dm_connector_state(connector_state);
7900 
7901 	int ret = -EINVAL;
7902 
7903 	if (property == dev->mode_config.scaling_mode_property) {
7904 		enum amdgpu_rmx_type rmx_type;
7905 
7906 		switch (val) {
7907 		case DRM_MODE_SCALE_CENTER:
7908 			rmx_type = RMX_CENTER;
7909 			break;
7910 		case DRM_MODE_SCALE_ASPECT:
7911 			rmx_type = RMX_ASPECT;
7912 			break;
7913 		case DRM_MODE_SCALE_FULLSCREEN:
7914 			rmx_type = RMX_FULL;
7915 			break;
7916 		case DRM_MODE_SCALE_NONE:
7917 		default:
7918 			rmx_type = RMX_OFF;
7919 			break;
7920 		}
7921 
7922 		if (dm_old_state->scaling == rmx_type)
7923 			return 0;
7924 
7925 		dm_new_state->scaling = rmx_type;
7926 		ret = 0;
7927 	} else if (property == adev->mode_info.underscan_hborder_property) {
7928 		dm_new_state->underscan_hborder = val;
7929 		ret = 0;
7930 	} else if (property == adev->mode_info.underscan_vborder_property) {
7931 		dm_new_state->underscan_vborder = val;
7932 		ret = 0;
7933 	} else if (property == adev->mode_info.underscan_property) {
7934 		dm_new_state->underscan_enable = val;
7935 		ret = 0;
7936 	} else if (property == adev->mode_info.abm_level_property) {
7937 		switch (val) {
7938 		case ABM_SYSFS_CONTROL:
7939 			dm_new_state->abm_sysfs_forbidden = false;
7940 			break;
7941 		case ABM_LEVEL_OFF:
7942 			dm_new_state->abm_sysfs_forbidden = true;
7943 			dm_new_state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7944 			break;
7945 		default:
7946 			dm_new_state->abm_sysfs_forbidden = true;
7947 			dm_new_state->abm_level = val;
7948 		}
7949 		ret = 0;
7950 	}
7951 
7952 	return ret;
7953 }
7954 
7955 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
7956 					    const struct drm_connector_state *state,
7957 					    struct drm_property *property,
7958 					    uint64_t *val)
7959 {
7960 	struct drm_device *dev = connector->dev;
7961 	struct amdgpu_device *adev = drm_to_adev(dev);
7962 	struct dm_connector_state *dm_state =
7963 		to_dm_connector_state(state);
7964 	int ret = -EINVAL;
7965 
7966 	if (property == dev->mode_config.scaling_mode_property) {
7967 		switch (dm_state->scaling) {
7968 		case RMX_CENTER:
7969 			*val = DRM_MODE_SCALE_CENTER;
7970 			break;
7971 		case RMX_ASPECT:
7972 			*val = DRM_MODE_SCALE_ASPECT;
7973 			break;
7974 		case RMX_FULL:
7975 			*val = DRM_MODE_SCALE_FULLSCREEN;
7976 			break;
7977 		case RMX_OFF:
7978 		default:
7979 			*val = DRM_MODE_SCALE_NONE;
7980 			break;
7981 		}
7982 		ret = 0;
7983 	} else if (property == adev->mode_info.underscan_hborder_property) {
7984 		*val = dm_state->underscan_hborder;
7985 		ret = 0;
7986 	} else if (property == adev->mode_info.underscan_vborder_property) {
7987 		*val = dm_state->underscan_vborder;
7988 		ret = 0;
7989 	} else if (property == adev->mode_info.underscan_property) {
7990 		*val = dm_state->underscan_enable;
7991 		ret = 0;
7992 	} else if (property == adev->mode_info.abm_level_property) {
7993 		if (!dm_state->abm_sysfs_forbidden)
7994 			*val = ABM_SYSFS_CONTROL;
7995 		else
7996 			*val = (dm_state->abm_level != ABM_LEVEL_IMMEDIATE_DISABLE) ?
7997 				dm_state->abm_level : 0;
7998 		ret = 0;
7999 	}
8000 
8001 	return ret;
8002 }
8003 
8004 /**
8005  * DOC: panel power savings
8006  *
8007  * The display manager allows you to set your desired **panel power savings**
8008  * level (between 0-4, with 0 representing off), e.g. using the following::
8009  *
8010  *   # echo 3 > /sys/class/drm/card0-eDP-1/amdgpu/panel_power_savings
8011  *
8012  * Modifying this value can have implications on color accuracy, so tread
8013  * carefully.
8014  */
8015 
8016 static ssize_t panel_power_savings_show(struct device *device,
8017 					struct device_attribute *attr,
8018 					char *buf)
8019 {
8020 	struct drm_connector *connector = dev_get_drvdata(device);
8021 	struct drm_device *dev = connector->dev;
8022 	u8 val;
8023 
8024 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
8025 	val = to_dm_connector_state(connector->state)->abm_level ==
8026 		ABM_LEVEL_IMMEDIATE_DISABLE ? 0 :
8027 		to_dm_connector_state(connector->state)->abm_level;
8028 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
8029 
8030 	return sysfs_emit(buf, "%u\n", val);
8031 }
8032 
8033 static ssize_t panel_power_savings_store(struct device *device,
8034 					 struct device_attribute *attr,
8035 					 const char *buf, size_t count)
8036 {
8037 	struct drm_connector *connector = dev_get_drvdata(device);
8038 	struct drm_device *dev = connector->dev;
8039 	long val;
8040 	int ret;
8041 
8042 	ret = kstrtol(buf, 0, &val);
8043 
8044 	if (ret)
8045 		return ret;
8046 
8047 	if (val < 0 || val > 4)
8048 		return -EINVAL;
8049 
8050 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
8051 	if (to_dm_connector_state(connector->state)->abm_sysfs_forbidden)
8052 		ret = -EBUSY;
8053 	else
8054 		to_dm_connector_state(connector->state)->abm_level = val ?:
8055 			ABM_LEVEL_IMMEDIATE_DISABLE;
8056 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
8057 
8058 	if (ret)
8059 		return ret;
8060 
8061 	drm_kms_helper_hotplug_event(dev);
8062 
8063 	return count;
8064 }
8065 
8066 static DEVICE_ATTR_RW(panel_power_savings);
8067 
8068 static struct attribute *amdgpu_attrs[] = {
8069 	&dev_attr_panel_power_savings.attr,
8070 	NULL
8071 };
8072 
8073 static const struct attribute_group amdgpu_group = {
8074 	.name = "amdgpu",
8075 	.attrs = amdgpu_attrs
8076 };
8077 
8078 static bool
8079 amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector *amdgpu_dm_connector)
8080 {
8081 	if (amdgpu_dm_abm_level >= 0)
8082 		return false;
8083 
8084 	if (amdgpu_dm_connector->base.connector_type != DRM_MODE_CONNECTOR_eDP)
8085 		return false;
8086 
8087 	/* check for OLED panels */
8088 	if (amdgpu_dm_connector->bl_idx >= 0) {
8089 		struct drm_device *drm = amdgpu_dm_connector->base.dev;
8090 		struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
8091 		struct amdgpu_dm_backlight_caps *caps;
8092 
8093 		caps = &dm->backlight_caps[amdgpu_dm_connector->bl_idx];
8094 		if (caps->aux_support)
8095 			return false;
8096 	}
8097 
8098 	return true;
8099 }
8100 
8101 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
8102 {
8103 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
8104 
8105 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector))
8106 		sysfs_remove_group(&connector->kdev->kobj, &amdgpu_group);
8107 
8108 	cec_notifier_conn_unregister(amdgpu_dm_connector->notifier);
8109 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
8110 }
8111 
8112 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
8113 {
8114 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8115 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8116 	struct amdgpu_display_manager *dm = &adev->dm;
8117 
8118 	/*
8119 	 * Call only if mst_mgr was initialized before since it's not done
8120 	 * for all connector types.
8121 	 */
8122 	if (aconnector->mst_mgr.dev)
8123 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
8124 
8125 	/* Cancel and flush any pending HDMI HPD debounce work */
8126 	if (aconnector->hdmi_hpd_debounce_delay_ms) {
8127 		cancel_delayed_work_sync(&aconnector->hdmi_hpd_debounce_work);
8128 		if (aconnector->hdmi_prev_sink) {
8129 			dc_sink_release(aconnector->hdmi_prev_sink);
8130 			aconnector->hdmi_prev_sink = NULL;
8131 		}
8132 	}
8133 
8134 	if (aconnector->bl_idx != -1) {
8135 		backlight_device_unregister(dm->backlight_dev[aconnector->bl_idx]);
8136 		dm->backlight_dev[aconnector->bl_idx] = NULL;
8137 	}
8138 
8139 	if (aconnector->dc_em_sink)
8140 		dc_sink_release(aconnector->dc_em_sink);
8141 	aconnector->dc_em_sink = NULL;
8142 	if (aconnector->dc_sink)
8143 		dc_sink_release(aconnector->dc_sink);
8144 	aconnector->dc_sink = NULL;
8145 
8146 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
8147 	drm_connector_unregister(connector);
8148 	drm_connector_cleanup(connector);
8149 	kfree(aconnector->dm_dp_aux.aux.name);
8150 
8151 	kfree(connector);
8152 }
8153 
8154 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
8155 {
8156 	struct dm_connector_state *state =
8157 		to_dm_connector_state(connector->state);
8158 
8159 	if (connector->state)
8160 		__drm_atomic_helper_connector_destroy_state(connector->state);
8161 
8162 	kfree(state);
8163 
8164 	state = kzalloc_obj(*state);
8165 
8166 	if (state) {
8167 		state->scaling = RMX_OFF;
8168 		state->underscan_enable = false;
8169 		state->underscan_hborder = 0;
8170 		state->underscan_vborder = 0;
8171 		state->base.max_requested_bpc = 8;
8172 		state->vcpi_slots = 0;
8173 		state->pbn = 0;
8174 
8175 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) {
8176 			if (amdgpu_dm_abm_level <= 0)
8177 				state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
8178 			else
8179 				state->abm_level = amdgpu_dm_abm_level;
8180 		}
8181 
8182 		__drm_atomic_helper_connector_reset(connector, &state->base);
8183 	}
8184 }
8185 
8186 struct drm_connector_state *
8187 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
8188 {
8189 	struct dm_connector_state *state =
8190 		to_dm_connector_state(connector->state);
8191 
8192 	struct dm_connector_state *new_state =
8193 			kmemdup(state, sizeof(*state), GFP_KERNEL);
8194 
8195 	if (!new_state)
8196 		return NULL;
8197 
8198 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
8199 
8200 	new_state->freesync_capable = state->freesync_capable;
8201 	new_state->abm_level = state->abm_level;
8202 	new_state->scaling = state->scaling;
8203 	new_state->underscan_enable = state->underscan_enable;
8204 	new_state->underscan_hborder = state->underscan_hborder;
8205 	new_state->underscan_vborder = state->underscan_vborder;
8206 	new_state->vcpi_slots = state->vcpi_slots;
8207 	new_state->pbn = state->pbn;
8208 	return &new_state->base;
8209 }
8210 
8211 static int
8212 amdgpu_dm_connector_late_register(struct drm_connector *connector)
8213 {
8214 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8215 		to_amdgpu_dm_connector(connector);
8216 	int r;
8217 
8218 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector)) {
8219 		r = sysfs_create_group(&connector->kdev->kobj,
8220 				       &amdgpu_group);
8221 		if (r)
8222 			return r;
8223 	}
8224 
8225 	amdgpu_dm_register_backlight_device(amdgpu_dm_connector);
8226 
8227 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
8228 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
8229 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
8230 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
8231 		if (r)
8232 			return r;
8233 	}
8234 
8235 #if defined(CONFIG_DEBUG_FS)
8236 	connector_debugfs_init(amdgpu_dm_connector);
8237 #endif
8238 
8239 	return 0;
8240 }
8241 
8242 static void amdgpu_dm_connector_funcs_force(struct drm_connector *connector)
8243 {
8244 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8245 	struct dc_link *dc_link = aconnector->dc_link;
8246 	struct dc_sink *dc_em_sink = aconnector->dc_em_sink;
8247 	const struct drm_edid *drm_edid;
8248 	struct i2c_adapter *ddc;
8249 	struct drm_device *dev = connector->dev;
8250 
8251 	if (dc_link && dc_link->aux_mode)
8252 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8253 	else
8254 		ddc = &aconnector->i2c->base;
8255 
8256 	drm_edid = drm_edid_read_ddc(connector, ddc);
8257 	drm_edid_connector_update(connector, drm_edid);
8258 	if (!drm_edid) {
8259 		drm_err(dev, "No EDID found on connector: %s.\n", connector->name);
8260 		return;
8261 	}
8262 
8263 	aconnector->drm_edid = drm_edid;
8264 	/* Update emulated (virtual) sink's EDID */
8265 	if (dc_em_sink && dc_link) {
8266 		// FIXME: Get rid of drm_edid_raw()
8267 		const struct edid *edid = drm_edid_raw(drm_edid);
8268 
8269 		memset(&dc_em_sink->edid_caps, 0, sizeof(struct dc_edid_caps));
8270 		memmove(dc_em_sink->dc_edid.raw_edid, edid,
8271 			(edid->extensions + 1) * EDID_LENGTH);
8272 		dm_helpers_parse_edid_caps(
8273 			dc_link,
8274 			&dc_em_sink->dc_edid,
8275 			&dc_em_sink->edid_caps);
8276 	}
8277 }
8278 
8279 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
8280 	.reset = amdgpu_dm_connector_funcs_reset,
8281 	.detect = amdgpu_dm_connector_detect,
8282 	.fill_modes = drm_helper_probe_single_connector_modes,
8283 	.destroy = amdgpu_dm_connector_destroy,
8284 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
8285 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
8286 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
8287 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
8288 	.late_register = amdgpu_dm_connector_late_register,
8289 	.early_unregister = amdgpu_dm_connector_unregister,
8290 	.force = amdgpu_dm_connector_funcs_force
8291 };
8292 
8293 static int get_modes(struct drm_connector *connector)
8294 {
8295 	return amdgpu_dm_connector_get_modes(connector);
8296 }
8297 
8298 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
8299 {
8300 	struct drm_connector *connector = &aconnector->base;
8301 	struct dc_link *dc_link = aconnector->dc_link;
8302 	struct dc_sink_init_data init_params = {
8303 			.link = aconnector->dc_link,
8304 			.sink_signal = SIGNAL_TYPE_VIRTUAL
8305 	};
8306 	const struct drm_edid *drm_edid;
8307 	const struct edid *edid;
8308 	struct i2c_adapter *ddc;
8309 
8310 	if (dc_link && dc_link->aux_mode)
8311 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8312 	else
8313 		ddc = &aconnector->i2c->base;
8314 
8315 	drm_edid = drm_edid_read_ddc(connector, ddc);
8316 	drm_edid_connector_update(connector, drm_edid);
8317 	if (!drm_edid) {
8318 		drm_err(connector->dev, "No EDID found on connector: %s.\n", connector->name);
8319 		return;
8320 	}
8321 
8322 	if (connector->display_info.is_hdmi)
8323 		init_params.sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
8324 
8325 	aconnector->drm_edid = drm_edid;
8326 
8327 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
8328 	aconnector->dc_em_sink = dc_link_add_remote_sink(
8329 		aconnector->dc_link,
8330 		(uint8_t *)edid,
8331 		(edid->extensions + 1) * EDID_LENGTH,
8332 		&init_params);
8333 
8334 	if (aconnector->base.force == DRM_FORCE_ON) {
8335 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
8336 		aconnector->dc_link->local_sink :
8337 		aconnector->dc_em_sink;
8338 		if (aconnector->dc_sink)
8339 			dc_sink_retain(aconnector->dc_sink);
8340 	}
8341 }
8342 
8343 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
8344 {
8345 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
8346 
8347 	/*
8348 	 * In case of headless boot with force on for DP managed connector
8349 	 * Those settings have to be != 0 to get initial modeset
8350 	 */
8351 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
8352 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
8353 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
8354 	}
8355 
8356 	create_eml_sink(aconnector);
8357 }
8358 
8359 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
8360 						struct dc_stream_state *stream)
8361 {
8362 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
8363 	struct dc_plane_state *dc_plane_state = NULL;
8364 	struct dc_state *dc_state = NULL;
8365 
8366 	if (!stream)
8367 		goto cleanup;
8368 
8369 	dc_plane_state = dc_create_plane_state(dc);
8370 	if (!dc_plane_state)
8371 		goto cleanup;
8372 
8373 	dc_state = dc_state_create(dc, NULL);
8374 	if (!dc_state)
8375 		goto cleanup;
8376 
8377 	/* populate stream to plane */
8378 	dc_plane_state->src_rect.height  = stream->src.height;
8379 	dc_plane_state->src_rect.width   = stream->src.width;
8380 	dc_plane_state->dst_rect.height  = stream->src.height;
8381 	dc_plane_state->dst_rect.width   = stream->src.width;
8382 	dc_plane_state->clip_rect.height = stream->src.height;
8383 	dc_plane_state->clip_rect.width  = stream->src.width;
8384 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
8385 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
8386 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
8387 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
8388 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
8389 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
8390 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
8391 	dc_plane_state->rotation = ROTATION_ANGLE_0;
8392 	dc_plane_state->is_tiling_rotated = false;
8393 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
8394 
8395 	dc_result = dc_validate_stream(dc, stream);
8396 	if (dc_result == DC_OK)
8397 		dc_result = dc_validate_plane(dc, dc_plane_state);
8398 
8399 	if (dc_result == DC_OK)
8400 		dc_result = dc_state_add_stream(dc, dc_state, stream);
8401 
8402 	if (dc_result == DC_OK && !dc_state_add_plane(
8403 						dc,
8404 						stream,
8405 						dc_plane_state,
8406 						dc_state))
8407 		dc_result = DC_FAIL_ATTACH_SURFACES;
8408 
8409 	if (dc_result == DC_OK)
8410 		dc_result = dc_validate_global_state(dc, dc_state, DC_VALIDATE_MODE_ONLY);
8411 
8412 cleanup:
8413 	if (dc_state)
8414 		dc_state_release(dc_state);
8415 
8416 	if (dc_plane_state)
8417 		dc_plane_state_release(dc_plane_state);
8418 
8419 	return dc_result;
8420 }
8421 
8422 struct dc_stream_state *
8423 create_validate_stream_for_sink(struct drm_connector *connector,
8424 				const struct drm_display_mode *drm_mode,
8425 				const struct dm_connector_state *dm_state,
8426 				const struct dc_stream_state *old_stream)
8427 {
8428 	struct amdgpu_dm_connector *aconnector = NULL;
8429 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8430 	struct dc_stream_state *stream;
8431 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
8432 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
8433 	enum dc_status dc_result = DC_OK;
8434 	uint8_t bpc_limit = 6;
8435 
8436 	if (!dm_state)
8437 		return NULL;
8438 
8439 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
8440 		aconnector = to_amdgpu_dm_connector(connector);
8441 
8442 	if (aconnector &&
8443 	    (aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
8444 	     aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_FRL ||
8445 	     aconnector->dc_link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER))
8446 		bpc_limit = 8;
8447 
8448 	do {
8449 		drm_dbg_kms(connector->dev, "Trying with %d bpc\n", requested_bpc);
8450 		stream = create_stream_for_sink(connector, drm_mode,
8451 						dm_state, old_stream,
8452 						requested_bpc);
8453 		if (stream == NULL) {
8454 			drm_err(adev_to_drm(adev), "Failed to create stream for sink!\n");
8455 			break;
8456 		}
8457 
8458 		dc_result = dc_validate_stream(adev->dm.dc, stream);
8459 
8460 		if (!aconnector) /* writeback connector */
8461 			return stream;
8462 
8463 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
8464 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
8465 
8466 		if (dc_result == DC_OK)
8467 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
8468 
8469 		if (dc_result != DC_OK) {
8470 			drm_dbg_kms(connector->dev, "Pruned mode %d x %d (clk %d) %s %s -- %s\n",
8471 				      drm_mode->hdisplay,
8472 				      drm_mode->vdisplay,
8473 				      drm_mode->clock,
8474 				      dc_pixel_encoding_to_str(stream->timing.pixel_encoding),
8475 				      dc_color_depth_to_str(stream->timing.display_color_depth),
8476 				      dc_status_to_str(dc_result));
8477 
8478 			dc_stream_release(stream);
8479 			stream = NULL;
8480 			requested_bpc -= 2; /* lower bpc to retry validation */
8481 		}
8482 
8483 	} while (stream == NULL && requested_bpc >= bpc_limit);
8484 
8485 	switch (dc_result) {
8486 	/*
8487 	 * If we failed to validate DP bandwidth stream with the requested RGB color depth,
8488 	 * we try to fallback and configure in order:
8489 	 * YUV422 (8bpc, 6bpc)
8490 	 * YUV420 (8bpc, 6bpc)
8491 	 */
8492 	case DC_FAIL_ENC_VALIDATE:
8493 	case DC_EXCEED_DONGLE_CAP:
8494 	case DC_NO_DP_LINK_BANDWIDTH:
8495 		/* recursively entered twice and already tried both YUV422 and YUV420 */
8496 		if (aconnector->force_yuv422_output && aconnector->force_yuv420_output)
8497 			break;
8498 		/* first failure; try YUV422 */
8499 		if (!aconnector->force_yuv422_output) {
8500 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV422\n",
8501 				    __func__, __LINE__, dc_result);
8502 			aconnector->force_yuv422_output = true;
8503 		/* recursively entered and YUV422 failed, try YUV420 */
8504 		} else if (!aconnector->force_yuv420_output) {
8505 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV420\n",
8506 				    __func__, __LINE__, dc_result);
8507 			aconnector->force_yuv420_output = true;
8508 		}
8509 		stream = create_validate_stream_for_sink(connector, drm_mode,
8510 							 dm_state, old_stream);
8511 		aconnector->force_yuv422_output = false;
8512 		aconnector->force_yuv420_output = false;
8513 		break;
8514 	case DC_OK:
8515 		break;
8516 	default:
8517 		drm_dbg_kms(connector->dev, "%s:%d Unhandled validation failure %d\n",
8518 			    __func__, __LINE__, dc_result);
8519 		break;
8520 	}
8521 
8522 	return stream;
8523 }
8524 
8525 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
8526 				   const struct drm_display_mode *mode)
8527 {
8528 	int result = MODE_ERROR;
8529 	struct dc_sink *dc_sink;
8530 	struct drm_display_mode *test_mode;
8531 	/* TODO: Unhardcode stream count */
8532 	struct dc_stream_state *stream;
8533 	/* we always have an amdgpu_dm_connector here since we got
8534 	 * here via the amdgpu_dm_connector_helper_funcs
8535 	 */
8536 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8537 
8538 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
8539 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
8540 		return result;
8541 
8542 	/*
8543 	 * Only run this the first time mode_valid is called to initilialize
8544 	 * EDID mgmt
8545 	 */
8546 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
8547 		!aconnector->dc_em_sink)
8548 		handle_edid_mgmt(aconnector);
8549 
8550 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
8551 
8552 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
8553 				aconnector->base.force != DRM_FORCE_ON) {
8554 		drm_err(connector->dev, "dc_sink is NULL!\n");
8555 		goto fail;
8556 	}
8557 
8558 	test_mode = drm_mode_duplicate(connector->dev, mode);
8559 	if (!test_mode)
8560 		goto fail;
8561 
8562 	drm_mode_set_crtcinfo(test_mode, 0);
8563 
8564 	stream = create_validate_stream_for_sink(connector, test_mode,
8565 						 to_dm_connector_state(connector->state),
8566 						 NULL);
8567 	drm_mode_destroy(connector->dev, test_mode);
8568 	if (stream) {
8569 		dc_stream_release(stream);
8570 		result = MODE_OK;
8571 	}
8572 
8573 fail:
8574 	/* TODO: error handling*/
8575 	return result;
8576 }
8577 
8578 static int fill_hdr_info_packet(const struct drm_connector_state *state,
8579 				struct dc_info_packet *out)
8580 {
8581 	struct hdmi_drm_infoframe frame;
8582 	unsigned char buf[30]; /* 26 + 4 */
8583 	ssize_t len;
8584 	int ret, i;
8585 
8586 	memset(out, 0, sizeof(*out));
8587 
8588 	if (!state->hdr_output_metadata)
8589 		return 0;
8590 
8591 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
8592 	if (ret)
8593 		return ret;
8594 
8595 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
8596 	if (len < 0)
8597 		return (int)len;
8598 
8599 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
8600 	if (len != 30)
8601 		return -EINVAL;
8602 
8603 	/* Prepare the infopacket for DC. */
8604 	switch (state->connector->connector_type) {
8605 	case DRM_MODE_CONNECTOR_HDMIA:
8606 		out->hb0 = 0x87; /* type */
8607 		out->hb1 = 0x01; /* version */
8608 		out->hb2 = 0x1A; /* length */
8609 		out->sb[0] = buf[3]; /* checksum */
8610 		i = 1;
8611 		break;
8612 
8613 	case DRM_MODE_CONNECTOR_DisplayPort:
8614 	case DRM_MODE_CONNECTOR_eDP:
8615 		out->hb0 = 0x00; /* sdp id, zero */
8616 		out->hb1 = 0x87; /* type */
8617 		out->hb2 = 0x1D; /* payload len - 1 */
8618 		out->hb3 = (0x13 << 2); /* sdp version */
8619 		out->sb[0] = 0x01; /* version */
8620 		out->sb[1] = 0x1A; /* length */
8621 		i = 2;
8622 		break;
8623 
8624 	default:
8625 		return -EINVAL;
8626 	}
8627 
8628 	memcpy(&out->sb[i], &buf[4], 26);
8629 	out->valid = true;
8630 
8631 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
8632 		       sizeof(out->sb), false);
8633 
8634 	return 0;
8635 }
8636 
8637 static int
8638 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
8639 				 struct drm_atomic_commit *state)
8640 {
8641 	struct drm_connector_state *new_con_state =
8642 		drm_atomic_get_new_connector_state(state, conn);
8643 	struct drm_connector_state *old_con_state =
8644 		drm_atomic_get_old_connector_state(state, conn);
8645 	struct drm_crtc *crtc = new_con_state->crtc;
8646 	struct drm_crtc_state *new_crtc_state;
8647 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
8648 	int ret;
8649 
8650 	if (WARN_ON(unlikely(!old_con_state || !new_con_state)))
8651 		return -EINVAL;
8652 
8653 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
8654 
8655 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
8656 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
8657 		if (ret < 0)
8658 			return ret;
8659 	}
8660 
8661 	if (!crtc)
8662 		return 0;
8663 
8664 	if (new_con_state->privacy_screen_sw_state != old_con_state->privacy_screen_sw_state) {
8665 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8666 		if (IS_ERR(new_crtc_state))
8667 			return PTR_ERR(new_crtc_state);
8668 
8669 		new_crtc_state->mode_changed = true;
8670 	}
8671 
8672 	if (new_con_state->colorspace != old_con_state->colorspace) {
8673 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8674 		if (IS_ERR(new_crtc_state))
8675 			return PTR_ERR(new_crtc_state);
8676 
8677 		new_crtc_state->mode_changed = true;
8678 	}
8679 
8680 	if (new_con_state->content_type != old_con_state->content_type) {
8681 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8682 		if (IS_ERR(new_crtc_state))
8683 			return PTR_ERR(new_crtc_state);
8684 
8685 		new_crtc_state->mode_changed = true;
8686 	}
8687 
8688 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
8689 		struct dc_info_packet hdr_infopacket;
8690 
8691 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
8692 		if (ret)
8693 			return ret;
8694 
8695 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8696 		if (IS_ERR(new_crtc_state))
8697 			return PTR_ERR(new_crtc_state);
8698 
8699 		/*
8700 		 * DC considers the stream backends changed if the
8701 		 * static metadata changes. Forcing the modeset also
8702 		 * gives a simple way for userspace to switch from
8703 		 * 8bpc to 10bpc when setting the metadata to enter
8704 		 * or exit HDR.
8705 		 *
8706 		 * Changing the static metadata after it's been
8707 		 * set is permissible, however. So only force a
8708 		 * modeset if we're entering or exiting HDR.
8709 		 */
8710 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
8711 			!old_con_state->hdr_output_metadata ||
8712 			!new_con_state->hdr_output_metadata;
8713 	}
8714 
8715 	return 0;
8716 }
8717 
8718 static const struct drm_connector_helper_funcs
8719 amdgpu_dm_connector_helper_funcs = {
8720 	/*
8721 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
8722 	 * modes will be filtered by drm_mode_validate_size(), and those modes
8723 	 * are missing after user start lightdm. So we need to renew modes list.
8724 	 * in get_modes call back, not just return the modes count
8725 	 */
8726 	.get_modes = get_modes,
8727 	.mode_valid = amdgpu_dm_connector_mode_valid,
8728 	.atomic_check = amdgpu_dm_connector_atomic_check,
8729 };
8730 
8731 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
8732 {
8733 
8734 }
8735 
8736 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
8737 {
8738 	switch (display_color_depth) {
8739 	case COLOR_DEPTH_666:
8740 		return 6;
8741 	case COLOR_DEPTH_888:
8742 		return 8;
8743 	case COLOR_DEPTH_101010:
8744 		return 10;
8745 	case COLOR_DEPTH_121212:
8746 		return 12;
8747 	case COLOR_DEPTH_141414:
8748 		return 14;
8749 	case COLOR_DEPTH_161616:
8750 		return 16;
8751 	default:
8752 		break;
8753 	}
8754 	return 0;
8755 }
8756 
8757 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
8758 					  struct drm_crtc_state *crtc_state,
8759 					  struct drm_connector_state *conn_state)
8760 {
8761 	struct drm_atomic_commit *state = crtc_state->state;
8762 	struct drm_connector *connector = conn_state->connector;
8763 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8764 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
8765 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
8766 	struct drm_dp_mst_topology_mgr *mst_mgr;
8767 	struct drm_dp_mst_port *mst_port;
8768 	struct drm_dp_mst_topology_state *mst_state;
8769 	enum dc_color_depth color_depth;
8770 	int clock, bpp = 0;
8771 	bool is_y420 = false;
8772 
8773 	if ((connector->connector_type == DRM_MODE_CONNECTOR_eDP) ||
8774 	    (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)) {
8775 		struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8776 		struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8777 		enum drm_mode_status result;
8778 
8779 		result = drm_crtc_helper_mode_valid_fixed(encoder->crtc, adjusted_mode, native_mode);
8780 		if (result != MODE_OK && dm_new_connector_state->scaling == RMX_OFF) {
8781 			drm_dbg_driver(encoder->dev,
8782 				       "mode %dx%d@%dHz is not native, enabling scaling\n",
8783 				       adjusted_mode->hdisplay, adjusted_mode->vdisplay,
8784 				       drm_mode_vrefresh(adjusted_mode));
8785 			dm_new_connector_state->scaling = RMX_ASPECT;
8786 		}
8787 		return 0;
8788 	}
8789 
8790 	if (!aconnector->mst_output_port)
8791 		return 0;
8792 
8793 	mst_port = aconnector->mst_output_port;
8794 	mst_mgr = &aconnector->mst_root->mst_mgr;
8795 
8796 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
8797 		return 0;
8798 
8799 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
8800 	if (IS_ERR(mst_state))
8801 		return PTR_ERR(mst_state);
8802 
8803 	mst_state->pbn_div.full = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
8804 
8805 	if (!state->duplicated) {
8806 		int max_bpc = conn_state->max_requested_bpc;
8807 
8808 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
8809 			  aconnector->force_yuv420_output;
8810 		color_depth = convert_color_depth_from_display_info(connector,
8811 								    is_y420,
8812 								    max_bpc);
8813 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
8814 		clock = adjusted_mode->clock;
8815 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
8816 	}
8817 
8818 	dm_new_connector_state->vcpi_slots =
8819 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
8820 					      dm_new_connector_state->pbn);
8821 	if (dm_new_connector_state->vcpi_slots < 0) {
8822 		drm_dbg_atomic(connector->dev, "failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
8823 		return dm_new_connector_state->vcpi_slots;
8824 	}
8825 	return 0;
8826 }
8827 
8828 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
8829 	.disable = dm_encoder_helper_disable,
8830 	.atomic_check = dm_encoder_helper_atomic_check
8831 };
8832 
8833 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_commit *state,
8834 					    struct dc_state *dc_state,
8835 					    struct dsc_mst_fairness_vars *vars)
8836 {
8837 	struct dc_stream_state *stream = NULL;
8838 	struct drm_connector *connector;
8839 	struct drm_connector_state *new_con_state;
8840 	struct amdgpu_dm_connector *aconnector;
8841 	struct dm_connector_state *dm_conn_state;
8842 	int i, j, ret;
8843 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
8844 
8845 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8846 
8847 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
8848 			continue;
8849 
8850 		aconnector = to_amdgpu_dm_connector(connector);
8851 
8852 		if (!aconnector->mst_output_port)
8853 			continue;
8854 
8855 		if (!new_con_state || !new_con_state->crtc)
8856 			continue;
8857 
8858 		dm_conn_state = to_dm_connector_state(new_con_state);
8859 
8860 		for (j = 0; j < dc_state->stream_count; j++) {
8861 			stream = dc_state->streams[j];
8862 			if (!stream)
8863 				continue;
8864 
8865 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
8866 				break;
8867 
8868 			stream = NULL;
8869 		}
8870 
8871 		if (!stream)
8872 			continue;
8873 
8874 		pbn_div = dm_mst_get_pbn_divider(stream->link);
8875 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
8876 		for (j = 0; j < dc_state->stream_count; j++) {
8877 			if (vars[j].aconnector == aconnector) {
8878 				pbn = vars[j].pbn;
8879 				break;
8880 			}
8881 		}
8882 
8883 		if (j == dc_state->stream_count || pbn_div == 0)
8884 			continue;
8885 
8886 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
8887 
8888 		if (stream->timing.flags.DSC != 1) {
8889 			dm_conn_state->pbn = pbn;
8890 			dm_conn_state->vcpi_slots = slot_num;
8891 
8892 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
8893 							   dm_conn_state->pbn, false);
8894 			if (ret < 0)
8895 				return ret;
8896 
8897 			continue;
8898 		}
8899 
8900 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
8901 		if (vcpi < 0)
8902 			return vcpi;
8903 
8904 		dm_conn_state->pbn = pbn;
8905 		dm_conn_state->vcpi_slots = vcpi;
8906 	}
8907 	return 0;
8908 }
8909 
8910 static int to_drm_connector_type(enum signal_type st, uint32_t connector_id)
8911 {
8912 	switch (st) {
8913 	case SIGNAL_TYPE_HDMI_TYPE_A:
8914 		return DRM_MODE_CONNECTOR_HDMIA;
8915 	case SIGNAL_TYPE_EDP:
8916 		return DRM_MODE_CONNECTOR_eDP;
8917 	case SIGNAL_TYPE_LVDS:
8918 		return DRM_MODE_CONNECTOR_LVDS;
8919 	case SIGNAL_TYPE_RGB:
8920 		return DRM_MODE_CONNECTOR_VGA;
8921 	case SIGNAL_TYPE_DISPLAY_PORT:
8922 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
8923 		/* External DP bridges have a different connector type. */
8924 		if (connector_id == CONNECTOR_ID_VGA)
8925 			return DRM_MODE_CONNECTOR_VGA;
8926 		else if (connector_id == CONNECTOR_ID_LVDS)
8927 			return DRM_MODE_CONNECTOR_LVDS;
8928 
8929 		return DRM_MODE_CONNECTOR_DisplayPort;
8930 	case SIGNAL_TYPE_DVI_DUAL_LINK:
8931 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
8932 		if (connector_id == CONNECTOR_ID_SINGLE_LINK_DVII ||
8933 			connector_id == CONNECTOR_ID_DUAL_LINK_DVII)
8934 			return DRM_MODE_CONNECTOR_DVII;
8935 
8936 		return DRM_MODE_CONNECTOR_DVID;
8937 	case SIGNAL_TYPE_VIRTUAL:
8938 		return DRM_MODE_CONNECTOR_VIRTUAL;
8939 
8940 	default:
8941 		return DRM_MODE_CONNECTOR_Unknown;
8942 	}
8943 }
8944 
8945 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
8946 {
8947 	struct drm_encoder *encoder;
8948 
8949 	/* There is only one encoder per connector */
8950 	drm_connector_for_each_possible_encoder(connector, encoder)
8951 		return encoder;
8952 
8953 	return NULL;
8954 }
8955 
8956 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
8957 {
8958 	struct drm_encoder *encoder;
8959 	struct amdgpu_encoder *amdgpu_encoder;
8960 
8961 	encoder = amdgpu_dm_connector_to_encoder(connector);
8962 
8963 	if (encoder == NULL)
8964 		return;
8965 
8966 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8967 
8968 	amdgpu_encoder->native_mode.clock = 0;
8969 
8970 	if (!list_empty(&connector->probed_modes)) {
8971 		struct drm_display_mode *preferred_mode = NULL;
8972 
8973 		list_for_each_entry(preferred_mode,
8974 				    &connector->probed_modes,
8975 				    head) {
8976 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
8977 				amdgpu_encoder->native_mode = *preferred_mode;
8978 
8979 			break;
8980 		}
8981 
8982 	}
8983 }
8984 
8985 static struct drm_display_mode *
8986 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
8987 			     const char *name,
8988 			     int hdisplay, int vdisplay)
8989 {
8990 	struct drm_device *dev = encoder->dev;
8991 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8992 	struct drm_display_mode *mode = NULL;
8993 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8994 
8995 	mode = drm_mode_duplicate(dev, native_mode);
8996 
8997 	if (mode == NULL)
8998 		return NULL;
8999 
9000 	mode->hdisplay = hdisplay;
9001 	mode->vdisplay = vdisplay;
9002 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
9003 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
9004 
9005 	return mode;
9006 
9007 }
9008 
9009 static const struct amdgpu_dm_mode_size {
9010 	char name[DRM_DISPLAY_MODE_LEN];
9011 	int w;
9012 	int h;
9013 } common_modes[] = {
9014 	{  "640x480",  640,  480},
9015 	{  "800x600",  800,  600},
9016 	{ "1024x768", 1024,  768},
9017 	{ "1280x720", 1280,  720},
9018 	{ "1280x800", 1280,  800},
9019 	{"1280x1024", 1280, 1024},
9020 	{ "1440x900", 1440,  900},
9021 	{"1680x1050", 1680, 1050},
9022 	{"1600x1200", 1600, 1200},
9023 	{"1920x1080", 1920, 1080},
9024 	{"1920x1200", 1920, 1200}
9025 };
9026 
9027 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
9028 						 struct drm_connector *connector)
9029 {
9030 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
9031 	struct drm_display_mode *mode = NULL;
9032 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
9033 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9034 				to_amdgpu_dm_connector(connector);
9035 	int i;
9036 	int n;
9037 
9038 	if ((connector->connector_type != DRM_MODE_CONNECTOR_eDP) &&
9039 	    (connector->connector_type != DRM_MODE_CONNECTOR_LVDS))
9040 		return;
9041 
9042 	n = ARRAY_SIZE(common_modes);
9043 
9044 	for (i = 0; i < n; i++) {
9045 		struct drm_display_mode *curmode = NULL;
9046 		bool mode_existed = false;
9047 
9048 		if (common_modes[i].w > native_mode->hdisplay ||
9049 		    common_modes[i].h > native_mode->vdisplay ||
9050 		   (common_modes[i].w == native_mode->hdisplay &&
9051 		    common_modes[i].h == native_mode->vdisplay))
9052 			continue;
9053 
9054 		list_for_each_entry(curmode, &connector->probed_modes, head) {
9055 			if (common_modes[i].w == curmode->hdisplay &&
9056 			    common_modes[i].h == curmode->vdisplay) {
9057 				mode_existed = true;
9058 				break;
9059 			}
9060 		}
9061 
9062 		if (mode_existed)
9063 			continue;
9064 
9065 		mode = amdgpu_dm_create_common_mode(encoder,
9066 				common_modes[i].name, common_modes[i].w,
9067 				common_modes[i].h);
9068 		if (!mode)
9069 			continue;
9070 
9071 		drm_mode_probed_add(connector, mode);
9072 		amdgpu_dm_connector->num_modes++;
9073 	}
9074 }
9075 
9076 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
9077 {
9078 	struct drm_encoder *encoder;
9079 	struct amdgpu_encoder *amdgpu_encoder;
9080 	const struct drm_display_mode *native_mode;
9081 
9082 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
9083 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
9084 		return;
9085 
9086 	mutex_lock(&connector->dev->mode_config.mutex);
9087 	amdgpu_dm_connector_get_modes(connector);
9088 	mutex_unlock(&connector->dev->mode_config.mutex);
9089 
9090 	encoder = amdgpu_dm_connector_to_encoder(connector);
9091 	if (!encoder)
9092 		return;
9093 
9094 	amdgpu_encoder = to_amdgpu_encoder(encoder);
9095 
9096 	native_mode = &amdgpu_encoder->native_mode;
9097 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
9098 		return;
9099 
9100 	drm_connector_set_panel_orientation_with_quirk(connector,
9101 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
9102 						       native_mode->hdisplay,
9103 						       native_mode->vdisplay);
9104 }
9105 
9106 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
9107 					      const struct drm_edid *drm_edid)
9108 {
9109 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9110 			to_amdgpu_dm_connector(connector);
9111 
9112 	if (drm_edid) {
9113 		/* empty probed_modes */
9114 		INIT_LIST_HEAD(&connector->probed_modes);
9115 		amdgpu_dm_connector->num_modes =
9116 				drm_edid_connector_add_modes(connector);
9117 
9118 		/* sorting the probed modes before calling function
9119 		 * amdgpu_dm_get_native_mode() since EDID can have
9120 		 * more than one preferred mode. The modes that are
9121 		 * later in the probed mode list could be of higher
9122 		 * and preferred resolution. For example, 3840x2160
9123 		 * resolution in base EDID preferred timing and 4096x2160
9124 		 * preferred resolution in DID extension block later.
9125 		 */
9126 		drm_mode_sort(&connector->probed_modes);
9127 		amdgpu_dm_get_native_mode(connector);
9128 
9129 		/* Freesync capabilities are reset by calling
9130 		 * drm_edid_connector_add_modes() and need to be
9131 		 * restored here.
9132 		 */
9133 		amdgpu_dm_update_freesync_caps(connector, drm_edid, false);
9134 	} else {
9135 		amdgpu_dm_connector->num_modes = 0;
9136 	}
9137 }
9138 
9139 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
9140 			      struct drm_display_mode *mode)
9141 {
9142 	struct drm_display_mode *m;
9143 
9144 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
9145 		if (drm_mode_equal(m, mode))
9146 			return true;
9147 	}
9148 
9149 	return false;
9150 }
9151 
9152 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
9153 {
9154 	const struct drm_display_mode *m;
9155 	struct drm_display_mode *new_mode;
9156 	uint i;
9157 	u32 new_modes_count = 0;
9158 
9159 	/* Standard FPS values
9160 	 *
9161 	 * 23.976       - TV/NTSC
9162 	 * 24           - Cinema
9163 	 * 25           - TV/PAL
9164 	 * 29.97        - TV/NTSC
9165 	 * 30           - TV/NTSC
9166 	 * 48           - Cinema HFR
9167 	 * 50           - TV/PAL
9168 	 * 60           - Commonly used
9169 	 * 48,72,96,120 - Multiples of 24
9170 	 */
9171 	static const u32 common_rates[] = {
9172 		23976, 24000, 25000, 29970, 30000,
9173 		48000, 50000, 60000, 72000, 96000, 120000
9174 	};
9175 
9176 	/*
9177 	 * Find mode with highest refresh rate with the same resolution
9178 	 * as the preferred mode. Some monitors report a preferred mode
9179 	 * with lower resolution than the highest refresh rate supported.
9180 	 */
9181 
9182 	m = get_highest_refresh_rate_mode(aconnector, true);
9183 	if (!m)
9184 		return 0;
9185 
9186 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
9187 		u64 target_vtotal, target_vtotal_diff;
9188 		u64 num, den;
9189 
9190 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
9191 			continue;
9192 
9193 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
9194 		    common_rates[i] > aconnector->max_vfreq * 1000)
9195 			continue;
9196 
9197 		num = (unsigned long long)m->clock * 1000 * 1000;
9198 		den = common_rates[i] * (unsigned long long)m->htotal;
9199 		target_vtotal = div_u64(num, den);
9200 		target_vtotal_diff = target_vtotal - m->vtotal;
9201 
9202 		/* Check for illegal modes */
9203 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
9204 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
9205 		    m->vtotal + target_vtotal_diff < m->vsync_end)
9206 			continue;
9207 
9208 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
9209 		if (!new_mode)
9210 			goto out;
9211 
9212 		new_mode->vtotal += (u16)target_vtotal_diff;
9213 		new_mode->vsync_start += (u16)target_vtotal_diff;
9214 		new_mode->vsync_end += (u16)target_vtotal_diff;
9215 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
9216 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
9217 
9218 		if (!is_duplicate_mode(aconnector, new_mode)) {
9219 			drm_mode_probed_add(&aconnector->base, new_mode);
9220 			new_modes_count += 1;
9221 		} else
9222 			drm_mode_destroy(aconnector->base.dev, new_mode);
9223 	}
9224  out:
9225 	return new_modes_count;
9226 }
9227 
9228 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
9229 						   const struct drm_edid *drm_edid)
9230 {
9231 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9232 		to_amdgpu_dm_connector(connector);
9233 
9234 	if (!(amdgpu_freesync_vid_mode && drm_edid))
9235 		return;
9236 
9237 	if (!amdgpu_dm_connector->dc_sink || !amdgpu_dm_connector->dc_link)
9238 		return;
9239 
9240 	if (!dc_supports_vrr(amdgpu_dm_connector->dc_sink->ctx->dce_version))
9241 		return;
9242 
9243 	if (dc_connector_supports_analog(amdgpu_dm_connector->dc_link->link_id.id) &&
9244 	    amdgpu_dm_connector->dc_sink->edid_caps.analog)
9245 		return;
9246 
9247 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
9248 		amdgpu_dm_connector->num_modes +=
9249 			add_fs_modes(amdgpu_dm_connector);
9250 }
9251 
9252 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
9253 {
9254 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9255 			to_amdgpu_dm_connector(connector);
9256 	struct dc_link *dc_link = amdgpu_dm_connector->dc_link;
9257 	struct drm_encoder *encoder;
9258 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
9259 	struct dc_link_settings *verified_link_cap = &dc_link->verified_link_cap;
9260 	const struct dc *dc = dc_link->dc;
9261 
9262 	encoder = amdgpu_dm_connector_to_encoder(connector);
9263 
9264 	if (!drm_edid) {
9265 		amdgpu_dm_connector->num_modes =
9266 				drm_add_modes_noedid(connector, 640, 480);
9267 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
9268 			amdgpu_dm_connector->num_modes +=
9269 				drm_add_modes_noedid(connector, 1920, 1080);
9270 
9271 		if (amdgpu_dm_connector->dc_sink &&
9272 		    amdgpu_dm_connector->dc_sink->edid_caps.analog &&
9273 		    dc_connector_supports_analog(dc_link->link_id.id)) {
9274 			/* Analog monitor connected by DAC load detection.
9275 			 * Add common modes. It will be up to the user to select one that works.
9276 			 */
9277 			for (int i = 0; i < ARRAY_SIZE(common_modes); i++)
9278 				amdgpu_dm_connector->num_modes += drm_add_modes_noedid(
9279 					connector, common_modes[i].w, common_modes[i].h);
9280 		}
9281 	} else {
9282 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
9283 		if (encoder)
9284 			amdgpu_dm_connector_add_common_modes(encoder, connector);
9285 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
9286 	}
9287 	amdgpu_dm_fbc_init(connector);
9288 
9289 	return amdgpu_dm_connector->num_modes;
9290 }
9291 
9292 static const u32 supported_colorspaces =
9293 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
9294 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
9295 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
9296 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
9297 
9298 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
9299 				     struct amdgpu_dm_connector *aconnector,
9300 				     int connector_type,
9301 				     struct dc_link *link,
9302 				     int link_index)
9303 {
9304 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
9305 
9306 	/*
9307 	 * Some of the properties below require access to state, like bpc.
9308 	 * Allocate some default initial connector state with our reset helper.
9309 	 */
9310 	if (aconnector->base.funcs->reset)
9311 		aconnector->base.funcs->reset(&aconnector->base);
9312 
9313 	aconnector->connector_id = link_index;
9314 	aconnector->bl_idx = -1;
9315 	aconnector->dc_link = link;
9316 	aconnector->base.interlace_allowed = false;
9317 	aconnector->base.doublescan_allowed = false;
9318 	aconnector->base.stereo_allowed = false;
9319 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
9320 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
9321 	aconnector->audio_inst = -1;
9322 	aconnector->pack_sdp_v1_3 = false;
9323 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
9324 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
9325 	mutex_init(&aconnector->hpd_lock);
9326 	mutex_init(&aconnector->handle_mst_msg_ready);
9327 
9328 	/*
9329 	 * If HDMI HPD debounce delay is set, use the minimum between selected
9330 	 * value and AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS
9331 	 */
9332 	if (amdgpu_hdmi_hpd_debounce_delay_ms) {
9333 		aconnector->hdmi_hpd_debounce_delay_ms = min(amdgpu_hdmi_hpd_debounce_delay_ms,
9334 							     AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS);
9335 		INIT_DELAYED_WORK(&aconnector->hdmi_hpd_debounce_work, hdmi_hpd_debounce_work);
9336 		aconnector->hdmi_prev_sink = NULL;
9337 	} else {
9338 		aconnector->hdmi_hpd_debounce_delay_ms = 0;
9339 	}
9340 
9341 	/*
9342 	 * configure support HPD hot plug connector_>polled default value is 0
9343 	 * which means HPD hot plug not supported
9344 	 */
9345 	switch (connector_type) {
9346 	case DRM_MODE_CONNECTOR_HDMIA:
9347 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9348 		aconnector->base.ycbcr_420_allowed =
9349 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
9350 		break;
9351 	case DRM_MODE_CONNECTOR_DisplayPort:
9352 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9353 		link->link_enc = link_enc_cfg_get_link_enc(link);
9354 		ASSERT(link->link_enc);
9355 		if (link->link_enc)
9356 			aconnector->base.ycbcr_420_allowed =
9357 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
9358 		break;
9359 	case DRM_MODE_CONNECTOR_DVID:
9360 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9361 		break;
9362 	case DRM_MODE_CONNECTOR_DVII:
9363 	case DRM_MODE_CONNECTOR_VGA:
9364 		aconnector->base.polled =
9365 			DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT;
9366 		break;
9367 	default:
9368 		break;
9369 	}
9370 
9371 	drm_object_attach_property(&aconnector->base.base,
9372 				dm->ddev->mode_config.scaling_mode_property,
9373 				DRM_MODE_SCALE_NONE);
9374 
9375 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA
9376 		|| (connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root))
9377 		drm_connector_attach_broadcast_rgb_property(&aconnector->base);
9378 
9379 	drm_object_attach_property(&aconnector->base.base,
9380 				adev->mode_info.underscan_property,
9381 				UNDERSCAN_OFF);
9382 	drm_object_attach_property(&aconnector->base.base,
9383 				adev->mode_info.underscan_hborder_property,
9384 				0);
9385 	drm_object_attach_property(&aconnector->base.base,
9386 				adev->mode_info.underscan_vborder_property,
9387 				0);
9388 
9389 	if (!aconnector->mst_root)
9390 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
9391 
9392 	aconnector->base.state->max_bpc = 16;
9393 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
9394 
9395 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9396 		/* Content Type is currently only implemented for HDMI. */
9397 		drm_connector_attach_content_type_property(&aconnector->base);
9398 	}
9399 
9400 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9401 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
9402 			drm_connector_attach_colorspace_property(&aconnector->base);
9403 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
9404 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
9405 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
9406 			drm_connector_attach_colorspace_property(&aconnector->base);
9407 	}
9408 
9409 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9410 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
9411 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
9412 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
9413 
9414 		if (!aconnector->mst_root)
9415 			drm_connector_attach_vrr_capable_property(&aconnector->base);
9416 
9417 		if (adev->dm.hdcp_workqueue)
9418 			drm_connector_attach_content_protection_property(&aconnector->base, true);
9419 	}
9420 
9421 	if (connector_type == DRM_MODE_CONNECTOR_eDP) {
9422 		struct drm_privacy_screen *privacy_screen;
9423 
9424 		drm_connector_attach_panel_type_property(&aconnector->base);
9425 
9426 		privacy_screen = drm_privacy_screen_get(adev_to_drm(adev)->dev, NULL);
9427 		if (!IS_ERR(privacy_screen)) {
9428 			drm_connector_attach_privacy_screen_provider(&aconnector->base,
9429 								     privacy_screen);
9430 		} else if (PTR_ERR(privacy_screen) != -ENODEV) {
9431 			drm_warn(adev_to_drm(adev), "Error getting privacy-screen\n");
9432 		}
9433 	}
9434 }
9435 
9436 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
9437 			      struct i2c_msg *msgs, int num)
9438 {
9439 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
9440 	struct ddc_service *ddc_service = i2c->ddc_service;
9441 	struct i2c_command cmd;
9442 	int i;
9443 	int result = -EIO;
9444 
9445 	if (!ddc_service->ddc_pin)
9446 		return result;
9447 
9448 	cmd.payloads = kzalloc_objs(struct i2c_payload, num);
9449 
9450 	if (!cmd.payloads)
9451 		return result;
9452 
9453 	cmd.number_of_payloads = num;
9454 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
9455 	cmd.speed = 100;
9456 
9457 	for (i = 0; i < num; i++) {
9458 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
9459 		cmd.payloads[i].address = msgs[i].addr;
9460 		cmd.payloads[i].length = msgs[i].len;
9461 		cmd.payloads[i].data = msgs[i].buf;
9462 	}
9463 
9464 	if (i2c->oem) {
9465 		if (dc_submit_i2c_oem(
9466 			    ddc_service->ctx->dc,
9467 			    &cmd))
9468 			result = num;
9469 	} else {
9470 		if (dc_submit_i2c(
9471 			    ddc_service->ctx->dc,
9472 			    ddc_service->link->link_index,
9473 			    &cmd))
9474 			result = num;
9475 	}
9476 
9477 	kfree(cmd.payloads);
9478 	return result;
9479 }
9480 
9481 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
9482 {
9483 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
9484 }
9485 
9486 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
9487 	.master_xfer = amdgpu_dm_i2c_xfer,
9488 	.functionality = amdgpu_dm_i2c_func,
9489 };
9490 
9491 static struct amdgpu_i2c_adapter *
9492 create_i2c(struct ddc_service *ddc_service, bool oem)
9493 {
9494 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
9495 	struct amdgpu_i2c_adapter *i2c;
9496 
9497 	i2c = kzalloc_obj(struct amdgpu_i2c_adapter);
9498 	if (!i2c)
9499 		return NULL;
9500 	i2c->base.owner = THIS_MODULE;
9501 	i2c->base.dev.parent = &adev->pdev->dev;
9502 	i2c->base.algo = &amdgpu_dm_i2c_algo;
9503 	if (oem)
9504 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c OEM bus");
9505 	else
9506 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d",
9507 			 ddc_service->link->link_index);
9508 	i2c_set_adapdata(&i2c->base, i2c);
9509 	i2c->ddc_service = ddc_service;
9510 	i2c->oem = oem;
9511 
9512 	return i2c;
9513 }
9514 
9515 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
9516 {
9517 	struct cec_connector_info conn_info;
9518 	struct drm_device *ddev = aconnector->base.dev;
9519 	struct device *hdmi_dev = ddev->dev;
9520 
9521 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
9522 		drm_info(ddev, "HDMI-CEC feature masked\n");
9523 		return -EINVAL;
9524 	}
9525 
9526 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
9527 	aconnector->notifier =
9528 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
9529 	if (!aconnector->notifier) {
9530 		drm_err(ddev, "Failed to create cec notifier\n");
9531 		return -ENOMEM;
9532 	}
9533 
9534 	return 0;
9535 }
9536 
9537 /*
9538  * Note: this function assumes that dc_link_detect() was called for the
9539  * dc_link which will be represented by this aconnector.
9540  */
9541 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
9542 				    struct amdgpu_dm_connector *aconnector,
9543 				    u32 link_index,
9544 				    struct amdgpu_encoder *aencoder)
9545 {
9546 	int res = 0;
9547 	int connector_type;
9548 	struct dc *dc = dm->dc;
9549 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
9550 	struct amdgpu_i2c_adapter *i2c;
9551 
9552 	/* Not needed for writeback connector */
9553 	link->priv = aconnector;
9554 
9555 
9556 	i2c = create_i2c(link->ddc, false);
9557 	if (!i2c) {
9558 		drm_err(adev_to_drm(dm->adev), "Failed to create i2c adapter data\n");
9559 		return -ENOMEM;
9560 	}
9561 
9562 	aconnector->i2c = i2c;
9563 	res = devm_i2c_add_adapter(dm->adev->dev, &i2c->base);
9564 
9565 	if (res) {
9566 		drm_err(adev_to_drm(dm->adev), "Failed to register hw i2c %d\n", link->link_index);
9567 		goto out_free;
9568 	}
9569 
9570 	connector_type = to_drm_connector_type(link->connector_signal, link->link_id.id);
9571 
9572 	res = drm_connector_init_with_ddc(
9573 			dm->ddev,
9574 			&aconnector->base,
9575 			&amdgpu_dm_connector_funcs,
9576 			connector_type,
9577 			&i2c->base);
9578 
9579 	if (res) {
9580 		drm_err(adev_to_drm(dm->adev), "connector_init failed\n");
9581 		aconnector->connector_id = -1;
9582 		goto out_free;
9583 	}
9584 
9585 	drm_connector_helper_add(
9586 			&aconnector->base,
9587 			&amdgpu_dm_connector_helper_funcs);
9588 
9589 	amdgpu_dm_connector_init_helper(
9590 		dm,
9591 		aconnector,
9592 		connector_type,
9593 		link,
9594 		link_index);
9595 
9596 	drm_connector_attach_encoder(
9597 		&aconnector->base, &aencoder->base);
9598 
9599 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9600 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
9601 		amdgpu_dm_initialize_hdmi_connector(aconnector);
9602 
9603 	if (dc_is_dp_signal(link->connector_signal))
9604 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
9605 
9606 out_free:
9607 	if (res) {
9608 		kfree(i2c);
9609 		aconnector->i2c = NULL;
9610 	}
9611 	return res;
9612 }
9613 
9614 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
9615 {
9616 	switch (adev->mode_info.num_crtc) {
9617 	case 1:
9618 		return 0x1;
9619 	case 2:
9620 		return 0x3;
9621 	case 3:
9622 		return 0x7;
9623 	case 4:
9624 		return 0xf;
9625 	case 5:
9626 		return 0x1f;
9627 	case 6:
9628 	default:
9629 		return 0x3f;
9630 	}
9631 }
9632 
9633 static int amdgpu_dm_encoder_init(struct drm_device *dev,
9634 				  struct amdgpu_encoder *aencoder,
9635 				  uint32_t link_index)
9636 {
9637 	struct amdgpu_device *adev = drm_to_adev(dev);
9638 
9639 	int res = drm_encoder_init(dev,
9640 				   &aencoder->base,
9641 				   &amdgpu_dm_encoder_funcs,
9642 				   DRM_MODE_ENCODER_TMDS,
9643 				   NULL);
9644 
9645 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
9646 
9647 	if (!res)
9648 		aencoder->encoder_id = link_index;
9649 	else
9650 		aencoder->encoder_id = -1;
9651 
9652 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
9653 
9654 	return res;
9655 }
9656 
9657 static void manage_dm_interrupts(struct amdgpu_device *adev,
9658 				 struct amdgpu_crtc *acrtc,
9659 				 struct dm_crtc_state *acrtc_state)
9660 {	/*
9661 	 * We cannot be sure that the frontend index maps to the same
9662 	 * backend index - some even map to more than one.
9663 	 * So we have to go through the CRTC to find the right IRQ.
9664 	 */
9665 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
9666 			adev,
9667 			acrtc->crtc_id);
9668 	struct drm_device *dev = adev_to_drm(adev);
9669 
9670 	struct drm_vblank_crtc_config config = {0};
9671 	struct dc_crtc_timing *timing;
9672 	int offdelay;
9673 
9674 	if (acrtc_state) {
9675 		timing = &acrtc_state->stream->timing;
9676 
9677 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) >=
9678 		      IP_VERSION(3, 2, 0) &&
9679 		      !(adev->flags & AMD_IS_APU)) {
9680 			/*
9681 			 * DGPUs NV3x and newer that support idle optimizations
9682 			 * experience intermittent flip-done timeouts on cursor
9683 			 * updates. Restore 5s offdelay behavior for now.
9684 			 *
9685 			 * Discussion on the issue:
9686 			 * https://lore.kernel.org/amd-gfx/20260217191632.1243826-1-sysdadmin@m1k.cloud/
9687 			 */
9688 			config.offdelay_ms = 5000;
9689 			config.disable_immediate = false;
9690 		} else if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
9691 			     IP_VERSION(3, 5, 0)) {
9692 			/*
9693 			 * Older HW and DGPU have issues with instant off;
9694 			 * use a 2 frame offdelay.
9695 			 */
9696 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
9697 						      timing->v_total *
9698 						      timing->h_total,
9699 						      timing->pix_clk_100hz);
9700 
9701 			config.offdelay_ms = offdelay ?: 30;
9702 		} else {
9703 			/* offdelay_ms = 0 will never disable vblank */
9704 			config.offdelay_ms = 1;
9705 			config.disable_immediate = true;
9706 		}
9707 
9708 		drm_crtc_vblank_on_config(&acrtc->base,
9709 					  &config);
9710 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_get.*/
9711 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9712 		case IP_VERSION(3, 0, 0):
9713 		case IP_VERSION(3, 0, 2):
9714 		case IP_VERSION(3, 0, 3):
9715 		case IP_VERSION(3, 2, 0):
9716 			if (amdgpu_irq_get(adev, &adev->pageflip_irq, irq_type))
9717 				drm_err(dev, "DM_IRQ: Cannot get pageflip irq!\n");
9718 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9719 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
9720 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
9721 #endif
9722 		}
9723 
9724 	} else {
9725 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
9726 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9727 		case IP_VERSION(3, 0, 0):
9728 		case IP_VERSION(3, 0, 2):
9729 		case IP_VERSION(3, 0, 3):
9730 		case IP_VERSION(3, 2, 0):
9731 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9732 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
9733 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
9734 #endif
9735 			if (amdgpu_irq_put(adev, &adev->pageflip_irq, irq_type))
9736 				drm_err(dev, "DM_IRQ: Cannot put pageflip irq!\n");
9737 		}
9738 
9739 		drm_crtc_vblank_off(&acrtc->base);
9740 	}
9741 }
9742 
9743 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
9744 				      struct amdgpu_crtc *acrtc)
9745 {
9746 	int irq_type =
9747 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
9748 
9749 	/**
9750 	 * This reads the current state for the IRQ and force reapplies
9751 	 * the setting to hardware.
9752 	 */
9753 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
9754 }
9755 
9756 static bool
9757 is_scaling_state_different(const struct dm_connector_state *dm_state,
9758 			   const struct dm_connector_state *old_dm_state)
9759 {
9760 	if (dm_state->scaling != old_dm_state->scaling)
9761 		return true;
9762 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
9763 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
9764 			return true;
9765 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
9766 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
9767 			return true;
9768 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
9769 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
9770 		return true;
9771 	return false;
9772 }
9773 
9774 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
9775 					    struct drm_crtc_state *old_crtc_state,
9776 					    struct drm_connector_state *new_conn_state,
9777 					    struct drm_connector_state *old_conn_state,
9778 					    const struct drm_connector *connector,
9779 					    struct hdcp_workqueue *hdcp_w)
9780 {
9781 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
9782 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
9783 
9784 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
9785 		connector->index, connector->status, connector->dpms);
9786 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
9787 		old_conn_state->content_protection, new_conn_state->content_protection);
9788 
9789 	if (old_crtc_state)
9790 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9791 		old_crtc_state->enable,
9792 		old_crtc_state->active,
9793 		old_crtc_state->mode_changed,
9794 		old_crtc_state->active_changed,
9795 		old_crtc_state->connectors_changed);
9796 
9797 	if (new_crtc_state)
9798 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9799 		new_crtc_state->enable,
9800 		new_crtc_state->active,
9801 		new_crtc_state->mode_changed,
9802 		new_crtc_state->active_changed,
9803 		new_crtc_state->connectors_changed);
9804 
9805 	/* hdcp content type change */
9806 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
9807 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
9808 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9809 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
9810 		return true;
9811 	}
9812 
9813 	/* CP is being re enabled, ignore this */
9814 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
9815 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9816 		if (new_crtc_state && new_crtc_state->mode_changed) {
9817 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9818 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
9819 			return true;
9820 		}
9821 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
9822 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
9823 		return false;
9824 	}
9825 
9826 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
9827 	 *
9828 	 * Handles:	UNDESIRED -> ENABLED
9829 	 */
9830 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
9831 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
9832 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9833 
9834 	/* Stream removed and re-enabled
9835 	 *
9836 	 * Can sometimes overlap with the HPD case,
9837 	 * thus set update_hdcp to false to avoid
9838 	 * setting HDCP multiple times.
9839 	 *
9840 	 * Handles:	DESIRED -> DESIRED (Special case)
9841 	 */
9842 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
9843 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
9844 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9845 		dm_con_state->update_hdcp = false;
9846 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
9847 			__func__);
9848 		return true;
9849 	}
9850 
9851 	/* Hot-plug, headless s3, dpms
9852 	 *
9853 	 * Only start HDCP if the display is connected/enabled.
9854 	 * update_hdcp flag will be set to false until the next
9855 	 * HPD comes in.
9856 	 *
9857 	 * Handles:	DESIRED -> DESIRED (Special case)
9858 	 */
9859 	if (dm_con_state->update_hdcp &&
9860 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
9861 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
9862 		dm_con_state->update_hdcp = false;
9863 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
9864 			__func__);
9865 		return true;
9866 	}
9867 
9868 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
9869 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9870 			if (new_crtc_state && new_crtc_state->mode_changed) {
9871 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
9872 					__func__);
9873 				return true;
9874 			}
9875 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
9876 				__func__);
9877 			return false;
9878 		}
9879 
9880 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
9881 		return false;
9882 	}
9883 
9884 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9885 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
9886 			__func__);
9887 		return true;
9888 	}
9889 
9890 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
9891 	return false;
9892 }
9893 
9894 static void remove_stream(struct amdgpu_device *adev,
9895 			  struct amdgpu_crtc *acrtc,
9896 			  struct dc_stream_state *stream)
9897 {
9898 	/* this is the update mode case */
9899 
9900 	acrtc->otg_inst = -1;
9901 	acrtc->enabled = false;
9902 }
9903 
9904 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
9905 {
9906 
9907 	assert_spin_locked(&acrtc->base.dev->event_lock);
9908 	WARN_ON(acrtc->event);
9909 
9910 	acrtc->event = acrtc->base.state->event;
9911 
9912 	/* Set the flip status */
9913 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
9914 
9915 	/* Mark this event as consumed */
9916 	acrtc->base.state->event = NULL;
9917 
9918 	drm_dbg_state(acrtc->base.dev,
9919 		      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
9920 		      acrtc->crtc_id);
9921 }
9922 
9923 static void update_freesync_state_on_stream(
9924 	struct amdgpu_display_manager *dm,
9925 	struct dm_crtc_state *new_crtc_state,
9926 	struct dc_stream_state *new_stream,
9927 	struct dc_plane_state *surface,
9928 	u32 flip_timestamp_in_us)
9929 {
9930 	struct mod_vrr_params vrr_params;
9931 	struct dc_info_packet vrr_infopacket = {0};
9932 	struct amdgpu_device *adev = dm->adev;
9933 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9934 	unsigned long flags;
9935 	bool pack_sdp_v1_3 = false;
9936 	struct amdgpu_dm_connector *aconn;
9937 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
9938 
9939 	if (!new_stream)
9940 		return;
9941 
9942 	/*
9943 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9944 	 * For now it's sufficient to just guard against these conditions.
9945 	 */
9946 
9947 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9948 		return;
9949 
9950 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9951 	vrr_params = acrtc->dm_irq_params.vrr_params;
9952 
9953 	if (surface) {
9954 		mod_freesync_handle_preflip(
9955 			dm->freesync_module,
9956 			surface,
9957 			new_stream,
9958 			flip_timestamp_in_us,
9959 			&vrr_params);
9960 
9961 		if (adev->family < AMDGPU_FAMILY_AI &&
9962 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
9963 			mod_freesync_handle_v_update(dm->freesync_module,
9964 						     new_stream, &vrr_params);
9965 
9966 			/* Need to call this before the frame ends. */
9967 			dc_stream_adjust_vmin_vmax(dm->dc,
9968 						   new_crtc_state->stream,
9969 						   &vrr_params.adjust);
9970 		}
9971 	}
9972 
9973 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
9974 
9975 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
9976 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
9977 
9978 		if (aconn->vsdb_info.amd_vsdb_version == 1)
9979 			packet_type = PACKET_TYPE_FS_V1;
9980 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
9981 			packet_type = PACKET_TYPE_FS_V2;
9982 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
9983 			packet_type = PACKET_TYPE_FS_V3;
9984 
9985 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
9986 					&new_stream->adaptive_sync_infopacket);
9987 	}
9988 
9989 	mod_freesync_build_vrr_infopacket(
9990 		dm->freesync_module,
9991 		new_stream,
9992 		&vrr_params,
9993 		packet_type,
9994 		TRANSFER_FUNC_UNKNOWN,
9995 		&vrr_infopacket,
9996 		pack_sdp_v1_3);
9997 
9998 	new_crtc_state->freesync_vrr_info_changed |=
9999 		(memcmp(&new_crtc_state->vrr_infopacket,
10000 			&vrr_infopacket,
10001 			sizeof(vrr_infopacket)) != 0);
10002 
10003 	acrtc->dm_irq_params.vrr_params = vrr_params;
10004 	new_crtc_state->vrr_infopacket = vrr_infopacket;
10005 
10006 	new_stream->vrr_infopacket = vrr_infopacket;
10007 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
10008 
10009 	if (new_crtc_state->freesync_vrr_info_changed)
10010 		drm_dbg_kms(adev_to_drm(adev), "VRR packet update: crtc=%u enabled=%d state=%d",
10011 			      new_crtc_state->base.crtc->base.id,
10012 			      (int)new_crtc_state->base.vrr_enabled,
10013 			      (int)vrr_params.state);
10014 
10015 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10016 }
10017 
10018 static void update_stream_irq_parameters(
10019 	struct amdgpu_display_manager *dm,
10020 	struct dm_crtc_state *new_crtc_state)
10021 {
10022 	struct dc_stream_state *new_stream = new_crtc_state->stream;
10023 	struct mod_vrr_params vrr_params;
10024 	struct mod_freesync_config config = new_crtc_state->freesync_config;
10025 	struct amdgpu_device *adev = dm->adev;
10026 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
10027 	unsigned long flags;
10028 
10029 	if (!new_stream)
10030 		return;
10031 
10032 	/*
10033 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
10034 	 * For now it's sufficient to just guard against these conditions.
10035 	 */
10036 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
10037 		return;
10038 
10039 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
10040 	vrr_params = acrtc->dm_irq_params.vrr_params;
10041 
10042 	if (new_crtc_state->vrr_supported &&
10043 	    config.min_refresh_in_uhz &&
10044 	    config.max_refresh_in_uhz) {
10045 		/*
10046 		 * if freesync compatible mode was set, config.state will be set
10047 		 * in atomic check
10048 		 */
10049 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
10050 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
10051 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
10052 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
10053 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
10054 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
10055 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
10056 		} else {
10057 			config.state = new_crtc_state->base.vrr_enabled ?
10058 						     VRR_STATE_ACTIVE_VARIABLE :
10059 						     VRR_STATE_INACTIVE;
10060 		}
10061 	} else {
10062 		config.state = VRR_STATE_UNSUPPORTED;
10063 	}
10064 
10065 	mod_freesync_build_vrr_params(dm->freesync_module,
10066 				      new_stream,
10067 				      &config, &vrr_params);
10068 
10069 	new_crtc_state->freesync_config = config;
10070 	/* Copy state for access from DM IRQ handler */
10071 	acrtc->dm_irq_params.freesync_config = config;
10072 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
10073 	acrtc->dm_irq_params.vrr_params = vrr_params;
10074 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10075 }
10076 
10077 static void amdgpu_dm_handle_vrr_transition(struct amdgpu_display_manager *dm,
10078 					    struct dm_crtc_state *old_state,
10079 					    struct dm_crtc_state *new_state)
10080 {
10081 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
10082 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
10083 
10084 	if (!old_vrr_active && new_vrr_active) {
10085 		/* Transition VRR inactive -> active:
10086 		 * While VRR is active, we must not disable vblank irq, as a
10087 		 * reenable after disable would compute bogus vblank/pflip
10088 		 * timestamps if it likely happened inside display front-porch.
10089 		 *
10090 		 * We also need vupdate irq for the actual core vblank handling
10091 		 * at end of vblank.
10092 		 */
10093 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
10094 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
10095 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR off->on: Get vblank ref\n",
10096 				 __func__, new_state->base.crtc->base.id);
10097 
10098 		scoped_guard(mutex, &dm->dc_lock) {
10099 			dc_exit_ips_for_hw_access(dm->dc);
10100 			amdgpu_dm_psr_set_event(dm, new_state->stream, true,
10101 				psr_event_vrr_transition, true);
10102 			amdgpu_dm_replay_set_event(dm, new_state->stream, true,
10103 				replay_event_vrr, true);
10104 		}
10105 	} else if (old_vrr_active && !new_vrr_active) {
10106 		/* Transition VRR active -> inactive:
10107 		 * Allow vblank irq disable again for fixed refresh rate.
10108 		 */
10109 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
10110 		drm_crtc_vblank_put(new_state->base.crtc);
10111 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR on->off: Drop vblank ref\n",
10112 				 __func__, new_state->base.crtc->base.id);
10113 
10114 		scoped_guard(mutex, &dm->dc_lock) {
10115 			dc_exit_ips_for_hw_access(dm->dc);
10116 			amdgpu_dm_psr_set_event(dm, new_state->stream, false,
10117 				psr_event_vrr_transition, false);
10118 			amdgpu_dm_replay_set_event(dm, new_state->stream, false,
10119 				replay_event_vrr, false);
10120 		}
10121 	}
10122 }
10123 
10124 static void amdgpu_dm_commit_cursors(struct drm_atomic_commit *state)
10125 {
10126 	struct drm_plane *plane;
10127 	struct drm_plane_state *old_plane_state;
10128 	int i;
10129 
10130 	/*
10131 	 * TODO: Make this per-stream so we don't issue redundant updates for
10132 	 * commits with multiple streams.
10133 	 */
10134 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
10135 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
10136 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
10137 }
10138 
10139 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
10140 {
10141 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
10142 
10143 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
10144 }
10145 
10146 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
10147 				    struct drm_plane_state *old_plane_state,
10148 				    struct dc_stream_update *update)
10149 {
10150 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
10151 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
10152 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
10153 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
10154 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
10155 	uint64_t address = afb ? afb->address : 0;
10156 	struct dc_cursor_position position = {0};
10157 	struct dc_cursor_attributes attributes;
10158 	int ret;
10159 
10160 	if (!plane->state->fb && !old_plane_state->fb)
10161 		return;
10162 
10163 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
10164 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
10165 		       plane->state->crtc_h);
10166 
10167 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
10168 	if (ret)
10169 		return;
10170 
10171 	if (!position.enable) {
10172 		/* turn off cursor */
10173 		if (crtc_state && crtc_state->stream) {
10174 			dc_stream_set_cursor_position(crtc_state->stream,
10175 						      &position);
10176 			update->cursor_position = &crtc_state->stream->cursor_position;
10177 		}
10178 		return;
10179 	}
10180 
10181 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
10182 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
10183 
10184 	memset(&attributes, 0, sizeof(attributes));
10185 	attributes.address.high_part = upper_32_bits(address);
10186 	attributes.address.low_part  = lower_32_bits(address);
10187 	attributes.width             = plane->state->crtc_w;
10188 	attributes.height            = plane->state->crtc_h;
10189 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
10190 	attributes.rotation_angle    = 0;
10191 	attributes.attribute_flags.value = 0;
10192 
10193 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
10194 	 * legacy gamma setup.
10195 	 */
10196 	if (crtc_state->cm_is_degamma_srgb &&
10197 	    adev->dm.dc->caps.color.dpp.gamma_corr)
10198 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
10199 
10200 	if (afb)
10201 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
10202 
10203 	if (crtc_state->stream) {
10204 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
10205 						     &attributes))
10206 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
10207 
10208 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
10209 
10210 		if (!dc_stream_set_cursor_position(crtc_state->stream,
10211 						   &position))
10212 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
10213 
10214 		update->cursor_position = &crtc_state->stream->cursor_position;
10215 	}
10216 }
10217 
10218 static void amdgpu_dm_enable_self_refresh(struct amdgpu_display_manager *dm,
10219 					  struct amdgpu_crtc *acrtc_attach,
10220 					  const struct dm_crtc_state *acrtc_state,
10221 					  const u64 current_ts)
10222 {
10223 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
10224 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
10225 	struct amdgpu_dm_connector *aconn =
10226 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
10227 
10228 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
10229 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
10230 	    (psr->psr_feature_enabled || pr->replay_feature_enabled)) {
10231 		if (aconn->sr_skip_count > 0)
10232 			aconn->sr_skip_count--;
10233 
10234 		/* Allow SR when skip count is 0. */
10235 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
10236 
10237 		/*
10238 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
10239 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
10240 		 * can be enabled immediately once OS demonstrates an
10241 		 * adequate number of fast atomic commits to notify KMD
10242 		 * of update events.
10243 		 * See `amdgpu_dm_crtc_vblank_control_worker()`.
10244 		 */
10245 		if (acrtc_attach->dm_irq_params.allow_sr_entry &&
10246 			(current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
10247 			amdgpu_dm_psr_set_event(dm, acrtc_state->stream, false,
10248 				psr_event_hw_programming, false);
10249 
10250 			amdgpu_dm_replay_set_event(dm, acrtc_state->stream, false,
10251 				replay_event_hw_programming, false);
10252 		}
10253 	} else {
10254 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
10255 	}
10256 }
10257 
10258 static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state,
10259 				    struct drm_device *dev,
10260 				    struct amdgpu_display_manager *dm,
10261 				    struct drm_crtc *pcrtc,
10262 				    bool wait_for_vblank)
10263 {
10264 	u32 i;
10265 	u64 timestamp_ns = ktime_get_ns();
10266 	struct drm_plane *plane;
10267 	struct drm_plane_state *old_plane_state, *new_plane_state;
10268 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
10269 	struct drm_crtc_state *new_pcrtc_state =
10270 			drm_atomic_get_new_crtc_state(state, pcrtc);
10271 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
10272 	struct dm_crtc_state *dm_old_crtc_state =
10273 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
10274 	int planes_count = 0, vpos, hpos;
10275 	unsigned long flags;
10276 	u32 target_vblank, last_flip_vblank;
10277 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
10278 	bool cursor_update = false;
10279 	bool pflip_present = false;
10280 	bool dirty_rects_changed = false;
10281 	bool updated_planes_and_streams = false;
10282 	struct {
10283 		struct dc_surface_update surface_updates[MAX_SURFACES];
10284 		struct dc_plane_info plane_infos[MAX_SURFACES];
10285 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
10286 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
10287 		struct dc_stream_update stream_update;
10288 	} *bundle;
10289 
10290 	bundle = kzalloc_obj(*bundle);
10291 
10292 	if (!bundle) {
10293 		drm_err(dev, "Failed to allocate update bundle\n");
10294 		goto cleanup;
10295 	}
10296 
10297 	/*
10298 	 * Disable the cursor first if we're disabling all the planes.
10299 	 * It'll remain on the screen after the planes are re-enabled
10300 	 * if we don't.
10301 	 *
10302 	 * If the cursor is transitioning from native to overlay mode, the
10303 	 * native cursor needs to be disabled first.
10304 	 */
10305 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
10306 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10307 		struct dc_cursor_position cursor_position = {0};
10308 
10309 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
10310 						   &cursor_position))
10311 			drm_err(dev, "DC failed to disable native cursor\n");
10312 
10313 		bundle->stream_update.cursor_position =
10314 				&acrtc_state->stream->cursor_position;
10315 	}
10316 
10317 	if (acrtc_state->active_planes == 0 &&
10318 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10319 		amdgpu_dm_commit_cursors(state);
10320 
10321 	/* update planes when needed */
10322 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
10323 		struct drm_crtc *crtc = new_plane_state->crtc;
10324 		struct drm_crtc_state *new_crtc_state;
10325 		struct drm_framebuffer *fb = new_plane_state->fb;
10326 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
10327 		bool plane_needs_flip;
10328 		struct dc_plane_state *dc_plane;
10329 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
10330 
10331 		/* Cursor plane is handled after stream updates */
10332 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
10333 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10334 			if ((fb && crtc == pcrtc) ||
10335 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
10336 				cursor_update = true;
10337 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
10338 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
10339 			}
10340 
10341 			continue;
10342 		}
10343 
10344 		if (!fb || !crtc || pcrtc != crtc)
10345 			continue;
10346 
10347 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
10348 		if (!new_crtc_state->active)
10349 			continue;
10350 
10351 		dc_plane = dm_new_plane_state->dc_state;
10352 		if (!dc_plane)
10353 			continue;
10354 
10355 		bundle->surface_updates[planes_count].surface = dc_plane;
10356 		if (new_pcrtc_state->color_mgmt_changed || new_plane_state->color_mgmt_changed) {
10357 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
10358 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
10359 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
10360 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
10361 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
10362 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
10363 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
10364 		}
10365 
10366 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
10367 				     &bundle->scaling_infos[planes_count]);
10368 
10369 		bundle->surface_updates[planes_count].scaling_info =
10370 			&bundle->scaling_infos[planes_count];
10371 
10372 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
10373 
10374 		pflip_present = pflip_present || plane_needs_flip;
10375 
10376 		if (!plane_needs_flip) {
10377 			planes_count += 1;
10378 			continue;
10379 		}
10380 
10381 		fill_dc_plane_info_and_addr(
10382 			dm->adev, new_plane_state,
10383 			afb->tiling_flags,
10384 			&bundle->plane_infos[planes_count],
10385 			&bundle->flip_addrs[planes_count].address,
10386 			afb->tmz_surface);
10387 
10388 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
10389 				 new_plane_state->plane->index,
10390 				 bundle->plane_infos[planes_count].dcc.enable);
10391 
10392 		bundle->surface_updates[planes_count].plane_info =
10393 			&bundle->plane_infos[planes_count];
10394 
10395 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
10396 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
10397 			fill_dc_dirty_rects(plane, old_plane_state,
10398 					    new_plane_state, new_crtc_state,
10399 					    &bundle->flip_addrs[planes_count],
10400 					    acrtc_state->stream->link->psr_settings.psr_version ==
10401 					    DC_PSR_VERSION_SU_1,
10402 					    &dirty_rects_changed);
10403 
10404 			/*
10405 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
10406 			 * and enabled it again after dirty regions are stable to avoid video glitch.
10407 			 * PSR-SU will be enabled in
10408 			 * amdgpu_dm_crtc_vblank_control_worker() if user
10409 			 * pause the video during the PSR-SU was disabled.
10410 			 */
10411 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
10412 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
10413 			    dirty_rects_changed) {
10414 				mutex_lock(&dm->dc_lock);
10415 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
10416 				timestamp_ns;
10417 				dc_exit_ips_for_hw_access(dm->dc);
10418 				amdgpu_dm_psr_set_event(dm, acrtc_state->stream, true,
10419 					psr_event_hw_programming, true);
10420 				mutex_unlock(&dm->dc_lock);
10421 			}
10422 		}
10423 
10424 		/*
10425 		 * Only allow immediate flips for fast updates that don't
10426 		 * change memory domain, FB pitch, DCC state, rotation or
10427 		 * mirroring.
10428 		 *
10429 		 * dm_crtc_helper_atomic_check() only accepts async flips with
10430 		 * fast updates.
10431 		 */
10432 		if (crtc->state->async_flip &&
10433 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
10434 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
10435 			drm_warn_once(state->dev,
10436 				      "[PLANE:%d:%s] async flip with non-fast update\n",
10437 				      plane->base.id, plane->name);
10438 
10439 		bundle->flip_addrs[planes_count].flip_immediate =
10440 			crtc->state->async_flip &&
10441 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
10442 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
10443 
10444 		timestamp_ns = ktime_get_ns();
10445 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
10446 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
10447 		bundle->surface_updates[planes_count].surface = dc_plane;
10448 
10449 		if (!bundle->surface_updates[planes_count].surface) {
10450 			drm_err(dev, "No surface for CRTC: id=%d\n",
10451 					acrtc_attach->crtc_id);
10452 			continue;
10453 		}
10454 
10455 		if (plane == pcrtc->primary)
10456 			update_freesync_state_on_stream(
10457 				dm,
10458 				acrtc_state,
10459 				acrtc_state->stream,
10460 				dc_plane,
10461 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
10462 
10463 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
10464 				 __func__,
10465 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
10466 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
10467 
10468 		planes_count += 1;
10469 
10470 	}
10471 
10472 	if (pflip_present) {
10473 		if (!vrr_active) {
10474 			/* Use old throttling in non-vrr fixed refresh rate mode
10475 			 * to keep flip scheduling based on target vblank counts
10476 			 * working in a backwards compatible way, e.g., for
10477 			 * clients using the GLX_OML_sync_control extension or
10478 			 * DRI3/Present extension with defined target_msc.
10479 			 */
10480 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
10481 		} else {
10482 			/* For variable refresh rate mode only:
10483 			 * Get vblank of last completed flip to avoid > 1 vrr
10484 			 * flips per video frame by use of throttling, but allow
10485 			 * flip programming anywhere in the possibly large
10486 			 * variable vrr vblank interval for fine-grained flip
10487 			 * timing control and more opportunity to avoid stutter
10488 			 * on late submission of flips.
10489 			 */
10490 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10491 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
10492 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10493 		}
10494 
10495 		target_vblank = last_flip_vblank + wait_for_vblank;
10496 
10497 		/*
10498 		 * Wait until we're out of the vertical blank period before the one
10499 		 * targeted by the flip
10500 		 */
10501 		while ((acrtc_attach->enabled &&
10502 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
10503 							    0, &vpos, &hpos, NULL,
10504 							    NULL, &pcrtc->hwmode)
10505 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
10506 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
10507 			(int)(target_vblank -
10508 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
10509 			usleep_range(1000, 1100);
10510 		}
10511 
10512 		/**
10513 		 * Prepare the flip event for the pageflip interrupt to handle.
10514 		 *
10515 		 * This only works in the case where we've already turned on the
10516 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
10517 		 * from 0 -> n planes we have to skip a hardware generated event
10518 		 * and rely on sending it from software.
10519 		 */
10520 		if (acrtc_attach->base.state->event &&
10521 		    acrtc_state->active_planes > 0) {
10522 			drm_crtc_vblank_get(pcrtc);
10523 
10524 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10525 
10526 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
10527 			prepare_flip_isr(acrtc_attach);
10528 
10529 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10530 		}
10531 
10532 		if (acrtc_state->stream) {
10533 			if (acrtc_state->freesync_vrr_info_changed)
10534 				bundle->stream_update.vrr_infopacket =
10535 					&acrtc_state->stream->vrr_infopacket;
10536 		}
10537 	} else if (cursor_update && acrtc_state->active_planes > 0) {
10538 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10539 		if (acrtc_attach->base.state->event) {
10540 			drm_crtc_vblank_get(pcrtc);
10541 			acrtc_attach->event = acrtc_attach->base.state->event;
10542 			acrtc_attach->base.state->event = NULL;
10543 		}
10544 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10545 	}
10546 
10547 	/* Update the planes if changed or disable if we don't have any. */
10548 	if ((planes_count || acrtc_state->active_planes == 0) &&
10549 		acrtc_state->stream) {
10550 		/*
10551 		 * If PSR or idle optimizations are enabled then flush out
10552 		 * any pending work before hardware programming.
10553 		 */
10554 		if (dm->vblank_control_workqueue)
10555 			flush_workqueue(dm->vblank_control_workqueue);
10556 
10557 		bundle->stream_update.stream = acrtc_state->stream;
10558 		if (new_pcrtc_state->mode_changed) {
10559 			bundle->stream_update.src = acrtc_state->stream->src;
10560 			bundle->stream_update.dst = acrtc_state->stream->dst;
10561 		}
10562 
10563 		if (new_pcrtc_state->color_mgmt_changed) {
10564 			/*
10565 			 * TODO: This isn't fully correct since we've actually
10566 			 * already modified the stream in place.
10567 			 */
10568 			bundle->stream_update.gamut_remap =
10569 				&acrtc_state->stream->gamut_remap_matrix;
10570 			bundle->stream_update.output_csc_transform =
10571 				&acrtc_state->stream->csc_color_matrix;
10572 			bundle->stream_update.out_transfer_func =
10573 				&acrtc_state->stream->out_transfer_func;
10574 			bundle->stream_update.lut3d_func =
10575 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
10576 			bundle->stream_update.func_shaper =
10577 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
10578 		}
10579 
10580 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
10581 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
10582 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
10583 
10584 		/*
10585 		 * If FreeSync state on the stream has changed then we need to
10586 		 * re-adjust the min/max bounds now that DC doesn't handle this
10587 		 * as part of commit.
10588 		 */
10589 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
10590 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10591 			dc_stream_adjust_vmin_vmax(
10592 				dm->dc, acrtc_state->stream,
10593 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
10594 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10595 		}
10596 		mutex_lock(&dm->dc_lock);
10597 		update_planes_and_stream_adapter(dm->dc,
10598 					 acrtc_state->update_type,
10599 					 planes_count,
10600 					 acrtc_state->stream,
10601 					 &bundle->stream_update,
10602 					 bundle->surface_updates);
10603 		updated_planes_and_streams = true;
10604 
10605 		/**
10606 		 * Enable or disable the interrupts on the backend.
10607 		 *
10608 		 * Most pipes are put into power gating when unused.
10609 		 *
10610 		 * When power gating is enabled on a pipe we lose the
10611 		 * interrupt enablement state when power gating is disabled.
10612 		 *
10613 		 * So we need to update the IRQ control state in hardware
10614 		 * whenever the pipe turns on (since it could be previously
10615 		 * power gated) or off (since some pipes can't be power gated
10616 		 * on some ASICs).
10617 		 */
10618 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
10619 			dm_update_pflip_irq_state(drm_to_adev(dev),
10620 						  acrtc_attach);
10621 		amdgpu_dm_enable_self_refresh(dm, acrtc_attach, acrtc_state,
10622 					      timestamp_ns);
10623 		mutex_unlock(&dm->dc_lock);
10624 	}
10625 
10626 	/*
10627 	 * Update cursor state *after* programming all the planes.
10628 	 * This avoids redundant programming in the case where we're going
10629 	 * to be disabling a single plane - those pipes are being disabled.
10630 	 */
10631 	if (acrtc_state->active_planes &&
10632 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
10633 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10634 		amdgpu_dm_commit_cursors(state);
10635 
10636 cleanup:
10637 	kfree(bundle);
10638 }
10639 
10640 static void amdgpu_dm_commit_audio(struct drm_device *dev,
10641 				   struct drm_atomic_commit *state)
10642 {
10643 	struct amdgpu_device *adev = drm_to_adev(dev);
10644 	struct amdgpu_dm_connector *aconnector;
10645 	struct drm_connector *connector;
10646 	struct drm_connector_state *old_con_state, *new_con_state;
10647 	struct drm_crtc_state *new_crtc_state;
10648 	struct dm_crtc_state *new_dm_crtc_state;
10649 	const struct dc_stream_status *status;
10650 	int i, inst;
10651 
10652 	/* Notify device removals. */
10653 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10654 		if (old_con_state->crtc != new_con_state->crtc) {
10655 			/* CRTC changes require notification. */
10656 			goto notify;
10657 		}
10658 
10659 		if (!new_con_state->crtc)
10660 			continue;
10661 
10662 		new_crtc_state = drm_atomic_get_new_crtc_state(
10663 			state, new_con_state->crtc);
10664 
10665 		if (!new_crtc_state)
10666 			continue;
10667 
10668 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10669 			continue;
10670 
10671 notify:
10672 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10673 			continue;
10674 
10675 		aconnector = to_amdgpu_dm_connector(connector);
10676 
10677 		mutex_lock(&adev->dm.audio_lock);
10678 		inst = aconnector->audio_inst;
10679 		aconnector->audio_inst = -1;
10680 		mutex_unlock(&adev->dm.audio_lock);
10681 
10682 		amdgpu_dm_audio_eld_notify(adev, inst);
10683 	}
10684 
10685 	/* Notify audio device additions. */
10686 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10687 		if (!new_con_state->crtc)
10688 			continue;
10689 
10690 		new_crtc_state = drm_atomic_get_new_crtc_state(
10691 			state, new_con_state->crtc);
10692 
10693 		if (!new_crtc_state)
10694 			continue;
10695 
10696 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10697 			continue;
10698 
10699 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
10700 		if (!new_dm_crtc_state->stream)
10701 			continue;
10702 
10703 		status = dc_stream_get_status(new_dm_crtc_state->stream);
10704 		if (!status)
10705 			continue;
10706 
10707 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10708 			continue;
10709 
10710 		aconnector = to_amdgpu_dm_connector(connector);
10711 
10712 		mutex_lock(&adev->dm.audio_lock);
10713 		inst = status->audio_inst;
10714 		aconnector->audio_inst = inst;
10715 		mutex_unlock(&adev->dm.audio_lock);
10716 
10717 		amdgpu_dm_audio_eld_notify(adev, inst);
10718 	}
10719 }
10720 
10721 /*
10722  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
10723  * @crtc_state: the DRM CRTC state
10724  * @stream_state: the DC stream state.
10725  *
10726  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
10727  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
10728  */
10729 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
10730 						struct dc_stream_state *stream_state)
10731 {
10732 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
10733 }
10734 
10735 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
10736 			      struct dm_crtc_state *crtc_state)
10737 {
10738 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
10739 }
10740 
10741 /**
10742  * amdgpu_dm_mod_power_update_streams - update mod_power stream state on modeset
10743  * @state: the drm atomic state
10744  * @dm: the display manager to update mod_power on
10745  *
10746  * Notify mod_power of stream changes on modeset events, and disable PSR/Replay
10747  * in preparation for hardware programming. See also
10748  * amdgpu_dm_mod_power_setup_streams() for post-modeset mod_power setup.
10749  */
10750 static void amdgpu_dm_mod_power_update_streams(struct drm_atomic_commit *state,
10751 					       struct amdgpu_display_manager *dm)
10752 {
10753 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10754 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10755 	struct amdgpu_dm_connector *aconnector;
10756 	struct drm_crtc *crtc;
10757 	int i = 0;
10758 
10759 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10760 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10761 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10762 
10763 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10764 			continue;
10765 
10766 		/*
10767 		 * Update mod_power on modeset event in preparation for hw
10768 		 * programming. Always use the old stream, since it would have
10769 		 * been previously added to mod_power. If old stream is null (on
10770 		 * crtc enable, for example), mod_power will no-op, which is the
10771 		 * desried behavior.
10772 		 */
10773 		if (old_crtc_state->active) {
10774 			scoped_guard(mutex, &dm->dc_lock) {
10775 				dc_exit_ips_for_hw_access(dm->dc);
10776 				amdgpu_dm_psr_set_event(dm, dm_old_crtc_state->stream, true,
10777 					psr_event_hw_programming, true);
10778 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, true,
10779 					replay_event_hw_programming, true);
10780 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, false,
10781 					replay_event_general_ui, false);
10782 			}
10783 		}
10784 
10785 		if (new_crtc_state->active) {
10786 			aconnector = (struct amdgpu_dm_connector *)
10787 				dm_new_crtc_state->stream->dm_stream_context;
10788 			if (old_crtc_state->active) {
10789 				mod_power_replace_stream(dm->power_module,
10790 					dm_old_crtc_state->stream,
10791 					dm_new_crtc_state->stream,
10792 					&aconnector->psr_caps);
10793 			} else {
10794 				mod_power_add_stream(dm->power_module,
10795 					dm_new_crtc_state->stream,
10796 					&aconnector->psr_caps);
10797 			}
10798 		} else if (old_crtc_state->active) {
10799 			mod_power_remove_stream(dm->power_module,
10800 				dm_old_crtc_state->stream);
10801 		}
10802 	}
10803 }
10804 
10805 /**
10806  * amdgpu_dm_mod_power_setup_streams - setup mod_power stream state post modeset
10807  * @state: the drm atomic state
10808  * @dm: the display manager to update mod_power on
10809  *
10810  * Notify mod_power of mode_change. This needs to be done after dc_stream
10811  * updates have been committed, and VRR parameters have been updated.
10812  */
10813 static void amdgpu_dm_mod_power_setup_streams(struct drm_atomic_commit *state,
10814 					      struct amdgpu_display_manager *dm)
10815 {
10816 	struct dm_crtc_state *dm_new_crtc_state;
10817 	struct drm_crtc_state *new_crtc_state;
10818 	struct amdgpu_crtc *acrtc;
10819 	struct drm_crtc *crtc;
10820 	int i = 0;
10821 
10822 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10823 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10824 		acrtc = to_amdgpu_crtc(crtc);
10825 
10826 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10827 			continue;
10828 
10829 		if (new_crtc_state->active) {
10830 			amdgpu_dm_link_setup_replay(dm_new_crtc_state->stream,
10831 					&acrtc->dm_irq_params.vrr_params);
10832 			mod_power_notify_mode_change(dm->power_module,
10833 						dm_new_crtc_state->stream,
10834 						false);
10835 
10836 			/*
10837 			 * Block PSR / Replay on the new stream until display settles post-modeset.
10838 			 * These events will be cleared by amdgpu_dm_enable_self_refresh() once
10839 			 * allow_sr_entry becomes true.
10840 			 */
10841 			amdgpu_dm_psr_set_event(dm, dm_new_crtc_state->stream, true,
10842 				psr_event_hw_programming, true);
10843 
10844 			amdgpu_dm_replay_set_event(dm, dm_new_crtc_state->stream, true,
10845 				replay_event_hw_programming | replay_event_general_ui,
10846 				true);
10847 		}
10848 	}
10849 
10850 }
10851 
10852 static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state,
10853 					struct dc_state *dc_state)
10854 {
10855 	struct drm_device *dev = state->dev;
10856 	struct amdgpu_device *adev = drm_to_adev(dev);
10857 	struct amdgpu_display_manager *dm = &adev->dm;
10858 	struct drm_crtc *crtc;
10859 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10860 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10861 	struct drm_connector_state *old_con_state;
10862 	struct drm_connector *connector;
10863 	bool mode_set_reset_required = false;
10864 	u32 i;
10865 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
10866 	bool set_backlight_level = false;
10867 
10868 	/* Disable writeback */
10869 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
10870 		struct dm_connector_state *dm_old_con_state;
10871 		struct amdgpu_crtc *acrtc;
10872 
10873 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
10874 			continue;
10875 
10876 		old_crtc_state = NULL;
10877 
10878 		dm_old_con_state = to_dm_connector_state(old_con_state);
10879 		if (!dm_old_con_state->base.crtc)
10880 			continue;
10881 
10882 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
10883 		if (acrtc)
10884 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10885 
10886 		if (!acrtc || !acrtc->wb_enabled)
10887 			continue;
10888 
10889 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10890 
10891 		dm_clear_writeback(dm, dm_old_crtc_state);
10892 		acrtc->wb_enabled = false;
10893 	}
10894 
10895 	amdgpu_dm_mod_power_update_streams(state, dm);
10896 
10897 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
10898 				      new_crtc_state, i) {
10899 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10900 
10901 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10902 
10903 		if (old_crtc_state->active &&
10904 		    (!new_crtc_state->active ||
10905 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10906 			manage_dm_interrupts(adev, acrtc, NULL);
10907 			dc_stream_release(dm_old_crtc_state->stream);
10908 		}
10909 	}
10910 
10911 	drm_atomic_helper_calc_timestamping_constants(state);
10912 
10913 	/* update changed items */
10914 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10915 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10916 
10917 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10918 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10919 
10920 		drm_dbg_state(state->dev,
10921 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
10922 			acrtc->crtc_id,
10923 			new_crtc_state->enable,
10924 			new_crtc_state->active,
10925 			new_crtc_state->planes_changed,
10926 			new_crtc_state->mode_changed,
10927 			new_crtc_state->active_changed,
10928 			new_crtc_state->connectors_changed);
10929 
10930 		/* Disable cursor if disabling crtc */
10931 		if (old_crtc_state->active && !new_crtc_state->active) {
10932 			struct dc_cursor_position position;
10933 
10934 			memset(&position, 0, sizeof(position));
10935 			mutex_lock(&dm->dc_lock);
10936 			dc_exit_ips_for_hw_access(dm->dc);
10937 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
10938 			mutex_unlock(&dm->dc_lock);
10939 		}
10940 
10941 		/* Copy all transient state flags into dc state */
10942 		if (dm_new_crtc_state->stream) {
10943 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
10944 							    dm_new_crtc_state->stream);
10945 		}
10946 
10947 		/* handles headless hotplug case, updating new_state and
10948 		 * aconnector as needed
10949 		 */
10950 
10951 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
10952 
10953 			drm_dbg_atomic(dev,
10954 				       "Atomic commit: SET crtc id %d: [%p]\n",
10955 				       acrtc->crtc_id, acrtc);
10956 
10957 			if (!dm_new_crtc_state->stream) {
10958 				/*
10959 				 * this could happen because of issues with
10960 				 * userspace notifications delivery.
10961 				 * In this case userspace tries to set mode on
10962 				 * display which is disconnected in fact.
10963 				 * dc_sink is NULL in this case on aconnector.
10964 				 * We expect reset mode will come soon.
10965 				 *
10966 				 * This can also happen when unplug is done
10967 				 * during resume sequence ended
10968 				 *
10969 				 * In this case, we want to pretend we still
10970 				 * have a sink to keep the pipe running so that
10971 				 * hw state is consistent with the sw state
10972 				 */
10973 				drm_dbg_atomic(dev,
10974 					       "Failed to create new stream for crtc %d\n",
10975 						acrtc->base.base.id);
10976 				continue;
10977 			}
10978 
10979 			if (dm_old_crtc_state->stream)
10980 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10981 
10982 			pm_runtime_get_noresume(dev->dev);
10983 
10984 			acrtc->enabled = true;
10985 			acrtc->hw_mode = new_crtc_state->mode;
10986 			crtc->hwmode = new_crtc_state->mode;
10987 			mode_set_reset_required = true;
10988 			set_backlight_level = true;
10989 		} else if (modereset_required(new_crtc_state)) {
10990 			drm_dbg_atomic(dev,
10991 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
10992 				       acrtc->crtc_id, acrtc);
10993 			/* i.e. reset mode */
10994 			if (dm_old_crtc_state->stream)
10995 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10996 
10997 			mode_set_reset_required = true;
10998 		}
10999 	} /* for_each_crtc_in_state() */
11000 
11001 	/* if there mode set or reset, flush vblank work queue */
11002 	if (mode_set_reset_required) {
11003 		if (dm->vblank_control_workqueue)
11004 			flush_workqueue(dm->vblank_control_workqueue);
11005 	}
11006 
11007 	dm_enable_per_frame_crtc_master_sync(dc_state);
11008 	mutex_lock(&dm->dc_lock);
11009 	dc_exit_ips_for_hw_access(dm->dc);
11010 	WARN_ON(!dc_commit_streams(dm->dc, &params));
11011 
11012 	bool frl_stream_found = false;
11013 
11014 	for (i = 0; i < params.stream_count; i++) {
11015 		struct dc_stream_state *stream = params.streams[i];
11016 
11017 		if (stream->signal == SIGNAL_TYPE_HDMI_FRL) {
11018 			frl_stream_found = true;
11019 			break;
11020 		}
11021 	}
11022 	if (frl_stream_found) {
11023 		if (queue_delayed_work(dm->hdmi_frl_status_polling_wq,
11024 				       &dm->hdmi_frl_status_polling_work,
11025 				       msecs_to_jiffies(dm->hdmi_frl_status_polling_delay_ms)))
11026 			drm_dbg_kms(dev, "200ms frl status polling starts ...\n");
11027 	} else {
11028 		if (cancel_delayed_work_sync(&dm->hdmi_frl_status_polling_work))
11029 			drm_dbg_kms(dev, "200ms frl status polling stops ...\n");
11030 	}
11031 	/* Allow idle optimization when vblank count is 0 for display off */
11032 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
11033 		dc_allow_idle_optimizations(dm->dc, true);
11034 	mutex_unlock(&dm->dc_lock);
11035 
11036 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11037 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11038 
11039 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11040 
11041 		if (dm_new_crtc_state->stream != NULL) {
11042 			const struct dc_stream_status *status =
11043 					dc_stream_get_status(dm_new_crtc_state->stream);
11044 
11045 			if (!status)
11046 				status = dc_state_get_stream_status(dc_state,
11047 									 dm_new_crtc_state->stream);
11048 			if (!status)
11049 				drm_err(dev,
11050 					"got no status for stream %p on acrtc%p\n",
11051 					dm_new_crtc_state->stream, acrtc);
11052 			else
11053 				acrtc->otg_inst = status->primary_otg_inst;
11054 		}
11055 	}
11056 
11057 	/* During boot up and resume the DC layer will reset the panel brightness
11058 	 * to fix a flicker issue.
11059 	 * It will cause the dm->actual_brightness is not the current panel brightness
11060 	 * level. (the dm->brightness is the correct panel level)
11061 	 * So we set the backlight level with dm->brightness value after set mode
11062 	 */
11063 	if (set_backlight_level) {
11064 		for (i = 0; i < dm->num_of_edps; i++) {
11065 			if (dm->backlight_dev[i])
11066 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11067 		}
11068 	}
11069 }
11070 
11071 static void dm_set_writeback(struct amdgpu_display_manager *dm,
11072 			      struct dm_crtc_state *crtc_state,
11073 			      struct drm_connector *connector,
11074 			      struct drm_connector_state *new_con_state)
11075 {
11076 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
11077 	struct amdgpu_device *adev = dm->adev;
11078 	struct amdgpu_crtc *acrtc;
11079 	struct dc_writeback_info *wb_info;
11080 	struct pipe_ctx *pipe = NULL;
11081 	struct amdgpu_framebuffer *afb;
11082 	int i = 0;
11083 
11084 	wb_info = kzalloc_obj(*wb_info);
11085 	if (!wb_info) {
11086 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
11087 		return;
11088 	}
11089 
11090 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
11091 	if (!acrtc) {
11092 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
11093 		kfree(wb_info);
11094 		return;
11095 	}
11096 
11097 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
11098 	if (!afb) {
11099 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
11100 		kfree(wb_info);
11101 		return;
11102 	}
11103 
11104 	for (i = 0; i < MAX_PIPES; i++) {
11105 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
11106 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
11107 			break;
11108 		}
11109 	}
11110 
11111 	/* fill in wb_info */
11112 	wb_info->wb_enabled = true;
11113 
11114 	wb_info->dwb_pipe_inst = 0;
11115 	wb_info->dwb_params.dwbscl_black_color = 0;
11116 	wb_info->dwb_params.hdr_mult = 0x1F000;
11117 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
11118 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
11119 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
11120 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
11121 
11122 	/* width & height from crtc */
11123 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
11124 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
11125 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
11126 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
11127 
11128 	wb_info->dwb_params.cnv_params.crop_en = false;
11129 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
11130 
11131 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
11132 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
11133 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
11134 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
11135 
11136 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
11137 
11138 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
11139 
11140 	wb_info->dwb_params.scaler_taps.h_taps = 1;
11141 	wb_info->dwb_params.scaler_taps.v_taps = 1;
11142 	wb_info->dwb_params.scaler_taps.h_taps_c = 1;
11143 	wb_info->dwb_params.scaler_taps.v_taps_c = 1;
11144 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
11145 
11146 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
11147 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
11148 
11149 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
11150 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
11151 		wb_info->mcif_buf_params.chroma_address[i] = 0;
11152 	}
11153 
11154 	wb_info->mcif_buf_params.p_vmid = 1;
11155 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
11156 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
11157 		wb_info->mcif_warmup_params.region_size =
11158 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
11159 	}
11160 	wb_info->mcif_warmup_params.p_vmid = 1;
11161 	wb_info->writeback_source_plane = pipe->plane_state;
11162 
11163 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
11164 
11165 	acrtc->wb_pending = true;
11166 	acrtc->wb_conn = wb_conn;
11167 	drm_writeback_queue_job(wb_conn, new_con_state);
11168 }
11169 
11170 static void amdgpu_dm_update_hdcp(struct drm_atomic_commit *state)
11171 {
11172 	struct drm_connector_state *old_con_state, *new_con_state;
11173 	struct drm_device *dev = state->dev;
11174 	struct drm_connector *connector;
11175 	struct amdgpu_device *adev = drm_to_adev(dev);
11176 	int i;
11177 
11178 	if (!adev->dm.hdcp_workqueue)
11179 		return;
11180 
11181 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11182 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11183 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11184 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11185 		struct dm_crtc_state *dm_new_crtc_state;
11186 		struct amdgpu_dm_connector *aconnector;
11187 
11188 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11189 			continue;
11190 
11191 		aconnector = to_amdgpu_dm_connector(connector);
11192 
11193 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
11194 
11195 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
11196 			connector->index, connector->status, connector->dpms);
11197 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
11198 			old_con_state->content_protection, new_con_state->content_protection);
11199 
11200 		if (aconnector->dc_sink) {
11201 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
11202 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
11203 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
11204 				aconnector->dc_sink->edid_caps.display_name);
11205 			}
11206 		}
11207 
11208 		new_crtc_state = NULL;
11209 		old_crtc_state = NULL;
11210 
11211 		if (acrtc) {
11212 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11213 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11214 		}
11215 
11216 		if (old_crtc_state)
11217 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11218 			old_crtc_state->enable,
11219 			old_crtc_state->active,
11220 			old_crtc_state->mode_changed,
11221 			old_crtc_state->active_changed,
11222 			old_crtc_state->connectors_changed);
11223 
11224 		if (new_crtc_state)
11225 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11226 			new_crtc_state->enable,
11227 			new_crtc_state->active,
11228 			new_crtc_state->mode_changed,
11229 			new_crtc_state->active_changed,
11230 			new_crtc_state->connectors_changed);
11231 
11232 
11233 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11234 
11235 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
11236 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
11237 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
11238 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
11239 			dm_new_con_state->update_hdcp = true;
11240 			continue;
11241 		}
11242 
11243 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
11244 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
11245 			/* when display is unplugged from mst hub, connctor will
11246 			 * be destroyed within dm_dp_mst_connector_destroy. connector
11247 			 * hdcp perperties, like type, undesired, desired, enabled,
11248 			 * will be lost. So, save hdcp properties into hdcp_work within
11249 			 * amdgpu_dm_atomic_commit_tail. if the same display is
11250 			 * plugged back with same display index, its hdcp properties
11251 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
11252 			 */
11253 
11254 			bool enable_encryption = false;
11255 
11256 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
11257 				enable_encryption = true;
11258 
11259 			if (aconnector->dc_link && aconnector->dc_sink &&
11260 				aconnector->dc_link->type == dc_connection_mst_branch) {
11261 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
11262 				struct hdcp_workqueue *hdcp_w =
11263 					&hdcp_work[aconnector->dc_link->link_index];
11264 
11265 				hdcp_w->hdcp_content_type[connector->index] =
11266 					new_con_state->hdcp_content_type;
11267 				hdcp_w->content_protection[connector->index] =
11268 					new_con_state->content_protection;
11269 			}
11270 
11271 			if (new_crtc_state && new_crtc_state->mode_changed &&
11272 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
11273 				enable_encryption = true;
11274 
11275 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
11276 
11277 			if (aconnector->dc_link)
11278 				hdcp_update_display(
11279 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
11280 					new_con_state->hdcp_content_type, enable_encryption);
11281 		}
11282 	}
11283 }
11284 
11285 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state)
11286 {
11287 	struct drm_crtc *crtc;
11288 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11289 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11290 	int i, ret;
11291 
11292 	ret = drm_dp_mst_atomic_setup_commit(state);
11293 	if (ret)
11294 		return ret;
11295 
11296 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11297 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11298 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11299 		/*
11300 		 * Color management settings. We also update color properties
11301 		 * when a modeset is needed, to ensure it gets reprogrammed.
11302 		 */
11303 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
11304 		    (dm_new_crtc_state->base.color_mgmt_changed ||
11305 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11306 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11307 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
11308 			if (ret) {
11309 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
11310 				return ret;
11311 			}
11312 		}
11313 	}
11314 
11315 	return 0;
11316 }
11317 
11318 /**
11319  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
11320  * @state: The atomic state to commit
11321  *
11322  * This will tell DC to commit the constructed DC state from atomic_check,
11323  * programming the hardware. Any failures here implies a hardware failure, since
11324  * atomic check should have filtered anything non-kosher.
11325  */
11326 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state)
11327 {
11328 	struct drm_device *dev = state->dev;
11329 	struct amdgpu_device *adev = drm_to_adev(dev);
11330 	struct amdgpu_display_manager *dm = &adev->dm;
11331 	struct dm_atomic_state *dm_state;
11332 	struct dc_state *dc_state = NULL;
11333 	u32 i, j;
11334 	struct drm_crtc *crtc;
11335 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11336 	unsigned long flags;
11337 	bool wait_for_vblank = true;
11338 	struct drm_connector *connector;
11339 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
11340 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11341 	int crtc_disable_count = 0;
11342 
11343 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
11344 
11345 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
11346 	drm_dp_mst_atomic_wait_for_dependencies(state);
11347 
11348 	dm_state = dm_atomic_get_new_state(state);
11349 	if (dm_state && dm_state->context) {
11350 		dc_state = dm_state->context;
11351 		amdgpu_dm_commit_streams(state, dc_state);
11352 	}
11353 
11354 	amdgpu_dm_update_hdcp(state);
11355 
11356 	/* Handle connector state changes */
11357 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11358 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11359 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
11360 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11361 		struct dc_surface_update *dummy_updates;
11362 		struct dc_stream_update stream_update;
11363 		struct dc_info_packet hdr_packet;
11364 		struct dc_stream_status *status = NULL;
11365 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
11366 
11367 		memset(&stream_update, 0, sizeof(stream_update));
11368 
11369 		if (acrtc) {
11370 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11371 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11372 		}
11373 
11374 		/* Skip any modesets/resets */
11375 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
11376 			continue;
11377 
11378 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11379 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11380 
11381 		scaling_changed = is_scaling_state_different(dm_new_con_state,
11382 							     dm_old_con_state);
11383 
11384 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
11385 			(dm_old_crtc_state->stream->output_color_space !=
11386 				get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
11387 			output_color_space_changed = true;
11388 
11389 		abm_changed = dm_new_crtc_state->abm_level !=
11390 			      dm_old_crtc_state->abm_level;
11391 
11392 		hdr_changed =
11393 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
11394 
11395 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
11396 			continue;
11397 
11398 		stream_update.stream = dm_new_crtc_state->stream;
11399 		if (scaling_changed) {
11400 			update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
11401 					dm_new_con_state, dm_new_crtc_state->stream);
11402 
11403 			stream_update.src = dm_new_crtc_state->stream->src;
11404 			stream_update.dst = dm_new_crtc_state->stream->dst;
11405 		}
11406 
11407 		if (output_color_space_changed) {
11408 			dm_new_crtc_state->stream->output_color_space
11409 				= get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
11410 
11411 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
11412 		}
11413 
11414 		if (abm_changed) {
11415 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
11416 
11417 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
11418 		}
11419 
11420 		if (hdr_changed) {
11421 			fill_hdr_info_packet(new_con_state, &hdr_packet);
11422 			stream_update.hdr_static_metadata = &hdr_packet;
11423 		}
11424 
11425 		status = dc_stream_get_status(dm_new_crtc_state->stream);
11426 
11427 		if (WARN_ON(!status))
11428 			continue;
11429 
11430 		WARN_ON(!status->plane_count);
11431 
11432 		/*
11433 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
11434 		 * Here we create an empty update on each plane.
11435 		 * To fix this, DC should permit updating only stream properties.
11436 		 */
11437 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
11438 		if (!dummy_updates) {
11439 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
11440 			continue;
11441 		}
11442 		for (j = 0; j < status->plane_count; j++)
11443 			dummy_updates[j].surface = status->plane_states[j];
11444 
11445 		sort(dummy_updates, status->plane_count,
11446 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
11447 
11448 		mutex_lock(&dm->dc_lock);
11449 		dc_exit_ips_for_hw_access(dm->dc);
11450 		dc_update_planes_and_stream(dm->dc,
11451 					    dummy_updates,
11452 					    status->plane_count,
11453 					    dm_new_crtc_state->stream,
11454 					    &stream_update);
11455 		mutex_unlock(&dm->dc_lock);
11456 		kfree(dummy_updates);
11457 
11458 		drm_connector_update_privacy_screen(new_con_state);
11459 	}
11460 
11461 	/**
11462 	 * Enable interrupts for CRTCs that are newly enabled or went through
11463 	 * a modeset. It was intentionally deferred until after the front end
11464 	 * state was modified to wait until the OTG was on and so the IRQ
11465 	 * handlers didn't access stale or invalid state.
11466 	 */
11467 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11468 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11469 #ifdef CONFIG_DEBUG_FS
11470 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
11471 #endif
11472 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
11473 		if (old_crtc_state->active && !new_crtc_state->active)
11474 			crtc_disable_count++;
11475 
11476 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11477 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11478 
11479 		/* For freesync config update on crtc state and params for irq */
11480 		update_stream_irq_parameters(dm, dm_new_crtc_state);
11481 
11482 #ifdef CONFIG_DEBUG_FS
11483 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11484 		cur_crc_src = acrtc->dm_irq_params.crc_src;
11485 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11486 #endif
11487 
11488 		if (new_crtc_state->active &&
11489 		    (!old_crtc_state->active ||
11490 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11491 			dc_stream_retain(dm_new_crtc_state->stream);
11492 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
11493 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
11494 		}
11495 		/* Handle vrr on->off / off->on transitions */
11496 		amdgpu_dm_handle_vrr_transition(dm, dm_old_crtc_state, dm_new_crtc_state);
11497 
11498 #ifdef CONFIG_DEBUG_FS
11499 		if (new_crtc_state->active &&
11500 		    (!old_crtc_state->active ||
11501 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11502 			/**
11503 			 * Frontend may have changed so reapply the CRC capture
11504 			 * settings for the stream.
11505 			 */
11506 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
11507 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
11508 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
11509 					uint8_t cnt;
11510 
11511 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11512 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
11513 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
11514 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
11515 
11516 							/**
11517 							 * It takes 2 frames for HW to stably generate CRC when
11518 							 * resuming from suspend, so we set skip_frame_cnt 2.
11519 							 */
11520 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
11521 						}
11522 					}
11523 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11524 				}
11525 #endif
11526 				if (amdgpu_dm_crtc_configure_crc_source(
11527 					crtc, dm_new_crtc_state, cur_crc_src))
11528 					drm_dbg_atomic(dev, "Failed to configure crc source");
11529 			}
11530 		}
11531 #endif
11532 	}
11533 
11534 	amdgpu_dm_mod_power_setup_streams(state, dm);
11535 
11536 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
11537 		if (new_crtc_state->async_flip)
11538 			wait_for_vblank = false;
11539 
11540 	/* update planes when needed per crtc*/
11541 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
11542 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11543 
11544 		if (dm_new_crtc_state->stream)
11545 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
11546 	}
11547 
11548 	/* Enable writeback */
11549 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11550 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11551 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11552 
11553 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11554 			continue;
11555 
11556 		if (!new_con_state->writeback_job)
11557 			continue;
11558 
11559 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11560 
11561 		if (!new_crtc_state)
11562 			continue;
11563 
11564 		if (acrtc->wb_enabled)
11565 			continue;
11566 
11567 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11568 
11569 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
11570 		acrtc->wb_enabled = true;
11571 	}
11572 
11573 	/* Update audio instances for each connector. */
11574 	amdgpu_dm_commit_audio(dev, state);
11575 
11576 	/* restore the backlight level */
11577 	for (i = 0; i < dm->num_of_edps; i++) {
11578 		if (dm->backlight_dev[i] &&
11579 		    (dm->actual_brightness[i] != dm->brightness[i]))
11580 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11581 	}
11582 
11583 	/*
11584 	 * send vblank event on all events not handled in flip and
11585 	 * mark consumed event for drm_atomic_helper_commit_hw_done
11586 	 */
11587 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11588 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11589 
11590 		if (new_crtc_state->event)
11591 			drm_send_event_locked(dev, &new_crtc_state->event->base);
11592 
11593 		new_crtc_state->event = NULL;
11594 	}
11595 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11596 
11597 	/* Signal HW programming completion */
11598 	drm_atomic_helper_commit_hw_done(state);
11599 
11600 	if (wait_for_vblank)
11601 		drm_atomic_helper_wait_for_flip_done(dev, state);
11602 
11603 	drm_atomic_helper_cleanup_planes(dev, state);
11604 
11605 	/* Don't free the memory if we are hitting this as part of suspend.
11606 	 * This way we don't free any memory during suspend; see
11607 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
11608 	 * non-suspend modeset or when the driver is torn down.
11609 	 */
11610 	if (!adev->in_suspend) {
11611 		/* return the stolen vga memory back to VRAM */
11612 		if (!adev->mman.keep_stolen_vga_memory)
11613 			amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_VGA);
11614 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_EXTENDED);
11615 	}
11616 
11617 	/*
11618 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
11619 	 * so we can put the GPU into runtime suspend if we're not driving any
11620 	 * displays anymore
11621 	 */
11622 	for (i = 0; i < crtc_disable_count; i++)
11623 		pm_runtime_put_autosuspend(dev->dev);
11624 	pm_runtime_mark_last_busy(dev->dev);
11625 
11626 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
11627 }
11628 
11629 static int dm_force_atomic_commit(struct drm_connector *connector)
11630 {
11631 	int ret = 0;
11632 	struct drm_device *ddev = connector->dev;
11633 	struct drm_atomic_commit *state = drm_atomic_commit_alloc(ddev);
11634 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11635 	struct drm_plane *plane = disconnected_acrtc->base.primary;
11636 	struct drm_connector_state *conn_state;
11637 	struct drm_crtc_state *crtc_state;
11638 	struct drm_plane_state *plane_state;
11639 
11640 	if (!state)
11641 		return -ENOMEM;
11642 
11643 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
11644 
11645 	/* Construct an atomic state to restore previous display setting */
11646 
11647 	/*
11648 	 * Attach connectors to drm_atomic_commit
11649 	 */
11650 	conn_state = drm_atomic_get_connector_state(state, connector);
11651 
11652 	/* Check for error in getting connector state */
11653 	if (IS_ERR(conn_state)) {
11654 		ret = PTR_ERR(conn_state);
11655 		goto out;
11656 	}
11657 
11658 	/* Attach crtc to drm_atomic_commit*/
11659 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
11660 
11661 	/* Check for error in getting crtc state */
11662 	if (IS_ERR(crtc_state)) {
11663 		ret = PTR_ERR(crtc_state);
11664 		goto out;
11665 	}
11666 
11667 	/* force a restore */
11668 	crtc_state->mode_changed = true;
11669 
11670 	/* Attach plane to drm_atomic_commit */
11671 	plane_state = drm_atomic_get_plane_state(state, plane);
11672 
11673 	/* Check for error in getting plane state */
11674 	if (IS_ERR(plane_state)) {
11675 		ret = PTR_ERR(plane_state);
11676 		goto out;
11677 	}
11678 
11679 	/* Call commit internally with the state we just constructed */
11680 	ret = drm_atomic_commit(state);
11681 
11682 out:
11683 	drm_atomic_commit_put(state);
11684 	if (ret)
11685 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
11686 
11687 	return ret;
11688 }
11689 
11690 /*
11691  * This function handles all cases when set mode does not come upon hotplug.
11692  * This includes when a display is unplugged then plugged back into the
11693  * same port and when running without usermode desktop manager supprot
11694  */
11695 void dm_restore_drm_connector_state(struct drm_device *dev,
11696 				    struct drm_connector *connector)
11697 {
11698 	struct amdgpu_dm_connector *aconnector;
11699 	struct amdgpu_crtc *disconnected_acrtc;
11700 	struct dm_crtc_state *acrtc_state;
11701 
11702 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11703 		return;
11704 
11705 	aconnector = to_amdgpu_dm_connector(connector);
11706 
11707 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
11708 		return;
11709 
11710 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11711 	if (!disconnected_acrtc)
11712 		return;
11713 
11714 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
11715 	if (!acrtc_state->stream)
11716 		return;
11717 
11718 	/*
11719 	 * If the previous sink is not released and different from the current,
11720 	 * we deduce we are in a state where we can not rely on usermode call
11721 	 * to turn on the display, so we do it here
11722 	 */
11723 	if (acrtc_state->stream->sink != aconnector->dc_sink)
11724 		dm_force_atomic_commit(&aconnector->base);
11725 }
11726 
11727 /*
11728  * Grabs all modesetting locks to serialize against any blocking commits,
11729  * Waits for completion of all non blocking commits.
11730  */
11731 static int do_aquire_global_lock(struct drm_device *dev,
11732 				 struct drm_atomic_commit *state)
11733 {
11734 	struct drm_crtc *crtc;
11735 	struct drm_crtc_commit *commit;
11736 	long ret;
11737 
11738 	/*
11739 	 * Adding all modeset locks to aquire_ctx will
11740 	 * ensure that when the framework release it the
11741 	 * extra locks we are locking here will get released to
11742 	 */
11743 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
11744 	if (ret)
11745 		return ret;
11746 
11747 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
11748 		spin_lock(&crtc->commit_lock);
11749 		commit = list_first_entry_or_null(&crtc->commit_list,
11750 				struct drm_crtc_commit, commit_entry);
11751 		if (commit)
11752 			drm_crtc_commit_get(commit);
11753 		spin_unlock(&crtc->commit_lock);
11754 
11755 		if (!commit)
11756 			continue;
11757 
11758 		/*
11759 		 * Make sure all pending HW programming completed and
11760 		 * page flips done
11761 		 */
11762 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
11763 
11764 		if (ret > 0)
11765 			ret = wait_for_completion_interruptible_timeout(
11766 					&commit->flip_done, 10*HZ);
11767 
11768 		if (ret == 0)
11769 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
11770 				  crtc->base.id, crtc->name);
11771 
11772 		drm_crtc_commit_put(commit);
11773 	}
11774 
11775 	return ret < 0 ? ret : 0;
11776 }
11777 
11778 static void get_freesync_config_for_crtc(
11779 	struct dm_crtc_state *new_crtc_state,
11780 	struct dm_connector_state *new_con_state)
11781 {
11782 	struct mod_freesync_config config = {0};
11783 	struct amdgpu_dm_connector *aconnector;
11784 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
11785 	int vrefresh = drm_mode_vrefresh(mode);
11786 	bool fs_vid_mode = false;
11787 
11788 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11789 		return;
11790 
11791 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
11792 
11793 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
11794 					vrefresh >= aconnector->min_vfreq &&
11795 					vrefresh <= aconnector->max_vfreq;
11796 
11797 	if (new_crtc_state->vrr_supported) {
11798 		new_crtc_state->stream->ignore_msa_timing_param = true;
11799 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
11800 
11801 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
11802 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
11803 		config.vsif_supported = true;
11804 		config.btr = true;
11805 
11806 		if (fs_vid_mode) {
11807 			config.state = VRR_STATE_ACTIVE_FIXED;
11808 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
11809 			goto out;
11810 		} else if (new_crtc_state->base.vrr_enabled) {
11811 			config.state = VRR_STATE_ACTIVE_VARIABLE;
11812 		} else {
11813 			config.state = VRR_STATE_INACTIVE;
11814 		}
11815 	} else {
11816 		config.state = VRR_STATE_UNSUPPORTED;
11817 	}
11818 out:
11819 	new_crtc_state->freesync_config = config;
11820 }
11821 
11822 static void reset_freesync_config_for_crtc(
11823 	struct dm_crtc_state *new_crtc_state)
11824 {
11825 	new_crtc_state->vrr_supported = false;
11826 
11827 	memset(&new_crtc_state->vrr_infopacket, 0,
11828 	       sizeof(new_crtc_state->vrr_infopacket));
11829 }
11830 
11831 static bool
11832 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
11833 				 struct drm_crtc_state *new_crtc_state)
11834 {
11835 	const struct drm_display_mode *old_mode, *new_mode;
11836 
11837 	if (!old_crtc_state || !new_crtc_state)
11838 		return false;
11839 
11840 	old_mode = &old_crtc_state->mode;
11841 	new_mode = &new_crtc_state->mode;
11842 
11843 	if (old_mode->clock       == new_mode->clock &&
11844 	    old_mode->hdisplay    == new_mode->hdisplay &&
11845 	    old_mode->vdisplay    == new_mode->vdisplay &&
11846 	    old_mode->htotal      == new_mode->htotal &&
11847 	    old_mode->vtotal      != new_mode->vtotal &&
11848 	    old_mode->hsync_start == new_mode->hsync_start &&
11849 	    old_mode->vsync_start != new_mode->vsync_start &&
11850 	    old_mode->hsync_end   == new_mode->hsync_end &&
11851 	    old_mode->vsync_end   != new_mode->vsync_end &&
11852 	    old_mode->hskew       == new_mode->hskew &&
11853 	    old_mode->vscan       == new_mode->vscan &&
11854 	    (old_mode->vsync_end - old_mode->vsync_start) ==
11855 	    (new_mode->vsync_end - new_mode->vsync_start))
11856 		return true;
11857 
11858 	return false;
11859 }
11860 
11861 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
11862 {
11863 	u64 num, den, res;
11864 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
11865 
11866 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
11867 
11868 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
11869 	den = (unsigned long long)new_crtc_state->mode.htotal *
11870 	      (unsigned long long)new_crtc_state->mode.vtotal;
11871 
11872 	res = div_u64(num, den);
11873 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
11874 }
11875 
11876 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
11877 			 struct drm_atomic_commit *state,
11878 			 struct drm_crtc *crtc,
11879 			 struct drm_crtc_state *old_crtc_state,
11880 			 struct drm_crtc_state *new_crtc_state,
11881 			 bool enable,
11882 			 bool *lock_and_validation_needed)
11883 {
11884 	struct dm_atomic_state *dm_state = NULL;
11885 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11886 	struct dc_stream_state *new_stream;
11887 	struct amdgpu_device *adev = dm->adev;
11888 	int ret = 0;
11889 
11890 	/*
11891 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
11892 	 * update changed items
11893 	 */
11894 	struct amdgpu_crtc *acrtc = NULL;
11895 	struct drm_connector *connector = NULL;
11896 	struct amdgpu_dm_connector *aconnector = NULL;
11897 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
11898 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
11899 
11900 	new_stream = NULL;
11901 
11902 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11903 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11904 	acrtc = to_amdgpu_crtc(crtc);
11905 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
11906 	if (connector)
11907 		aconnector = to_amdgpu_dm_connector(connector);
11908 
11909 	/* TODO This hack should go away */
11910 	if (connector && enable) {
11911 		/* Make sure fake sink is created in plug-in scenario */
11912 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
11913 									connector);
11914 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
11915 									connector);
11916 
11917 		if (WARN_ON(!drm_new_conn_state)) {
11918 			ret = -EINVAL;
11919 			goto fail;
11920 		}
11921 
11922 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
11923 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
11924 
11925 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11926 			goto skip_modeset;
11927 
11928 		new_stream = create_validate_stream_for_sink(connector,
11929 							     &new_crtc_state->mode,
11930 							     dm_new_conn_state,
11931 							     dm_old_crtc_state->stream);
11932 
11933 		/*
11934 		 * we can have no stream on ACTION_SET if a display
11935 		 * was disconnected during S3, in this case it is not an
11936 		 * error, the OS will be updated after detection, and
11937 		 * will do the right thing on next atomic commit
11938 		 */
11939 
11940 		if (!new_stream) {
11941 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
11942 					__func__, acrtc->base.base.id);
11943 			ret = -ENOMEM;
11944 			goto fail;
11945 		}
11946 
11947 		/*
11948 		 * TODO: Check VSDB bits to decide whether this should
11949 		 * be enabled or not.
11950 		 */
11951 		new_stream->triggered_crtc_reset.enabled =
11952 			dm->force_timing_sync;
11953 
11954 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11955 
11956 		ret = fill_hdr_info_packet(drm_new_conn_state,
11957 					   &new_stream->hdr_static_metadata);
11958 		if (ret)
11959 			goto fail;
11960 
11961 		/*
11962 		 * If we already removed the old stream from the context
11963 		 * (and set the new stream to NULL) then we can't reuse
11964 		 * the old stream even if the stream and scaling are unchanged.
11965 		 * We'll hit the BUG_ON and black screen.
11966 		 *
11967 		 * TODO: Refactor this function to allow this check to work
11968 		 * in all conditions.
11969 		 */
11970 		if (amdgpu_freesync_vid_mode &&
11971 		    dm_new_crtc_state->stream &&
11972 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
11973 			goto skip_modeset;
11974 
11975 		if (dm_new_crtc_state->stream &&
11976 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11977 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
11978 			new_crtc_state->mode_changed = false;
11979 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
11980 					 new_crtc_state->mode_changed);
11981 		}
11982 	}
11983 
11984 	/* mode_changed flag may get updated above, need to check again */
11985 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11986 		goto skip_modeset;
11987 
11988 	drm_dbg_state(state->dev,
11989 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
11990 		acrtc->crtc_id,
11991 		new_crtc_state->enable,
11992 		new_crtc_state->active,
11993 		new_crtc_state->planes_changed,
11994 		new_crtc_state->mode_changed,
11995 		new_crtc_state->active_changed,
11996 		new_crtc_state->connectors_changed);
11997 
11998 	/* Remove stream for any changed/disabled CRTC */
11999 	if (!enable) {
12000 
12001 		if (!dm_old_crtc_state->stream)
12002 			goto skip_modeset;
12003 
12004 		/* Unset freesync video if it was active before */
12005 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
12006 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
12007 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
12008 		}
12009 
12010 		/* Now check if we should set freesync video mode */
12011 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
12012 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
12013 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
12014 		    is_timing_unchanged_for_freesync(new_crtc_state,
12015 						     old_crtc_state)) {
12016 			new_crtc_state->mode_changed = false;
12017 			drm_dbg_driver(adev_to_drm(adev),
12018 				"Mode change not required for front porch change, setting mode_changed to %d",
12019 				new_crtc_state->mode_changed);
12020 
12021 			set_freesync_fixed_config(dm_new_crtc_state);
12022 
12023 			goto skip_modeset;
12024 		} else if (amdgpu_freesync_vid_mode && aconnector &&
12025 			   is_freesync_video_mode(&new_crtc_state->mode,
12026 						  aconnector)) {
12027 			struct drm_display_mode *high_mode;
12028 
12029 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
12030 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
12031 				set_freesync_fixed_config(dm_new_crtc_state);
12032 		}
12033 
12034 		ret = dm_atomic_get_state(state, &dm_state);
12035 		if (ret)
12036 			goto fail;
12037 
12038 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
12039 				crtc->base.id);
12040 
12041 		/* i.e. reset mode */
12042 		if (dc_state_remove_stream(
12043 				dm->dc,
12044 				dm_state->context,
12045 				dm_old_crtc_state->stream) != DC_OK) {
12046 			ret = -EINVAL;
12047 			goto fail;
12048 		}
12049 
12050 		dc_stream_release(dm_old_crtc_state->stream);
12051 		dm_new_crtc_state->stream = NULL;
12052 
12053 		reset_freesync_config_for_crtc(dm_new_crtc_state);
12054 
12055 		*lock_and_validation_needed = true;
12056 
12057 	} else {/* Add stream for any updated/enabled CRTC */
12058 		/*
12059 		 * Quick fix to prevent NULL pointer on new_stream when
12060 		 * added MST connectors not found in existing crtc_state in the chained mode
12061 		 * TODO: need to dig out the root cause of that
12062 		 */
12063 		if (!connector)
12064 			goto skip_modeset;
12065 
12066 		if (modereset_required(new_crtc_state))
12067 			goto skip_modeset;
12068 
12069 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
12070 				     dm_old_crtc_state->stream)) {
12071 
12072 			WARN_ON(dm_new_crtc_state->stream);
12073 
12074 			ret = dm_atomic_get_state(state, &dm_state);
12075 			if (ret)
12076 				goto fail;
12077 
12078 			dm_new_crtc_state->stream = new_stream;
12079 
12080 			dc_stream_retain(new_stream);
12081 
12082 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
12083 					 crtc->base.id);
12084 
12085 			if (dc_state_add_stream(
12086 					dm->dc,
12087 					dm_state->context,
12088 					dm_new_crtc_state->stream) != DC_OK) {
12089 				ret = -EINVAL;
12090 				goto fail;
12091 			}
12092 
12093 			*lock_and_validation_needed = true;
12094 		}
12095 	}
12096 
12097 skip_modeset:
12098 	/* Release extra reference */
12099 	if (new_stream)
12100 		dc_stream_release(new_stream);
12101 
12102 	/*
12103 	 * We want to do dc stream updates that do not require a
12104 	 * full modeset below.
12105 	 */
12106 	if (!(enable && connector && new_crtc_state->active))
12107 		return 0;
12108 	/*
12109 	 * Given above conditions, the dc state cannot be NULL because:
12110 	 * 1. We're in the process of enabling CRTCs (just been added
12111 	 *    to the dc context, or already is on the context)
12112 	 * 2. Has a valid connector attached, and
12113 	 * 3. Is currently active and enabled.
12114 	 * => The dc stream state currently exists.
12115 	 */
12116 	BUG_ON(dm_new_crtc_state->stream == NULL);
12117 
12118 	/* Scaling or underscan settings */
12119 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
12120 				drm_atomic_crtc_needs_modeset(new_crtc_state))
12121 		update_stream_scaling_settings(adev_to_drm(adev),
12122 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
12123 
12124 	/* ABM settings */
12125 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
12126 
12127 	/*
12128 	 * Color management settings. We also update color properties
12129 	 * when a modeset is needed, to ensure it gets reprogrammed.
12130 	 */
12131 	if (dm_new_crtc_state->base.color_mgmt_changed ||
12132 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
12133 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
12134 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
12135 		if (ret)
12136 			goto fail;
12137 	}
12138 
12139 	/* Update Freesync settings. */
12140 	get_freesync_config_for_crtc(dm_new_crtc_state,
12141 				     dm_new_conn_state);
12142 
12143 	return ret;
12144 
12145 fail:
12146 	if (new_stream)
12147 		dc_stream_release(new_stream);
12148 	return ret;
12149 }
12150 
12151 static bool should_reset_plane(struct drm_atomic_commit *state,
12152 			       struct drm_plane *plane,
12153 			       struct drm_plane_state *old_plane_state,
12154 			       struct drm_plane_state *new_plane_state)
12155 {
12156 	struct drm_plane *other;
12157 	struct drm_plane_state *old_other_state, *new_other_state;
12158 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12159 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
12160 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
12161 	struct drm_connector_state *new_con_state;
12162 	struct drm_connector *connector;
12163 	int i;
12164 
12165 	/*
12166 	 * TODO: Remove this hack for all asics once it proves that the
12167 	 * fast updates works fine on DCN3.2+.
12168 	 */
12169 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
12170 	    state->allow_modeset)
12171 		return true;
12172 
12173 	/* Check for writeback commit */
12174 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
12175 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
12176 			continue;
12177 
12178 		if (new_con_state->writeback_job)
12179 			return true;
12180 	}
12181 
12182 	if (amdgpu_in_reset(adev) && state->allow_modeset)
12183 		return true;
12184 
12185 	/* Exit early if we know that we're adding or removing the plane. */
12186 	if (old_plane_state->crtc != new_plane_state->crtc)
12187 		return true;
12188 
12189 	/* old crtc == new_crtc == NULL, plane not in context. */
12190 	if (!new_plane_state->crtc)
12191 		return false;
12192 
12193 	new_crtc_state =
12194 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
12195 	old_crtc_state =
12196 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
12197 
12198 	if (!new_crtc_state)
12199 		return true;
12200 
12201 	/*
12202 	 * A change in cursor mode means a new dc pipe needs to be acquired or
12203 	 * released from the state
12204 	 */
12205 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
12206 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
12207 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
12208 	    old_dm_crtc_state != NULL &&
12209 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
12210 		return true;
12211 	}
12212 
12213 	/* CRTC Degamma changes currently require us to recreate planes. */
12214 	if (new_crtc_state->color_mgmt_changed)
12215 		return true;
12216 
12217 	/* Plane color pipeline or its colorop changes. */
12218 	if (new_plane_state->color_mgmt_changed)
12219 		return true;
12220 
12221 	/*
12222 	 * On zpos change, planes need to be reordered by removing and re-adding
12223 	 * them one by one to the dc state, in order of descending zpos.
12224 	 *
12225 	 * TODO: We can likely skip bandwidth validation if the only thing that
12226 	 * changed about the plane was it'z z-ordering.
12227 	 */
12228 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
12229 		return true;
12230 
12231 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
12232 		return true;
12233 
12234 	/*
12235 	 * If there are any new primary or overlay planes being added or
12236 	 * removed then the z-order can potentially change. To ensure
12237 	 * correct z-order and pipe acquisition the current DC architecture
12238 	 * requires us to remove and recreate all existing planes.
12239 	 *
12240 	 * TODO: Come up with a more elegant solution for this.
12241 	 */
12242 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
12243 		struct amdgpu_framebuffer *old_afb, *new_afb;
12244 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
12245 
12246 		dm_new_other_state = to_dm_plane_state(new_other_state);
12247 		dm_old_other_state = to_dm_plane_state(old_other_state);
12248 
12249 		if (other->type == DRM_PLANE_TYPE_CURSOR)
12250 			continue;
12251 
12252 		if (old_other_state->crtc != new_plane_state->crtc &&
12253 		    new_other_state->crtc != new_plane_state->crtc)
12254 			continue;
12255 
12256 		if (old_other_state->crtc != new_other_state->crtc)
12257 			return true;
12258 
12259 		/* Src/dst size and scaling updates. */
12260 		if (old_other_state->src_w != new_other_state->src_w ||
12261 		    old_other_state->src_h != new_other_state->src_h ||
12262 		    old_other_state->crtc_w != new_other_state->crtc_w ||
12263 		    old_other_state->crtc_h != new_other_state->crtc_h)
12264 			return true;
12265 
12266 		/* Rotation / mirroring updates. */
12267 		if (old_other_state->rotation != new_other_state->rotation)
12268 			return true;
12269 
12270 		/* Blending updates. */
12271 		if (old_other_state->pixel_blend_mode !=
12272 		    new_other_state->pixel_blend_mode)
12273 			return true;
12274 
12275 		/* Alpha updates. */
12276 		if (old_other_state->alpha != new_other_state->alpha)
12277 			return true;
12278 
12279 		/* Colorspace changes. */
12280 		if (old_other_state->color_range != new_other_state->color_range ||
12281 		    old_other_state->color_encoding != new_other_state->color_encoding)
12282 			return true;
12283 
12284 		/* HDR/Transfer Function changes. */
12285 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
12286 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
12287 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
12288 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
12289 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
12290 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
12291 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
12292 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
12293 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
12294 			return true;
12295 
12296 		/* Framebuffer checks fall at the end. */
12297 		if (!old_other_state->fb || !new_other_state->fb)
12298 			continue;
12299 
12300 		/* Pixel format changes can require bandwidth updates. */
12301 		if (old_other_state->fb->format != new_other_state->fb->format)
12302 			return true;
12303 
12304 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
12305 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
12306 
12307 		/* Tiling and DCC changes also require bandwidth updates. */
12308 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
12309 		    old_afb->base.modifier != new_afb->base.modifier)
12310 			return true;
12311 	}
12312 
12313 	return false;
12314 }
12315 
12316 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
12317 			      struct drm_plane_state *new_plane_state,
12318 			      struct drm_framebuffer *fb)
12319 {
12320 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
12321 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
12322 	unsigned int pitch;
12323 	bool linear;
12324 
12325 	if (fb->width > new_acrtc->max_cursor_width ||
12326 	    fb->height > new_acrtc->max_cursor_height) {
12327 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB size %dx%d\n",
12328 				 new_plane_state->fb->width,
12329 				 new_plane_state->fb->height);
12330 		return -EINVAL;
12331 	}
12332 	if (new_plane_state->src_w != fb->width << 16 ||
12333 	    new_plane_state->src_h != fb->height << 16) {
12334 		drm_dbg_atomic(adev_to_drm(adev), "Cropping not supported for cursor plane\n");
12335 		return -EINVAL;
12336 	}
12337 
12338 	/* Pitch in pixels */
12339 	pitch = fb->pitches[0] / fb->format->cpp[0];
12340 
12341 	if (fb->width != pitch) {
12342 		drm_dbg_atomic(adev_to_drm(adev), "Cursor FB width %d doesn't match pitch %d",
12343 				 fb->width, pitch);
12344 		return -EINVAL;
12345 	}
12346 
12347 	switch (pitch) {
12348 	case 64:
12349 	case 128:
12350 	case 256:
12351 		/* FB pitch is supported by cursor plane */
12352 		break;
12353 	default:
12354 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB pitch %d px\n", pitch);
12355 		return -EINVAL;
12356 	}
12357 
12358 	/* Core DRM takes care of checking FB modifiers, so we only need to
12359 	 * check tiling flags when the FB doesn't have a modifier.
12360 	 */
12361 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
12362 		if (adev->family == AMDGPU_FAMILY_GC_12_0_0) {
12363 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
12364 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
12365 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
12366 		} else {
12367 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
12368 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
12369 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
12370 		}
12371 		if (!linear) {
12372 			drm_dbg_atomic(adev_to_drm(adev), "Cursor FB not linear");
12373 			return -EINVAL;
12374 		}
12375 	}
12376 
12377 	return 0;
12378 }
12379 
12380 /*
12381  * Helper function for checking the cursor in native mode
12382  */
12383 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
12384 					struct drm_plane *plane,
12385 					struct drm_plane_state *new_plane_state,
12386 					bool enable)
12387 {
12388 
12389 	struct amdgpu_crtc *new_acrtc;
12390 	int ret;
12391 
12392 	if (!enable || !new_plane_crtc ||
12393 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
12394 		return 0;
12395 
12396 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
12397 
12398 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
12399 		drm_dbg_atomic(new_plane_crtc->dev, "Cropping not supported for cursor plane\n");
12400 		return -EINVAL;
12401 	}
12402 
12403 	if (new_plane_state->fb) {
12404 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
12405 						new_plane_state->fb);
12406 		if (ret)
12407 			return ret;
12408 	}
12409 
12410 	return 0;
12411 }
12412 
12413 static bool dm_should_update_native_cursor(struct drm_atomic_commit *state,
12414 					   struct drm_crtc *old_plane_crtc,
12415 					   struct drm_crtc *new_plane_crtc,
12416 					   bool enable)
12417 {
12418 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12419 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12420 
12421 	if (!enable) {
12422 		if (old_plane_crtc == NULL)
12423 			return true;
12424 
12425 		old_crtc_state = drm_atomic_get_old_crtc_state(
12426 			state, old_plane_crtc);
12427 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12428 
12429 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12430 	} else {
12431 		if (new_plane_crtc == NULL)
12432 			return true;
12433 
12434 		new_crtc_state = drm_atomic_get_new_crtc_state(
12435 			state, new_plane_crtc);
12436 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12437 
12438 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12439 	}
12440 }
12441 
12442 static int dm_update_plane_state(struct dc *dc,
12443 				 struct drm_atomic_commit *state,
12444 				 struct drm_plane *plane,
12445 				 struct drm_plane_state *old_plane_state,
12446 				 struct drm_plane_state *new_plane_state,
12447 				 bool enable,
12448 				 bool *lock_and_validation_needed,
12449 				 bool *is_top_most_overlay)
12450 {
12451 
12452 	struct dm_atomic_state *dm_state = NULL;
12453 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
12454 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12455 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
12456 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
12457 	bool needs_reset, update_native_cursor;
12458 	int ret = 0;
12459 
12460 
12461 	new_plane_crtc = new_plane_state->crtc;
12462 	old_plane_crtc = old_plane_state->crtc;
12463 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
12464 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
12465 
12466 	update_native_cursor = dm_should_update_native_cursor(state,
12467 							      old_plane_crtc,
12468 							      new_plane_crtc,
12469 							      enable);
12470 
12471 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
12472 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12473 						    new_plane_state, enable);
12474 		if (ret)
12475 			return ret;
12476 
12477 		return 0;
12478 	}
12479 
12480 	needs_reset = should_reset_plane(state, plane, old_plane_state,
12481 					 new_plane_state);
12482 
12483 	/* Remove any changed/removed planes */
12484 	if (!enable) {
12485 		if (!needs_reset)
12486 			return 0;
12487 
12488 		if (!old_plane_crtc)
12489 			return 0;
12490 
12491 		old_crtc_state = drm_atomic_get_old_crtc_state(
12492 				state, old_plane_crtc);
12493 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12494 
12495 		if (!dm_old_crtc_state->stream)
12496 			return 0;
12497 
12498 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
12499 				plane->base.id, old_plane_crtc->base.id);
12500 
12501 		ret = dm_atomic_get_state(state, &dm_state);
12502 		if (ret)
12503 			return ret;
12504 
12505 		if (!dc_state_remove_plane(
12506 				dc,
12507 				dm_old_crtc_state->stream,
12508 				dm_old_plane_state->dc_state,
12509 				dm_state->context)) {
12510 
12511 			return -EINVAL;
12512 		}
12513 
12514 		if (dm_old_plane_state->dc_state)
12515 			dc_plane_state_release(dm_old_plane_state->dc_state);
12516 
12517 		dm_new_plane_state->dc_state = NULL;
12518 
12519 		*lock_and_validation_needed = true;
12520 
12521 	} else { /* Add new planes */
12522 		struct dc_plane_state *dc_new_plane_state;
12523 
12524 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
12525 			return 0;
12526 
12527 		if (!new_plane_crtc)
12528 			return 0;
12529 
12530 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
12531 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12532 
12533 		if (!dm_new_crtc_state->stream)
12534 			return 0;
12535 
12536 		if (!needs_reset)
12537 			return 0;
12538 
12539 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
12540 		if (ret)
12541 			goto out;
12542 
12543 		WARN_ON(dm_new_plane_state->dc_state);
12544 
12545 		dc_new_plane_state = dc_create_plane_state(dc);
12546 		if (!dc_new_plane_state) {
12547 			ret = -ENOMEM;
12548 			goto out;
12549 		}
12550 
12551 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
12552 				 plane->base.id, new_plane_crtc->base.id);
12553 
12554 		ret = fill_dc_plane_attributes(
12555 			drm_to_adev(new_plane_crtc->dev),
12556 			dc_new_plane_state,
12557 			new_plane_state,
12558 			new_crtc_state);
12559 		if (ret) {
12560 			dc_plane_state_release(dc_new_plane_state);
12561 			goto out;
12562 		}
12563 
12564 		ret = dm_atomic_get_state(state, &dm_state);
12565 		if (ret) {
12566 			dc_plane_state_release(dc_new_plane_state);
12567 			goto out;
12568 		}
12569 
12570 		/*
12571 		 * Any atomic check errors that occur after this will
12572 		 * not need a release. The plane state will be attached
12573 		 * to the stream, and therefore part of the atomic
12574 		 * state. It'll be released when the atomic state is
12575 		 * cleaned.
12576 		 */
12577 		if (!dc_state_add_plane(
12578 				dc,
12579 				dm_new_crtc_state->stream,
12580 				dc_new_plane_state,
12581 				dm_state->context)) {
12582 
12583 			dc_plane_state_release(dc_new_plane_state);
12584 			ret = -EINVAL;
12585 			goto out;
12586 		}
12587 
12588 		dm_new_plane_state->dc_state = dc_new_plane_state;
12589 
12590 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
12591 
12592 		/* Tell DC to do a full surface update every time there
12593 		 * is a plane change. Inefficient, but works for now.
12594 		 */
12595 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
12596 
12597 		*lock_and_validation_needed = true;
12598 	}
12599 
12600 out:
12601 	/* If enabling cursor overlay failed, attempt fallback to native mode */
12602 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
12603 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12604 						    new_plane_state, enable);
12605 		if (ret)
12606 			return ret;
12607 
12608 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
12609 	}
12610 
12611 	return ret;
12612 }
12613 
12614 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
12615 				       int *src_w, int *src_h)
12616 {
12617 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
12618 	case DRM_MODE_ROTATE_90:
12619 	case DRM_MODE_ROTATE_270:
12620 		*src_w = plane_state->src_h >> 16;
12621 		*src_h = plane_state->src_w >> 16;
12622 		break;
12623 	case DRM_MODE_ROTATE_0:
12624 	case DRM_MODE_ROTATE_180:
12625 	default:
12626 		*src_w = plane_state->src_w >> 16;
12627 		*src_h = plane_state->src_h >> 16;
12628 		break;
12629 	}
12630 }
12631 
12632 static void
12633 dm_get_plane_scale(struct drm_plane_state *plane_state,
12634 		   int *out_plane_scale_w, int *out_plane_scale_h)
12635 {
12636 	int plane_src_w, plane_src_h;
12637 
12638 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
12639 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
12640 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
12641 }
12642 
12643 /*
12644  * The normalized_zpos value cannot be used by this iterator directly. It's only
12645  * calculated for enabled planes, potentially causing normalized_zpos collisions
12646  * between enabled/disabled planes in the atomic state. We need a unique value
12647  * so that the iterator will not generate the same object twice, or loop
12648  * indefinitely.
12649  */
12650 static inline struct __drm_planes_state *__get_next_zpos(
12651 	struct drm_atomic_commit *state,
12652 	struct __drm_planes_state *prev)
12653 {
12654 	unsigned int highest_zpos = 0, prev_zpos = 256;
12655 	uint32_t highest_id = 0, prev_id = UINT_MAX;
12656 	struct drm_plane_state *new_plane_state;
12657 	struct drm_plane *plane;
12658 	int i, highest_i = -1;
12659 
12660 	if (prev != NULL) {
12661 		prev_zpos = prev->new_state->zpos;
12662 		prev_id = prev->ptr->base.id;
12663 	}
12664 
12665 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
12666 		/* Skip planes with higher zpos than the previously returned */
12667 		if (new_plane_state->zpos > prev_zpos ||
12668 		    (new_plane_state->zpos == prev_zpos &&
12669 		     plane->base.id >= prev_id))
12670 			continue;
12671 
12672 		/* Save the index of the plane with highest zpos */
12673 		if (new_plane_state->zpos > highest_zpos ||
12674 		    (new_plane_state->zpos == highest_zpos &&
12675 		     plane->base.id > highest_id)) {
12676 			highest_zpos = new_plane_state->zpos;
12677 			highest_id = plane->base.id;
12678 			highest_i = i;
12679 		}
12680 	}
12681 
12682 	if (highest_i < 0)
12683 		return NULL;
12684 
12685 	return &state->planes[highest_i];
12686 }
12687 
12688 /*
12689  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
12690  * by descending zpos, as read from the new plane state. This is the same
12691  * ordering as defined by drm_atomic_normalize_zpos().
12692  */
12693 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
12694 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
12695 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
12696 		for_each_if(((plane) = __i->ptr,				\
12697 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
12698 			     (old_plane_state) = __i->old_state,		\
12699 			     (new_plane_state) = __i->new_state, 1))
12700 
12701 static int add_affected_mst_dsc_crtcs(struct drm_atomic_commit *state, struct drm_crtc *crtc)
12702 {
12703 	struct drm_connector *connector;
12704 	struct drm_connector_state *conn_state, *old_conn_state;
12705 	struct amdgpu_dm_connector *aconnector = NULL;
12706 	int i;
12707 
12708 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
12709 		if (!conn_state->crtc)
12710 			conn_state = old_conn_state;
12711 
12712 		if (conn_state->crtc != crtc)
12713 			continue;
12714 
12715 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
12716 			continue;
12717 
12718 		aconnector = to_amdgpu_dm_connector(connector);
12719 		if (!aconnector->mst_output_port || !aconnector->mst_root)
12720 			aconnector = NULL;
12721 		else
12722 			break;
12723 	}
12724 
12725 	if (!aconnector)
12726 		return 0;
12727 
12728 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
12729 }
12730 
12731 /**
12732  * DOC: Cursor Modes - Native vs Overlay
12733  *
12734  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
12735  * plane. It does not require a dedicated hw plane to enable, but it is
12736  * subjected to the same z-order and scaling as the hw plane. It also has format
12737  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
12738  * hw plane.
12739  *
12740  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
12741  * own scaling and z-pos. It also has no blending restrictions. It lends to a
12742  * cursor behavior more akin to a DRM client's expectations. However, it does
12743  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
12744  * available.
12745  */
12746 
12747 /**
12748  * dm_plane_color_pipeline_active() - Check if a plane's color pipeline active.
12749  * @state: DRM atomic state
12750  * @plane: DRM plane to check
12751  * @use_old: if true, inspect the old colorop states; otherwise the new ones
12752  *
12753  * A color pipeline may be selected (color_pipeline != NULL) but still is
12754  * inactive if every colorop in the chain is bypassed.  Only return
12755  * true when at least one colorop has bypass == false, meaning the cursor
12756  * would be subjected to the transformation in native mode.
12757  *
12758  * Return: true if the pipeline modifies pixels, false otherwise.
12759  */
12760 static bool dm_plane_color_pipeline_active(struct drm_atomic_commit *state,
12761 					   struct drm_plane *plane,
12762 					   bool use_old)
12763 {
12764 	struct drm_colorop *colorop;
12765 	struct drm_colorop_state *old_colorop_state, *new_colorop_state;
12766 	int i;
12767 
12768 	for_each_oldnew_colorop_in_state(state, colorop, old_colorop_state, new_colorop_state, i) {
12769 		struct drm_colorop_state *cstate = use_old ? old_colorop_state : new_colorop_state;
12770 
12771 		if (cstate->colorop->plane != plane)
12772 			continue;
12773 		if (!cstate->bypass)
12774 			return true;
12775 	}
12776 	return false;
12777 }
12778 
12779 /**
12780  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
12781  * @adev: amdgpu device
12782  * @state: DRM atomic state
12783  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
12784  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
12785  *
12786  * Get whether the cursor should be enabled in native mode, or overlay mode, on
12787  * the dm_crtc_state.
12788  *
12789  * The cursor should be enabled in overlay mode if there exists an underlying
12790  * plane - on which the cursor may be blended - that is either YUV formatted,
12791  * scaled differently from the cursor, or has a color pipeline active.
12792  *
12793  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
12794  * calling this function.
12795  *
12796  * Return: 0 on success, or an error code if getting the cursor plane state
12797  * failed.
12798  */
12799 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
12800 				   struct drm_atomic_commit *state,
12801 				   struct dm_crtc_state *dm_crtc_state,
12802 				   enum amdgpu_dm_cursor_mode *cursor_mode)
12803 {
12804 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
12805 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
12806 	struct drm_plane *plane;
12807 	bool consider_mode_change = false;
12808 	bool entire_crtc_covered = false;
12809 	bool cursor_changed = false;
12810 	int underlying_scale_w, underlying_scale_h;
12811 	int cursor_scale_w, cursor_scale_h;
12812 	int i;
12813 
12814 	/* Overlay cursor not supported on HW before DCN
12815 	 * DCN401/420 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
12816 	 * as previous DCN generations, so enable native mode on DCN401/420
12817 	 */
12818 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1) ||
12819 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
12820 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 1)) {
12821 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12822 		return 0;
12823 	}
12824 
12825 	/* Init cursor_mode to be the same as current */
12826 	*cursor_mode = dm_crtc_state->cursor_mode;
12827 
12828 	/*
12829 	 * Cursor mode can change if a plane's format changes, scale changes, is
12830 	 * enabled/disabled, z-order changes, or color management properties change.
12831 	 */
12832 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
12833 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
12834 
12835 		/* Only care about planes on this CRTC */
12836 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
12837 			continue;
12838 
12839 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
12840 			cursor_changed = true;
12841 
12842 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
12843 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
12844 		    old_plane_state->fb->format != plane_state->fb->format) {
12845 			consider_mode_change = true;
12846 			break;
12847 		}
12848 
12849 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
12850 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
12851 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
12852 			consider_mode_change = true;
12853 			break;
12854 		}
12855 
12856 		if (dm_plane_color_pipeline_active(state, plane, true) !=
12857 		    dm_plane_color_pipeline_active(state, plane, false)) {
12858 			consider_mode_change = true;
12859 			break;
12860 		}
12861 	}
12862 
12863 	if (!consider_mode_change && !crtc_state->zpos_changed)
12864 		return 0;
12865 
12866 	/*
12867 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
12868 	 * no need to set cursor mode. This avoids needlessly locking the cursor
12869 	 * state.
12870 	 */
12871 	if (!cursor_changed &&
12872 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
12873 		return 0;
12874 	}
12875 
12876 	cursor_state = drm_atomic_get_plane_state(state,
12877 						  crtc_state->crtc->cursor);
12878 	if (IS_ERR(cursor_state))
12879 		return PTR_ERR(cursor_state);
12880 
12881 	/* Cursor is disabled */
12882 	if (!cursor_state->fb)
12883 		return 0;
12884 
12885 	/* For all planes in descending z-order (all of which are below cursor
12886 	 * as per zpos definitions), check their scaling and format
12887 	 */
12888 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
12889 
12890 		/* Only care about non-cursor planes on this CRTC */
12891 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
12892 		    plane->type == DRM_PLANE_TYPE_CURSOR)
12893 			continue;
12894 
12895 		/* Underlying plane is YUV format - use overlay cursor */
12896 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
12897 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12898 			return 0;
12899 		}
12900 
12901 		/* Underlying plane has an active color pipeline - cursor would be transformed */
12902 		if (dm_plane_color_pipeline_active(state, plane, false)) {
12903 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12904 			return 0;
12905 		}
12906 
12907 		dm_get_plane_scale(plane_state,
12908 				   &underlying_scale_w, &underlying_scale_h);
12909 		dm_get_plane_scale(cursor_state,
12910 				   &cursor_scale_w, &cursor_scale_h);
12911 
12912 		/* Underlying plane has different scale - use overlay cursor */
12913 		if (cursor_scale_w != underlying_scale_w &&
12914 		    cursor_scale_h != underlying_scale_h) {
12915 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12916 			return 0;
12917 		}
12918 
12919 		/* If this plane covers the whole CRTC, no need to check planes underneath */
12920 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
12921 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
12922 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
12923 			entire_crtc_covered = true;
12924 			break;
12925 		}
12926 	}
12927 
12928 	/* If planes do not cover the entire CRTC, use overlay mode to enable
12929 	 * cursor over holes
12930 	 */
12931 	if (entire_crtc_covered)
12932 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12933 	else
12934 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12935 
12936 	return 0;
12937 }
12938 
12939 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
12940 					    struct drm_atomic_commit *state,
12941 					    struct drm_crtc_state *crtc_state)
12942 {
12943 	struct drm_plane *plane;
12944 	struct drm_plane_state *new_plane_state, *old_plane_state;
12945 
12946 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
12947 		new_plane_state = drm_atomic_get_new_plane_state(state, plane);
12948 		old_plane_state = drm_atomic_get_old_plane_state(state, plane);
12949 
12950 		if (!old_plane_state || !new_plane_state)
12951 			continue;
12952 
12953 		if (old_plane_state->fb && new_plane_state->fb &&
12954 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
12955 			return true;
12956 	}
12957 
12958 	return false;
12959 }
12960 
12961 /**
12962  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
12963  *
12964  * @dev: The DRM device
12965  * @state: The atomic state to commit
12966  *
12967  * Validate that the given atomic state is programmable by DC into hardware.
12968  * This involves constructing a &struct dc_state reflecting the new hardware
12969  * state we wish to commit, then querying DC to see if it is programmable. It's
12970  * important not to modify the existing DC state. Otherwise, atomic_check
12971  * may unexpectedly commit hardware changes.
12972  *
12973  * When validating the DC state, it's important that the right locks are
12974  * acquired. For full updates case which removes/adds/updates streams on one
12975  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
12976  * that any such full update commit will wait for completion of any outstanding
12977  * flip using DRMs synchronization events.
12978  *
12979  * Note that DM adds the affected connectors for all CRTCs in state, when that
12980  * might not seem necessary. This is because DC stream creation requires the
12981  * DC sink, which is tied to the DRM connector state. Cleaning this up should
12982  * be possible but non-trivial - a possible TODO item.
12983  *
12984  * Return: -Error code if validation failed.
12985  */
12986 static int amdgpu_dm_atomic_check(struct drm_device *dev,
12987 				  struct drm_atomic_commit *state)
12988 {
12989 	struct amdgpu_device *adev = drm_to_adev(dev);
12990 	struct dm_atomic_state *dm_state = NULL;
12991 	struct dc *dc = adev->dm.dc;
12992 	struct drm_connector *connector;
12993 	struct drm_connector_state *old_con_state, *new_con_state;
12994 	struct drm_crtc *crtc;
12995 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12996 	struct drm_plane *plane;
12997 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
12998 	enum dc_status status;
12999 	int ret, i;
13000 	bool lock_and_validation_needed = false;
13001 	bool is_top_most_overlay = true;
13002 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
13003 	struct drm_dp_mst_topology_mgr *mgr;
13004 	struct drm_dp_mst_topology_state *mst_state;
13005 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
13006 
13007 	trace_amdgpu_dm_atomic_check_begin(state);
13008 
13009 	ret = drm_atomic_helper_check_modeset(dev, state);
13010 	if (ret) {
13011 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
13012 		goto fail;
13013 	}
13014 
13015 	/* Check connector changes */
13016 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
13017 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
13018 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
13019 
13020 		/* Skip connectors that are disabled or part of modeset already. */
13021 		if (!new_con_state->crtc)
13022 			continue;
13023 
13024 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
13025 		if (IS_ERR(new_crtc_state)) {
13026 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
13027 			ret = PTR_ERR(new_crtc_state);
13028 			goto fail;
13029 		}
13030 
13031 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
13032 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
13033 			new_crtc_state->connectors_changed = true;
13034 	}
13035 
13036 	if (dc_resource_is_dsc_encoding_supported(dc)) {
13037 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13038 			dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13039 			dm_new_crtc_state->mode_changed_independent_from_dsc = new_crtc_state->mode_changed;
13040 		}
13041 
13042 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13043 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
13044 				ret = add_affected_mst_dsc_crtcs(state, crtc);
13045 				if (ret) {
13046 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
13047 					goto fail;
13048 				}
13049 			}
13050 		}
13051 	}
13052 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13053 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
13054 
13055 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
13056 		    !new_crtc_state->color_mgmt_changed &&
13057 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
13058 			dm_old_crtc_state->dsc_force_changed == false)
13059 			continue;
13060 
13061 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
13062 		if (ret) {
13063 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
13064 			goto fail;
13065 		}
13066 
13067 		if (!new_crtc_state->enable)
13068 			continue;
13069 
13070 		ret = drm_atomic_add_affected_connectors(state, crtc);
13071 		if (ret) {
13072 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
13073 			goto fail;
13074 		}
13075 
13076 		ret = drm_atomic_add_affected_planes(state, crtc);
13077 		if (ret) {
13078 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
13079 			goto fail;
13080 		}
13081 
13082 		if (dm_old_crtc_state->dsc_force_changed)
13083 			new_crtc_state->mode_changed = true;
13084 	}
13085 
13086 	/*
13087 	 * Add all primary and overlay planes on the CRTC to the state
13088 	 * whenever a plane is enabled to maintain correct z-ordering
13089 	 * and to enable fast surface updates.
13090 	 */
13091 	drm_for_each_crtc(crtc, dev) {
13092 		bool modified = false;
13093 
13094 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
13095 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
13096 				continue;
13097 
13098 			if (new_plane_state->crtc == crtc ||
13099 			    old_plane_state->crtc == crtc) {
13100 				modified = true;
13101 				break;
13102 			}
13103 		}
13104 
13105 		if (!modified)
13106 			continue;
13107 
13108 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
13109 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
13110 				continue;
13111 
13112 			new_plane_state =
13113 				drm_atomic_get_plane_state(state, plane);
13114 
13115 			if (IS_ERR(new_plane_state)) {
13116 				ret = PTR_ERR(new_plane_state);
13117 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
13118 				goto fail;
13119 			}
13120 		}
13121 	}
13122 
13123 	/*
13124 	 * DC consults the zpos (layer_index in DC terminology) to determine the
13125 	 * hw plane on which to enable the hw cursor (see
13126 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
13127 	 * atomic state, so call drm helper to normalize zpos.
13128 	 */
13129 	ret = drm_atomic_normalize_zpos(dev, state);
13130 	if (ret) {
13131 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
13132 		goto fail;
13133 	}
13134 
13135 	/*
13136 	 * Determine whether cursors on each CRTC should be enabled in native or
13137 	 * overlay mode.
13138 	 */
13139 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13140 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13141 
13142 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
13143 					      &dm_new_crtc_state->cursor_mode);
13144 		if (ret) {
13145 			drm_dbg(dev, "Failed to determine cursor mode\n");
13146 			goto fail;
13147 		}
13148 
13149 		/*
13150 		 * If overlay cursor is needed, DC cannot go through the
13151 		 * native cursor update path. All enabled planes on the CRTC
13152 		 * need to be added for DC to not disable a plane by mistake
13153 		 */
13154 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
13155 			if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
13156 				drm_dbg(dev, "Overlay cursor not supported on DCE\n");
13157 				ret = -EINVAL;
13158 				goto fail;
13159 			}
13160 
13161 			ret = drm_atomic_add_affected_planes(state, crtc);
13162 			if (ret)
13163 				goto fail;
13164 		}
13165 	}
13166 
13167 	/* Remove exiting planes if they are modified */
13168 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13169 
13170 		ret = dm_update_plane_state(dc, state, plane,
13171 					    old_plane_state,
13172 					    new_plane_state,
13173 					    false,
13174 					    &lock_and_validation_needed,
13175 					    &is_top_most_overlay);
13176 		if (ret) {
13177 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13178 			goto fail;
13179 		}
13180 	}
13181 
13182 	/* Disable all crtcs which require disable */
13183 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13184 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
13185 					   old_crtc_state,
13186 					   new_crtc_state,
13187 					   false,
13188 					   &lock_and_validation_needed);
13189 		if (ret) {
13190 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
13191 			goto fail;
13192 		}
13193 	}
13194 
13195 	/* Enable all crtcs which require enable */
13196 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13197 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
13198 					   old_crtc_state,
13199 					   new_crtc_state,
13200 					   true,
13201 					   &lock_and_validation_needed);
13202 		if (ret) {
13203 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
13204 			goto fail;
13205 		}
13206 	}
13207 
13208 	/* Add new/modified planes */
13209 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13210 		ret = dm_update_plane_state(dc, state, plane,
13211 					    old_plane_state,
13212 					    new_plane_state,
13213 					    true,
13214 					    &lock_and_validation_needed,
13215 					    &is_top_most_overlay);
13216 		if (ret) {
13217 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13218 			goto fail;
13219 		}
13220 	}
13221 
13222 #if defined(CONFIG_DRM_AMD_DC_FP)
13223 	if (dc_resource_is_dsc_encoding_supported(dc)) {
13224 		ret = pre_validate_dsc(state, &dm_state, vars);
13225 		if (ret != 0)
13226 			goto fail;
13227 	}
13228 #endif
13229 
13230 	/* Run this here since we want to validate the streams we created */
13231 	ret = drm_atomic_helper_check_planes(dev, state);
13232 	if (ret) {
13233 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
13234 		goto fail;
13235 	}
13236 
13237 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13238 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13239 		if (dm_new_crtc_state->mpo_requested)
13240 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
13241 	}
13242 
13243 	/* Check cursor restrictions */
13244 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13245 		enum amdgpu_dm_cursor_mode required_cursor_mode;
13246 		int is_rotated, is_scaled;
13247 
13248 		/* Overlay cusor not subject to native cursor restrictions */
13249 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13250 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
13251 			continue;
13252 
13253 		/* Check if rotation or scaling is enabled on DCN401 */
13254 		if ((drm_plane_mask(crtc->cursor) &
13255 		     new_crtc_state->plane_mask) &&
13256 		    (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 1) ||
13257 		     amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
13258 		     amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1))) {
13259 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
13260 
13261 			is_rotated = new_cursor_state &&
13262 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
13263 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
13264 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
13265 
13266 			if (is_rotated || is_scaled) {
13267 				drm_dbg_driver(
13268 					crtc->dev,
13269 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
13270 					crtc->base.id, crtc->name);
13271 				ret = -EINVAL;
13272 				goto fail;
13273 			}
13274 		}
13275 
13276 		/* If HW can only do native cursor, check restrictions again */
13277 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
13278 					      &required_cursor_mode);
13279 		if (ret) {
13280 			drm_dbg_driver(crtc->dev,
13281 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
13282 				       crtc->base.id, crtc->name);
13283 			goto fail;
13284 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
13285 			drm_dbg_driver(crtc->dev,
13286 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling, YUV, or color pipeline restrictions\n",
13287 				       crtc->base.id, crtc->name);
13288 			ret = -EINVAL;
13289 			goto fail;
13290 		}
13291 	}
13292 
13293 	if (state->legacy_cursor_update) {
13294 		/*
13295 		 * This is a fast cursor update coming from the plane update
13296 		 * helper, check if it can be done asynchronously for better
13297 		 * performance.
13298 		 */
13299 		state->async_update =
13300 			!drm_atomic_helper_async_check(dev, state);
13301 
13302 		/*
13303 		 * Skip the remaining global validation if this is an async
13304 		 * update. Cursor updates can be done without affecting
13305 		 * state or bandwidth calcs and this avoids the performance
13306 		 * penalty of locking the private state object and
13307 		 * allocating a new dc_state.
13308 		 */
13309 		if (state->async_update)
13310 			return 0;
13311 	}
13312 
13313 	/* Check scaling and underscan changes*/
13314 	/* TODO Removed scaling changes validation due to inability to commit
13315 	 * new stream into context w\o causing full reset. Need to
13316 	 * decide how to handle.
13317 	 */
13318 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
13319 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
13320 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
13321 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
13322 
13323 		/* Skip any modesets/resets */
13324 		if (!acrtc || drm_atomic_crtc_needs_modeset(
13325 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
13326 			continue;
13327 
13328 		/* Skip any thing not scale or underscan changes */
13329 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
13330 			continue;
13331 
13332 		lock_and_validation_needed = true;
13333 	}
13334 
13335 	/* set the slot info for each mst_state based on the link encoding format */
13336 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
13337 		struct amdgpu_dm_connector *aconnector;
13338 		struct drm_connector *connector;
13339 		struct drm_connector_list_iter iter;
13340 		u8 link_coding_cap;
13341 
13342 		drm_connector_list_iter_begin(dev, &iter);
13343 		drm_for_each_connector_iter(connector, &iter) {
13344 			if (connector->index == mst_state->mgr->conn_base_id) {
13345 				aconnector = to_amdgpu_dm_connector(connector);
13346 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
13347 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
13348 
13349 				break;
13350 			}
13351 		}
13352 		drm_connector_list_iter_end(&iter);
13353 	}
13354 
13355 	/**
13356 	 * Streams and planes are reset when there are changes that affect
13357 	 * bandwidth. Anything that affects bandwidth needs to go through
13358 	 * DC global validation to ensure that the configuration can be applied
13359 	 * to hardware.
13360 	 *
13361 	 * We have to currently stall out here in atomic_check for outstanding
13362 	 * commits to finish in this case because our IRQ handlers reference
13363 	 * DRM state directly - we can end up disabling interrupts too early
13364 	 * if we don't.
13365 	 *
13366 	 * TODO: Remove this stall and drop DM state private objects.
13367 	 */
13368 	if (lock_and_validation_needed) {
13369 		ret = dm_atomic_get_state(state, &dm_state);
13370 		if (ret) {
13371 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
13372 			goto fail;
13373 		}
13374 
13375 		ret = do_aquire_global_lock(dev, state);
13376 		if (ret) {
13377 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
13378 			goto fail;
13379 		}
13380 
13381 #if defined(CONFIG_DRM_AMD_DC_FP)
13382 		if (dc_resource_is_dsc_encoding_supported(dc)) {
13383 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
13384 			if (ret) {
13385 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
13386 				ret = -EINVAL;
13387 				goto fail;
13388 			}
13389 		}
13390 #endif
13391 
13392 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
13393 		if (ret) {
13394 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
13395 			goto fail;
13396 		}
13397 
13398 		/*
13399 		 * Perform validation of MST topology in the state:
13400 		 * We need to perform MST atomic check before calling
13401 		 * dc_validate_global_state(), or there is a chance
13402 		 * to get stuck in an infinite loop and hang eventually.
13403 		 */
13404 		ret = drm_dp_mst_atomic_check(state);
13405 		if (ret) {
13406 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
13407 			goto fail;
13408 		}
13409 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
13410 		if (status != DC_OK) {
13411 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
13412 				       dc_status_to_str(status), status);
13413 			ret = -EINVAL;
13414 			goto fail;
13415 		}
13416 	} else {
13417 		/*
13418 		 * The commit is a fast update. Fast updates shouldn't change
13419 		 * the DC context, affect global validation, and can have their
13420 		 * commit work done in parallel with other commits not touching
13421 		 * the same resource. If we have a new DC context as part of
13422 		 * the DM atomic state from validation we need to free it and
13423 		 * retain the existing one instead.
13424 		 *
13425 		 * Furthermore, since the DM atomic state only contains the DC
13426 		 * context and can safely be annulled, we can free the state
13427 		 * and clear the associated private object now to free
13428 		 * some memory and avoid a possible use-after-free later.
13429 		 */
13430 
13431 		for (i = 0; i < state->num_private_objs; i++) {
13432 			struct drm_private_obj *obj = state->private_objs[i].ptr;
13433 
13434 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
13435 				int j = state->num_private_objs-1;
13436 
13437 				dm_atomic_destroy_state(obj,
13438 						state->private_objs[i].state_to_destroy);
13439 
13440 				/* If i is not at the end of the array then the
13441 				 * last element needs to be moved to where i was
13442 				 * before the array can safely be truncated.
13443 				 */
13444 				if (i != j)
13445 					state->private_objs[i] =
13446 						state->private_objs[j];
13447 
13448 				state->private_objs[j].ptr = NULL;
13449 				state->private_objs[j].state_to_destroy = NULL;
13450 				state->private_objs[j].old_state = NULL;
13451 				state->private_objs[j].new_state = NULL;
13452 
13453 				state->num_private_objs = j;
13454 				break;
13455 			}
13456 		}
13457 	}
13458 
13459 	/* Store the overall update type for use later in atomic check. */
13460 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13461 		struct dm_crtc_state *dm_new_crtc_state =
13462 			to_dm_crtc_state(new_crtc_state);
13463 
13464 		/*
13465 		 * Only allow async flips for fast updates that don't change
13466 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
13467 		 */
13468 		if (new_crtc_state->async_flip &&
13469 		    (lock_and_validation_needed ||
13470 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
13471 			drm_dbg_atomic(crtc->dev,
13472 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
13473 				       crtc->base.id, crtc->name);
13474 			ret = -EINVAL;
13475 			goto fail;
13476 		}
13477 
13478 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
13479 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
13480 	}
13481 
13482 	/* Must be success */
13483 	WARN_ON(ret);
13484 
13485 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13486 
13487 	return ret;
13488 
13489 fail:
13490 	if (ret == -EDEADLK)
13491 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
13492 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
13493 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
13494 	else
13495 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
13496 
13497 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13498 
13499 	return ret;
13500 }
13501 
13502 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
13503 		unsigned int offset,
13504 		unsigned int total_length,
13505 		u8 *data,
13506 		unsigned int length,
13507 		struct amdgpu_hdmi_vsdb_info *vsdb)
13508 {
13509 	bool res;
13510 	union dmub_rb_cmd cmd;
13511 	struct dmub_cmd_send_edid_cea *input;
13512 	struct dmub_cmd_edid_cea_output *output;
13513 
13514 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
13515 		return false;
13516 
13517 	memset(&cmd, 0, sizeof(cmd));
13518 
13519 	input = &cmd.edid_cea.data.input;
13520 
13521 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
13522 	cmd.edid_cea.header.sub_type = 0;
13523 	cmd.edid_cea.header.payload_bytes =
13524 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
13525 	input->offset = offset;
13526 	input->length = length;
13527 	input->cea_total_length = total_length;
13528 	memcpy(input->payload, data, length);
13529 
13530 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
13531 	if (!res) {
13532 		drm_err(adev_to_drm(dm->adev), "EDID CEA parser failed\n");
13533 		return false;
13534 	}
13535 
13536 	output = &cmd.edid_cea.data.output;
13537 
13538 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
13539 		if (!output->ack.success) {
13540 			drm_err(adev_to_drm(dm->adev), "EDID CEA ack failed at offset %d\n",
13541 					output->ack.offset);
13542 		}
13543 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
13544 		if (!output->amd_vsdb.vsdb_found)
13545 			return false;
13546 
13547 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
13548 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
13549 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
13550 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
13551 		vsdb->freesync_mccs_vcp_code = output->amd_vsdb.freesync_mccs_vcp_code;
13552 	} else {
13553 		drm_warn(adev_to_drm(dm->adev), "Unknown EDID CEA parser results\n");
13554 		return false;
13555 	}
13556 
13557 	return true;
13558 }
13559 
13560 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
13561 		u8 *edid_ext, int len,
13562 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13563 {
13564 	int i;
13565 
13566 	/* send extension block to DMCU for parsing */
13567 	for (i = 0; i < len; i += 8) {
13568 		bool res;
13569 		int offset;
13570 
13571 		/* send 8 bytes a time */
13572 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
13573 			return false;
13574 
13575 		if (i+8 == len) {
13576 			/* EDID block sent completed, expect result */
13577 			int version, min_rate, max_rate;
13578 
13579 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
13580 			if (res) {
13581 				/* amd vsdb found */
13582 				vsdb_info->freesync_supported = 1;
13583 				vsdb_info->amd_vsdb_version = version;
13584 				vsdb_info->min_refresh_rate_hz = min_rate;
13585 				vsdb_info->max_refresh_rate_hz = max_rate;
13586 				/* Not enabled on DMCU*/
13587 				vsdb_info->freesync_mccs_vcp_code = 0;
13588 				return true;
13589 			}
13590 			/* not amd vsdb */
13591 			return false;
13592 		}
13593 
13594 		/* check for ack*/
13595 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
13596 		if (!res)
13597 			return false;
13598 	}
13599 
13600 	return false;
13601 }
13602 
13603 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
13604 		u8 *edid_ext, int len,
13605 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13606 {
13607 	int i;
13608 
13609 	/* send extension block to DMCU for parsing */
13610 	for (i = 0; i < len; i += 8) {
13611 		/* send 8 bytes a time */
13612 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
13613 			return false;
13614 	}
13615 
13616 	return vsdb_info->freesync_supported;
13617 }
13618 
13619 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
13620 		u8 *edid_ext, int len,
13621 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13622 {
13623 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
13624 	bool ret;
13625 
13626 	mutex_lock(&adev->dm.dc_lock);
13627 	if (adev->dm.dmub_srv)
13628 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
13629 	else
13630 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
13631 	mutex_unlock(&adev->dm.dc_lock);
13632 	return ret;
13633 }
13634 
13635 static void parse_edid_displayid_vrr(struct drm_connector *connector,
13636 				     const struct edid *edid)
13637 {
13638 	u8 *edid_ext = NULL;
13639 	int i;
13640 	int j = 0;
13641 	u16 min_vfreq;
13642 	u16 max_vfreq;
13643 
13644 	if (!edid || !edid->extensions)
13645 		return;
13646 
13647 	/* Find DisplayID extension */
13648 	for (i = 0; i < edid->extensions; i++) {
13649 		edid_ext = (void *)(edid + (i + 1));
13650 		if (edid_ext[0] == DISPLAYID_EXT)
13651 			break;
13652 	}
13653 
13654 	if (i == edid->extensions)
13655 		return;
13656 
13657 	while (j < EDID_LENGTH) {
13658 		/* Get dynamic video timing range from DisplayID if available */
13659 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
13660 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
13661 			min_vfreq = edid_ext[j+9];
13662 			if (edid_ext[j+1] & 7)
13663 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
13664 			else
13665 				max_vfreq = edid_ext[j+10];
13666 
13667 			if (max_vfreq && min_vfreq) {
13668 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
13669 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
13670 
13671 				return;
13672 			}
13673 		}
13674 		j++;
13675 	}
13676 }
13677 
13678 static int get_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13679 			struct amdgpu_hdmi_vsdb_info *vsdb_info)
13680 {
13681 	struct drm_connector *connector = &aconnector->base;
13682 
13683 	vsdb_info->replay_mode = connector->display_info.amd_vsdb.replay_mode;
13684 	vsdb_info->amd_vsdb_version = connector->display_info.amd_vsdb.version;
13685 
13686 	return connector->display_info.amd_vsdb.version != 0;
13687 }
13688 
13689 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13690 			       const struct edid *edid,
13691 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
13692 {
13693 	u8 *edid_ext = NULL;
13694 	int i;
13695 	bool valid_vsdb_found = false;
13696 
13697 	/*----- drm_find_cea_extension() -----*/
13698 	/* No EDID or EDID extensions */
13699 	if (edid == NULL || edid->extensions == 0)
13700 		return -ENODEV;
13701 
13702 	/* Find CEA extension */
13703 	for (i = 0; i < edid->extensions; i++) {
13704 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
13705 		if (edid_ext[0] == CEA_EXT)
13706 			break;
13707 	}
13708 
13709 	if (i == edid->extensions)
13710 		return -ENODEV;
13711 
13712 	/*----- cea_db_offsets() -----*/
13713 	if (edid_ext[0] != CEA_EXT)
13714 		return -ENODEV;
13715 
13716 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
13717 
13718 	return valid_vsdb_found ? i : -ENODEV;
13719 }
13720 
13721 /**
13722  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
13723  *
13724  * @connector: Connector to query.
13725  * @drm_edid: DRM EDID from monitor
13726  * @do_mccs: Controls whether MCCS (Monitor Control Command Set) over
13727  *	      DDC (Display Data Channel) transactions are performed. When true,
13728  *	      the driver queries the monitor to get or update additional FreeSync
13729  *	      capability information. When false, these transactions are skipped.
13730  *
13731  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
13732  * track of some of the display information in the internal data struct used by
13733  * amdgpu_dm. This function checks which type of connector we need to set the
13734  * FreeSync parameters.
13735  */
13736 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
13737 				    const struct drm_edid *drm_edid, bool do_mccs)
13738 {
13739 	int i = 0;
13740 	struct amdgpu_dm_connector *amdgpu_dm_connector =
13741 			to_amdgpu_dm_connector(connector);
13742 	struct dm_connector_state *dm_con_state = NULL;
13743 	struct dc_sink *sink;
13744 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
13745 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
13746 	const struct edid *edid;
13747 	bool freesync_capable = false;
13748 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
13749 
13750 	if (!connector->state) {
13751 		drm_err(adev_to_drm(adev), "%s - Connector has no state", __func__);
13752 		goto update;
13753 	}
13754 
13755 	sink = amdgpu_dm_connector->dc_sink ?
13756 		amdgpu_dm_connector->dc_sink :
13757 		amdgpu_dm_connector->dc_em_sink;
13758 
13759 	drm_edid_connector_update(connector, drm_edid);
13760 
13761 	if (!drm_edid || !sink) {
13762 		dm_con_state = to_dm_connector_state(connector->state);
13763 
13764 		amdgpu_dm_connector->min_vfreq = 0;
13765 		amdgpu_dm_connector->max_vfreq = 0;
13766 		freesync_capable = false;
13767 
13768 		goto update;
13769 	}
13770 
13771 	dm_con_state = to_dm_connector_state(connector->state);
13772 
13773 	if (!adev->dm.freesync_module || !dc_supports_vrr(sink->ctx->dce_version))
13774 		goto update;
13775 
13776 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
13777 
13778 	/* Some eDP panels only have the refresh rate range info in DisplayID */
13779 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
13780 	     connector->display_info.monitor_range.max_vfreq == 0))
13781 		parse_edid_displayid_vrr(connector, edid);
13782 
13783 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
13784 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
13785 		if (amdgpu_dm_connector->dc_link &&
13786 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
13787 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
13788 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
13789 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13790 				freesync_capable = true;
13791 		}
13792 
13793 		get_amd_vsdb(amdgpu_dm_connector, &vsdb_info);
13794 
13795 		if (vsdb_info.replay_mode) {
13796 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
13797 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
13798 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
13799 		}
13800 
13801 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
13802 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13803 		if (i >= 0) {
13804 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13805 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13806 
13807 			if (vsdb_info.freesync_supported) {
13808 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13809 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13810 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13811 					freesync_capable = true;
13812 
13813 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13814 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13815 			}
13816 		}
13817 	}
13818 
13819 	if (amdgpu_dm_connector->dc_link)
13820 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
13821 
13822 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
13823 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13824 		if (i >= 0) {
13825 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13826 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13827 
13828 			if (vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
13829 				amdgpu_dm_connector->pack_sdp_v1_3 = true;
13830 				amdgpu_dm_connector->as_type = as_type;
13831 
13832 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13833 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13834 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13835 					freesync_capable = true;
13836 
13837 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13838 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13839 			}
13840 		}
13841 	}
13842 
13843 	/* Handle MCCS */
13844 	if (do_mccs) {
13845 		dm_helpers_read_mccs_caps(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13846 
13847 		if (sink->edid_caps.freesync_vcp_code && !sink->mccs_caps.freesync_supported)
13848 			freesync_capable = false;
13849 
13850 		if (sink->mccs_caps.freesync_supported && freesync_capable)
13851 			dm_helpers_mccs_vcp_set(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13852 	}
13853 
13854 update:
13855 	if (dm_con_state)
13856 		dm_con_state->freesync_capable = freesync_capable;
13857 
13858 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
13859 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
13860 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
13861 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
13862 	}
13863 
13864 	if (connector->vrr_capable_property)
13865 		drm_connector_set_vrr_capable_property(connector,
13866 						       freesync_capable);
13867 }
13868 
13869 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
13870 {
13871 	struct amdgpu_device *adev = drm_to_adev(dev);
13872 	struct dc *dc = adev->dm.dc;
13873 	int i;
13874 
13875 	mutex_lock(&adev->dm.dc_lock);
13876 	if (dc->current_state) {
13877 		for (i = 0; i < dc->current_state->stream_count; ++i)
13878 			dc->current_state->streams[i]
13879 				->triggered_crtc_reset.enabled =
13880 				adev->dm.force_timing_sync;
13881 
13882 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
13883 		dc_trigger_sync(dc, dc->current_state);
13884 	}
13885 	mutex_unlock(&adev->dm.dc_lock);
13886 }
13887 
13888 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
13889 {
13890 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
13891 		dc_exit_ips_for_hw_access(dc);
13892 }
13893 
13894 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
13895 		       u32 value, const char *func_name)
13896 {
13897 #ifdef DM_CHECK_ADDR_0
13898 	if (address == 0) {
13899 		drm_err(adev_to_drm(ctx->driver_context),
13900 			"invalid register write. address = 0");
13901 		return;
13902 	}
13903 #endif
13904 
13905 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13906 	cgs_write_register(ctx->cgs_device, address, value);
13907 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
13908 }
13909 
13910 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
13911 			  const char *func_name)
13912 {
13913 	u32 value;
13914 #ifdef DM_CHECK_ADDR_0
13915 	if (address == 0) {
13916 		drm_err(adev_to_drm(ctx->driver_context),
13917 			"invalid register read; address = 0\n");
13918 		return 0;
13919 	}
13920 #endif
13921 
13922 	if (ctx->dmub_srv &&
13923 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
13924 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
13925 		ASSERT(false);
13926 		return 0;
13927 	}
13928 
13929 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13930 
13931 	value = cgs_read_register(ctx->cgs_device, address);
13932 
13933 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
13934 
13935 	return value;
13936 }
13937 
13938 int amdgpu_dm_process_dmub_aux_transfer_sync(
13939 		struct dc_context *ctx,
13940 		unsigned int link_index,
13941 		struct aux_payload *payload,
13942 		enum aux_return_code_type *operation_result)
13943 {
13944 	struct amdgpu_device *adev = ctx->driver_context;
13945 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
13946 	int ret = -1;
13947 
13948 	mutex_lock(&adev->dm.dpia_aux_lock);
13949 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
13950 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
13951 		goto out;
13952 	}
13953 
13954 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13955 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13956 		*operation_result = AUX_RET_ERROR_TIMEOUT;
13957 		goto out;
13958 	}
13959 
13960 	if (p_notify->result != AUX_RET_SUCCESS) {
13961 		/*
13962 		 * Transient states before tunneling is enabled could
13963 		 * lead to this error. We can ignore this for now.
13964 		 */
13965 		if (p_notify->result == AUX_RET_ERROR_PROTOCOL_ERROR) {
13966 			drm_warn(adev_to_drm(adev), "DPIA AUX failed on 0x%x(%d), error %d\n",
13967 					payload->address, payload->length,
13968 					p_notify->result);
13969 		}
13970 		*operation_result = p_notify->result;
13971 		goto out;
13972 	}
13973 
13974 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command & 0xF;
13975 	if (adev->dm.dmub_notify->aux_reply.command & 0xF0)
13976 		/* The reply is stored in the top nibble of the command. */
13977 		payload->reply[0] = (adev->dm.dmub_notify->aux_reply.command >> 4) & 0xF;
13978 
13979 	/*write req may receive a byte indicating partially written number as well*/
13980 	if (p_notify->aux_reply.length)
13981 		memcpy(payload->data, p_notify->aux_reply.data,
13982 				p_notify->aux_reply.length);
13983 
13984 	/* success */
13985 	ret = p_notify->aux_reply.length;
13986 	*operation_result = p_notify->result;
13987 out:
13988 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
13989 	mutex_unlock(&adev->dm.dpia_aux_lock);
13990 	return ret;
13991 }
13992 
13993 static void abort_fused_io(
13994 		struct dc_context *ctx,
13995 		const struct dmub_cmd_fused_request *request
13996 )
13997 {
13998 	union dmub_rb_cmd command = { 0 };
13999 	struct dmub_rb_cmd_fused_io *io = &command.fused_io;
14000 
14001 	io->header.type = DMUB_CMD__FUSED_IO;
14002 	io->header.sub_type = DMUB_CMD__FUSED_IO_ABORT;
14003 	io->header.payload_bytes = sizeof(*io) - sizeof(io->header);
14004 	io->request = *request;
14005 	dm_execute_dmub_cmd(ctx, &command, DM_DMUB_WAIT_TYPE_NO_WAIT);
14006 }
14007 
14008 static bool execute_fused_io(
14009 		struct amdgpu_device *dev,
14010 		struct dc_context *ctx,
14011 		union dmub_rb_cmd *commands,
14012 		uint8_t count,
14013 		uint32_t timeout_us
14014 )
14015 {
14016 	const uint8_t ddc_line = commands[0].fused_io.request.u.aux.ddc_line;
14017 
14018 	if (ddc_line >= ARRAY_SIZE(dev->dm.fused_io))
14019 		return false;
14020 
14021 	struct fused_io_sync *sync = &dev->dm.fused_io[ddc_line];
14022 	struct dmub_rb_cmd_fused_io *first = &commands[0].fused_io;
14023 	const bool result = dm_execute_dmub_cmd_list(ctx, count, commands, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY)
14024 			&& first->header.ret_status
14025 			&& first->request.status == FUSED_REQUEST_STATUS_SUCCESS;
14026 
14027 	if (!result)
14028 		return false;
14029 
14030 	while (wait_for_completion_timeout(&sync->replied, usecs_to_jiffies(timeout_us))) {
14031 		reinit_completion(&sync->replied);
14032 
14033 		struct dmub_cmd_fused_request *reply = (struct dmub_cmd_fused_request *) sync->reply_data;
14034 
14035 		static_assert(sizeof(*reply) <= sizeof(sync->reply_data), "Size mismatch");
14036 
14037 		if (reply->identifier == first->request.identifier) {
14038 			first->request = *reply;
14039 			return true;
14040 		}
14041 	}
14042 
14043 	reinit_completion(&sync->replied);
14044 	first->request.status = FUSED_REQUEST_STATUS_TIMEOUT;
14045 	abort_fused_io(ctx, &first->request);
14046 	return false;
14047 }
14048 
14049 bool amdgpu_dm_execute_fused_io(
14050 		struct amdgpu_device *dev,
14051 		struct dc_link *link,
14052 		union dmub_rb_cmd *commands,
14053 		uint8_t count,
14054 		uint32_t timeout_us)
14055 {
14056 	struct amdgpu_display_manager *dm = &dev->dm;
14057 
14058 	mutex_lock(&dm->dpia_aux_lock);
14059 
14060 	const bool result = execute_fused_io(dev, link->ctx, commands, count, timeout_us);
14061 
14062 	mutex_unlock(&dm->dpia_aux_lock);
14063 	return result;
14064 }
14065 
14066 int amdgpu_dm_process_dmub_set_config_sync(
14067 		struct dc_context *ctx,
14068 		unsigned int link_index,
14069 		struct set_config_cmd_payload *payload,
14070 		enum set_config_status *operation_result)
14071 {
14072 	struct amdgpu_device *adev = ctx->driver_context;
14073 	bool is_cmd_complete;
14074 	int ret;
14075 
14076 	mutex_lock(&adev->dm.dpia_aux_lock);
14077 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
14078 			link_index, payload, adev->dm.dmub_notify);
14079 
14080 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
14081 		ret = 0;
14082 		*operation_result = adev->dm.dmub_notify->sc_status;
14083 	} else {
14084 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
14085 		ret = -1;
14086 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
14087 	}
14088 
14089 	if (!is_cmd_complete)
14090 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
14091 	mutex_unlock(&adev->dm.dpia_aux_lock);
14092 	return ret;
14093 }
14094 
14095 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
14096 {
14097 	struct amdgpu_device *adev = ctx->driver_context;
14098 
14099 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
14100 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
14101 }
14102 
14103 bool dm_execute_dmub_cmd_list(const struct dc_context *ctx, unsigned int count, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
14104 {
14105 	struct amdgpu_device *adev = ctx->driver_context;
14106 
14107 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
14108 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
14109 }
14110 
14111 void dm_acpi_process_phy_transition_interlock(
14112 	const struct dc_context *ctx,
14113 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
14114 {
14115 	// Not yet implemented
14116 }
14117