xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision 056e065a6b6e01ab54bb9770c0d5a15350e571e2)
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;
6618 	struct drm_mode_rect *clips;
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 	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
6635 	clips = drm_plane_get_damage_clips(new_plane_state);
6636 
6637 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
6638 						   is_psr_su)))
6639 		goto ffu;
6640 
6641 	if (!dm_crtc_state->mpo_requested) {
6642 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
6643 			goto ffu;
6644 
6645 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
6646 			fill_dc_dirty_rect(new_plane_state->plane,
6647 					   &dirty_rects[flip_addrs->dirty_rect_count],
6648 					   clips->x1, clips->y1,
6649 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
6650 					   &flip_addrs->dirty_rect_count,
6651 					   false);
6652 		return;
6653 	}
6654 
6655 	/*
6656 	 * MPO is requested. Add entire plane bounding box to dirty rects if
6657 	 * flipped to or damaged.
6658 	 *
6659 	 * If plane is moved or resized, also add old bounding box to dirty
6660 	 * rects.
6661 	 */
6662 	fb_changed = old_plane_state->fb->base.id !=
6663 		     new_plane_state->fb->base.id;
6664 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
6665 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
6666 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
6667 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
6668 
6669 	drm_dbg(plane->dev,
6670 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
6671 		new_plane_state->plane->base.id,
6672 		bb_changed, fb_changed, num_clips);
6673 
6674 	*dirty_regions_changed = bb_changed;
6675 
6676 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
6677 		goto ffu;
6678 
6679 	if (bb_changed) {
6680 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6681 				   new_plane_state->crtc_x,
6682 				   new_plane_state->crtc_y,
6683 				   new_plane_state->crtc_w,
6684 				   new_plane_state->crtc_h, &i, false);
6685 
6686 		/* Add old plane bounding-box if plane is moved or resized */
6687 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6688 				   old_plane_state->crtc_x,
6689 				   old_plane_state->crtc_y,
6690 				   old_plane_state->crtc_w,
6691 				   old_plane_state->crtc_h, &i, false);
6692 	}
6693 
6694 	if (num_clips) {
6695 		for (; i < num_clips; clips++)
6696 			fill_dc_dirty_rect(new_plane_state->plane,
6697 					   &dirty_rects[i], clips->x1,
6698 					   clips->y1, clips->x2 - clips->x1,
6699 					   clips->y2 - clips->y1, &i, false);
6700 	} else if (fb_changed && !bb_changed) {
6701 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6702 				   new_plane_state->crtc_x,
6703 				   new_plane_state->crtc_y,
6704 				   new_plane_state->crtc_w,
6705 				   new_plane_state->crtc_h, &i, false);
6706 	}
6707 
6708 	flip_addrs->dirty_rect_count = i;
6709 	return;
6710 
6711 ffu:
6712 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
6713 			   dm_crtc_state->base.mode.crtc_hdisplay,
6714 			   dm_crtc_state->base.mode.crtc_vdisplay,
6715 			   &flip_addrs->dirty_rect_count, true);
6716 }
6717 
6718 static void update_stream_scaling_settings(struct drm_device *dev,
6719 					   const struct drm_display_mode *mode,
6720 					   const struct dm_connector_state *dm_state,
6721 					   struct dc_stream_state *stream)
6722 {
6723 	enum amdgpu_rmx_type rmx_type;
6724 
6725 	struct rect src = { 0 }; /* viewport in composition space*/
6726 	struct rect dst = { 0 }; /* stream addressable area */
6727 
6728 	/* no mode. nothing to be done */
6729 	if (!mode)
6730 		return;
6731 
6732 	/* Full screen scaling by default */
6733 	src.width = mode->hdisplay;
6734 	src.height = mode->vdisplay;
6735 	dst.width = stream->timing.h_addressable;
6736 	dst.height = stream->timing.v_addressable;
6737 
6738 	if (dm_state) {
6739 		rmx_type = dm_state->scaling;
6740 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
6741 			if (src.width * dst.height <
6742 					src.height * dst.width) {
6743 				/* height needs less upscaling/more downscaling */
6744 				dst.width = src.width *
6745 						dst.height / src.height;
6746 			} else {
6747 				/* width needs less upscaling/more downscaling */
6748 				dst.height = src.height *
6749 						dst.width / src.width;
6750 			}
6751 		} else if (rmx_type == RMX_CENTER) {
6752 			dst = src;
6753 		}
6754 
6755 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
6756 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
6757 
6758 		if (dm_state->underscan_enable) {
6759 			dst.x += dm_state->underscan_hborder / 2;
6760 			dst.y += dm_state->underscan_vborder / 2;
6761 			dst.width -= dm_state->underscan_hborder;
6762 			dst.height -= dm_state->underscan_vborder;
6763 		}
6764 	}
6765 
6766 	stream->src = src;
6767 	stream->dst = dst;
6768 
6769 	drm_dbg_kms(dev, "Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
6770 		    dst.x, dst.y, dst.width, dst.height);
6771 
6772 }
6773 
6774 static enum dc_color_depth
6775 convert_color_depth_from_display_info(const struct drm_connector *connector,
6776 				      bool is_y420, int requested_bpc)
6777 {
6778 	u8 bpc;
6779 
6780 	if (is_y420) {
6781 		bpc = 8;
6782 
6783 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
6784 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
6785 			bpc = 16;
6786 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
6787 			bpc = 12;
6788 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
6789 			bpc = 10;
6790 	} else {
6791 		bpc = (uint8_t)connector->display_info.bpc;
6792 		/* Assume 8 bpc by default if no bpc is specified. */
6793 		bpc = bpc ? bpc : 8;
6794 	}
6795 
6796 	if (requested_bpc > 0) {
6797 		/*
6798 		 * Cap display bpc based on the user requested value.
6799 		 *
6800 		 * The value for state->max_bpc may not correctly updated
6801 		 * depending on when the connector gets added to the state
6802 		 * or if this was called outside of atomic check, so it
6803 		 * can't be used directly.
6804 		 */
6805 		bpc = min_t(u8, bpc, requested_bpc);
6806 
6807 		/* Round down to the nearest even number. */
6808 		bpc = bpc - (bpc & 1);
6809 	}
6810 
6811 	switch (bpc) {
6812 	case 0:
6813 		/*
6814 		 * Temporary Work around, DRM doesn't parse color depth for
6815 		 * EDID revision before 1.4
6816 		 * TODO: Fix edid parsing
6817 		 */
6818 		return COLOR_DEPTH_888;
6819 	case 6:
6820 		return COLOR_DEPTH_666;
6821 	case 8:
6822 		return COLOR_DEPTH_888;
6823 	case 10:
6824 		return COLOR_DEPTH_101010;
6825 	case 12:
6826 		return COLOR_DEPTH_121212;
6827 	case 14:
6828 		return COLOR_DEPTH_141414;
6829 	case 16:
6830 		return COLOR_DEPTH_161616;
6831 	default:
6832 		return COLOR_DEPTH_UNDEFINED;
6833 	}
6834 }
6835 
6836 static enum dc_aspect_ratio
6837 get_aspect_ratio(const struct drm_display_mode *mode_in)
6838 {
6839 	/* 1-1 mapping, since both enums follow the HDMI spec. */
6840 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
6841 }
6842 
6843 static enum dc_color_space
6844 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
6845 		       const struct drm_connector_state *connector_state)
6846 {
6847 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
6848 
6849 	switch (connector_state->colorspace) {
6850 	case DRM_MODE_COLORIMETRY_BT601_YCC:
6851 		if (dc_crtc_timing->flags.Y_ONLY)
6852 			color_space = COLOR_SPACE_YCBCR601_LIMITED;
6853 		else
6854 			color_space = COLOR_SPACE_YCBCR601;
6855 		break;
6856 	case DRM_MODE_COLORIMETRY_BT709_YCC:
6857 		if (dc_crtc_timing->flags.Y_ONLY)
6858 			color_space = COLOR_SPACE_YCBCR709_LIMITED;
6859 		else
6860 			color_space = COLOR_SPACE_YCBCR709;
6861 		break;
6862 	case DRM_MODE_COLORIMETRY_OPRGB:
6863 		color_space = COLOR_SPACE_ADOBERGB;
6864 		break;
6865 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
6866 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
6867 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
6868 			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
6869 		else
6870 			color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6871 		break;
6872 	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
6873 	default:
6874 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
6875 			color_space = COLOR_SPACE_SRGB;
6876 			if (connector_state->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_LIMITED)
6877 				color_space = COLOR_SPACE_SRGB_LIMITED;
6878 		/*
6879 		 * 27030khz is the separation point between HDTV and SDTV
6880 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
6881 		 * respectively
6882 		 */
6883 		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
6884 			if (dc_crtc_timing->flags.Y_ONLY)
6885 				color_space =
6886 					COLOR_SPACE_YCBCR709_LIMITED;
6887 			else
6888 				color_space = COLOR_SPACE_YCBCR709;
6889 		} else {
6890 			if (dc_crtc_timing->flags.Y_ONLY)
6891 				color_space =
6892 					COLOR_SPACE_YCBCR601_LIMITED;
6893 			else
6894 				color_space = COLOR_SPACE_YCBCR601;
6895 		}
6896 		break;
6897 	}
6898 
6899 	return color_space;
6900 }
6901 
6902 static enum display_content_type
6903 get_output_content_type(const struct drm_connector_state *connector_state)
6904 {
6905 	switch (connector_state->content_type) {
6906 	default:
6907 	case DRM_MODE_CONTENT_TYPE_NO_DATA:
6908 		return DISPLAY_CONTENT_TYPE_NO_DATA;
6909 	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
6910 		return DISPLAY_CONTENT_TYPE_GRAPHICS;
6911 	case DRM_MODE_CONTENT_TYPE_PHOTO:
6912 		return DISPLAY_CONTENT_TYPE_PHOTO;
6913 	case DRM_MODE_CONTENT_TYPE_CINEMA:
6914 		return DISPLAY_CONTENT_TYPE_CINEMA;
6915 	case DRM_MODE_CONTENT_TYPE_GAME:
6916 		return DISPLAY_CONTENT_TYPE_GAME;
6917 	}
6918 }
6919 
6920 static bool adjust_colour_depth_from_display_info(
6921 	struct dc_crtc_timing *timing_out,
6922 	const struct drm_display_info *info)
6923 {
6924 	enum dc_color_depth depth = timing_out->display_color_depth;
6925 	int normalized_clk;
6926 
6927 	do {
6928 		normalized_clk = timing_out->pix_clk_100hz / 10;
6929 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
6930 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
6931 			normalized_clk /= 2;
6932 		/* Adjusting pix clock following on HDMI spec based on colour depth */
6933 		switch (depth) {
6934 		case COLOR_DEPTH_888:
6935 			break;
6936 		case COLOR_DEPTH_101010:
6937 			normalized_clk = (normalized_clk * 30) / 24;
6938 			break;
6939 		case COLOR_DEPTH_121212:
6940 			normalized_clk = (normalized_clk * 36) / 24;
6941 			break;
6942 		case COLOR_DEPTH_161616:
6943 			normalized_clk = (normalized_clk * 48) / 24;
6944 			break;
6945 		default:
6946 			/* The above depths are the only ones valid for HDMI. */
6947 			return false;
6948 		}
6949 		if (normalized_clk <= info->max_tmds_clock) {
6950 			timing_out->display_color_depth = depth;
6951 			return true;
6952 		}
6953 	} while (--depth > COLOR_DEPTH_666);
6954 	return false;
6955 }
6956 
6957 static void fill_stream_properties_from_drm_display_mode(
6958 	struct dc_stream_state *stream,
6959 	const struct drm_display_mode *mode_in,
6960 	const struct drm_connector *connector,
6961 	const struct drm_connector_state *connector_state,
6962 	const struct dc_stream_state *old_stream,
6963 	int requested_bpc)
6964 {
6965 	struct dc_crtc_timing *timing_out = &stream->timing;
6966 	const struct drm_display_info *info = &connector->display_info;
6967 	struct amdgpu_dm_connector *aconnector = NULL;
6968 	struct hdmi_vendor_infoframe hv_frame;
6969 	struct hdmi_avi_infoframe avi_frame;
6970 	ssize_t err;
6971 
6972 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
6973 		aconnector = to_amdgpu_dm_connector(connector);
6974 
6975 	memset(&hv_frame, 0, sizeof(hv_frame));
6976 	memset(&avi_frame, 0, sizeof(avi_frame));
6977 
6978 	timing_out->h_border_left = 0;
6979 	timing_out->h_border_right = 0;
6980 	timing_out->v_border_top = 0;
6981 	timing_out->v_border_bottom = 0;
6982 	/* TODO: un-hardcode */
6983 	if (drm_mode_is_420_only(info, mode_in)
6984 			&& (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
6985 			    stream->signal == SIGNAL_TYPE_HDMI_FRL)
6986 			&& aconnector
6987 			&& aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR420)
6988 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6989 	else if (drm_mode_is_420_also(info, mode_in)
6990 			&& aconnector
6991 			&& (aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR420
6992 			|| aconnector->force_yuv420_output))
6993 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6994 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR422))
6995 			&& aconnector
6996 			&& (aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR422
6997 			|| aconnector->force_yuv422_output))
6998 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR422;
6999 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR444))
7000 			&& (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7001 			    stream->signal == SIGNAL_TYPE_HDMI_FRL)
7002 			&& aconnector
7003 			&& aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR444)
7004 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
7005 	else
7006 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
7007 
7008 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
7009 	timing_out->display_color_depth = convert_color_depth_from_display_info(
7010 		connector,
7011 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
7012 		requested_bpc);
7013 	timing_out->scan_type = SCANNING_TYPE_NODATA;
7014 	timing_out->hdmi_vic = 0;
7015 
7016 	if (old_stream) {
7017 		timing_out->vic = old_stream->timing.vic;
7018 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
7019 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
7020 	} else {
7021 		timing_out->vic = drm_match_cea_mode(mode_in);
7022 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
7023 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
7024 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
7025 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
7026 	}
7027 
7028 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7029 		stream->signal == SIGNAL_TYPE_HDMI_FRL) {
7030 		err = drm_hdmi_avi_infoframe_from_display_mode(&avi_frame,
7031 							       (struct drm_connector *)connector,
7032 							       mode_in);
7033 		if (err < 0)
7034 			drm_warn_once(connector->dev, "Failed to setup avi infoframe on connector %s: %zd\n",
7035 				      connector->name, err);
7036 		timing_out->vic = avi_frame.video_code;
7037 		err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame,
7038 								  (struct drm_connector *)connector,
7039 								  mode_in);
7040 		if (err < 0)
7041 			drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n",
7042 				      connector->name, err);
7043 		timing_out->hdmi_vic = hv_frame.vic;
7044 	}
7045 
7046 	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
7047 		timing_out->h_addressable = mode_in->hdisplay;
7048 		timing_out->h_total = mode_in->htotal;
7049 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
7050 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
7051 		timing_out->v_total = mode_in->vtotal;
7052 		timing_out->v_addressable = mode_in->vdisplay;
7053 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
7054 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
7055 		timing_out->pix_clk_100hz = mode_in->clock * 10;
7056 	} else {
7057 		timing_out->h_addressable = mode_in->crtc_hdisplay;
7058 		timing_out->h_total = mode_in->crtc_htotal;
7059 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
7060 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
7061 		timing_out->v_total = mode_in->crtc_vtotal;
7062 		timing_out->v_addressable = mode_in->crtc_vdisplay;
7063 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
7064 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
7065 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
7066 	}
7067 
7068 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
7069 
7070 	stream->out_transfer_func.type = TF_TYPE_PREDEFINED;
7071 	stream->out_transfer_func.tf = TRANSFER_FUNCTION_SRGB;
7072 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
7073 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
7074 		    drm_mode_is_420_also(info, mode_in) &&
7075 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
7076 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
7077 			adjust_colour_depth_from_display_info(timing_out, info);
7078 		}
7079 	}
7080 
7081 	stream->output_color_space = get_output_color_space(timing_out, connector_state);
7082 	stream->content_type = get_output_content_type(connector_state);
7083 }
7084 
7085 static void fill_audio_info(struct audio_info *audio_info,
7086 			    const struct drm_connector *drm_connector,
7087 			    const struct dc_sink *dc_sink)
7088 {
7089 	int i = 0;
7090 	int cea_revision = 0;
7091 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
7092 
7093 	audio_info->manufacture_id = edid_caps->manufacturer_id;
7094 	audio_info->product_id = edid_caps->product_id;
7095 
7096 	cea_revision = drm_connector->display_info.cea_rev;
7097 
7098 	strscpy(audio_info->display_name,
7099 		edid_caps->display_name,
7100 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
7101 
7102 	if (cea_revision >= 3) {
7103 		audio_info->mode_count = edid_caps->audio_mode_count;
7104 
7105 		for (i = 0; i < audio_info->mode_count; ++i) {
7106 			audio_info->modes[i].format_code =
7107 					(enum audio_format_code)
7108 					(edid_caps->audio_modes[i].format_code);
7109 			audio_info->modes[i].channel_count =
7110 					edid_caps->audio_modes[i].channel_count;
7111 			audio_info->modes[i].sample_rates.all =
7112 					edid_caps->audio_modes[i].sample_rate;
7113 			audio_info->modes[i].sample_size =
7114 					edid_caps->audio_modes[i].sample_size;
7115 		}
7116 	}
7117 
7118 	audio_info->flags.all = edid_caps->speaker_flags;
7119 
7120 	/* TODO: We only check for the progressive mode, check for interlace mode too */
7121 	if (drm_connector->latency_present[0]) {
7122 		audio_info->video_latency = drm_connector->video_latency[0];
7123 		audio_info->audio_latency = drm_connector->audio_latency[0];
7124 	}
7125 
7126 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
7127 
7128 }
7129 
7130 static void
7131 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
7132 				      struct drm_display_mode *dst_mode)
7133 {
7134 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
7135 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
7136 	dst_mode->crtc_clock = src_mode->crtc_clock;
7137 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
7138 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
7139 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
7140 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
7141 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
7142 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
7143 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
7144 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
7145 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
7146 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
7147 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
7148 }
7149 
7150 static void
7151 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
7152 					const struct drm_display_mode *native_mode,
7153 					bool scale_enabled)
7154 {
7155 	if (scale_enabled || (
7156 	    native_mode->clock == drm_mode->clock &&
7157 	    native_mode->htotal == drm_mode->htotal &&
7158 	    native_mode->vtotal == drm_mode->vtotal)) {
7159 		if (native_mode->crtc_clock)
7160 			copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
7161 	} else {
7162 		/* no scaling nor amdgpu inserted, no need to patch */
7163 	}
7164 }
7165 
7166 static struct dc_sink *
7167 create_fake_sink(struct drm_device *dev, struct dc_link *link)
7168 {
7169 	struct dc_sink_init_data sink_init_data = { 0 };
7170 	struct dc_sink *sink = NULL;
7171 
7172 	sink_init_data.link = link;
7173 	sink_init_data.sink_signal = link->connector_signal;
7174 
7175 	sink = dc_sink_create(&sink_init_data);
7176 	if (!sink) {
7177 		drm_err(dev, "Failed to create sink!\n");
7178 		return NULL;
7179 	}
7180 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
7181 
7182 	return sink;
7183 }
7184 
7185 static void set_multisync_trigger_params(
7186 		struct dc_stream_state *stream)
7187 {
7188 	struct dc_stream_state *master = NULL;
7189 
7190 	if (stream->triggered_crtc_reset.enabled) {
7191 		master = stream->triggered_crtc_reset.event_source;
7192 		stream->triggered_crtc_reset.event =
7193 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
7194 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
7195 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
7196 	}
7197 }
7198 
7199 static void set_master_stream(struct dc_stream_state *stream_set[],
7200 			      int stream_count)
7201 {
7202 	int j, highest_rfr = 0, master_stream = 0;
7203 
7204 	for (j = 0;  j < stream_count; j++) {
7205 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
7206 			int refresh_rate = 0;
7207 
7208 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
7209 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
7210 			if (refresh_rate > highest_rfr) {
7211 				highest_rfr = refresh_rate;
7212 				master_stream = j;
7213 			}
7214 		}
7215 	}
7216 	for (j = 0;  j < stream_count; j++) {
7217 		if (stream_set[j])
7218 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
7219 	}
7220 }
7221 
7222 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
7223 {
7224 	int i = 0;
7225 	struct dc_stream_state *stream;
7226 
7227 	if (context->stream_count < 2)
7228 		return;
7229 	for (i = 0; i < context->stream_count ; i++) {
7230 		if (!context->streams[i])
7231 			continue;
7232 		/*
7233 		 * TODO: add a function to read AMD VSDB bits and set
7234 		 * crtc_sync_master.multi_sync_enabled flag
7235 		 * For now it's set to false
7236 		 */
7237 	}
7238 
7239 	set_master_stream(context->streams, context->stream_count);
7240 
7241 	for (i = 0; i < context->stream_count ; i++) {
7242 		stream = context->streams[i];
7243 
7244 		if (!stream)
7245 			continue;
7246 
7247 		set_multisync_trigger_params(stream);
7248 	}
7249 }
7250 
7251 /**
7252  * DOC: FreeSync Video
7253  *
7254  * When a userspace application wants to play a video, the content follows a
7255  * standard format definition that usually specifies the FPS for that format.
7256  * The below list illustrates some video format and the expected FPS,
7257  * respectively:
7258  *
7259  * - TV/NTSC (23.976 FPS)
7260  * - Cinema (24 FPS)
7261  * - TV/PAL (25 FPS)
7262  * - TV/NTSC (29.97 FPS)
7263  * - TV/NTSC (30 FPS)
7264  * - Cinema HFR (48 FPS)
7265  * - TV/PAL (50 FPS)
7266  * - Commonly used (60 FPS)
7267  * - Multiples of 24 (48,72,96 FPS)
7268  *
7269  * The list of standards video format is not huge and can be added to the
7270  * connector modeset list beforehand. With that, userspace can leverage
7271  * FreeSync to extends the front porch in order to attain the target refresh
7272  * rate. Such a switch will happen seamlessly, without screen blanking or
7273  * reprogramming of the output in any other way. If the userspace requests a
7274  * modesetting change compatible with FreeSync modes that only differ in the
7275  * refresh rate, DC will skip the full update and avoid blink during the
7276  * transition. For example, the video player can change the modesetting from
7277  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
7278  * causing any display blink. This same concept can be applied to a mode
7279  * setting change.
7280  */
7281 static struct drm_display_mode *
7282 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
7283 		bool use_probed_modes)
7284 {
7285 	struct drm_display_mode *m, *m_pref = NULL;
7286 	u16 current_refresh, highest_refresh;
7287 	struct list_head *list_head = use_probed_modes ?
7288 		&aconnector->base.probed_modes :
7289 		&aconnector->base.modes;
7290 
7291 	if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
7292 		return NULL;
7293 
7294 	if (aconnector->freesync_vid_base.clock != 0)
7295 		return &aconnector->freesync_vid_base;
7296 
7297 	/* Find the preferred mode */
7298 	list_for_each_entry(m, list_head, head) {
7299 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
7300 			m_pref = m;
7301 			break;
7302 		}
7303 	}
7304 
7305 	if (!m_pref) {
7306 		/* Probably an EDID with no preferred mode. Fallback to first entry */
7307 		m_pref = list_first_entry_or_null(
7308 				&aconnector->base.modes, struct drm_display_mode, head);
7309 		if (!m_pref) {
7310 			drm_dbg_driver(aconnector->base.dev, "No preferred mode found in EDID\n");
7311 			return NULL;
7312 		}
7313 	}
7314 
7315 	highest_refresh = drm_mode_vrefresh(m_pref);
7316 
7317 	/*
7318 	 * Find the mode with highest refresh rate with same resolution.
7319 	 * For some monitors, preferred mode is not the mode with highest
7320 	 * supported refresh rate.
7321 	 */
7322 	list_for_each_entry(m, list_head, head) {
7323 		current_refresh  = drm_mode_vrefresh(m);
7324 
7325 		if (m->hdisplay == m_pref->hdisplay &&
7326 		    m->vdisplay == m_pref->vdisplay &&
7327 		    highest_refresh < current_refresh) {
7328 			highest_refresh = current_refresh;
7329 			m_pref = m;
7330 		}
7331 	}
7332 
7333 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
7334 	return m_pref;
7335 }
7336 
7337 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
7338 		struct amdgpu_dm_connector *aconnector)
7339 {
7340 	struct drm_display_mode *high_mode;
7341 	int timing_diff;
7342 
7343 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
7344 	if (!high_mode || !mode)
7345 		return false;
7346 
7347 	timing_diff = high_mode->vtotal - mode->vtotal;
7348 
7349 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
7350 	    high_mode->hdisplay != mode->hdisplay ||
7351 	    high_mode->vdisplay != mode->vdisplay ||
7352 	    high_mode->hsync_start != mode->hsync_start ||
7353 	    high_mode->hsync_end != mode->hsync_end ||
7354 	    high_mode->htotal != mode->htotal ||
7355 	    high_mode->hskew != mode->hskew ||
7356 	    high_mode->vscan != mode->vscan ||
7357 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
7358 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
7359 		return false;
7360 	else
7361 		return true;
7362 }
7363 
7364 #if defined(CONFIG_DRM_AMD_DC_FP)
7365 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
7366 			    struct dc_sink *sink, struct dc_stream_state *stream,
7367 			    struct dsc_dec_dpcd_caps *dsc_caps)
7368 {
7369 	stream->timing.flags.DSC = 0;
7370 	dsc_caps->is_dsc_supported = false;
7371 
7372 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
7373 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
7374 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE)
7375 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7376 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7377 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7378 				dsc_caps);
7379 		else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7380 			if (aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.fields.dsc_support.DSC_PASSTHROUGH_SUPPORT &&
7381 					!aconnector->dsc_settings.dsc_force_disable_passthrough &&
7382 					aconnector->dc_link->dpcd_caps.dongle_caps.dp_hdmi_frl_max_link_bw_in_kbps > 0 &&
7383 					sink->edid_caps.frl_dsc_support &&
7384 					sink->edid_caps.max_frl_rate > 0 &&
7385 					sink->edid_caps.frl_dsc_max_frl_rate > 0)
7386 				dc_dsc_parse_dsc_edid(aconnector->dc_link->ctx->dc, &sink->edid_caps, dsc_caps);
7387 			else
7388 				dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7389 				      aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7390 				      aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7391 				      dsc_caps);
7392 		}
7393 	} else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_HDMI_FRL) {
7394 		if (sink->edid_caps.frl_dsc_support &&
7395 				sink->edid_caps.max_frl_rate > 0 &&
7396 				sink->edid_caps.frl_dsc_max_frl_rate > 0)
7397 			dc_dsc_parse_dsc_edid(aconnector->dc_link->ctx->dc, &sink->edid_caps, dsc_caps);
7398 	}
7399 }
7400 
7401 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
7402 				    struct dc_sink *sink, struct dc_stream_state *stream,
7403 				    struct dsc_dec_dpcd_caps *dsc_caps,
7404 				    uint32_t max_dsc_target_bpp_limit_override)
7405 {
7406 	const struct dc_link_settings *verified_link_cap = NULL;
7407 	u32 link_bw_in_kbps;
7408 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
7409 	struct dc *dc = sink->ctx->dc;
7410 	struct dc_dsc_bw_range bw_range = {0};
7411 	struct dc_dsc_config dsc_cfg = {0};
7412 	struct dc_dsc_config_options dsc_options = {0};
7413 
7414 	dc_dsc_get_default_config_option(dc, &dsc_options);
7415 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7416 
7417 	verified_link_cap = dc_link_get_link_cap(stream->link);
7418 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
7419 	edp_min_bpp_x16 = 8 * 16;
7420 	edp_max_bpp_x16 = 8 * 16;
7421 
7422 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
7423 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
7424 
7425 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
7426 		edp_min_bpp_x16 = edp_max_bpp_x16;
7427 
7428 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
7429 				dc->debug.dsc_min_slice_height_override,
7430 				edp_min_bpp_x16, edp_max_bpp_x16,
7431 				dsc_caps,
7432 				&stream->timing,
7433 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7434 				&bw_range)) {
7435 
7436 		if (bw_range.max_kbps < link_bw_in_kbps) {
7437 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7438 					dsc_caps,
7439 					&dsc_options,
7440 					0,
7441 					&stream->timing,
7442 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7443 					&dsc_cfg)) {
7444 				stream->timing.dsc_cfg = dsc_cfg;
7445 				stream->timing.flags.DSC = 1;
7446 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
7447 			}
7448 			return;
7449 		}
7450 	}
7451 
7452 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7453 				dsc_caps,
7454 				&dsc_options,
7455 				link_bw_in_kbps,
7456 				&stream->timing,
7457 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7458 				&dsc_cfg)) {
7459 		stream->timing.dsc_cfg = dsc_cfg;
7460 		stream->timing.flags.DSC = 1;
7461 	}
7462 }
7463 
7464 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
7465 					struct dc_sink *sink, struct dc_stream_state *stream,
7466 					struct dsc_dec_dpcd_caps *dsc_caps)
7467 {
7468 	struct drm_connector *drm_connector = &aconnector->base;
7469 	u32 link_bandwidth_kbps;
7470 	struct dc *dc = sink->ctx->dc;
7471 	const struct dc_hdmi_frl_link_settings *frl_verified_link_cap = NULL;
7472 	u32 converter_bw_in_kbps;
7473 	u32 sink_bw_in_kbps;
7474 	u32 dsc_sink_bw_in_kbps;
7475 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
7476 	u32 dsc_max_supported_bw_in_kbps;
7477 	u32 max_dsc_target_bpp_limit_override =
7478 		drm_connector->display_info.max_dsc_bpp;
7479 	struct dc_dsc_config_options dsc_options = {0};
7480 
7481 	dc_dsc_get_default_config_option(dc, &dsc_options);
7482 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7483 
7484 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
7485 							dc_link_get_link_cap(aconnector->dc_link));
7486 
7487 	/* Set DSC policy according to dsc_clock_en */
7488 	dc_dsc_policy_set_enable_dsc_when_not_needed(
7489 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
7490 
7491 	if (sink->sink_signal == SIGNAL_TYPE_EDP &&
7492 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
7493 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
7494 
7495 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
7496 
7497 	} else if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
7498 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
7499 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7500 						dsc_caps,
7501 						&dsc_options,
7502 						link_bandwidth_kbps,
7503 						&stream->timing,
7504 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7505 						&stream->timing.dsc_cfg)) {
7506 				stream->timing.flags.DSC = 1;
7507 				drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from SST RX\n",
7508 							__func__, drm_connector->name);
7509 			}
7510 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7511 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
7512 					dc_link_get_highest_encoding_format(aconnector->dc_link));
7513 			converter_bw_in_kbps = aconnector->dc_link->dpcd_caps.dongle_caps.dp_hdmi_frl_max_link_bw_in_kbps;
7514 			sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.max_frl_rate);
7515 			dsc_sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.frl_dsc_max_frl_rate);
7516 
7517 			if (dsc_caps->is_frl) {
7518 				max_supported_bw_in_kbps = min(link_bandwidth_kbps, converter_bw_in_kbps);
7519 				max_supported_bw_in_kbps = min(max_supported_bw_in_kbps, sink_bw_in_kbps);
7520 				dsc_max_supported_bw_in_kbps = min(max_supported_bw_in_kbps, dsc_sink_bw_in_kbps);
7521 			} else {
7522 				max_supported_bw_in_kbps = link_bandwidth_kbps;
7523 				dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
7524 			}
7525 
7526 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
7527 					max_supported_bw_in_kbps > 0 &&
7528 					dsc_max_supported_bw_in_kbps > 0)
7529 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7530 						dsc_caps,
7531 						&dsc_options,
7532 						dsc_max_supported_bw_in_kbps,
7533 						&stream->timing,
7534 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7535 						&stream->timing.dsc_cfg)) {
7536 					stream->timing.flags.DSC = 1;
7537 					drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from %s\n",
7538 							__func__, drm_connector->name,
7539 							(dsc_caps->is_frl == 1) ? "HDMI FRL RX" : "DP-HDMI PCON");
7540 				}
7541 		}
7542 	}
7543 	else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_HDMI_FRL) {
7544 		struct dc_dsc_policy dsc_policy = {0};
7545 
7546 		frl_verified_link_cap = dc_link_get_frl_link_cap(stream->link);
7547 		if (frl_verified_link_cap->frl_link_rate != HDMI_FRL_LINK_RATE_DISABLE &&
7548 			aconnector->dc_link->frl_flags.force_frl_dsc) {
7549 			dc_dsc_policy_set_enable_dsc_when_not_needed(true);
7550 			dc_dsc_get_policy_for_timing(&stream->timing, 0, &dsc_policy, dc_link_get_highest_encoding_format(stream->link));
7551 		}
7552 
7553 		timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing, DC_LINK_ENCODING_HDMI_FRL);
7554 		link_bandwidth_kbps = dc_link_frl_bandwidth_kbps(stream->link, frl_verified_link_cap->frl_link_rate);
7555 		dsc_sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.frl_dsc_max_frl_rate);
7556 
7557 		if ((timing_bw_in_kbps > link_bandwidth_kbps && dsc_sink_bw_in_kbps > 0) ||
7558 		    (dsc_policy.enable_dsc_when_not_needed || dsc_options.force_dsc_when_not_needed)) {
7559 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7560 					dsc_caps,
7561 					&dsc_options,
7562 					dsc_sink_bw_in_kbps,
7563 					&stream->timing,
7564 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7565 					&stream->timing.dsc_cfg)) {
7566 				stream->timing.flags.DSC = 1;
7567 				drm_dbg_driver(drm_connector->dev, "%s: HDMI_FRL_DSC [%s] DSC is selected from HDMI FRL RX\n",
7568 						__func__, drm_connector->name);
7569 			}
7570 		}
7571 	}
7572 
7573 	/* Overwrite the stream flag if DSC is enabled through debugfs */
7574 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
7575 		stream->timing.flags.DSC = 1;
7576 
7577 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
7578 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
7579 
7580 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
7581 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
7582 
7583 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
7584 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
7585 }
7586 #endif
7587 
7588 static struct dc_stream_state *
7589 create_stream_for_sink(struct drm_connector *connector,
7590 		       const struct drm_display_mode *drm_mode,
7591 		       const struct dm_connector_state *dm_state,
7592 		       const struct dc_stream_state *old_stream,
7593 		       int requested_bpc)
7594 {
7595 	struct drm_device *dev = connector->dev;
7596 	struct amdgpu_dm_connector *aconnector = NULL;
7597 	struct drm_display_mode *preferred_mode = NULL;
7598 	const struct drm_connector_state *con_state = &dm_state->base;
7599 	struct dc_stream_state *stream = NULL;
7600 	struct drm_display_mode mode;
7601 	struct drm_display_mode saved_mode;
7602 	struct drm_display_mode *freesync_mode = NULL;
7603 	bool native_mode_found = false;
7604 	bool recalculate_timing = false;
7605 	bool scale = dm_state->scaling != RMX_OFF;
7606 	int mode_refresh;
7607 	int preferred_refresh = 0;
7608 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
7609 #if defined(CONFIG_DRM_AMD_DC_FP)
7610 	struct dsc_dec_dpcd_caps dsc_caps = {0};
7611 #endif
7612 	struct dc_link *link = NULL;
7613 	struct dc_sink *sink = NULL;
7614 
7615 	drm_mode_init(&mode, drm_mode);
7616 	memset(&saved_mode, 0, sizeof(saved_mode));
7617 
7618 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK) {
7619 		aconnector = NULL;
7620 		aconnector = to_amdgpu_dm_connector(connector);
7621 		link = aconnector->dc_link;
7622 	} else {
7623 		struct drm_writeback_connector *wbcon = NULL;
7624 		struct amdgpu_dm_wb_connector *dm_wbcon = NULL;
7625 
7626 		wbcon = drm_connector_to_writeback(connector);
7627 		dm_wbcon = to_amdgpu_dm_wb_connector(wbcon);
7628 		link = dm_wbcon->link;
7629 	}
7630 
7631 	if (!aconnector || !aconnector->dc_sink) {
7632 		sink = create_fake_sink(dev, link);
7633 		if (!sink)
7634 			return stream;
7635 
7636 	} else {
7637 		sink = aconnector->dc_sink;
7638 		dc_sink_retain(sink);
7639 	}
7640 
7641 	stream = dc_create_stream_for_sink(sink);
7642 
7643 	if (stream == NULL) {
7644 		drm_err(dev, "Failed to create stream for sink!\n");
7645 		goto finish;
7646 	}
7647 
7648 	/* We leave this NULL for writeback connectors */
7649 	stream->dm_stream_context = aconnector;
7650 
7651 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
7652 		connector->display_info.hdmi.scdc.scrambling.low_rates;
7653 
7654 	list_for_each_entry(preferred_mode, &connector->modes, head) {
7655 		/* Search for preferred mode */
7656 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
7657 			native_mode_found = true;
7658 			break;
7659 		}
7660 	}
7661 	if (!native_mode_found)
7662 		preferred_mode = list_first_entry_or_null(
7663 				&connector->modes,
7664 				struct drm_display_mode,
7665 				head);
7666 
7667 	mode_refresh = drm_mode_vrefresh(&mode);
7668 
7669 	if (preferred_mode == NULL) {
7670 		/*
7671 		 * This may not be an error, the use case is when we have no
7672 		 * usermode calls to reset and set mode upon hotplug. In this
7673 		 * case, we call set mode ourselves to restore the previous mode
7674 		 * and the modelist may not be filled in time.
7675 		 */
7676 		drm_dbg_driver(dev, "No preferred mode found\n");
7677 	} else if (aconnector) {
7678 		recalculate_timing = amdgpu_freesync_vid_mode &&
7679 				 is_freesync_video_mode(&mode, aconnector);
7680 		if (recalculate_timing) {
7681 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
7682 			drm_mode_copy(&saved_mode, &mode);
7683 			saved_mode.picture_aspect_ratio = mode.picture_aspect_ratio;
7684 			drm_mode_copy(&mode, freesync_mode);
7685 			mode.picture_aspect_ratio = saved_mode.picture_aspect_ratio;
7686 		} else {
7687 			decide_crtc_timing_for_drm_display_mode(
7688 					&mode, preferred_mode, scale);
7689 
7690 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
7691 		}
7692 	}
7693 
7694 	if (recalculate_timing)
7695 		drm_mode_set_crtcinfo(&saved_mode, 0);
7696 
7697 	/*
7698 	 * If scaling is enabled and refresh rate didn't change
7699 	 * we copy the vic and polarities of the old timings
7700 	 */
7701 	if (!scale || mode_refresh != preferred_refresh)
7702 		fill_stream_properties_from_drm_display_mode(
7703 			stream, &mode, connector, con_state, NULL,
7704 			requested_bpc);
7705 	else
7706 		fill_stream_properties_from_drm_display_mode(
7707 			stream, &mode, connector, con_state, old_stream,
7708 			requested_bpc);
7709 
7710 	/* The rest isn't needed for writeback connectors */
7711 	if (!aconnector)
7712 		goto finish;
7713 
7714 	if (aconnector->timing_changed) {
7715 		drm_dbg(aconnector->base.dev,
7716 			"overriding timing for automated test, bpc %d, changing to %d\n",
7717 			stream->timing.display_color_depth,
7718 			aconnector->timing_requested->display_color_depth);
7719 		stream->timing = *aconnector->timing_requested;
7720 	}
7721 
7722 #if defined(CONFIG_DRM_AMD_DC_FP)
7723 	/* SST DSC determination policy */
7724 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
7725 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
7726 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
7727 #endif
7728 
7729 	update_stream_scaling_settings(dev, &mode, dm_state, stream);
7730 
7731 	fill_audio_info(
7732 		&stream->audio_info,
7733 		connector,
7734 		sink);
7735 
7736 	update_stream_signal(stream, sink);
7737 
7738 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7739 	    stream->signal == SIGNAL_TYPE_HDMI_FRL)
7740 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket, false, false);
7741 
7742 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT ||
7743 	    stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
7744 	    stream->signal == SIGNAL_TYPE_EDP) {
7745 		const struct dc_edid_caps *edid_caps;
7746 		unsigned int disable_colorimetry = 0;
7747 
7748 		if (aconnector->dc_sink) {
7749 			edid_caps = &aconnector->dc_sink->edid_caps;
7750 			disable_colorimetry = edid_caps->panel_patch.disable_colorimetry;
7751 		}
7752 
7753 		//
7754 		// should decide stream support vsc sdp colorimetry capability
7755 		// before building vsc info packet
7756 		//
7757 		stream->use_vsc_sdp_for_colorimetry = stream->link->dpcd_caps.dpcd_rev.raw >= 0x14 &&
7758 						      stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED &&
7759 						      !disable_colorimetry;
7760 
7761 		if (stream->out_transfer_func.tf == TRANSFER_FUNCTION_GAMMA22)
7762 			tf = TRANSFER_FUNC_GAMMA_22;
7763 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
7764 		aconnector->sr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
7765 
7766 	}
7767 finish:
7768 	dc_sink_release(sink);
7769 
7770 	return stream;
7771 }
7772 
7773 /**
7774  * amdgpu_dm_connector_poll - Poll a connector to see if it's connected to a display
7775  * @aconnector: DM connector to poll (owns @base drm_connector and @dc_link)
7776  * @force: if true, force polling even when DAC load detection was used
7777  *
7778  * Used for connectors that don't support HPD (hotplug detection) to
7779  * periodically check whether the connector is connected to a display.
7780  *
7781  * When connection was determined via DAC load detection, we avoid
7782  * re-running it on normal polls to prevent visible glitches, unless
7783  * @force is set.
7784  *
7785  * Return: The probed connector status (connected/disconnected/unknown).
7786  */
7787 static enum drm_connector_status
7788 amdgpu_dm_connector_poll(struct amdgpu_dm_connector *aconnector, bool force)
7789 {
7790 	struct drm_connector *connector = &aconnector->base;
7791 	struct drm_device *dev = connector->dev;
7792 	struct amdgpu_device *adev = drm_to_adev(dev);
7793 	struct dc_link *link = aconnector->dc_link;
7794 	enum dc_connection_type conn_type = dc_connection_none;
7795 	enum drm_connector_status status = connector_status_disconnected;
7796 
7797 	/* When we determined the connection using DAC load detection,
7798 	 * do NOT poll the connector do detect disconnect because
7799 	 * that would run DAC load detection again which can cause
7800 	 * visible visual glitches.
7801 	 *
7802 	 * Only allow to poll such a connector again when forcing.
7803 	 */
7804 	if (!force && link->local_sink && link->type == dc_connection_analog_load)
7805 		return connector->status;
7806 
7807 	mutex_lock(&aconnector->hpd_lock);
7808 
7809 	if (dc_link_detect_connection_type(aconnector->dc_link, &conn_type) &&
7810 	    conn_type != dc_connection_none) {
7811 		mutex_lock(&adev->dm.dc_lock);
7812 
7813 		/* Only call full link detection when a sink isn't created yet,
7814 		 * ie. just when the display is plugged in, otherwise we risk flickering.
7815 		 */
7816 		if (link->local_sink ||
7817 			dc_link_detect(link, DETECT_REASON_HPD))
7818 			status = connector_status_connected;
7819 
7820 		mutex_unlock(&adev->dm.dc_lock);
7821 	}
7822 
7823 	if (connector->status != status) {
7824 		if (status == connector_status_disconnected) {
7825 			if (link->local_sink)
7826 				dc_sink_release(link->local_sink);
7827 
7828 			link->local_sink = NULL;
7829 			link->dpcd_sink_count = 0;
7830 			link->type = dc_connection_none;
7831 		}
7832 
7833 		amdgpu_dm_update_connector_after_detect(aconnector);
7834 	}
7835 
7836 	mutex_unlock(&aconnector->hpd_lock);
7837 	return status;
7838 }
7839 
7840 /**
7841  * amdgpu_dm_connector_detect() - Detect whether a DRM connector is connected to a display
7842  *
7843  * A connector is considered connected when it has a sink that is not NULL.
7844  * For connectors that support HPD (hotplug detection), the connection is
7845  * handled in the HPD interrupt.
7846  * For connectors that may not support HPD, such as analog connectors,
7847  * DRM will call this function repeatedly to poll them.
7848  *
7849  * Notes:
7850  * 1. This interface is NOT called in context of HPD irq.
7851  * 2. This interface *is called* in context of user-mode ioctl. Which
7852  *    makes it a bad place for *any* MST-related activity.
7853  *
7854  * @connector: The DRM connector we are checking. We convert it to
7855  *             amdgpu_dm_connector so we can read the DC link and state.
7856  * @force:     If true, do a full detect again. This is used even when
7857  *             a lighter check would normally be used to avoid flicker.
7858  *
7859  * Return: The connector status (connected, disconnected, or unknown).
7860  *
7861  */
7862 static enum drm_connector_status
7863 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
7864 {
7865 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7866 
7867 	update_subconnector_property(aconnector);
7868 
7869 	if (aconnector->base.force == DRM_FORCE_ON ||
7870 		aconnector->base.force == DRM_FORCE_ON_DIGITAL)
7871 		return connector_status_connected;
7872 	else if (aconnector->base.force == DRM_FORCE_OFF)
7873 		return connector_status_disconnected;
7874 
7875 	/* Poll analog connectors and only when either
7876 	 * disconnected or connected to an analog display.
7877 	 */
7878 	if (drm_kms_helper_is_poll_worker() &&
7879 		dc_connector_supports_analog(aconnector->dc_link->link_id.id) &&
7880 		(!aconnector->dc_sink || aconnector->dc_sink->edid_caps.analog))
7881 		return amdgpu_dm_connector_poll(aconnector, force);
7882 
7883 	return (aconnector->dc_sink ? connector_status_connected :
7884 			connector_status_disconnected);
7885 }
7886 
7887 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
7888 					    struct drm_connector_state *connector_state,
7889 					    struct drm_property *property,
7890 					    uint64_t val)
7891 {
7892 	struct drm_device *dev = connector->dev;
7893 	struct amdgpu_device *adev = drm_to_adev(dev);
7894 	struct dm_connector_state *dm_old_state =
7895 		to_dm_connector_state(connector->state);
7896 	struct dm_connector_state *dm_new_state =
7897 		to_dm_connector_state(connector_state);
7898 
7899 	int ret = -EINVAL;
7900 
7901 	if (property == dev->mode_config.scaling_mode_property) {
7902 		enum amdgpu_rmx_type rmx_type;
7903 
7904 		switch (val) {
7905 		case DRM_MODE_SCALE_CENTER:
7906 			rmx_type = RMX_CENTER;
7907 			break;
7908 		case DRM_MODE_SCALE_ASPECT:
7909 			rmx_type = RMX_ASPECT;
7910 			break;
7911 		case DRM_MODE_SCALE_FULLSCREEN:
7912 			rmx_type = RMX_FULL;
7913 			break;
7914 		case DRM_MODE_SCALE_NONE:
7915 		default:
7916 			rmx_type = RMX_OFF;
7917 			break;
7918 		}
7919 
7920 		if (dm_old_state->scaling == rmx_type)
7921 			return 0;
7922 
7923 		dm_new_state->scaling = rmx_type;
7924 		ret = 0;
7925 	} else if (property == adev->mode_info.underscan_hborder_property) {
7926 		dm_new_state->underscan_hborder = val;
7927 		ret = 0;
7928 	} else if (property == adev->mode_info.underscan_vborder_property) {
7929 		dm_new_state->underscan_vborder = val;
7930 		ret = 0;
7931 	} else if (property == adev->mode_info.underscan_property) {
7932 		dm_new_state->underscan_enable = val;
7933 		ret = 0;
7934 	} else if (property == adev->mode_info.abm_level_property) {
7935 		switch (val) {
7936 		case ABM_SYSFS_CONTROL:
7937 			dm_new_state->abm_sysfs_forbidden = false;
7938 			break;
7939 		case ABM_LEVEL_OFF:
7940 			dm_new_state->abm_sysfs_forbidden = true;
7941 			dm_new_state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7942 			break;
7943 		default:
7944 			dm_new_state->abm_sysfs_forbidden = true;
7945 			dm_new_state->abm_level = val;
7946 		}
7947 		ret = 0;
7948 	}
7949 
7950 	return ret;
7951 }
7952 
7953 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
7954 					    const struct drm_connector_state *state,
7955 					    struct drm_property *property,
7956 					    uint64_t *val)
7957 {
7958 	struct drm_device *dev = connector->dev;
7959 	struct amdgpu_device *adev = drm_to_adev(dev);
7960 	struct dm_connector_state *dm_state =
7961 		to_dm_connector_state(state);
7962 	int ret = -EINVAL;
7963 
7964 	if (property == dev->mode_config.scaling_mode_property) {
7965 		switch (dm_state->scaling) {
7966 		case RMX_CENTER:
7967 			*val = DRM_MODE_SCALE_CENTER;
7968 			break;
7969 		case RMX_ASPECT:
7970 			*val = DRM_MODE_SCALE_ASPECT;
7971 			break;
7972 		case RMX_FULL:
7973 			*val = DRM_MODE_SCALE_FULLSCREEN;
7974 			break;
7975 		case RMX_OFF:
7976 		default:
7977 			*val = DRM_MODE_SCALE_NONE;
7978 			break;
7979 		}
7980 		ret = 0;
7981 	} else if (property == adev->mode_info.underscan_hborder_property) {
7982 		*val = dm_state->underscan_hborder;
7983 		ret = 0;
7984 	} else if (property == adev->mode_info.underscan_vborder_property) {
7985 		*val = dm_state->underscan_vborder;
7986 		ret = 0;
7987 	} else if (property == adev->mode_info.underscan_property) {
7988 		*val = dm_state->underscan_enable;
7989 		ret = 0;
7990 	} else if (property == adev->mode_info.abm_level_property) {
7991 		if (!dm_state->abm_sysfs_forbidden)
7992 			*val = ABM_SYSFS_CONTROL;
7993 		else
7994 			*val = (dm_state->abm_level != ABM_LEVEL_IMMEDIATE_DISABLE) ?
7995 				dm_state->abm_level : 0;
7996 		ret = 0;
7997 	}
7998 
7999 	return ret;
8000 }
8001 
8002 /**
8003  * DOC: panel power savings
8004  *
8005  * The display manager allows you to set your desired **panel power savings**
8006  * level (between 0-4, with 0 representing off), e.g. using the following::
8007  *
8008  *   # echo 3 > /sys/class/drm/card0-eDP-1/amdgpu/panel_power_savings
8009  *
8010  * Modifying this value can have implications on color accuracy, so tread
8011  * carefully.
8012  */
8013 
8014 static ssize_t panel_power_savings_show(struct device *device,
8015 					struct device_attribute *attr,
8016 					char *buf)
8017 {
8018 	struct drm_connector *connector = dev_get_drvdata(device);
8019 	struct drm_device *dev = connector->dev;
8020 	u8 val;
8021 
8022 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
8023 	val = to_dm_connector_state(connector->state)->abm_level ==
8024 		ABM_LEVEL_IMMEDIATE_DISABLE ? 0 :
8025 		to_dm_connector_state(connector->state)->abm_level;
8026 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
8027 
8028 	return sysfs_emit(buf, "%u\n", val);
8029 }
8030 
8031 static ssize_t panel_power_savings_store(struct device *device,
8032 					 struct device_attribute *attr,
8033 					 const char *buf, size_t count)
8034 {
8035 	struct drm_connector *connector = dev_get_drvdata(device);
8036 	struct drm_device *dev = connector->dev;
8037 	long val;
8038 	int ret;
8039 
8040 	ret = kstrtol(buf, 0, &val);
8041 
8042 	if (ret)
8043 		return ret;
8044 
8045 	if (val < 0 || val > 4)
8046 		return -EINVAL;
8047 
8048 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
8049 	if (to_dm_connector_state(connector->state)->abm_sysfs_forbidden)
8050 		ret = -EBUSY;
8051 	else
8052 		to_dm_connector_state(connector->state)->abm_level = val ?:
8053 			ABM_LEVEL_IMMEDIATE_DISABLE;
8054 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
8055 
8056 	if (ret)
8057 		return ret;
8058 
8059 	drm_kms_helper_hotplug_event(dev);
8060 
8061 	return count;
8062 }
8063 
8064 static DEVICE_ATTR_RW(panel_power_savings);
8065 
8066 static struct attribute *amdgpu_attrs[] = {
8067 	&dev_attr_panel_power_savings.attr,
8068 	NULL
8069 };
8070 
8071 static const struct attribute_group amdgpu_group = {
8072 	.name = "amdgpu",
8073 	.attrs = amdgpu_attrs
8074 };
8075 
8076 static bool
8077 amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector *amdgpu_dm_connector)
8078 {
8079 	if (amdgpu_dm_abm_level >= 0)
8080 		return false;
8081 
8082 	if (amdgpu_dm_connector->base.connector_type != DRM_MODE_CONNECTOR_eDP)
8083 		return false;
8084 
8085 	/* check for OLED panels */
8086 	if (amdgpu_dm_connector->bl_idx >= 0) {
8087 		struct drm_device *drm = amdgpu_dm_connector->base.dev;
8088 		struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
8089 		struct amdgpu_dm_backlight_caps *caps;
8090 
8091 		caps = &dm->backlight_caps[amdgpu_dm_connector->bl_idx];
8092 		if (caps->aux_support)
8093 			return false;
8094 	}
8095 
8096 	return true;
8097 }
8098 
8099 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
8100 {
8101 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
8102 
8103 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector))
8104 		sysfs_remove_group(&connector->kdev->kobj, &amdgpu_group);
8105 
8106 	cec_notifier_conn_unregister(amdgpu_dm_connector->notifier);
8107 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
8108 }
8109 
8110 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
8111 {
8112 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8113 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8114 	struct amdgpu_display_manager *dm = &adev->dm;
8115 
8116 	/*
8117 	 * Call only if mst_mgr was initialized before since it's not done
8118 	 * for all connector types.
8119 	 */
8120 	if (aconnector->mst_mgr.dev)
8121 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
8122 
8123 	/* Cancel and flush any pending HDMI HPD debounce work */
8124 	if (aconnector->hdmi_hpd_debounce_delay_ms) {
8125 		cancel_delayed_work_sync(&aconnector->hdmi_hpd_debounce_work);
8126 		if (aconnector->hdmi_prev_sink) {
8127 			dc_sink_release(aconnector->hdmi_prev_sink);
8128 			aconnector->hdmi_prev_sink = NULL;
8129 		}
8130 	}
8131 
8132 	if (aconnector->bl_idx != -1) {
8133 		backlight_device_unregister(dm->backlight_dev[aconnector->bl_idx]);
8134 		dm->backlight_dev[aconnector->bl_idx] = NULL;
8135 	}
8136 
8137 	if (aconnector->dc_em_sink)
8138 		dc_sink_release(aconnector->dc_em_sink);
8139 	aconnector->dc_em_sink = NULL;
8140 	if (aconnector->dc_sink)
8141 		dc_sink_release(aconnector->dc_sink);
8142 	aconnector->dc_sink = NULL;
8143 
8144 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
8145 	drm_connector_unregister(connector);
8146 	drm_connector_cleanup(connector);
8147 	kfree(aconnector->dm_dp_aux.aux.name);
8148 
8149 	kfree(connector);
8150 }
8151 
8152 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
8153 {
8154 	struct dm_connector_state *state =
8155 		to_dm_connector_state(connector->state);
8156 
8157 	if (connector->state)
8158 		__drm_atomic_helper_connector_destroy_state(connector->state);
8159 
8160 	kfree(state);
8161 
8162 	state = kzalloc_obj(*state);
8163 
8164 	if (state) {
8165 		state->scaling = RMX_OFF;
8166 		state->underscan_enable = false;
8167 		state->underscan_hborder = 0;
8168 		state->underscan_vborder = 0;
8169 		state->base.max_requested_bpc = 8;
8170 		state->vcpi_slots = 0;
8171 		state->pbn = 0;
8172 
8173 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) {
8174 			if (amdgpu_dm_abm_level <= 0)
8175 				state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
8176 			else
8177 				state->abm_level = amdgpu_dm_abm_level;
8178 		}
8179 
8180 		__drm_atomic_helper_connector_reset(connector, &state->base);
8181 	}
8182 }
8183 
8184 struct drm_connector_state *
8185 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
8186 {
8187 	struct dm_connector_state *state =
8188 		to_dm_connector_state(connector->state);
8189 
8190 	struct dm_connector_state *new_state =
8191 			kmemdup(state, sizeof(*state), GFP_KERNEL);
8192 
8193 	if (!new_state)
8194 		return NULL;
8195 
8196 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
8197 
8198 	new_state->freesync_capable = state->freesync_capable;
8199 	new_state->abm_level = state->abm_level;
8200 	new_state->scaling = state->scaling;
8201 	new_state->underscan_enable = state->underscan_enable;
8202 	new_state->underscan_hborder = state->underscan_hborder;
8203 	new_state->underscan_vborder = state->underscan_vborder;
8204 	new_state->vcpi_slots = state->vcpi_slots;
8205 	new_state->pbn = state->pbn;
8206 	return &new_state->base;
8207 }
8208 
8209 static int
8210 amdgpu_dm_connector_late_register(struct drm_connector *connector)
8211 {
8212 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8213 		to_amdgpu_dm_connector(connector);
8214 	int r;
8215 
8216 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector)) {
8217 		r = sysfs_create_group(&connector->kdev->kobj,
8218 				       &amdgpu_group);
8219 		if (r)
8220 			return r;
8221 	}
8222 
8223 	amdgpu_dm_register_backlight_device(amdgpu_dm_connector);
8224 
8225 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
8226 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
8227 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
8228 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
8229 		if (r)
8230 			return r;
8231 	}
8232 
8233 #if defined(CONFIG_DEBUG_FS)
8234 	connector_debugfs_init(amdgpu_dm_connector);
8235 #endif
8236 
8237 	return 0;
8238 }
8239 
8240 static void amdgpu_dm_connector_funcs_force(struct drm_connector *connector)
8241 {
8242 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8243 	struct dc_link *dc_link = aconnector->dc_link;
8244 	struct dc_sink *dc_em_sink = aconnector->dc_em_sink;
8245 	const struct drm_edid *drm_edid;
8246 	struct i2c_adapter *ddc;
8247 	struct drm_device *dev = connector->dev;
8248 
8249 	if (dc_link && dc_link->aux_mode)
8250 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8251 	else
8252 		ddc = &aconnector->i2c->base;
8253 
8254 	drm_edid = drm_edid_read_ddc(connector, ddc);
8255 	drm_edid_connector_update(connector, drm_edid);
8256 	if (!drm_edid) {
8257 		drm_err(dev, "No EDID found on connector: %s.\n", connector->name);
8258 		return;
8259 	}
8260 
8261 	aconnector->drm_edid = drm_edid;
8262 	/* Update emulated (virtual) sink's EDID */
8263 	if (dc_em_sink && dc_link) {
8264 		// FIXME: Get rid of drm_edid_raw()
8265 		const struct edid *edid = drm_edid_raw(drm_edid);
8266 
8267 		memset(&dc_em_sink->edid_caps, 0, sizeof(struct dc_edid_caps));
8268 		memmove(dc_em_sink->dc_edid.raw_edid, edid,
8269 			(edid->extensions + 1) * EDID_LENGTH);
8270 		dm_helpers_parse_edid_caps(
8271 			dc_link,
8272 			&dc_em_sink->dc_edid,
8273 			&dc_em_sink->edid_caps);
8274 	}
8275 }
8276 
8277 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
8278 	.reset = amdgpu_dm_connector_funcs_reset,
8279 	.detect = amdgpu_dm_connector_detect,
8280 	.fill_modes = drm_helper_probe_single_connector_modes,
8281 	.destroy = amdgpu_dm_connector_destroy,
8282 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
8283 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
8284 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
8285 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
8286 	.late_register = amdgpu_dm_connector_late_register,
8287 	.early_unregister = amdgpu_dm_connector_unregister,
8288 	.force = amdgpu_dm_connector_funcs_force
8289 };
8290 
8291 static int get_modes(struct drm_connector *connector)
8292 {
8293 	return amdgpu_dm_connector_get_modes(connector);
8294 }
8295 
8296 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
8297 {
8298 	struct drm_connector *connector = &aconnector->base;
8299 	struct dc_link *dc_link = aconnector->dc_link;
8300 	struct dc_sink_init_data init_params = {
8301 			.link = aconnector->dc_link,
8302 			.sink_signal = SIGNAL_TYPE_VIRTUAL
8303 	};
8304 	const struct drm_edid *drm_edid;
8305 	const struct edid *edid;
8306 	struct i2c_adapter *ddc;
8307 
8308 	if (dc_link && dc_link->aux_mode)
8309 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8310 	else
8311 		ddc = &aconnector->i2c->base;
8312 
8313 	drm_edid = drm_edid_read_ddc(connector, ddc);
8314 	drm_edid_connector_update(connector, drm_edid);
8315 	if (!drm_edid) {
8316 		drm_err(connector->dev, "No EDID found on connector: %s.\n", connector->name);
8317 		return;
8318 	}
8319 
8320 	if (connector->display_info.is_hdmi)
8321 		init_params.sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
8322 
8323 	aconnector->drm_edid = drm_edid;
8324 
8325 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
8326 	aconnector->dc_em_sink = dc_link_add_remote_sink(
8327 		aconnector->dc_link,
8328 		(uint8_t *)edid,
8329 		(edid->extensions + 1) * EDID_LENGTH,
8330 		&init_params);
8331 
8332 	if (aconnector->base.force == DRM_FORCE_ON) {
8333 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
8334 		aconnector->dc_link->local_sink :
8335 		aconnector->dc_em_sink;
8336 		if (aconnector->dc_sink)
8337 			dc_sink_retain(aconnector->dc_sink);
8338 	}
8339 }
8340 
8341 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
8342 {
8343 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
8344 
8345 	/*
8346 	 * In case of headless boot with force on for DP managed connector
8347 	 * Those settings have to be != 0 to get initial modeset
8348 	 */
8349 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
8350 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
8351 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
8352 	}
8353 
8354 	create_eml_sink(aconnector);
8355 }
8356 
8357 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
8358 						struct dc_stream_state *stream)
8359 {
8360 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
8361 	struct dc_plane_state *dc_plane_state = NULL;
8362 	struct dc_state *dc_state = NULL;
8363 
8364 	if (!stream)
8365 		goto cleanup;
8366 
8367 	dc_plane_state = dc_create_plane_state(dc);
8368 	if (!dc_plane_state)
8369 		goto cleanup;
8370 
8371 	dc_state = dc_state_create(dc, NULL);
8372 	if (!dc_state)
8373 		goto cleanup;
8374 
8375 	/* populate stream to plane */
8376 	dc_plane_state->src_rect.height  = stream->src.height;
8377 	dc_plane_state->src_rect.width   = stream->src.width;
8378 	dc_plane_state->dst_rect.height  = stream->src.height;
8379 	dc_plane_state->dst_rect.width   = stream->src.width;
8380 	dc_plane_state->clip_rect.height = stream->src.height;
8381 	dc_plane_state->clip_rect.width  = stream->src.width;
8382 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
8383 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
8384 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
8385 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
8386 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
8387 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
8388 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
8389 	dc_plane_state->rotation = ROTATION_ANGLE_0;
8390 	dc_plane_state->is_tiling_rotated = false;
8391 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
8392 
8393 	dc_result = dc_validate_stream(dc, stream);
8394 	if (dc_result == DC_OK)
8395 		dc_result = dc_validate_plane(dc, dc_plane_state);
8396 
8397 	if (dc_result == DC_OK)
8398 		dc_result = dc_state_add_stream(dc, dc_state, stream);
8399 
8400 	if (dc_result == DC_OK && !dc_state_add_plane(
8401 						dc,
8402 						stream,
8403 						dc_plane_state,
8404 						dc_state))
8405 		dc_result = DC_FAIL_ATTACH_SURFACES;
8406 
8407 	if (dc_result == DC_OK)
8408 		dc_result = dc_validate_global_state(dc, dc_state, DC_VALIDATE_MODE_ONLY);
8409 
8410 cleanup:
8411 	if (dc_state)
8412 		dc_state_release(dc_state);
8413 
8414 	if (dc_plane_state)
8415 		dc_plane_state_release(dc_plane_state);
8416 
8417 	return dc_result;
8418 }
8419 
8420 struct dc_stream_state *
8421 create_validate_stream_for_sink(struct drm_connector *connector,
8422 				const struct drm_display_mode *drm_mode,
8423 				const struct dm_connector_state *dm_state,
8424 				const struct dc_stream_state *old_stream)
8425 {
8426 	struct amdgpu_dm_connector *aconnector = NULL;
8427 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8428 	struct dc_stream_state *stream;
8429 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
8430 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
8431 	enum dc_status dc_result = DC_OK;
8432 	uint8_t bpc_limit = 6;
8433 
8434 	if (!dm_state)
8435 		return NULL;
8436 
8437 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
8438 		aconnector = to_amdgpu_dm_connector(connector);
8439 
8440 	if (aconnector &&
8441 	    (aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
8442 	     aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_FRL ||
8443 	     aconnector->dc_link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER))
8444 		bpc_limit = 8;
8445 
8446 	do {
8447 		drm_dbg_kms(connector->dev, "Trying with %d bpc\n", requested_bpc);
8448 		stream = create_stream_for_sink(connector, drm_mode,
8449 						dm_state, old_stream,
8450 						requested_bpc);
8451 		if (stream == NULL) {
8452 			drm_err(adev_to_drm(adev), "Failed to create stream for sink!\n");
8453 			break;
8454 		}
8455 
8456 		dc_result = dc_validate_stream(adev->dm.dc, stream);
8457 
8458 		if (!aconnector) /* writeback connector */
8459 			return stream;
8460 
8461 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
8462 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
8463 
8464 		if (dc_result == DC_OK)
8465 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
8466 
8467 		if (dc_result != DC_OK) {
8468 			drm_dbg_kms(connector->dev, "Pruned mode %d x %d (clk %d) %s %s -- %s\n",
8469 				      drm_mode->hdisplay,
8470 				      drm_mode->vdisplay,
8471 				      drm_mode->clock,
8472 				      dc_pixel_encoding_to_str(stream->timing.pixel_encoding),
8473 				      dc_color_depth_to_str(stream->timing.display_color_depth),
8474 				      dc_status_to_str(dc_result));
8475 
8476 			dc_stream_release(stream);
8477 			stream = NULL;
8478 			requested_bpc -= 2; /* lower bpc to retry validation */
8479 		}
8480 
8481 	} while (stream == NULL && requested_bpc >= bpc_limit);
8482 
8483 	switch (dc_result) {
8484 	/*
8485 	 * If we failed to validate DP bandwidth stream with the requested RGB color depth,
8486 	 * we try to fallback and configure in order:
8487 	 * YUV422 (8bpc, 6bpc)
8488 	 * YUV420 (8bpc, 6bpc)
8489 	 */
8490 	case DC_FAIL_ENC_VALIDATE:
8491 	case DC_EXCEED_DONGLE_CAP:
8492 	case DC_NO_DP_LINK_BANDWIDTH:
8493 		/* recursively entered twice and already tried both YUV422 and YUV420 */
8494 		if (aconnector->force_yuv422_output && aconnector->force_yuv420_output)
8495 			break;
8496 		/* first failure; try YUV422 */
8497 		if (!aconnector->force_yuv422_output) {
8498 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV422\n",
8499 				    __func__, __LINE__, dc_result);
8500 			aconnector->force_yuv422_output = true;
8501 		/* recursively entered and YUV422 failed, try YUV420 */
8502 		} else if (!aconnector->force_yuv420_output) {
8503 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV420\n",
8504 				    __func__, __LINE__, dc_result);
8505 			aconnector->force_yuv420_output = true;
8506 		}
8507 		stream = create_validate_stream_for_sink(connector, drm_mode,
8508 							 dm_state, old_stream);
8509 		aconnector->force_yuv422_output = false;
8510 		aconnector->force_yuv420_output = false;
8511 		break;
8512 	case DC_OK:
8513 		break;
8514 	default:
8515 		drm_dbg_kms(connector->dev, "%s:%d Unhandled validation failure %d\n",
8516 			    __func__, __LINE__, dc_result);
8517 		break;
8518 	}
8519 
8520 	return stream;
8521 }
8522 
8523 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
8524 				   const struct drm_display_mode *mode)
8525 {
8526 	int result = MODE_ERROR;
8527 	struct dc_sink *dc_sink;
8528 	struct drm_display_mode *test_mode;
8529 	/* TODO: Unhardcode stream count */
8530 	struct dc_stream_state *stream;
8531 	/* we always have an amdgpu_dm_connector here since we got
8532 	 * here via the amdgpu_dm_connector_helper_funcs
8533 	 */
8534 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8535 
8536 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
8537 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
8538 		return result;
8539 
8540 	/*
8541 	 * Only run this the first time mode_valid is called to initilialize
8542 	 * EDID mgmt
8543 	 */
8544 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
8545 		!aconnector->dc_em_sink)
8546 		handle_edid_mgmt(aconnector);
8547 
8548 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
8549 
8550 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
8551 				aconnector->base.force != DRM_FORCE_ON) {
8552 		drm_err(connector->dev, "dc_sink is NULL!\n");
8553 		goto fail;
8554 	}
8555 
8556 	test_mode = drm_mode_duplicate(connector->dev, mode);
8557 	if (!test_mode)
8558 		goto fail;
8559 
8560 	drm_mode_set_crtcinfo(test_mode, 0);
8561 
8562 	stream = create_validate_stream_for_sink(connector, test_mode,
8563 						 to_dm_connector_state(connector->state),
8564 						 NULL);
8565 	drm_mode_destroy(connector->dev, test_mode);
8566 	if (stream) {
8567 		dc_stream_release(stream);
8568 		result = MODE_OK;
8569 	}
8570 
8571 fail:
8572 	/* TODO: error handling*/
8573 	return result;
8574 }
8575 
8576 static int fill_hdr_info_packet(const struct drm_connector_state *state,
8577 				struct dc_info_packet *out)
8578 {
8579 	struct hdmi_drm_infoframe frame;
8580 	unsigned char buf[30]; /* 26 + 4 */
8581 	ssize_t len;
8582 	int ret, i;
8583 
8584 	memset(out, 0, sizeof(*out));
8585 
8586 	if (!state->hdr_output_metadata)
8587 		return 0;
8588 
8589 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
8590 	if (ret)
8591 		return ret;
8592 
8593 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
8594 	if (len < 0)
8595 		return (int)len;
8596 
8597 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
8598 	if (len != 30)
8599 		return -EINVAL;
8600 
8601 	/* Prepare the infopacket for DC. */
8602 	switch (state->connector->connector_type) {
8603 	case DRM_MODE_CONNECTOR_HDMIA:
8604 		out->hb0 = 0x87; /* type */
8605 		out->hb1 = 0x01; /* version */
8606 		out->hb2 = 0x1A; /* length */
8607 		out->sb[0] = buf[3]; /* checksum */
8608 		i = 1;
8609 		break;
8610 
8611 	case DRM_MODE_CONNECTOR_DisplayPort:
8612 	case DRM_MODE_CONNECTOR_eDP:
8613 		out->hb0 = 0x00; /* sdp id, zero */
8614 		out->hb1 = 0x87; /* type */
8615 		out->hb2 = 0x1D; /* payload len - 1 */
8616 		out->hb3 = (0x13 << 2); /* sdp version */
8617 		out->sb[0] = 0x01; /* version */
8618 		out->sb[1] = 0x1A; /* length */
8619 		i = 2;
8620 		break;
8621 
8622 	default:
8623 		return -EINVAL;
8624 	}
8625 
8626 	memcpy(&out->sb[i], &buf[4], 26);
8627 	out->valid = true;
8628 
8629 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
8630 		       sizeof(out->sb), false);
8631 
8632 	return 0;
8633 }
8634 
8635 static int
8636 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
8637 				 struct drm_atomic_commit *state)
8638 {
8639 	struct drm_connector_state *new_con_state =
8640 		drm_atomic_get_new_connector_state(state, conn);
8641 	struct drm_connector_state *old_con_state =
8642 		drm_atomic_get_old_connector_state(state, conn);
8643 	struct drm_crtc *crtc = new_con_state->crtc;
8644 	struct drm_crtc_state *new_crtc_state;
8645 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
8646 	int ret;
8647 
8648 	if (WARN_ON(unlikely(!old_con_state || !new_con_state)))
8649 		return -EINVAL;
8650 
8651 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
8652 
8653 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
8654 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
8655 		if (ret < 0)
8656 			return ret;
8657 	}
8658 
8659 	if (!crtc)
8660 		return 0;
8661 
8662 	if (new_con_state->privacy_screen_sw_state != old_con_state->privacy_screen_sw_state) {
8663 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8664 		if (IS_ERR(new_crtc_state))
8665 			return PTR_ERR(new_crtc_state);
8666 
8667 		new_crtc_state->mode_changed = true;
8668 	}
8669 
8670 	if (new_con_state->colorspace != old_con_state->colorspace) {
8671 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8672 		if (IS_ERR(new_crtc_state))
8673 			return PTR_ERR(new_crtc_state);
8674 
8675 		new_crtc_state->mode_changed = true;
8676 	}
8677 
8678 	if (new_con_state->content_type != old_con_state->content_type) {
8679 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8680 		if (IS_ERR(new_crtc_state))
8681 			return PTR_ERR(new_crtc_state);
8682 
8683 		new_crtc_state->mode_changed = true;
8684 	}
8685 
8686 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
8687 		struct dc_info_packet hdr_infopacket;
8688 
8689 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
8690 		if (ret)
8691 			return ret;
8692 
8693 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8694 		if (IS_ERR(new_crtc_state))
8695 			return PTR_ERR(new_crtc_state);
8696 
8697 		/*
8698 		 * DC considers the stream backends changed if the
8699 		 * static metadata changes. Forcing the modeset also
8700 		 * gives a simple way for userspace to switch from
8701 		 * 8bpc to 10bpc when setting the metadata to enter
8702 		 * or exit HDR.
8703 		 *
8704 		 * Changing the static metadata after it's been
8705 		 * set is permissible, however. So only force a
8706 		 * modeset if we're entering or exiting HDR.
8707 		 */
8708 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
8709 			!old_con_state->hdr_output_metadata ||
8710 			!new_con_state->hdr_output_metadata;
8711 	}
8712 
8713 	return 0;
8714 }
8715 
8716 static const struct drm_connector_helper_funcs
8717 amdgpu_dm_connector_helper_funcs = {
8718 	/*
8719 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
8720 	 * modes will be filtered by drm_mode_validate_size(), and those modes
8721 	 * are missing after user start lightdm. So we need to renew modes list.
8722 	 * in get_modes call back, not just return the modes count
8723 	 */
8724 	.get_modes = get_modes,
8725 	.mode_valid = amdgpu_dm_connector_mode_valid,
8726 	.atomic_check = amdgpu_dm_connector_atomic_check,
8727 };
8728 
8729 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
8730 {
8731 
8732 }
8733 
8734 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
8735 {
8736 	switch (display_color_depth) {
8737 	case COLOR_DEPTH_666:
8738 		return 6;
8739 	case COLOR_DEPTH_888:
8740 		return 8;
8741 	case COLOR_DEPTH_101010:
8742 		return 10;
8743 	case COLOR_DEPTH_121212:
8744 		return 12;
8745 	case COLOR_DEPTH_141414:
8746 		return 14;
8747 	case COLOR_DEPTH_161616:
8748 		return 16;
8749 	default:
8750 		break;
8751 	}
8752 	return 0;
8753 }
8754 
8755 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
8756 					  struct drm_crtc_state *crtc_state,
8757 					  struct drm_connector_state *conn_state)
8758 {
8759 	struct drm_atomic_commit *state = crtc_state->state;
8760 	struct drm_connector *connector = conn_state->connector;
8761 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8762 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
8763 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
8764 	struct drm_dp_mst_topology_mgr *mst_mgr;
8765 	struct drm_dp_mst_port *mst_port;
8766 	struct drm_dp_mst_topology_state *mst_state;
8767 	enum dc_color_depth color_depth;
8768 	int clock, bpp = 0;
8769 	bool is_y420 = false;
8770 
8771 	if ((connector->connector_type == DRM_MODE_CONNECTOR_eDP) ||
8772 	    (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)) {
8773 		struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8774 		struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8775 		enum drm_mode_status result;
8776 
8777 		result = drm_crtc_helper_mode_valid_fixed(encoder->crtc, adjusted_mode, native_mode);
8778 		if (result != MODE_OK && dm_new_connector_state->scaling == RMX_OFF) {
8779 			drm_dbg_driver(encoder->dev,
8780 				       "mode %dx%d@%dHz is not native, enabling scaling\n",
8781 				       adjusted_mode->hdisplay, adjusted_mode->vdisplay,
8782 				       drm_mode_vrefresh(adjusted_mode));
8783 			dm_new_connector_state->scaling = RMX_ASPECT;
8784 		}
8785 		return 0;
8786 	}
8787 
8788 	if (!aconnector->mst_output_port)
8789 		return 0;
8790 
8791 	mst_port = aconnector->mst_output_port;
8792 	mst_mgr = &aconnector->mst_root->mst_mgr;
8793 
8794 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
8795 		return 0;
8796 
8797 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
8798 	if (IS_ERR(mst_state))
8799 		return PTR_ERR(mst_state);
8800 
8801 	mst_state->pbn_div.full = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
8802 
8803 	if (!state->duplicated) {
8804 		int max_bpc = conn_state->max_requested_bpc;
8805 
8806 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
8807 			  aconnector->force_yuv420_output;
8808 		color_depth = convert_color_depth_from_display_info(connector,
8809 								    is_y420,
8810 								    max_bpc);
8811 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
8812 		clock = adjusted_mode->clock;
8813 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
8814 	}
8815 
8816 	dm_new_connector_state->vcpi_slots =
8817 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
8818 					      dm_new_connector_state->pbn);
8819 	if (dm_new_connector_state->vcpi_slots < 0) {
8820 		drm_dbg_atomic(connector->dev, "failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
8821 		return dm_new_connector_state->vcpi_slots;
8822 	}
8823 	return 0;
8824 }
8825 
8826 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
8827 	.disable = dm_encoder_helper_disable,
8828 	.atomic_check = dm_encoder_helper_atomic_check
8829 };
8830 
8831 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_commit *state,
8832 					    struct dc_state *dc_state,
8833 					    struct dsc_mst_fairness_vars *vars)
8834 {
8835 	struct dc_stream_state *stream = NULL;
8836 	struct drm_connector *connector;
8837 	struct drm_connector_state *new_con_state;
8838 	struct amdgpu_dm_connector *aconnector;
8839 	struct dm_connector_state *dm_conn_state;
8840 	int i, j, ret;
8841 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
8842 
8843 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8844 
8845 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
8846 			continue;
8847 
8848 		aconnector = to_amdgpu_dm_connector(connector);
8849 
8850 		if (!aconnector->mst_output_port)
8851 			continue;
8852 
8853 		if (!new_con_state || !new_con_state->crtc)
8854 			continue;
8855 
8856 		dm_conn_state = to_dm_connector_state(new_con_state);
8857 
8858 		for (j = 0; j < dc_state->stream_count; j++) {
8859 			stream = dc_state->streams[j];
8860 			if (!stream)
8861 				continue;
8862 
8863 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
8864 				break;
8865 
8866 			stream = NULL;
8867 		}
8868 
8869 		if (!stream)
8870 			continue;
8871 
8872 		pbn_div = dm_mst_get_pbn_divider(stream->link);
8873 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
8874 		for (j = 0; j < dc_state->stream_count; j++) {
8875 			if (vars[j].aconnector == aconnector) {
8876 				pbn = vars[j].pbn;
8877 				break;
8878 			}
8879 		}
8880 
8881 		if (j == dc_state->stream_count || pbn_div == 0)
8882 			continue;
8883 
8884 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
8885 
8886 		if (stream->timing.flags.DSC != 1) {
8887 			dm_conn_state->pbn = pbn;
8888 			dm_conn_state->vcpi_slots = slot_num;
8889 
8890 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
8891 							   dm_conn_state->pbn, false);
8892 			if (ret < 0)
8893 				return ret;
8894 
8895 			continue;
8896 		}
8897 
8898 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
8899 		if (vcpi < 0)
8900 			return vcpi;
8901 
8902 		dm_conn_state->pbn = pbn;
8903 		dm_conn_state->vcpi_slots = vcpi;
8904 	}
8905 	return 0;
8906 }
8907 
8908 static int to_drm_connector_type(enum signal_type st, uint32_t connector_id)
8909 {
8910 	switch (st) {
8911 	case SIGNAL_TYPE_HDMI_TYPE_A:
8912 		return DRM_MODE_CONNECTOR_HDMIA;
8913 	case SIGNAL_TYPE_EDP:
8914 		return DRM_MODE_CONNECTOR_eDP;
8915 	case SIGNAL_TYPE_LVDS:
8916 		return DRM_MODE_CONNECTOR_LVDS;
8917 	case SIGNAL_TYPE_RGB:
8918 		return DRM_MODE_CONNECTOR_VGA;
8919 	case SIGNAL_TYPE_DISPLAY_PORT:
8920 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
8921 		/* External DP bridges have a different connector type. */
8922 		if (connector_id == CONNECTOR_ID_VGA)
8923 			return DRM_MODE_CONNECTOR_VGA;
8924 		else if (connector_id == CONNECTOR_ID_LVDS)
8925 			return DRM_MODE_CONNECTOR_LVDS;
8926 
8927 		return DRM_MODE_CONNECTOR_DisplayPort;
8928 	case SIGNAL_TYPE_DVI_DUAL_LINK:
8929 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
8930 		if (connector_id == CONNECTOR_ID_SINGLE_LINK_DVII ||
8931 			connector_id == CONNECTOR_ID_DUAL_LINK_DVII)
8932 			return DRM_MODE_CONNECTOR_DVII;
8933 
8934 		return DRM_MODE_CONNECTOR_DVID;
8935 	case SIGNAL_TYPE_VIRTUAL:
8936 		return DRM_MODE_CONNECTOR_VIRTUAL;
8937 
8938 	default:
8939 		return DRM_MODE_CONNECTOR_Unknown;
8940 	}
8941 }
8942 
8943 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
8944 {
8945 	struct drm_encoder *encoder;
8946 
8947 	/* There is only one encoder per connector */
8948 	drm_connector_for_each_possible_encoder(connector, encoder)
8949 		return encoder;
8950 
8951 	return NULL;
8952 }
8953 
8954 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
8955 {
8956 	struct drm_encoder *encoder;
8957 	struct amdgpu_encoder *amdgpu_encoder;
8958 
8959 	encoder = amdgpu_dm_connector_to_encoder(connector);
8960 
8961 	if (encoder == NULL)
8962 		return;
8963 
8964 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8965 
8966 	amdgpu_encoder->native_mode.clock = 0;
8967 
8968 	if (!list_empty(&connector->probed_modes)) {
8969 		struct drm_display_mode *preferred_mode = NULL;
8970 
8971 		list_for_each_entry(preferred_mode,
8972 				    &connector->probed_modes,
8973 				    head) {
8974 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
8975 				amdgpu_encoder->native_mode = *preferred_mode;
8976 
8977 			break;
8978 		}
8979 
8980 	}
8981 }
8982 
8983 static struct drm_display_mode *
8984 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
8985 			     const char *name,
8986 			     int hdisplay, int vdisplay)
8987 {
8988 	struct drm_device *dev = encoder->dev;
8989 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8990 	struct drm_display_mode *mode = NULL;
8991 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8992 
8993 	mode = drm_mode_duplicate(dev, native_mode);
8994 
8995 	if (mode == NULL)
8996 		return NULL;
8997 
8998 	mode->hdisplay = hdisplay;
8999 	mode->vdisplay = vdisplay;
9000 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
9001 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
9002 
9003 	return mode;
9004 
9005 }
9006 
9007 static const struct amdgpu_dm_mode_size {
9008 	char name[DRM_DISPLAY_MODE_LEN];
9009 	int w;
9010 	int h;
9011 } common_modes[] = {
9012 	{  "640x480",  640,  480},
9013 	{  "800x600",  800,  600},
9014 	{ "1024x768", 1024,  768},
9015 	{ "1280x720", 1280,  720},
9016 	{ "1280x800", 1280,  800},
9017 	{"1280x1024", 1280, 1024},
9018 	{ "1440x900", 1440,  900},
9019 	{"1680x1050", 1680, 1050},
9020 	{"1600x1200", 1600, 1200},
9021 	{"1920x1080", 1920, 1080},
9022 	{"1920x1200", 1920, 1200}
9023 };
9024 
9025 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
9026 						 struct drm_connector *connector)
9027 {
9028 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
9029 	struct drm_display_mode *mode = NULL;
9030 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
9031 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9032 				to_amdgpu_dm_connector(connector);
9033 	int i;
9034 	int n;
9035 
9036 	if ((connector->connector_type != DRM_MODE_CONNECTOR_eDP) &&
9037 	    (connector->connector_type != DRM_MODE_CONNECTOR_LVDS))
9038 		return;
9039 
9040 	n = ARRAY_SIZE(common_modes);
9041 
9042 	for (i = 0; i < n; i++) {
9043 		struct drm_display_mode *curmode = NULL;
9044 		bool mode_existed = false;
9045 
9046 		if (common_modes[i].w > native_mode->hdisplay ||
9047 		    common_modes[i].h > native_mode->vdisplay ||
9048 		   (common_modes[i].w == native_mode->hdisplay &&
9049 		    common_modes[i].h == native_mode->vdisplay))
9050 			continue;
9051 
9052 		list_for_each_entry(curmode, &connector->probed_modes, head) {
9053 			if (common_modes[i].w == curmode->hdisplay &&
9054 			    common_modes[i].h == curmode->vdisplay) {
9055 				mode_existed = true;
9056 				break;
9057 			}
9058 		}
9059 
9060 		if (mode_existed)
9061 			continue;
9062 
9063 		mode = amdgpu_dm_create_common_mode(encoder,
9064 				common_modes[i].name, common_modes[i].w,
9065 				common_modes[i].h);
9066 		if (!mode)
9067 			continue;
9068 
9069 		drm_mode_probed_add(connector, mode);
9070 		amdgpu_dm_connector->num_modes++;
9071 	}
9072 }
9073 
9074 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
9075 {
9076 	struct drm_encoder *encoder;
9077 	struct amdgpu_encoder *amdgpu_encoder;
9078 	const struct drm_display_mode *native_mode;
9079 
9080 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
9081 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
9082 		return;
9083 
9084 	mutex_lock(&connector->dev->mode_config.mutex);
9085 	amdgpu_dm_connector_get_modes(connector);
9086 	mutex_unlock(&connector->dev->mode_config.mutex);
9087 
9088 	encoder = amdgpu_dm_connector_to_encoder(connector);
9089 	if (!encoder)
9090 		return;
9091 
9092 	amdgpu_encoder = to_amdgpu_encoder(encoder);
9093 
9094 	native_mode = &amdgpu_encoder->native_mode;
9095 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
9096 		return;
9097 
9098 	drm_connector_set_panel_orientation_with_quirk(connector,
9099 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
9100 						       native_mode->hdisplay,
9101 						       native_mode->vdisplay);
9102 }
9103 
9104 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
9105 					      const struct drm_edid *drm_edid)
9106 {
9107 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9108 			to_amdgpu_dm_connector(connector);
9109 
9110 	if (drm_edid) {
9111 		/* empty probed_modes */
9112 		INIT_LIST_HEAD(&connector->probed_modes);
9113 		amdgpu_dm_connector->num_modes =
9114 				drm_edid_connector_add_modes(connector);
9115 
9116 		/* sorting the probed modes before calling function
9117 		 * amdgpu_dm_get_native_mode() since EDID can have
9118 		 * more than one preferred mode. The modes that are
9119 		 * later in the probed mode list could be of higher
9120 		 * and preferred resolution. For example, 3840x2160
9121 		 * resolution in base EDID preferred timing and 4096x2160
9122 		 * preferred resolution in DID extension block later.
9123 		 */
9124 		drm_mode_sort(&connector->probed_modes);
9125 		amdgpu_dm_get_native_mode(connector);
9126 
9127 		/* Freesync capabilities are reset by calling
9128 		 * drm_edid_connector_add_modes() and need to be
9129 		 * restored here.
9130 		 */
9131 		amdgpu_dm_update_freesync_caps(connector, drm_edid, false);
9132 	} else {
9133 		amdgpu_dm_connector->num_modes = 0;
9134 	}
9135 }
9136 
9137 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
9138 			      struct drm_display_mode *mode)
9139 {
9140 	struct drm_display_mode *m;
9141 
9142 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
9143 		if (drm_mode_equal(m, mode))
9144 			return true;
9145 	}
9146 
9147 	return false;
9148 }
9149 
9150 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
9151 {
9152 	const struct drm_display_mode *m;
9153 	struct drm_display_mode *new_mode;
9154 	uint i;
9155 	u32 new_modes_count = 0;
9156 
9157 	/* Standard FPS values
9158 	 *
9159 	 * 23.976       - TV/NTSC
9160 	 * 24           - Cinema
9161 	 * 25           - TV/PAL
9162 	 * 29.97        - TV/NTSC
9163 	 * 30           - TV/NTSC
9164 	 * 48           - Cinema HFR
9165 	 * 50           - TV/PAL
9166 	 * 60           - Commonly used
9167 	 * 48,72,96,120 - Multiples of 24
9168 	 */
9169 	static const u32 common_rates[] = {
9170 		23976, 24000, 25000, 29970, 30000,
9171 		48000, 50000, 60000, 72000, 96000, 120000
9172 	};
9173 
9174 	/*
9175 	 * Find mode with highest refresh rate with the same resolution
9176 	 * as the preferred mode. Some monitors report a preferred mode
9177 	 * with lower resolution than the highest refresh rate supported.
9178 	 */
9179 
9180 	m = get_highest_refresh_rate_mode(aconnector, true);
9181 	if (!m)
9182 		return 0;
9183 
9184 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
9185 		u64 target_vtotal, target_vtotal_diff;
9186 		u64 num, den;
9187 
9188 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
9189 			continue;
9190 
9191 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
9192 		    common_rates[i] > aconnector->max_vfreq * 1000)
9193 			continue;
9194 
9195 		num = (unsigned long long)m->clock * 1000 * 1000;
9196 		den = common_rates[i] * (unsigned long long)m->htotal;
9197 		target_vtotal = div_u64(num, den);
9198 		target_vtotal_diff = target_vtotal - m->vtotal;
9199 
9200 		/* Check for illegal modes */
9201 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
9202 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
9203 		    m->vtotal + target_vtotal_diff < m->vsync_end)
9204 			continue;
9205 
9206 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
9207 		if (!new_mode)
9208 			goto out;
9209 
9210 		new_mode->vtotal += (u16)target_vtotal_diff;
9211 		new_mode->vsync_start += (u16)target_vtotal_diff;
9212 		new_mode->vsync_end += (u16)target_vtotal_diff;
9213 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
9214 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
9215 
9216 		if (!is_duplicate_mode(aconnector, new_mode)) {
9217 			drm_mode_probed_add(&aconnector->base, new_mode);
9218 			new_modes_count += 1;
9219 		} else
9220 			drm_mode_destroy(aconnector->base.dev, new_mode);
9221 	}
9222  out:
9223 	return new_modes_count;
9224 }
9225 
9226 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
9227 						   const struct drm_edid *drm_edid)
9228 {
9229 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9230 		to_amdgpu_dm_connector(connector);
9231 
9232 	if (!(amdgpu_freesync_vid_mode && drm_edid))
9233 		return;
9234 
9235 	if (!amdgpu_dm_connector->dc_sink || !amdgpu_dm_connector->dc_link)
9236 		return;
9237 
9238 	if (!dc_supports_vrr(amdgpu_dm_connector->dc_sink->ctx->dce_version))
9239 		return;
9240 
9241 	if (dc_connector_supports_analog(amdgpu_dm_connector->dc_link->link_id.id) &&
9242 	    amdgpu_dm_connector->dc_sink->edid_caps.analog)
9243 		return;
9244 
9245 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
9246 		amdgpu_dm_connector->num_modes +=
9247 			add_fs_modes(amdgpu_dm_connector);
9248 }
9249 
9250 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
9251 {
9252 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9253 			to_amdgpu_dm_connector(connector);
9254 	struct dc_link *dc_link = amdgpu_dm_connector->dc_link;
9255 	struct drm_encoder *encoder;
9256 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
9257 	struct dc_link_settings *verified_link_cap = &dc_link->verified_link_cap;
9258 	const struct dc *dc = dc_link->dc;
9259 
9260 	encoder = amdgpu_dm_connector_to_encoder(connector);
9261 
9262 	if (!drm_edid) {
9263 		amdgpu_dm_connector->num_modes =
9264 				drm_add_modes_noedid(connector, 640, 480);
9265 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
9266 			amdgpu_dm_connector->num_modes +=
9267 				drm_add_modes_noedid(connector, 1920, 1080);
9268 
9269 		if (amdgpu_dm_connector->dc_sink &&
9270 		    amdgpu_dm_connector->dc_sink->edid_caps.analog &&
9271 		    dc_connector_supports_analog(dc_link->link_id.id)) {
9272 			/* Analog monitor connected by DAC load detection.
9273 			 * Add common modes. It will be up to the user to select one that works.
9274 			 */
9275 			for (int i = 0; i < ARRAY_SIZE(common_modes); i++)
9276 				amdgpu_dm_connector->num_modes += drm_add_modes_noedid(
9277 					connector, common_modes[i].w, common_modes[i].h);
9278 		}
9279 	} else {
9280 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
9281 		if (encoder)
9282 			amdgpu_dm_connector_add_common_modes(encoder, connector);
9283 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
9284 	}
9285 	amdgpu_dm_fbc_init(connector);
9286 
9287 	return amdgpu_dm_connector->num_modes;
9288 }
9289 
9290 static const u32 supported_colorspaces =
9291 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
9292 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
9293 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
9294 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
9295 
9296 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
9297 				     struct amdgpu_dm_connector *aconnector,
9298 				     int connector_type,
9299 				     struct dc_link *link,
9300 				     int link_index)
9301 {
9302 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
9303 
9304 	/*
9305 	 * Some of the properties below require access to state, like bpc.
9306 	 * Allocate some default initial connector state with our reset helper.
9307 	 */
9308 	if (aconnector->base.funcs->reset)
9309 		aconnector->base.funcs->reset(&aconnector->base);
9310 
9311 	aconnector->connector_id = link_index;
9312 	aconnector->bl_idx = -1;
9313 	aconnector->dc_link = link;
9314 	aconnector->base.interlace_allowed = false;
9315 	aconnector->base.doublescan_allowed = false;
9316 	aconnector->base.stereo_allowed = false;
9317 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
9318 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
9319 	aconnector->audio_inst = -1;
9320 	aconnector->pack_sdp_v1_3 = false;
9321 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
9322 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
9323 	mutex_init(&aconnector->hpd_lock);
9324 	mutex_init(&aconnector->handle_mst_msg_ready);
9325 
9326 	/*
9327 	 * If HDMI HPD debounce delay is set, use the minimum between selected
9328 	 * value and AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS
9329 	 */
9330 	if (amdgpu_hdmi_hpd_debounce_delay_ms) {
9331 		aconnector->hdmi_hpd_debounce_delay_ms = min(amdgpu_hdmi_hpd_debounce_delay_ms,
9332 							     AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS);
9333 		INIT_DELAYED_WORK(&aconnector->hdmi_hpd_debounce_work, hdmi_hpd_debounce_work);
9334 		aconnector->hdmi_prev_sink = NULL;
9335 	} else {
9336 		aconnector->hdmi_hpd_debounce_delay_ms = 0;
9337 	}
9338 
9339 	/*
9340 	 * configure support HPD hot plug connector_>polled default value is 0
9341 	 * which means HPD hot plug not supported
9342 	 */
9343 	switch (connector_type) {
9344 	case DRM_MODE_CONNECTOR_HDMIA:
9345 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9346 		aconnector->base.ycbcr_420_allowed =
9347 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
9348 		break;
9349 	case DRM_MODE_CONNECTOR_DisplayPort:
9350 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9351 		link->link_enc = link_enc_cfg_get_link_enc(link);
9352 		ASSERT(link->link_enc);
9353 		if (link->link_enc)
9354 			aconnector->base.ycbcr_420_allowed =
9355 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
9356 		break;
9357 	case DRM_MODE_CONNECTOR_DVID:
9358 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9359 		break;
9360 	case DRM_MODE_CONNECTOR_DVII:
9361 	case DRM_MODE_CONNECTOR_VGA:
9362 		aconnector->base.polled =
9363 			DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT;
9364 		break;
9365 	default:
9366 		break;
9367 	}
9368 
9369 	drm_object_attach_property(&aconnector->base.base,
9370 				dm->ddev->mode_config.scaling_mode_property,
9371 				DRM_MODE_SCALE_NONE);
9372 
9373 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA
9374 		|| (connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root))
9375 		drm_connector_attach_broadcast_rgb_property(&aconnector->base);
9376 
9377 	drm_object_attach_property(&aconnector->base.base,
9378 				adev->mode_info.underscan_property,
9379 				UNDERSCAN_OFF);
9380 	drm_object_attach_property(&aconnector->base.base,
9381 				adev->mode_info.underscan_hborder_property,
9382 				0);
9383 	drm_object_attach_property(&aconnector->base.base,
9384 				adev->mode_info.underscan_vborder_property,
9385 				0);
9386 
9387 	if (!aconnector->mst_root)
9388 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
9389 
9390 	aconnector->base.state->max_bpc = 16;
9391 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
9392 
9393 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9394 		/* Content Type is currently only implemented for HDMI. */
9395 		drm_connector_attach_content_type_property(&aconnector->base);
9396 	}
9397 
9398 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9399 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
9400 			drm_connector_attach_colorspace_property(&aconnector->base);
9401 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
9402 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
9403 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
9404 			drm_connector_attach_colorspace_property(&aconnector->base);
9405 	}
9406 
9407 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9408 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
9409 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
9410 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
9411 
9412 		if (!aconnector->mst_root)
9413 			drm_connector_attach_vrr_capable_property(&aconnector->base);
9414 
9415 		if (adev->dm.hdcp_workqueue)
9416 			drm_connector_attach_content_protection_property(&aconnector->base, true);
9417 	}
9418 
9419 	if (connector_type == DRM_MODE_CONNECTOR_eDP) {
9420 		struct drm_privacy_screen *privacy_screen;
9421 
9422 		drm_connector_attach_panel_type_property(&aconnector->base);
9423 
9424 		privacy_screen = drm_privacy_screen_get(adev_to_drm(adev)->dev, NULL);
9425 		if (!IS_ERR(privacy_screen)) {
9426 			drm_connector_attach_privacy_screen_provider(&aconnector->base,
9427 								     privacy_screen);
9428 		} else if (PTR_ERR(privacy_screen) != -ENODEV) {
9429 			drm_warn(adev_to_drm(adev), "Error getting privacy-screen\n");
9430 		}
9431 	}
9432 }
9433 
9434 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
9435 			      struct i2c_msg *msgs, int num)
9436 {
9437 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
9438 	struct ddc_service *ddc_service = i2c->ddc_service;
9439 	struct i2c_command cmd;
9440 	int i;
9441 	int result = -EIO;
9442 
9443 	if (!ddc_service->ddc_pin)
9444 		return result;
9445 
9446 	cmd.payloads = kzalloc_objs(struct i2c_payload, num);
9447 
9448 	if (!cmd.payloads)
9449 		return result;
9450 
9451 	cmd.number_of_payloads = num;
9452 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
9453 	cmd.speed = 100;
9454 
9455 	for (i = 0; i < num; i++) {
9456 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
9457 		cmd.payloads[i].address = msgs[i].addr;
9458 		cmd.payloads[i].length = msgs[i].len;
9459 		cmd.payloads[i].data = msgs[i].buf;
9460 	}
9461 
9462 	if (i2c->oem) {
9463 		if (dc_submit_i2c_oem(
9464 			    ddc_service->ctx->dc,
9465 			    &cmd))
9466 			result = num;
9467 	} else {
9468 		if (dc_submit_i2c(
9469 			    ddc_service->ctx->dc,
9470 			    ddc_service->link->link_index,
9471 			    &cmd))
9472 			result = num;
9473 	}
9474 
9475 	kfree(cmd.payloads);
9476 	return result;
9477 }
9478 
9479 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
9480 {
9481 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
9482 }
9483 
9484 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
9485 	.master_xfer = amdgpu_dm_i2c_xfer,
9486 	.functionality = amdgpu_dm_i2c_func,
9487 };
9488 
9489 static struct amdgpu_i2c_adapter *
9490 create_i2c(struct ddc_service *ddc_service, bool oem)
9491 {
9492 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
9493 	struct amdgpu_i2c_adapter *i2c;
9494 
9495 	i2c = kzalloc_obj(struct amdgpu_i2c_adapter);
9496 	if (!i2c)
9497 		return NULL;
9498 	i2c->base.owner = THIS_MODULE;
9499 	i2c->base.dev.parent = &adev->pdev->dev;
9500 	i2c->base.algo = &amdgpu_dm_i2c_algo;
9501 	if (oem)
9502 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c OEM bus");
9503 	else
9504 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d",
9505 			 ddc_service->link->link_index);
9506 	i2c_set_adapdata(&i2c->base, i2c);
9507 	i2c->ddc_service = ddc_service;
9508 	i2c->oem = oem;
9509 
9510 	return i2c;
9511 }
9512 
9513 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
9514 {
9515 	struct cec_connector_info conn_info;
9516 	struct drm_device *ddev = aconnector->base.dev;
9517 	struct device *hdmi_dev = ddev->dev;
9518 
9519 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
9520 		drm_info(ddev, "HDMI-CEC feature masked\n");
9521 		return -EINVAL;
9522 	}
9523 
9524 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
9525 	aconnector->notifier =
9526 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
9527 	if (!aconnector->notifier) {
9528 		drm_err(ddev, "Failed to create cec notifier\n");
9529 		return -ENOMEM;
9530 	}
9531 
9532 	return 0;
9533 }
9534 
9535 /*
9536  * Note: this function assumes that dc_link_detect() was called for the
9537  * dc_link which will be represented by this aconnector.
9538  */
9539 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
9540 				    struct amdgpu_dm_connector *aconnector,
9541 				    u32 link_index,
9542 				    struct amdgpu_encoder *aencoder)
9543 {
9544 	int res = 0;
9545 	int connector_type;
9546 	struct dc *dc = dm->dc;
9547 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
9548 	struct amdgpu_i2c_adapter *i2c;
9549 
9550 	/* Not needed for writeback connector */
9551 	link->priv = aconnector;
9552 
9553 
9554 	i2c = create_i2c(link->ddc, false);
9555 	if (!i2c) {
9556 		drm_err(adev_to_drm(dm->adev), "Failed to create i2c adapter data\n");
9557 		return -ENOMEM;
9558 	}
9559 
9560 	aconnector->i2c = i2c;
9561 	res = devm_i2c_add_adapter(dm->adev->dev, &i2c->base);
9562 
9563 	if (res) {
9564 		drm_err(adev_to_drm(dm->adev), "Failed to register hw i2c %d\n", link->link_index);
9565 		goto out_free;
9566 	}
9567 
9568 	connector_type = to_drm_connector_type(link->connector_signal, link->link_id.id);
9569 
9570 	res = drm_connector_init_with_ddc(
9571 			dm->ddev,
9572 			&aconnector->base,
9573 			&amdgpu_dm_connector_funcs,
9574 			connector_type,
9575 			&i2c->base);
9576 
9577 	if (res) {
9578 		drm_err(adev_to_drm(dm->adev), "connector_init failed\n");
9579 		aconnector->connector_id = -1;
9580 		goto out_free;
9581 	}
9582 
9583 	drm_connector_helper_add(
9584 			&aconnector->base,
9585 			&amdgpu_dm_connector_helper_funcs);
9586 
9587 	amdgpu_dm_connector_init_helper(
9588 		dm,
9589 		aconnector,
9590 		connector_type,
9591 		link,
9592 		link_index);
9593 
9594 	drm_connector_attach_encoder(
9595 		&aconnector->base, &aencoder->base);
9596 
9597 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9598 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
9599 		amdgpu_dm_initialize_hdmi_connector(aconnector);
9600 
9601 	if (dc_is_dp_signal(link->connector_signal))
9602 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
9603 
9604 out_free:
9605 	if (res) {
9606 		kfree(i2c);
9607 		aconnector->i2c = NULL;
9608 	}
9609 	return res;
9610 }
9611 
9612 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
9613 {
9614 	switch (adev->mode_info.num_crtc) {
9615 	case 1:
9616 		return 0x1;
9617 	case 2:
9618 		return 0x3;
9619 	case 3:
9620 		return 0x7;
9621 	case 4:
9622 		return 0xf;
9623 	case 5:
9624 		return 0x1f;
9625 	case 6:
9626 	default:
9627 		return 0x3f;
9628 	}
9629 }
9630 
9631 static int amdgpu_dm_encoder_init(struct drm_device *dev,
9632 				  struct amdgpu_encoder *aencoder,
9633 				  uint32_t link_index)
9634 {
9635 	struct amdgpu_device *adev = drm_to_adev(dev);
9636 
9637 	int res = drm_encoder_init(dev,
9638 				   &aencoder->base,
9639 				   &amdgpu_dm_encoder_funcs,
9640 				   DRM_MODE_ENCODER_TMDS,
9641 				   NULL);
9642 
9643 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
9644 
9645 	if (!res)
9646 		aencoder->encoder_id = link_index;
9647 	else
9648 		aencoder->encoder_id = -1;
9649 
9650 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
9651 
9652 	return res;
9653 }
9654 
9655 static void manage_dm_interrupts(struct amdgpu_device *adev,
9656 				 struct amdgpu_crtc *acrtc,
9657 				 struct dm_crtc_state *acrtc_state)
9658 {	/*
9659 	 * We cannot be sure that the frontend index maps to the same
9660 	 * backend index - some even map to more than one.
9661 	 * So we have to go through the CRTC to find the right IRQ.
9662 	 */
9663 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
9664 			adev,
9665 			acrtc->crtc_id);
9666 	struct drm_device *dev = adev_to_drm(adev);
9667 
9668 	struct drm_vblank_crtc_config config = {0};
9669 	struct dc_crtc_timing *timing;
9670 	int offdelay;
9671 
9672 	if (acrtc_state) {
9673 		timing = &acrtc_state->stream->timing;
9674 
9675 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) >=
9676 		      IP_VERSION(3, 2, 0) &&
9677 		      !(adev->flags & AMD_IS_APU)) {
9678 			/*
9679 			 * DGPUs NV3x and newer that support idle optimizations
9680 			 * experience intermittent flip-done timeouts on cursor
9681 			 * updates. Restore 5s offdelay behavior for now.
9682 			 *
9683 			 * Discussion on the issue:
9684 			 * https://lore.kernel.org/amd-gfx/20260217191632.1243826-1-sysdadmin@m1k.cloud/
9685 			 */
9686 			config.offdelay_ms = 5000;
9687 			config.disable_immediate = false;
9688 		} else if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
9689 			     IP_VERSION(3, 5, 0)) {
9690 			/*
9691 			 * Older HW and DGPU have issues with instant off;
9692 			 * use a 2 frame offdelay.
9693 			 */
9694 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
9695 						      timing->v_total *
9696 						      timing->h_total,
9697 						      timing->pix_clk_100hz);
9698 
9699 			config.offdelay_ms = offdelay ?: 30;
9700 		} else {
9701 			/* offdelay_ms = 0 will never disable vblank */
9702 			config.offdelay_ms = 1;
9703 			config.disable_immediate = true;
9704 		}
9705 
9706 		drm_crtc_vblank_on_config(&acrtc->base,
9707 					  &config);
9708 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_get.*/
9709 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9710 		case IP_VERSION(3, 0, 0):
9711 		case IP_VERSION(3, 0, 2):
9712 		case IP_VERSION(3, 0, 3):
9713 		case IP_VERSION(3, 2, 0):
9714 			if (amdgpu_irq_get(adev, &adev->pageflip_irq, irq_type))
9715 				drm_err(dev, "DM_IRQ: Cannot get pageflip irq!\n");
9716 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9717 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
9718 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
9719 #endif
9720 		}
9721 
9722 	} else {
9723 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
9724 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9725 		case IP_VERSION(3, 0, 0):
9726 		case IP_VERSION(3, 0, 2):
9727 		case IP_VERSION(3, 0, 3):
9728 		case IP_VERSION(3, 2, 0):
9729 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9730 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
9731 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
9732 #endif
9733 			if (amdgpu_irq_put(adev, &adev->pageflip_irq, irq_type))
9734 				drm_err(dev, "DM_IRQ: Cannot put pageflip irq!\n");
9735 		}
9736 
9737 		drm_crtc_vblank_off(&acrtc->base);
9738 	}
9739 }
9740 
9741 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
9742 				      struct amdgpu_crtc *acrtc)
9743 {
9744 	int irq_type =
9745 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
9746 
9747 	/**
9748 	 * This reads the current state for the IRQ and force reapplies
9749 	 * the setting to hardware.
9750 	 */
9751 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
9752 }
9753 
9754 static bool
9755 is_scaling_state_different(const struct dm_connector_state *dm_state,
9756 			   const struct dm_connector_state *old_dm_state)
9757 {
9758 	if (dm_state->scaling != old_dm_state->scaling)
9759 		return true;
9760 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
9761 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
9762 			return true;
9763 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
9764 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
9765 			return true;
9766 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
9767 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
9768 		return true;
9769 	return false;
9770 }
9771 
9772 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
9773 					    struct drm_crtc_state *old_crtc_state,
9774 					    struct drm_connector_state *new_conn_state,
9775 					    struct drm_connector_state *old_conn_state,
9776 					    const struct drm_connector *connector,
9777 					    struct hdcp_workqueue *hdcp_w)
9778 {
9779 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
9780 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
9781 
9782 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
9783 		connector->index, connector->status, connector->dpms);
9784 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
9785 		old_conn_state->content_protection, new_conn_state->content_protection);
9786 
9787 	if (old_crtc_state)
9788 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9789 		old_crtc_state->enable,
9790 		old_crtc_state->active,
9791 		old_crtc_state->mode_changed,
9792 		old_crtc_state->active_changed,
9793 		old_crtc_state->connectors_changed);
9794 
9795 	if (new_crtc_state)
9796 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9797 		new_crtc_state->enable,
9798 		new_crtc_state->active,
9799 		new_crtc_state->mode_changed,
9800 		new_crtc_state->active_changed,
9801 		new_crtc_state->connectors_changed);
9802 
9803 	/* hdcp content type change */
9804 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
9805 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
9806 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9807 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
9808 		return true;
9809 	}
9810 
9811 	/* CP is being re enabled, ignore this */
9812 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
9813 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9814 		if (new_crtc_state && new_crtc_state->mode_changed) {
9815 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9816 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
9817 			return true;
9818 		}
9819 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
9820 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
9821 		return false;
9822 	}
9823 
9824 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
9825 	 *
9826 	 * Handles:	UNDESIRED -> ENABLED
9827 	 */
9828 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
9829 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
9830 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9831 
9832 	/* Stream removed and re-enabled
9833 	 *
9834 	 * Can sometimes overlap with the HPD case,
9835 	 * thus set update_hdcp to false to avoid
9836 	 * setting HDCP multiple times.
9837 	 *
9838 	 * Handles:	DESIRED -> DESIRED (Special case)
9839 	 */
9840 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
9841 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
9842 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9843 		dm_con_state->update_hdcp = false;
9844 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
9845 			__func__);
9846 		return true;
9847 	}
9848 
9849 	/* Hot-plug, headless s3, dpms
9850 	 *
9851 	 * Only start HDCP if the display is connected/enabled.
9852 	 * update_hdcp flag will be set to false until the next
9853 	 * HPD comes in.
9854 	 *
9855 	 * Handles:	DESIRED -> DESIRED (Special case)
9856 	 */
9857 	if (dm_con_state->update_hdcp &&
9858 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
9859 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
9860 		dm_con_state->update_hdcp = false;
9861 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
9862 			__func__);
9863 		return true;
9864 	}
9865 
9866 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
9867 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9868 			if (new_crtc_state && new_crtc_state->mode_changed) {
9869 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
9870 					__func__);
9871 				return true;
9872 			}
9873 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
9874 				__func__);
9875 			return false;
9876 		}
9877 
9878 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
9879 		return false;
9880 	}
9881 
9882 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9883 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
9884 			__func__);
9885 		return true;
9886 	}
9887 
9888 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
9889 	return false;
9890 }
9891 
9892 static void remove_stream(struct amdgpu_device *adev,
9893 			  struct amdgpu_crtc *acrtc,
9894 			  struct dc_stream_state *stream)
9895 {
9896 	/* this is the update mode case */
9897 
9898 	acrtc->otg_inst = -1;
9899 	acrtc->enabled = false;
9900 }
9901 
9902 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
9903 {
9904 
9905 	assert_spin_locked(&acrtc->base.dev->event_lock);
9906 	WARN_ON(acrtc->event);
9907 
9908 	acrtc->event = acrtc->base.state->event;
9909 
9910 	/* Set the flip status */
9911 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
9912 
9913 	/* Mark this event as consumed */
9914 	acrtc->base.state->event = NULL;
9915 
9916 	drm_dbg_state(acrtc->base.dev,
9917 		      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
9918 		      acrtc->crtc_id);
9919 }
9920 
9921 static void update_freesync_state_on_stream(
9922 	struct amdgpu_display_manager *dm,
9923 	struct dm_crtc_state *new_crtc_state,
9924 	struct dc_stream_state *new_stream,
9925 	struct dc_plane_state *surface,
9926 	u32 flip_timestamp_in_us)
9927 {
9928 	struct mod_vrr_params vrr_params;
9929 	struct dc_info_packet vrr_infopacket = {0};
9930 	struct amdgpu_device *adev = dm->adev;
9931 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9932 	unsigned long flags;
9933 	bool pack_sdp_v1_3 = false;
9934 	struct amdgpu_dm_connector *aconn;
9935 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
9936 
9937 	if (!new_stream)
9938 		return;
9939 
9940 	/*
9941 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9942 	 * For now it's sufficient to just guard against these conditions.
9943 	 */
9944 
9945 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9946 		return;
9947 
9948 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9949 	vrr_params = acrtc->dm_irq_params.vrr_params;
9950 
9951 	if (surface) {
9952 		mod_freesync_handle_preflip(
9953 			dm->freesync_module,
9954 			surface,
9955 			new_stream,
9956 			flip_timestamp_in_us,
9957 			&vrr_params);
9958 
9959 		if (adev->family < AMDGPU_FAMILY_AI &&
9960 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
9961 			mod_freesync_handle_v_update(dm->freesync_module,
9962 						     new_stream, &vrr_params);
9963 
9964 			/* Need to call this before the frame ends. */
9965 			dc_stream_adjust_vmin_vmax(dm->dc,
9966 						   new_crtc_state->stream,
9967 						   &vrr_params.adjust);
9968 		}
9969 	}
9970 
9971 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
9972 
9973 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
9974 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
9975 
9976 		if (aconn->vsdb_info.amd_vsdb_version == 1)
9977 			packet_type = PACKET_TYPE_FS_V1;
9978 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
9979 			packet_type = PACKET_TYPE_FS_V2;
9980 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
9981 			packet_type = PACKET_TYPE_FS_V3;
9982 
9983 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
9984 					&new_stream->adaptive_sync_infopacket);
9985 	}
9986 
9987 	mod_freesync_build_vrr_infopacket(
9988 		dm->freesync_module,
9989 		new_stream,
9990 		&vrr_params,
9991 		packet_type,
9992 		TRANSFER_FUNC_UNKNOWN,
9993 		&vrr_infopacket,
9994 		pack_sdp_v1_3);
9995 
9996 	new_crtc_state->freesync_vrr_info_changed |=
9997 		(memcmp(&new_crtc_state->vrr_infopacket,
9998 			&vrr_infopacket,
9999 			sizeof(vrr_infopacket)) != 0);
10000 
10001 	acrtc->dm_irq_params.vrr_params = vrr_params;
10002 	new_crtc_state->vrr_infopacket = vrr_infopacket;
10003 
10004 	new_stream->vrr_infopacket = vrr_infopacket;
10005 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
10006 
10007 	if (new_crtc_state->freesync_vrr_info_changed)
10008 		drm_dbg_kms(adev_to_drm(adev), "VRR packet update: crtc=%u enabled=%d state=%d",
10009 			      new_crtc_state->base.crtc->base.id,
10010 			      (int)new_crtc_state->base.vrr_enabled,
10011 			      (int)vrr_params.state);
10012 
10013 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10014 }
10015 
10016 static void update_stream_irq_parameters(
10017 	struct amdgpu_display_manager *dm,
10018 	struct dm_crtc_state *new_crtc_state)
10019 {
10020 	struct dc_stream_state *new_stream = new_crtc_state->stream;
10021 	struct mod_vrr_params vrr_params;
10022 	struct mod_freesync_config config = new_crtc_state->freesync_config;
10023 	struct amdgpu_device *adev = dm->adev;
10024 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
10025 	unsigned long flags;
10026 
10027 	if (!new_stream)
10028 		return;
10029 
10030 	/*
10031 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
10032 	 * For now it's sufficient to just guard against these conditions.
10033 	 */
10034 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
10035 		return;
10036 
10037 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
10038 	vrr_params = acrtc->dm_irq_params.vrr_params;
10039 
10040 	if (new_crtc_state->vrr_supported &&
10041 	    config.min_refresh_in_uhz &&
10042 	    config.max_refresh_in_uhz) {
10043 		/*
10044 		 * if freesync compatible mode was set, config.state will be set
10045 		 * in atomic check
10046 		 */
10047 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
10048 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
10049 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
10050 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
10051 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
10052 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
10053 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
10054 		} else {
10055 			config.state = new_crtc_state->base.vrr_enabled ?
10056 						     VRR_STATE_ACTIVE_VARIABLE :
10057 						     VRR_STATE_INACTIVE;
10058 		}
10059 	} else {
10060 		config.state = VRR_STATE_UNSUPPORTED;
10061 	}
10062 
10063 	mod_freesync_build_vrr_params(dm->freesync_module,
10064 				      new_stream,
10065 				      &config, &vrr_params);
10066 
10067 	new_crtc_state->freesync_config = config;
10068 	/* Copy state for access from DM IRQ handler */
10069 	acrtc->dm_irq_params.freesync_config = config;
10070 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
10071 	acrtc->dm_irq_params.vrr_params = vrr_params;
10072 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10073 }
10074 
10075 static void amdgpu_dm_handle_vrr_transition(struct amdgpu_display_manager *dm,
10076 					    struct dm_crtc_state *old_state,
10077 					    struct dm_crtc_state *new_state)
10078 {
10079 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
10080 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
10081 
10082 	if (!old_vrr_active && new_vrr_active) {
10083 		/* Transition VRR inactive -> active:
10084 		 * While VRR is active, we must not disable vblank irq, as a
10085 		 * reenable after disable would compute bogus vblank/pflip
10086 		 * timestamps if it likely happened inside display front-porch.
10087 		 *
10088 		 * We also need vupdate irq for the actual core vblank handling
10089 		 * at end of vblank.
10090 		 */
10091 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
10092 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
10093 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR off->on: Get vblank ref\n",
10094 				 __func__, new_state->base.crtc->base.id);
10095 
10096 		scoped_guard(mutex, &dm->dc_lock) {
10097 			dc_exit_ips_for_hw_access(dm->dc);
10098 			amdgpu_dm_psr_set_event(dm, new_state->stream, true,
10099 				psr_event_vrr_transition, true);
10100 			amdgpu_dm_replay_set_event(dm, new_state->stream, true,
10101 				replay_event_vrr, true);
10102 		}
10103 	} else if (old_vrr_active && !new_vrr_active) {
10104 		/* Transition VRR active -> inactive:
10105 		 * Allow vblank irq disable again for fixed refresh rate.
10106 		 */
10107 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
10108 		drm_crtc_vblank_put(new_state->base.crtc);
10109 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR on->off: Drop vblank ref\n",
10110 				 __func__, new_state->base.crtc->base.id);
10111 
10112 		scoped_guard(mutex, &dm->dc_lock) {
10113 			dc_exit_ips_for_hw_access(dm->dc);
10114 			amdgpu_dm_psr_set_event(dm, new_state->stream, false,
10115 				psr_event_vrr_transition, false);
10116 			amdgpu_dm_replay_set_event(dm, new_state->stream, false,
10117 				replay_event_vrr, false);
10118 		}
10119 	}
10120 }
10121 
10122 static void amdgpu_dm_commit_cursors(struct drm_atomic_commit *state)
10123 {
10124 	struct drm_plane *plane;
10125 	struct drm_plane_state *old_plane_state;
10126 	int i;
10127 
10128 	/*
10129 	 * TODO: Make this per-stream so we don't issue redundant updates for
10130 	 * commits with multiple streams.
10131 	 */
10132 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
10133 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
10134 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
10135 }
10136 
10137 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
10138 {
10139 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
10140 
10141 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
10142 }
10143 
10144 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
10145 				    struct drm_plane_state *old_plane_state,
10146 				    struct dc_stream_update *update)
10147 {
10148 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
10149 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
10150 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
10151 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
10152 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
10153 	uint64_t address = afb ? afb->address : 0;
10154 	struct dc_cursor_position position = {0};
10155 	struct dc_cursor_attributes attributes;
10156 	int ret;
10157 
10158 	if (!plane->state->fb && !old_plane_state->fb)
10159 		return;
10160 
10161 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
10162 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
10163 		       plane->state->crtc_h);
10164 
10165 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
10166 	if (ret)
10167 		return;
10168 
10169 	if (!position.enable) {
10170 		/* turn off cursor */
10171 		if (crtc_state && crtc_state->stream) {
10172 			dc_stream_set_cursor_position(crtc_state->stream,
10173 						      &position);
10174 			update->cursor_position = &crtc_state->stream->cursor_position;
10175 		}
10176 		return;
10177 	}
10178 
10179 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
10180 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
10181 
10182 	memset(&attributes, 0, sizeof(attributes));
10183 	attributes.address.high_part = upper_32_bits(address);
10184 	attributes.address.low_part  = lower_32_bits(address);
10185 	attributes.width             = plane->state->crtc_w;
10186 	attributes.height            = plane->state->crtc_h;
10187 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
10188 	attributes.rotation_angle    = 0;
10189 	attributes.attribute_flags.value = 0;
10190 
10191 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
10192 	 * legacy gamma setup.
10193 	 */
10194 	if (crtc_state->cm_is_degamma_srgb &&
10195 	    adev->dm.dc->caps.color.dpp.gamma_corr)
10196 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
10197 
10198 	if (afb)
10199 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
10200 
10201 	if (crtc_state->stream) {
10202 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
10203 						     &attributes))
10204 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
10205 
10206 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
10207 
10208 		if (!dc_stream_set_cursor_position(crtc_state->stream,
10209 						   &position))
10210 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
10211 
10212 		update->cursor_position = &crtc_state->stream->cursor_position;
10213 	}
10214 }
10215 
10216 static void amdgpu_dm_enable_self_refresh(struct amdgpu_display_manager *dm,
10217 					  struct amdgpu_crtc *acrtc_attach,
10218 					  const struct dm_crtc_state *acrtc_state,
10219 					  const u64 current_ts)
10220 {
10221 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
10222 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
10223 	struct amdgpu_dm_connector *aconn =
10224 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
10225 
10226 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
10227 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
10228 	    (psr->psr_feature_enabled || pr->replay_feature_enabled)) {
10229 		if (aconn->sr_skip_count > 0)
10230 			aconn->sr_skip_count--;
10231 
10232 		/* Allow SR when skip count is 0. */
10233 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
10234 
10235 		/*
10236 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
10237 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
10238 		 * can be enabled immediately once OS demonstrates an
10239 		 * adequate number of fast atomic commits to notify KMD
10240 		 * of update events.
10241 		 * See `amdgpu_dm_crtc_vblank_control_worker()`.
10242 		 */
10243 		if (acrtc_attach->dm_irq_params.allow_sr_entry &&
10244 			(current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
10245 			amdgpu_dm_psr_set_event(dm, acrtc_state->stream, false,
10246 				psr_event_hw_programming, false);
10247 
10248 			amdgpu_dm_replay_set_event(dm, acrtc_state->stream, false,
10249 				replay_event_hw_programming, false);
10250 		}
10251 	} else {
10252 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
10253 	}
10254 }
10255 
10256 static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state,
10257 				    struct drm_device *dev,
10258 				    struct amdgpu_display_manager *dm,
10259 				    struct drm_crtc *pcrtc,
10260 				    bool wait_for_vblank)
10261 {
10262 	u32 i;
10263 	u64 timestamp_ns = ktime_get_ns();
10264 	struct drm_plane *plane;
10265 	struct drm_plane_state *old_plane_state, *new_plane_state;
10266 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
10267 	struct drm_crtc_state *new_pcrtc_state =
10268 			drm_atomic_get_new_crtc_state(state, pcrtc);
10269 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
10270 	struct dm_crtc_state *dm_old_crtc_state =
10271 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
10272 	int planes_count = 0, vpos, hpos;
10273 	unsigned long flags;
10274 	u32 target_vblank, last_flip_vblank;
10275 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
10276 	bool cursor_update = false;
10277 	bool pflip_present = false;
10278 	bool dirty_rects_changed = false;
10279 	bool updated_planes_and_streams = false;
10280 	struct {
10281 		struct dc_surface_update surface_updates[MAX_SURFACES];
10282 		struct dc_plane_info plane_infos[MAX_SURFACES];
10283 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
10284 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
10285 		struct dc_stream_update stream_update;
10286 	} *bundle;
10287 
10288 	bundle = kzalloc_obj(*bundle);
10289 
10290 	if (!bundle) {
10291 		drm_err(dev, "Failed to allocate update bundle\n");
10292 		goto cleanup;
10293 	}
10294 
10295 	/*
10296 	 * Disable the cursor first if we're disabling all the planes.
10297 	 * It'll remain on the screen after the planes are re-enabled
10298 	 * if we don't.
10299 	 *
10300 	 * If the cursor is transitioning from native to overlay mode, the
10301 	 * native cursor needs to be disabled first.
10302 	 */
10303 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
10304 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10305 		struct dc_cursor_position cursor_position = {0};
10306 
10307 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
10308 						   &cursor_position))
10309 			drm_err(dev, "DC failed to disable native cursor\n");
10310 
10311 		bundle->stream_update.cursor_position =
10312 				&acrtc_state->stream->cursor_position;
10313 	}
10314 
10315 	if (acrtc_state->active_planes == 0 &&
10316 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10317 		amdgpu_dm_commit_cursors(state);
10318 
10319 	/* update planes when needed */
10320 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
10321 		struct drm_crtc *crtc = new_plane_state->crtc;
10322 		struct drm_crtc_state *new_crtc_state;
10323 		struct drm_framebuffer *fb = new_plane_state->fb;
10324 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
10325 		bool plane_needs_flip;
10326 		struct dc_plane_state *dc_plane;
10327 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
10328 
10329 		/* Cursor plane is handled after stream updates */
10330 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
10331 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10332 			if ((fb && crtc == pcrtc) ||
10333 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
10334 				cursor_update = true;
10335 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
10336 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
10337 			}
10338 
10339 			continue;
10340 		}
10341 
10342 		if (!fb || !crtc || pcrtc != crtc)
10343 			continue;
10344 
10345 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
10346 		if (!new_crtc_state->active)
10347 			continue;
10348 
10349 		dc_plane = dm_new_plane_state->dc_state;
10350 		if (!dc_plane)
10351 			continue;
10352 
10353 		bundle->surface_updates[planes_count].surface = dc_plane;
10354 		if (new_pcrtc_state->color_mgmt_changed || new_plane_state->color_mgmt_changed) {
10355 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
10356 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
10357 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
10358 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
10359 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
10360 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
10361 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
10362 		}
10363 
10364 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
10365 				     &bundle->scaling_infos[planes_count]);
10366 
10367 		bundle->surface_updates[planes_count].scaling_info =
10368 			&bundle->scaling_infos[planes_count];
10369 
10370 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
10371 
10372 		pflip_present = pflip_present || plane_needs_flip;
10373 
10374 		if (!plane_needs_flip) {
10375 			planes_count += 1;
10376 			continue;
10377 		}
10378 
10379 		fill_dc_plane_info_and_addr(
10380 			dm->adev, new_plane_state,
10381 			afb->tiling_flags,
10382 			&bundle->plane_infos[planes_count],
10383 			&bundle->flip_addrs[planes_count].address,
10384 			afb->tmz_surface);
10385 
10386 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
10387 				 new_plane_state->plane->index,
10388 				 bundle->plane_infos[planes_count].dcc.enable);
10389 
10390 		bundle->surface_updates[planes_count].plane_info =
10391 			&bundle->plane_infos[planes_count];
10392 
10393 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
10394 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
10395 			fill_dc_dirty_rects(plane, old_plane_state,
10396 					    new_plane_state, new_crtc_state,
10397 					    &bundle->flip_addrs[planes_count],
10398 					    acrtc_state->stream->link->psr_settings.psr_version ==
10399 					    DC_PSR_VERSION_SU_1,
10400 					    &dirty_rects_changed);
10401 
10402 			/*
10403 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
10404 			 * and enabled it again after dirty regions are stable to avoid video glitch.
10405 			 * PSR-SU will be enabled in
10406 			 * amdgpu_dm_crtc_vblank_control_worker() if user
10407 			 * pause the video during the PSR-SU was disabled.
10408 			 */
10409 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
10410 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
10411 			    dirty_rects_changed) {
10412 				mutex_lock(&dm->dc_lock);
10413 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
10414 				timestamp_ns;
10415 				dc_exit_ips_for_hw_access(dm->dc);
10416 				amdgpu_dm_psr_set_event(dm, acrtc_state->stream, true,
10417 					psr_event_hw_programming, true);
10418 				mutex_unlock(&dm->dc_lock);
10419 			}
10420 		}
10421 
10422 		/*
10423 		 * Only allow immediate flips for fast updates that don't
10424 		 * change memory domain, FB pitch, DCC state, rotation or
10425 		 * mirroring.
10426 		 *
10427 		 * dm_crtc_helper_atomic_check() only accepts async flips with
10428 		 * fast updates.
10429 		 */
10430 		if (crtc->state->async_flip &&
10431 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
10432 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
10433 			drm_warn_once(state->dev,
10434 				      "[PLANE:%d:%s] async flip with non-fast update\n",
10435 				      plane->base.id, plane->name);
10436 
10437 		bundle->flip_addrs[planes_count].flip_immediate =
10438 			crtc->state->async_flip &&
10439 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
10440 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
10441 
10442 		timestamp_ns = ktime_get_ns();
10443 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
10444 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
10445 		bundle->surface_updates[planes_count].surface = dc_plane;
10446 
10447 		if (!bundle->surface_updates[planes_count].surface) {
10448 			drm_err(dev, "No surface for CRTC: id=%d\n",
10449 					acrtc_attach->crtc_id);
10450 			continue;
10451 		}
10452 
10453 		if (plane == pcrtc->primary)
10454 			update_freesync_state_on_stream(
10455 				dm,
10456 				acrtc_state,
10457 				acrtc_state->stream,
10458 				dc_plane,
10459 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
10460 
10461 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
10462 				 __func__,
10463 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
10464 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
10465 
10466 		planes_count += 1;
10467 
10468 	}
10469 
10470 	if (pflip_present) {
10471 		if (!vrr_active) {
10472 			/* Use old throttling in non-vrr fixed refresh rate mode
10473 			 * to keep flip scheduling based on target vblank counts
10474 			 * working in a backwards compatible way, e.g., for
10475 			 * clients using the GLX_OML_sync_control extension or
10476 			 * DRI3/Present extension with defined target_msc.
10477 			 */
10478 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
10479 		} else {
10480 			/* For variable refresh rate mode only:
10481 			 * Get vblank of last completed flip to avoid > 1 vrr
10482 			 * flips per video frame by use of throttling, but allow
10483 			 * flip programming anywhere in the possibly large
10484 			 * variable vrr vblank interval for fine-grained flip
10485 			 * timing control and more opportunity to avoid stutter
10486 			 * on late submission of flips.
10487 			 */
10488 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10489 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
10490 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10491 		}
10492 
10493 		target_vblank = last_flip_vblank + wait_for_vblank;
10494 
10495 		/*
10496 		 * Wait until we're out of the vertical blank period before the one
10497 		 * targeted by the flip
10498 		 */
10499 		while ((acrtc_attach->enabled &&
10500 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
10501 							    0, &vpos, &hpos, NULL,
10502 							    NULL, &pcrtc->hwmode)
10503 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
10504 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
10505 			(int)(target_vblank -
10506 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
10507 			usleep_range(1000, 1100);
10508 		}
10509 
10510 		/**
10511 		 * Prepare the flip event for the pageflip interrupt to handle.
10512 		 *
10513 		 * This only works in the case where we've already turned on the
10514 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
10515 		 * from 0 -> n planes we have to skip a hardware generated event
10516 		 * and rely on sending it from software.
10517 		 */
10518 		if (acrtc_attach->base.state->event &&
10519 		    acrtc_state->active_planes > 0) {
10520 			drm_crtc_vblank_get(pcrtc);
10521 
10522 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10523 
10524 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
10525 			prepare_flip_isr(acrtc_attach);
10526 
10527 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10528 		}
10529 
10530 		if (acrtc_state->stream) {
10531 			if (acrtc_state->freesync_vrr_info_changed)
10532 				bundle->stream_update.vrr_infopacket =
10533 					&acrtc_state->stream->vrr_infopacket;
10534 		}
10535 	} else if (cursor_update && acrtc_state->active_planes > 0) {
10536 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10537 		if (acrtc_attach->base.state->event) {
10538 			drm_crtc_vblank_get(pcrtc);
10539 			acrtc_attach->event = acrtc_attach->base.state->event;
10540 			acrtc_attach->base.state->event = NULL;
10541 		}
10542 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10543 	}
10544 
10545 	/* Update the planes if changed or disable if we don't have any. */
10546 	if ((planes_count || acrtc_state->active_planes == 0) &&
10547 		acrtc_state->stream) {
10548 		/*
10549 		 * If PSR or idle optimizations are enabled then flush out
10550 		 * any pending work before hardware programming.
10551 		 */
10552 		if (dm->vblank_control_workqueue)
10553 			flush_workqueue(dm->vblank_control_workqueue);
10554 
10555 		bundle->stream_update.stream = acrtc_state->stream;
10556 		if (new_pcrtc_state->mode_changed) {
10557 			bundle->stream_update.src = acrtc_state->stream->src;
10558 			bundle->stream_update.dst = acrtc_state->stream->dst;
10559 		}
10560 
10561 		if (new_pcrtc_state->color_mgmt_changed) {
10562 			/*
10563 			 * TODO: This isn't fully correct since we've actually
10564 			 * already modified the stream in place.
10565 			 */
10566 			bundle->stream_update.gamut_remap =
10567 				&acrtc_state->stream->gamut_remap_matrix;
10568 			bundle->stream_update.output_csc_transform =
10569 				&acrtc_state->stream->csc_color_matrix;
10570 			bundle->stream_update.out_transfer_func =
10571 				&acrtc_state->stream->out_transfer_func;
10572 			bundle->stream_update.lut3d_func =
10573 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
10574 			bundle->stream_update.func_shaper =
10575 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
10576 		}
10577 
10578 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
10579 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
10580 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
10581 
10582 		/*
10583 		 * If FreeSync state on the stream has changed then we need to
10584 		 * re-adjust the min/max bounds now that DC doesn't handle this
10585 		 * as part of commit.
10586 		 */
10587 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
10588 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10589 			dc_stream_adjust_vmin_vmax(
10590 				dm->dc, acrtc_state->stream,
10591 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
10592 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10593 		}
10594 		mutex_lock(&dm->dc_lock);
10595 		update_planes_and_stream_adapter(dm->dc,
10596 					 acrtc_state->update_type,
10597 					 planes_count,
10598 					 acrtc_state->stream,
10599 					 &bundle->stream_update,
10600 					 bundle->surface_updates);
10601 		updated_planes_and_streams = true;
10602 
10603 		/**
10604 		 * Enable or disable the interrupts on the backend.
10605 		 *
10606 		 * Most pipes are put into power gating when unused.
10607 		 *
10608 		 * When power gating is enabled on a pipe we lose the
10609 		 * interrupt enablement state when power gating is disabled.
10610 		 *
10611 		 * So we need to update the IRQ control state in hardware
10612 		 * whenever the pipe turns on (since it could be previously
10613 		 * power gated) or off (since some pipes can't be power gated
10614 		 * on some ASICs).
10615 		 */
10616 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
10617 			dm_update_pflip_irq_state(drm_to_adev(dev),
10618 						  acrtc_attach);
10619 		amdgpu_dm_enable_self_refresh(dm, acrtc_attach, acrtc_state,
10620 					      timestamp_ns);
10621 		mutex_unlock(&dm->dc_lock);
10622 	}
10623 
10624 	/*
10625 	 * Update cursor state *after* programming all the planes.
10626 	 * This avoids redundant programming in the case where we're going
10627 	 * to be disabling a single plane - those pipes are being disabled.
10628 	 */
10629 	if (acrtc_state->active_planes &&
10630 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
10631 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10632 		amdgpu_dm_commit_cursors(state);
10633 
10634 cleanup:
10635 	kfree(bundle);
10636 }
10637 
10638 static void amdgpu_dm_commit_audio(struct drm_device *dev,
10639 				   struct drm_atomic_commit *state)
10640 {
10641 	struct amdgpu_device *adev = drm_to_adev(dev);
10642 	struct amdgpu_dm_connector *aconnector;
10643 	struct drm_connector *connector;
10644 	struct drm_connector_state *old_con_state, *new_con_state;
10645 	struct drm_crtc_state *new_crtc_state;
10646 	struct dm_crtc_state *new_dm_crtc_state;
10647 	const struct dc_stream_status *status;
10648 	int i, inst;
10649 
10650 	/* Notify device removals. */
10651 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10652 		if (old_con_state->crtc != new_con_state->crtc) {
10653 			/* CRTC changes require notification. */
10654 			goto notify;
10655 		}
10656 
10657 		if (!new_con_state->crtc)
10658 			continue;
10659 
10660 		new_crtc_state = drm_atomic_get_new_crtc_state(
10661 			state, new_con_state->crtc);
10662 
10663 		if (!new_crtc_state)
10664 			continue;
10665 
10666 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10667 			continue;
10668 
10669 notify:
10670 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10671 			continue;
10672 
10673 		aconnector = to_amdgpu_dm_connector(connector);
10674 
10675 		mutex_lock(&adev->dm.audio_lock);
10676 		inst = aconnector->audio_inst;
10677 		aconnector->audio_inst = -1;
10678 		mutex_unlock(&adev->dm.audio_lock);
10679 
10680 		amdgpu_dm_audio_eld_notify(adev, inst);
10681 	}
10682 
10683 	/* Notify audio device additions. */
10684 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10685 		if (!new_con_state->crtc)
10686 			continue;
10687 
10688 		new_crtc_state = drm_atomic_get_new_crtc_state(
10689 			state, new_con_state->crtc);
10690 
10691 		if (!new_crtc_state)
10692 			continue;
10693 
10694 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10695 			continue;
10696 
10697 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
10698 		if (!new_dm_crtc_state->stream)
10699 			continue;
10700 
10701 		status = dc_stream_get_status(new_dm_crtc_state->stream);
10702 		if (!status)
10703 			continue;
10704 
10705 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10706 			continue;
10707 
10708 		aconnector = to_amdgpu_dm_connector(connector);
10709 
10710 		mutex_lock(&adev->dm.audio_lock);
10711 		inst = status->audio_inst;
10712 		aconnector->audio_inst = inst;
10713 		mutex_unlock(&adev->dm.audio_lock);
10714 
10715 		amdgpu_dm_audio_eld_notify(adev, inst);
10716 	}
10717 }
10718 
10719 /*
10720  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
10721  * @crtc_state: the DRM CRTC state
10722  * @stream_state: the DC stream state.
10723  *
10724  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
10725  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
10726  */
10727 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
10728 						struct dc_stream_state *stream_state)
10729 {
10730 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
10731 }
10732 
10733 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
10734 			      struct dm_crtc_state *crtc_state)
10735 {
10736 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
10737 }
10738 
10739 /**
10740  * amdgpu_dm_mod_power_update_streams - update mod_power stream state on modeset
10741  * @state: the drm atomic state
10742  * @dm: the display manager to update mod_power on
10743  *
10744  * Notify mod_power of stream changes on modeset events, and disable PSR/Replay
10745  * in preparation for hardware programming. See also
10746  * amdgpu_dm_mod_power_setup_streams() for post-modeset mod_power setup.
10747  */
10748 static void amdgpu_dm_mod_power_update_streams(struct drm_atomic_commit *state,
10749 					       struct amdgpu_display_manager *dm)
10750 {
10751 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10752 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10753 	struct amdgpu_dm_connector *aconnector;
10754 	struct drm_crtc *crtc;
10755 	int i = 0;
10756 
10757 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10758 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10759 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10760 
10761 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10762 			continue;
10763 
10764 		/*
10765 		 * Update mod_power on modeset event in preparation for hw
10766 		 * programming. Always use the old stream, since it would have
10767 		 * been previously added to mod_power. If old stream is null (on
10768 		 * crtc enable, for example), mod_power will no-op, which is the
10769 		 * desried behavior.
10770 		 */
10771 		if (old_crtc_state->active) {
10772 			scoped_guard(mutex, &dm->dc_lock) {
10773 				dc_exit_ips_for_hw_access(dm->dc);
10774 				amdgpu_dm_psr_set_event(dm, dm_old_crtc_state->stream, true,
10775 					psr_event_hw_programming, true);
10776 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, true,
10777 					replay_event_hw_programming, true);
10778 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, false,
10779 					replay_event_general_ui, false);
10780 			}
10781 		}
10782 
10783 		if (new_crtc_state->active) {
10784 			aconnector = (struct amdgpu_dm_connector *)
10785 				dm_new_crtc_state->stream->dm_stream_context;
10786 			if (old_crtc_state->active) {
10787 				mod_power_replace_stream(dm->power_module,
10788 					dm_old_crtc_state->stream,
10789 					dm_new_crtc_state->stream,
10790 					&aconnector->psr_caps);
10791 			} else {
10792 				mod_power_add_stream(dm->power_module,
10793 					dm_new_crtc_state->stream,
10794 					&aconnector->psr_caps);
10795 			}
10796 		} else if (old_crtc_state->active) {
10797 			mod_power_remove_stream(dm->power_module,
10798 				dm_old_crtc_state->stream);
10799 		}
10800 	}
10801 }
10802 
10803 /**
10804  * amdgpu_dm_mod_power_setup_streams - setup mod_power stream state post modeset
10805  * @state: the drm atomic state
10806  * @dm: the display manager to update mod_power on
10807  *
10808  * Notify mod_power of mode_change. This needs to be done after dc_stream
10809  * updates have been committed, and VRR parameters have been updated.
10810  */
10811 static void amdgpu_dm_mod_power_setup_streams(struct drm_atomic_commit *state,
10812 					      struct amdgpu_display_manager *dm)
10813 {
10814 	struct dm_crtc_state *dm_new_crtc_state;
10815 	struct drm_crtc_state *new_crtc_state;
10816 	struct amdgpu_crtc *acrtc;
10817 	struct drm_crtc *crtc;
10818 	int i = 0;
10819 
10820 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10821 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10822 		acrtc = to_amdgpu_crtc(crtc);
10823 
10824 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10825 			continue;
10826 
10827 		if (new_crtc_state->active) {
10828 			amdgpu_dm_link_setup_replay(dm_new_crtc_state->stream,
10829 					&acrtc->dm_irq_params.vrr_params);
10830 			mod_power_notify_mode_change(dm->power_module,
10831 						dm_new_crtc_state->stream,
10832 						false);
10833 
10834 			/*
10835 			 * Block PSR / Replay on the new stream until display settles post-modeset.
10836 			 * These events will be cleared by amdgpu_dm_enable_self_refresh() once
10837 			 * allow_sr_entry becomes true.
10838 			 */
10839 			amdgpu_dm_psr_set_event(dm, dm_new_crtc_state->stream, true,
10840 				psr_event_hw_programming, true);
10841 
10842 			amdgpu_dm_replay_set_event(dm, dm_new_crtc_state->stream, true,
10843 				replay_event_hw_programming | replay_event_general_ui,
10844 				true);
10845 		}
10846 	}
10847 
10848 }
10849 
10850 static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state,
10851 					struct dc_state *dc_state)
10852 {
10853 	struct drm_device *dev = state->dev;
10854 	struct amdgpu_device *adev = drm_to_adev(dev);
10855 	struct amdgpu_display_manager *dm = &adev->dm;
10856 	struct drm_crtc *crtc;
10857 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10858 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10859 	struct drm_connector_state *old_con_state;
10860 	struct drm_connector *connector;
10861 	bool mode_set_reset_required = false;
10862 	u32 i;
10863 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
10864 	bool set_backlight_level = false;
10865 
10866 	/* Disable writeback */
10867 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
10868 		struct dm_connector_state *dm_old_con_state;
10869 		struct amdgpu_crtc *acrtc;
10870 
10871 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
10872 			continue;
10873 
10874 		old_crtc_state = NULL;
10875 
10876 		dm_old_con_state = to_dm_connector_state(old_con_state);
10877 		if (!dm_old_con_state->base.crtc)
10878 			continue;
10879 
10880 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
10881 		if (acrtc)
10882 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10883 
10884 		if (!acrtc || !acrtc->wb_enabled)
10885 			continue;
10886 
10887 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10888 
10889 		dm_clear_writeback(dm, dm_old_crtc_state);
10890 		acrtc->wb_enabled = false;
10891 	}
10892 
10893 	amdgpu_dm_mod_power_update_streams(state, dm);
10894 
10895 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
10896 				      new_crtc_state, i) {
10897 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10898 
10899 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10900 
10901 		if (old_crtc_state->active &&
10902 		    (!new_crtc_state->active ||
10903 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10904 			manage_dm_interrupts(adev, acrtc, NULL);
10905 			dc_stream_release(dm_old_crtc_state->stream);
10906 		}
10907 	}
10908 
10909 	drm_atomic_helper_calc_timestamping_constants(state);
10910 
10911 	/* update changed items */
10912 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10913 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10914 
10915 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10916 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10917 
10918 		drm_dbg_state(state->dev,
10919 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
10920 			acrtc->crtc_id,
10921 			new_crtc_state->enable,
10922 			new_crtc_state->active,
10923 			new_crtc_state->planes_changed,
10924 			new_crtc_state->mode_changed,
10925 			new_crtc_state->active_changed,
10926 			new_crtc_state->connectors_changed);
10927 
10928 		/* Disable cursor if disabling crtc */
10929 		if (old_crtc_state->active && !new_crtc_state->active) {
10930 			struct dc_cursor_position position;
10931 
10932 			memset(&position, 0, sizeof(position));
10933 			mutex_lock(&dm->dc_lock);
10934 			dc_exit_ips_for_hw_access(dm->dc);
10935 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
10936 			mutex_unlock(&dm->dc_lock);
10937 		}
10938 
10939 		/* Copy all transient state flags into dc state */
10940 		if (dm_new_crtc_state->stream) {
10941 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
10942 							    dm_new_crtc_state->stream);
10943 		}
10944 
10945 		/* handles headless hotplug case, updating new_state and
10946 		 * aconnector as needed
10947 		 */
10948 
10949 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
10950 
10951 			drm_dbg_atomic(dev,
10952 				       "Atomic commit: SET crtc id %d: [%p]\n",
10953 				       acrtc->crtc_id, acrtc);
10954 
10955 			if (!dm_new_crtc_state->stream) {
10956 				/*
10957 				 * this could happen because of issues with
10958 				 * userspace notifications delivery.
10959 				 * In this case userspace tries to set mode on
10960 				 * display which is disconnected in fact.
10961 				 * dc_sink is NULL in this case on aconnector.
10962 				 * We expect reset mode will come soon.
10963 				 *
10964 				 * This can also happen when unplug is done
10965 				 * during resume sequence ended
10966 				 *
10967 				 * In this case, we want to pretend we still
10968 				 * have a sink to keep the pipe running so that
10969 				 * hw state is consistent with the sw state
10970 				 */
10971 				drm_dbg_atomic(dev,
10972 					       "Failed to create new stream for crtc %d\n",
10973 						acrtc->base.base.id);
10974 				continue;
10975 			}
10976 
10977 			if (dm_old_crtc_state->stream)
10978 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10979 
10980 			pm_runtime_get_noresume(dev->dev);
10981 
10982 			acrtc->enabled = true;
10983 			acrtc->hw_mode = new_crtc_state->mode;
10984 			crtc->hwmode = new_crtc_state->mode;
10985 			mode_set_reset_required = true;
10986 			set_backlight_level = true;
10987 		} else if (modereset_required(new_crtc_state)) {
10988 			drm_dbg_atomic(dev,
10989 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
10990 				       acrtc->crtc_id, acrtc);
10991 			/* i.e. reset mode */
10992 			if (dm_old_crtc_state->stream)
10993 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10994 
10995 			mode_set_reset_required = true;
10996 		}
10997 	} /* for_each_crtc_in_state() */
10998 
10999 	/* if there mode set or reset, flush vblank work queue */
11000 	if (mode_set_reset_required) {
11001 		if (dm->vblank_control_workqueue)
11002 			flush_workqueue(dm->vblank_control_workqueue);
11003 	}
11004 
11005 	dm_enable_per_frame_crtc_master_sync(dc_state);
11006 	mutex_lock(&dm->dc_lock);
11007 	dc_exit_ips_for_hw_access(dm->dc);
11008 	WARN_ON(!dc_commit_streams(dm->dc, &params));
11009 
11010 	bool frl_stream_found = false;
11011 
11012 	for (i = 0; i < params.stream_count; i++) {
11013 		struct dc_stream_state *stream = params.streams[i];
11014 
11015 		if (stream->signal == SIGNAL_TYPE_HDMI_FRL) {
11016 			frl_stream_found = true;
11017 			break;
11018 		}
11019 	}
11020 	if (frl_stream_found) {
11021 		if (queue_delayed_work(dm->hdmi_frl_status_polling_wq,
11022 				       &dm->hdmi_frl_status_polling_work,
11023 				       msecs_to_jiffies(dm->hdmi_frl_status_polling_delay_ms)))
11024 			drm_dbg_kms(dev, "200ms frl status polling starts ...\n");
11025 	} else {
11026 		if (cancel_delayed_work_sync(&dm->hdmi_frl_status_polling_work))
11027 			drm_dbg_kms(dev, "200ms frl status polling stops ...\n");
11028 	}
11029 	/* Allow idle optimization when vblank count is 0 for display off */
11030 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
11031 		dc_allow_idle_optimizations(dm->dc, true);
11032 	mutex_unlock(&dm->dc_lock);
11033 
11034 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11035 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11036 
11037 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11038 
11039 		if (dm_new_crtc_state->stream != NULL) {
11040 			const struct dc_stream_status *status =
11041 					dc_stream_get_status(dm_new_crtc_state->stream);
11042 
11043 			if (!status)
11044 				status = dc_state_get_stream_status(dc_state,
11045 									 dm_new_crtc_state->stream);
11046 			if (!status)
11047 				drm_err(dev,
11048 					"got no status for stream %p on acrtc%p\n",
11049 					dm_new_crtc_state->stream, acrtc);
11050 			else
11051 				acrtc->otg_inst = status->primary_otg_inst;
11052 		}
11053 	}
11054 
11055 	/* During boot up and resume the DC layer will reset the panel brightness
11056 	 * to fix a flicker issue.
11057 	 * It will cause the dm->actual_brightness is not the current panel brightness
11058 	 * level. (the dm->brightness is the correct panel level)
11059 	 * So we set the backlight level with dm->brightness value after set mode
11060 	 */
11061 	if (set_backlight_level) {
11062 		for (i = 0; i < dm->num_of_edps; i++) {
11063 			if (dm->backlight_dev[i])
11064 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11065 		}
11066 	}
11067 }
11068 
11069 static void dm_set_writeback(struct amdgpu_display_manager *dm,
11070 			      struct dm_crtc_state *crtc_state,
11071 			      struct drm_connector *connector,
11072 			      struct drm_connector_state *new_con_state)
11073 {
11074 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
11075 	struct amdgpu_device *adev = dm->adev;
11076 	struct amdgpu_crtc *acrtc;
11077 	struct dc_writeback_info *wb_info;
11078 	struct pipe_ctx *pipe = NULL;
11079 	struct amdgpu_framebuffer *afb;
11080 	int i = 0;
11081 
11082 	wb_info = kzalloc_obj(*wb_info);
11083 	if (!wb_info) {
11084 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
11085 		return;
11086 	}
11087 
11088 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
11089 	if (!acrtc) {
11090 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
11091 		kfree(wb_info);
11092 		return;
11093 	}
11094 
11095 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
11096 	if (!afb) {
11097 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
11098 		kfree(wb_info);
11099 		return;
11100 	}
11101 
11102 	for (i = 0; i < MAX_PIPES; i++) {
11103 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
11104 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
11105 			break;
11106 		}
11107 	}
11108 
11109 	/* fill in wb_info */
11110 	wb_info->wb_enabled = true;
11111 
11112 	wb_info->dwb_pipe_inst = 0;
11113 	wb_info->dwb_params.dwbscl_black_color = 0;
11114 	wb_info->dwb_params.hdr_mult = 0x1F000;
11115 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
11116 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
11117 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
11118 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
11119 
11120 	/* width & height from crtc */
11121 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
11122 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
11123 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
11124 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
11125 
11126 	wb_info->dwb_params.cnv_params.crop_en = false;
11127 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
11128 
11129 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
11130 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
11131 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
11132 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
11133 
11134 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
11135 
11136 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
11137 
11138 	wb_info->dwb_params.scaler_taps.h_taps = 1;
11139 	wb_info->dwb_params.scaler_taps.v_taps = 1;
11140 	wb_info->dwb_params.scaler_taps.h_taps_c = 1;
11141 	wb_info->dwb_params.scaler_taps.v_taps_c = 1;
11142 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
11143 
11144 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
11145 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
11146 
11147 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
11148 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
11149 		wb_info->mcif_buf_params.chroma_address[i] = 0;
11150 	}
11151 
11152 	wb_info->mcif_buf_params.p_vmid = 1;
11153 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
11154 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
11155 		wb_info->mcif_warmup_params.region_size =
11156 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
11157 	}
11158 	wb_info->mcif_warmup_params.p_vmid = 1;
11159 	wb_info->writeback_source_plane = pipe->plane_state;
11160 
11161 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
11162 
11163 	acrtc->wb_pending = true;
11164 	acrtc->wb_conn = wb_conn;
11165 	drm_writeback_queue_job(wb_conn, new_con_state);
11166 }
11167 
11168 static void amdgpu_dm_update_hdcp(struct drm_atomic_commit *state)
11169 {
11170 	struct drm_connector_state *old_con_state, *new_con_state;
11171 	struct drm_device *dev = state->dev;
11172 	struct drm_connector *connector;
11173 	struct amdgpu_device *adev = drm_to_adev(dev);
11174 	int i;
11175 
11176 	if (!adev->dm.hdcp_workqueue)
11177 		return;
11178 
11179 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11180 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11181 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11182 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11183 		struct dm_crtc_state *dm_new_crtc_state;
11184 		struct amdgpu_dm_connector *aconnector;
11185 
11186 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11187 			continue;
11188 
11189 		aconnector = to_amdgpu_dm_connector(connector);
11190 
11191 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
11192 
11193 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
11194 			connector->index, connector->status, connector->dpms);
11195 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
11196 			old_con_state->content_protection, new_con_state->content_protection);
11197 
11198 		if (aconnector->dc_sink) {
11199 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
11200 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
11201 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
11202 				aconnector->dc_sink->edid_caps.display_name);
11203 			}
11204 		}
11205 
11206 		new_crtc_state = NULL;
11207 		old_crtc_state = NULL;
11208 
11209 		if (acrtc) {
11210 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11211 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11212 		}
11213 
11214 		if (old_crtc_state)
11215 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11216 			old_crtc_state->enable,
11217 			old_crtc_state->active,
11218 			old_crtc_state->mode_changed,
11219 			old_crtc_state->active_changed,
11220 			old_crtc_state->connectors_changed);
11221 
11222 		if (new_crtc_state)
11223 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11224 			new_crtc_state->enable,
11225 			new_crtc_state->active,
11226 			new_crtc_state->mode_changed,
11227 			new_crtc_state->active_changed,
11228 			new_crtc_state->connectors_changed);
11229 
11230 
11231 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11232 
11233 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
11234 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
11235 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
11236 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
11237 			dm_new_con_state->update_hdcp = true;
11238 			continue;
11239 		}
11240 
11241 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
11242 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
11243 			/* when display is unplugged from mst hub, connctor will
11244 			 * be destroyed within dm_dp_mst_connector_destroy. connector
11245 			 * hdcp perperties, like type, undesired, desired, enabled,
11246 			 * will be lost. So, save hdcp properties into hdcp_work within
11247 			 * amdgpu_dm_atomic_commit_tail. if the same display is
11248 			 * plugged back with same display index, its hdcp properties
11249 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
11250 			 */
11251 
11252 			bool enable_encryption = false;
11253 
11254 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
11255 				enable_encryption = true;
11256 
11257 			if (aconnector->dc_link && aconnector->dc_sink &&
11258 				aconnector->dc_link->type == dc_connection_mst_branch) {
11259 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
11260 				struct hdcp_workqueue *hdcp_w =
11261 					&hdcp_work[aconnector->dc_link->link_index];
11262 
11263 				hdcp_w->hdcp_content_type[connector->index] =
11264 					new_con_state->hdcp_content_type;
11265 				hdcp_w->content_protection[connector->index] =
11266 					new_con_state->content_protection;
11267 			}
11268 
11269 			if (new_crtc_state && new_crtc_state->mode_changed &&
11270 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
11271 				enable_encryption = true;
11272 
11273 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
11274 
11275 			if (aconnector->dc_link)
11276 				hdcp_update_display(
11277 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
11278 					new_con_state->hdcp_content_type, enable_encryption);
11279 		}
11280 	}
11281 }
11282 
11283 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state)
11284 {
11285 	struct drm_crtc *crtc;
11286 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11287 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11288 	int i, ret;
11289 
11290 	ret = drm_dp_mst_atomic_setup_commit(state);
11291 	if (ret)
11292 		return ret;
11293 
11294 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11295 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11296 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11297 		/*
11298 		 * Color management settings. We also update color properties
11299 		 * when a modeset is needed, to ensure it gets reprogrammed.
11300 		 */
11301 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
11302 		    (dm_new_crtc_state->base.color_mgmt_changed ||
11303 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11304 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11305 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
11306 			if (ret) {
11307 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
11308 				return ret;
11309 			}
11310 		}
11311 	}
11312 
11313 	return 0;
11314 }
11315 
11316 /**
11317  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
11318  * @state: The atomic state to commit
11319  *
11320  * This will tell DC to commit the constructed DC state from atomic_check,
11321  * programming the hardware. Any failures here implies a hardware failure, since
11322  * atomic check should have filtered anything non-kosher.
11323  */
11324 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state)
11325 {
11326 	struct drm_device *dev = state->dev;
11327 	struct amdgpu_device *adev = drm_to_adev(dev);
11328 	struct amdgpu_display_manager *dm = &adev->dm;
11329 	struct dm_atomic_state *dm_state;
11330 	struct dc_state *dc_state = NULL;
11331 	u32 i, j;
11332 	struct drm_crtc *crtc;
11333 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11334 	unsigned long flags;
11335 	bool wait_for_vblank = true;
11336 	struct drm_connector *connector;
11337 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
11338 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11339 	int crtc_disable_count = 0;
11340 
11341 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
11342 
11343 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
11344 	drm_dp_mst_atomic_wait_for_dependencies(state);
11345 
11346 	dm_state = dm_atomic_get_new_state(state);
11347 	if (dm_state && dm_state->context) {
11348 		dc_state = dm_state->context;
11349 		amdgpu_dm_commit_streams(state, dc_state);
11350 	}
11351 
11352 	amdgpu_dm_update_hdcp(state);
11353 
11354 	/* Handle connector state changes */
11355 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11356 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11357 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
11358 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11359 		struct dc_surface_update *dummy_updates;
11360 		struct dc_stream_update stream_update;
11361 		struct dc_info_packet hdr_packet;
11362 		struct dc_stream_status *status = NULL;
11363 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
11364 
11365 		memset(&stream_update, 0, sizeof(stream_update));
11366 
11367 		if (acrtc) {
11368 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11369 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11370 		}
11371 
11372 		/* Skip any modesets/resets */
11373 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
11374 			continue;
11375 
11376 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11377 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11378 
11379 		scaling_changed = is_scaling_state_different(dm_new_con_state,
11380 							     dm_old_con_state);
11381 
11382 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
11383 			(dm_old_crtc_state->stream->output_color_space !=
11384 				get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
11385 			output_color_space_changed = true;
11386 
11387 		abm_changed = dm_new_crtc_state->abm_level !=
11388 			      dm_old_crtc_state->abm_level;
11389 
11390 		hdr_changed =
11391 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
11392 
11393 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
11394 			continue;
11395 
11396 		stream_update.stream = dm_new_crtc_state->stream;
11397 		if (scaling_changed) {
11398 			update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
11399 					dm_new_con_state, dm_new_crtc_state->stream);
11400 
11401 			stream_update.src = dm_new_crtc_state->stream->src;
11402 			stream_update.dst = dm_new_crtc_state->stream->dst;
11403 		}
11404 
11405 		if (output_color_space_changed) {
11406 			dm_new_crtc_state->stream->output_color_space
11407 				= get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
11408 
11409 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
11410 		}
11411 
11412 		if (abm_changed) {
11413 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
11414 
11415 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
11416 		}
11417 
11418 		if (hdr_changed) {
11419 			fill_hdr_info_packet(new_con_state, &hdr_packet);
11420 			stream_update.hdr_static_metadata = &hdr_packet;
11421 		}
11422 
11423 		status = dc_stream_get_status(dm_new_crtc_state->stream);
11424 
11425 		if (WARN_ON(!status))
11426 			continue;
11427 
11428 		WARN_ON(!status->plane_count);
11429 
11430 		/*
11431 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
11432 		 * Here we create an empty update on each plane.
11433 		 * To fix this, DC should permit updating only stream properties.
11434 		 */
11435 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
11436 		if (!dummy_updates) {
11437 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
11438 			continue;
11439 		}
11440 		for (j = 0; j < status->plane_count; j++)
11441 			dummy_updates[j].surface = status->plane_states[j];
11442 
11443 		sort(dummy_updates, status->plane_count,
11444 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
11445 
11446 		mutex_lock(&dm->dc_lock);
11447 		dc_exit_ips_for_hw_access(dm->dc);
11448 		dc_update_planes_and_stream(dm->dc,
11449 					    dummy_updates,
11450 					    status->plane_count,
11451 					    dm_new_crtc_state->stream,
11452 					    &stream_update);
11453 		mutex_unlock(&dm->dc_lock);
11454 		kfree(dummy_updates);
11455 
11456 		drm_connector_update_privacy_screen(new_con_state);
11457 	}
11458 
11459 	/**
11460 	 * Enable interrupts for CRTCs that are newly enabled or went through
11461 	 * a modeset. It was intentionally deferred until after the front end
11462 	 * state was modified to wait until the OTG was on and so the IRQ
11463 	 * handlers didn't access stale or invalid state.
11464 	 */
11465 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11466 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11467 #ifdef CONFIG_DEBUG_FS
11468 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
11469 #endif
11470 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
11471 		if (old_crtc_state->active && !new_crtc_state->active)
11472 			crtc_disable_count++;
11473 
11474 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11475 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11476 
11477 		/* For freesync config update on crtc state and params for irq */
11478 		update_stream_irq_parameters(dm, dm_new_crtc_state);
11479 
11480 #ifdef CONFIG_DEBUG_FS
11481 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11482 		cur_crc_src = acrtc->dm_irq_params.crc_src;
11483 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11484 #endif
11485 
11486 		if (new_crtc_state->active &&
11487 		    (!old_crtc_state->active ||
11488 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11489 			dc_stream_retain(dm_new_crtc_state->stream);
11490 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
11491 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
11492 		}
11493 		/* Handle vrr on->off / off->on transitions */
11494 		amdgpu_dm_handle_vrr_transition(dm, dm_old_crtc_state, dm_new_crtc_state);
11495 
11496 #ifdef CONFIG_DEBUG_FS
11497 		if (new_crtc_state->active &&
11498 		    (!old_crtc_state->active ||
11499 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11500 			/**
11501 			 * Frontend may have changed so reapply the CRC capture
11502 			 * settings for the stream.
11503 			 */
11504 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
11505 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
11506 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
11507 					uint8_t cnt;
11508 
11509 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11510 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
11511 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
11512 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
11513 
11514 							/**
11515 							 * It takes 2 frames for HW to stably generate CRC when
11516 							 * resuming from suspend, so we set skip_frame_cnt 2.
11517 							 */
11518 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
11519 						}
11520 					}
11521 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11522 				}
11523 #endif
11524 				if (amdgpu_dm_crtc_configure_crc_source(
11525 					crtc, dm_new_crtc_state, cur_crc_src))
11526 					drm_dbg_atomic(dev, "Failed to configure crc source");
11527 			}
11528 		}
11529 #endif
11530 	}
11531 
11532 	amdgpu_dm_mod_power_setup_streams(state, dm);
11533 
11534 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
11535 		if (new_crtc_state->async_flip)
11536 			wait_for_vblank = false;
11537 
11538 	/* update planes when needed per crtc*/
11539 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
11540 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11541 
11542 		if (dm_new_crtc_state->stream)
11543 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
11544 	}
11545 
11546 	/* Enable writeback */
11547 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11548 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11549 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11550 
11551 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11552 			continue;
11553 
11554 		if (!new_con_state->writeback_job)
11555 			continue;
11556 
11557 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11558 
11559 		if (!new_crtc_state)
11560 			continue;
11561 
11562 		if (acrtc->wb_enabled)
11563 			continue;
11564 
11565 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11566 
11567 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
11568 		acrtc->wb_enabled = true;
11569 	}
11570 
11571 	/* Update audio instances for each connector. */
11572 	amdgpu_dm_commit_audio(dev, state);
11573 
11574 	/* restore the backlight level */
11575 	for (i = 0; i < dm->num_of_edps; i++) {
11576 		if (dm->backlight_dev[i] &&
11577 		    (dm->actual_brightness[i] != dm->brightness[i]))
11578 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11579 	}
11580 
11581 	/*
11582 	 * send vblank event on all events not handled in flip and
11583 	 * mark consumed event for drm_atomic_helper_commit_hw_done
11584 	 */
11585 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11586 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11587 
11588 		if (new_crtc_state->event)
11589 			drm_send_event_locked(dev, &new_crtc_state->event->base);
11590 
11591 		new_crtc_state->event = NULL;
11592 	}
11593 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11594 
11595 	/* Signal HW programming completion */
11596 	drm_atomic_helper_commit_hw_done(state);
11597 
11598 	if (wait_for_vblank)
11599 		drm_atomic_helper_wait_for_flip_done(dev, state);
11600 
11601 	drm_atomic_helper_cleanup_planes(dev, state);
11602 
11603 	/* Don't free the memory if we are hitting this as part of suspend.
11604 	 * This way we don't free any memory during suspend; see
11605 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
11606 	 * non-suspend modeset or when the driver is torn down.
11607 	 */
11608 	if (!adev->in_suspend) {
11609 		/* return the stolen vga memory back to VRAM */
11610 		if (!adev->mman.keep_stolen_vga_memory)
11611 			amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_VGA);
11612 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_EXTENDED);
11613 	}
11614 
11615 	/*
11616 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
11617 	 * so we can put the GPU into runtime suspend if we're not driving any
11618 	 * displays anymore
11619 	 */
11620 	for (i = 0; i < crtc_disable_count; i++)
11621 		pm_runtime_put_autosuspend(dev->dev);
11622 	pm_runtime_mark_last_busy(dev->dev);
11623 
11624 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
11625 }
11626 
11627 static int dm_force_atomic_commit(struct drm_connector *connector)
11628 {
11629 	int ret = 0;
11630 	struct drm_device *ddev = connector->dev;
11631 	struct drm_atomic_commit *state = drm_atomic_commit_alloc(ddev);
11632 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11633 	struct drm_plane *plane = disconnected_acrtc->base.primary;
11634 	struct drm_connector_state *conn_state;
11635 	struct drm_crtc_state *crtc_state;
11636 	struct drm_plane_state *plane_state;
11637 
11638 	if (!state)
11639 		return -ENOMEM;
11640 
11641 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
11642 
11643 	/* Construct an atomic state to restore previous display setting */
11644 
11645 	/*
11646 	 * Attach connectors to drm_atomic_commit
11647 	 */
11648 	conn_state = drm_atomic_get_connector_state(state, connector);
11649 
11650 	/* Check for error in getting connector state */
11651 	if (IS_ERR(conn_state)) {
11652 		ret = PTR_ERR(conn_state);
11653 		goto out;
11654 	}
11655 
11656 	/* Attach crtc to drm_atomic_commit*/
11657 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
11658 
11659 	/* Check for error in getting crtc state */
11660 	if (IS_ERR(crtc_state)) {
11661 		ret = PTR_ERR(crtc_state);
11662 		goto out;
11663 	}
11664 
11665 	/* force a restore */
11666 	crtc_state->mode_changed = true;
11667 
11668 	/* Attach plane to drm_atomic_commit */
11669 	plane_state = drm_atomic_get_plane_state(state, plane);
11670 
11671 	/* Check for error in getting plane state */
11672 	if (IS_ERR(plane_state)) {
11673 		ret = PTR_ERR(plane_state);
11674 		goto out;
11675 	}
11676 
11677 	/* Call commit internally with the state we just constructed */
11678 	ret = drm_atomic_commit(state);
11679 
11680 out:
11681 	drm_atomic_commit_put(state);
11682 	if (ret)
11683 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
11684 
11685 	return ret;
11686 }
11687 
11688 /*
11689  * This function handles all cases when set mode does not come upon hotplug.
11690  * This includes when a display is unplugged then plugged back into the
11691  * same port and when running without usermode desktop manager supprot
11692  */
11693 void dm_restore_drm_connector_state(struct drm_device *dev,
11694 				    struct drm_connector *connector)
11695 {
11696 	struct amdgpu_dm_connector *aconnector;
11697 	struct amdgpu_crtc *disconnected_acrtc;
11698 	struct dm_crtc_state *acrtc_state;
11699 
11700 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11701 		return;
11702 
11703 	aconnector = to_amdgpu_dm_connector(connector);
11704 
11705 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
11706 		return;
11707 
11708 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11709 	if (!disconnected_acrtc)
11710 		return;
11711 
11712 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
11713 	if (!acrtc_state->stream)
11714 		return;
11715 
11716 	/*
11717 	 * If the previous sink is not released and different from the current,
11718 	 * we deduce we are in a state where we can not rely on usermode call
11719 	 * to turn on the display, so we do it here
11720 	 */
11721 	if (acrtc_state->stream->sink != aconnector->dc_sink)
11722 		dm_force_atomic_commit(&aconnector->base);
11723 }
11724 
11725 /*
11726  * Grabs all modesetting locks to serialize against any blocking commits,
11727  * Waits for completion of all non blocking commits.
11728  */
11729 static int do_aquire_global_lock(struct drm_device *dev,
11730 				 struct drm_atomic_commit *state)
11731 {
11732 	struct drm_crtc *crtc;
11733 	struct drm_crtc_commit *commit;
11734 	long ret;
11735 
11736 	/*
11737 	 * Adding all modeset locks to aquire_ctx will
11738 	 * ensure that when the framework release it the
11739 	 * extra locks we are locking here will get released to
11740 	 */
11741 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
11742 	if (ret)
11743 		return ret;
11744 
11745 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
11746 		spin_lock(&crtc->commit_lock);
11747 		commit = list_first_entry_or_null(&crtc->commit_list,
11748 				struct drm_crtc_commit, commit_entry);
11749 		if (commit)
11750 			drm_crtc_commit_get(commit);
11751 		spin_unlock(&crtc->commit_lock);
11752 
11753 		if (!commit)
11754 			continue;
11755 
11756 		/*
11757 		 * Make sure all pending HW programming completed and
11758 		 * page flips done
11759 		 */
11760 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
11761 
11762 		if (ret > 0)
11763 			ret = wait_for_completion_interruptible_timeout(
11764 					&commit->flip_done, 10*HZ);
11765 
11766 		if (ret == 0)
11767 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
11768 				  crtc->base.id, crtc->name);
11769 
11770 		drm_crtc_commit_put(commit);
11771 	}
11772 
11773 	return ret < 0 ? ret : 0;
11774 }
11775 
11776 static void get_freesync_config_for_crtc(
11777 	struct dm_crtc_state *new_crtc_state,
11778 	struct dm_connector_state *new_con_state)
11779 {
11780 	struct mod_freesync_config config = {0};
11781 	struct amdgpu_dm_connector *aconnector;
11782 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
11783 	int vrefresh = drm_mode_vrefresh(mode);
11784 	bool fs_vid_mode = false;
11785 
11786 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11787 		return;
11788 
11789 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
11790 
11791 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
11792 					vrefresh >= aconnector->min_vfreq &&
11793 					vrefresh <= aconnector->max_vfreq;
11794 
11795 	if (new_crtc_state->vrr_supported) {
11796 		new_crtc_state->stream->ignore_msa_timing_param = true;
11797 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
11798 
11799 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
11800 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
11801 		config.vsif_supported = true;
11802 		config.btr = true;
11803 
11804 		if (fs_vid_mode) {
11805 			config.state = VRR_STATE_ACTIVE_FIXED;
11806 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
11807 			goto out;
11808 		} else if (new_crtc_state->base.vrr_enabled) {
11809 			config.state = VRR_STATE_ACTIVE_VARIABLE;
11810 		} else {
11811 			config.state = VRR_STATE_INACTIVE;
11812 		}
11813 	} else {
11814 		config.state = VRR_STATE_UNSUPPORTED;
11815 	}
11816 out:
11817 	new_crtc_state->freesync_config = config;
11818 }
11819 
11820 static void reset_freesync_config_for_crtc(
11821 	struct dm_crtc_state *new_crtc_state)
11822 {
11823 	new_crtc_state->vrr_supported = false;
11824 
11825 	memset(&new_crtc_state->vrr_infopacket, 0,
11826 	       sizeof(new_crtc_state->vrr_infopacket));
11827 }
11828 
11829 static bool
11830 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
11831 				 struct drm_crtc_state *new_crtc_state)
11832 {
11833 	const struct drm_display_mode *old_mode, *new_mode;
11834 
11835 	if (!old_crtc_state || !new_crtc_state)
11836 		return false;
11837 
11838 	old_mode = &old_crtc_state->mode;
11839 	new_mode = &new_crtc_state->mode;
11840 
11841 	if (old_mode->clock       == new_mode->clock &&
11842 	    old_mode->hdisplay    == new_mode->hdisplay &&
11843 	    old_mode->vdisplay    == new_mode->vdisplay &&
11844 	    old_mode->htotal      == new_mode->htotal &&
11845 	    old_mode->vtotal      != new_mode->vtotal &&
11846 	    old_mode->hsync_start == new_mode->hsync_start &&
11847 	    old_mode->vsync_start != new_mode->vsync_start &&
11848 	    old_mode->hsync_end   == new_mode->hsync_end &&
11849 	    old_mode->vsync_end   != new_mode->vsync_end &&
11850 	    old_mode->hskew       == new_mode->hskew &&
11851 	    old_mode->vscan       == new_mode->vscan &&
11852 	    (old_mode->vsync_end - old_mode->vsync_start) ==
11853 	    (new_mode->vsync_end - new_mode->vsync_start))
11854 		return true;
11855 
11856 	return false;
11857 }
11858 
11859 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
11860 {
11861 	u64 num, den, res;
11862 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
11863 
11864 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
11865 
11866 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
11867 	den = (unsigned long long)new_crtc_state->mode.htotal *
11868 	      (unsigned long long)new_crtc_state->mode.vtotal;
11869 
11870 	res = div_u64(num, den);
11871 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
11872 }
11873 
11874 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
11875 			 struct drm_atomic_commit *state,
11876 			 struct drm_crtc *crtc,
11877 			 struct drm_crtc_state *old_crtc_state,
11878 			 struct drm_crtc_state *new_crtc_state,
11879 			 bool enable,
11880 			 bool *lock_and_validation_needed)
11881 {
11882 	struct dm_atomic_state *dm_state = NULL;
11883 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11884 	struct dc_stream_state *new_stream;
11885 	struct amdgpu_device *adev = dm->adev;
11886 	int ret = 0;
11887 
11888 	/*
11889 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
11890 	 * update changed items
11891 	 */
11892 	struct amdgpu_crtc *acrtc = NULL;
11893 	struct drm_connector *connector = NULL;
11894 	struct amdgpu_dm_connector *aconnector = NULL;
11895 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
11896 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
11897 
11898 	new_stream = NULL;
11899 
11900 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11901 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11902 	acrtc = to_amdgpu_crtc(crtc);
11903 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
11904 	if (connector)
11905 		aconnector = to_amdgpu_dm_connector(connector);
11906 
11907 	/* TODO This hack should go away */
11908 	if (connector && enable) {
11909 		/* Make sure fake sink is created in plug-in scenario */
11910 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
11911 									connector);
11912 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
11913 									connector);
11914 
11915 		if (WARN_ON(!drm_new_conn_state)) {
11916 			ret = -EINVAL;
11917 			goto fail;
11918 		}
11919 
11920 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
11921 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
11922 
11923 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11924 			goto skip_modeset;
11925 
11926 		new_stream = create_validate_stream_for_sink(connector,
11927 							     &new_crtc_state->mode,
11928 							     dm_new_conn_state,
11929 							     dm_old_crtc_state->stream);
11930 
11931 		/*
11932 		 * we can have no stream on ACTION_SET if a display
11933 		 * was disconnected during S3, in this case it is not an
11934 		 * error, the OS will be updated after detection, and
11935 		 * will do the right thing on next atomic commit
11936 		 */
11937 
11938 		if (!new_stream) {
11939 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
11940 					__func__, acrtc->base.base.id);
11941 			ret = -ENOMEM;
11942 			goto fail;
11943 		}
11944 
11945 		/*
11946 		 * TODO: Check VSDB bits to decide whether this should
11947 		 * be enabled or not.
11948 		 */
11949 		new_stream->triggered_crtc_reset.enabled =
11950 			dm->force_timing_sync;
11951 
11952 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11953 
11954 		ret = fill_hdr_info_packet(drm_new_conn_state,
11955 					   &new_stream->hdr_static_metadata);
11956 		if (ret)
11957 			goto fail;
11958 
11959 		/*
11960 		 * If we already removed the old stream from the context
11961 		 * (and set the new stream to NULL) then we can't reuse
11962 		 * the old stream even if the stream and scaling are unchanged.
11963 		 * We'll hit the BUG_ON and black screen.
11964 		 *
11965 		 * TODO: Refactor this function to allow this check to work
11966 		 * in all conditions.
11967 		 */
11968 		if (amdgpu_freesync_vid_mode &&
11969 		    dm_new_crtc_state->stream &&
11970 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
11971 			goto skip_modeset;
11972 
11973 		if (dm_new_crtc_state->stream &&
11974 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11975 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
11976 			new_crtc_state->mode_changed = false;
11977 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
11978 					 new_crtc_state->mode_changed);
11979 		}
11980 	}
11981 
11982 	/* mode_changed flag may get updated above, need to check again */
11983 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11984 		goto skip_modeset;
11985 
11986 	drm_dbg_state(state->dev,
11987 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
11988 		acrtc->crtc_id,
11989 		new_crtc_state->enable,
11990 		new_crtc_state->active,
11991 		new_crtc_state->planes_changed,
11992 		new_crtc_state->mode_changed,
11993 		new_crtc_state->active_changed,
11994 		new_crtc_state->connectors_changed);
11995 
11996 	/* Remove stream for any changed/disabled CRTC */
11997 	if (!enable) {
11998 
11999 		if (!dm_old_crtc_state->stream)
12000 			goto skip_modeset;
12001 
12002 		/* Unset freesync video if it was active before */
12003 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
12004 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
12005 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
12006 		}
12007 
12008 		/* Now check if we should set freesync video mode */
12009 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
12010 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
12011 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
12012 		    is_timing_unchanged_for_freesync(new_crtc_state,
12013 						     old_crtc_state)) {
12014 			new_crtc_state->mode_changed = false;
12015 			drm_dbg_driver(adev_to_drm(adev),
12016 				"Mode change not required for front porch change, setting mode_changed to %d",
12017 				new_crtc_state->mode_changed);
12018 
12019 			set_freesync_fixed_config(dm_new_crtc_state);
12020 
12021 			goto skip_modeset;
12022 		} else if (amdgpu_freesync_vid_mode && aconnector &&
12023 			   is_freesync_video_mode(&new_crtc_state->mode,
12024 						  aconnector)) {
12025 			struct drm_display_mode *high_mode;
12026 
12027 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
12028 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
12029 				set_freesync_fixed_config(dm_new_crtc_state);
12030 		}
12031 
12032 		ret = dm_atomic_get_state(state, &dm_state);
12033 		if (ret)
12034 			goto fail;
12035 
12036 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
12037 				crtc->base.id);
12038 
12039 		/* i.e. reset mode */
12040 		if (dc_state_remove_stream(
12041 				dm->dc,
12042 				dm_state->context,
12043 				dm_old_crtc_state->stream) != DC_OK) {
12044 			ret = -EINVAL;
12045 			goto fail;
12046 		}
12047 
12048 		dc_stream_release(dm_old_crtc_state->stream);
12049 		dm_new_crtc_state->stream = NULL;
12050 
12051 		reset_freesync_config_for_crtc(dm_new_crtc_state);
12052 
12053 		*lock_and_validation_needed = true;
12054 
12055 	} else {/* Add stream for any updated/enabled CRTC */
12056 		/*
12057 		 * Quick fix to prevent NULL pointer on new_stream when
12058 		 * added MST connectors not found in existing crtc_state in the chained mode
12059 		 * TODO: need to dig out the root cause of that
12060 		 */
12061 		if (!connector)
12062 			goto skip_modeset;
12063 
12064 		if (modereset_required(new_crtc_state))
12065 			goto skip_modeset;
12066 
12067 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
12068 				     dm_old_crtc_state->stream)) {
12069 
12070 			WARN_ON(dm_new_crtc_state->stream);
12071 
12072 			ret = dm_atomic_get_state(state, &dm_state);
12073 			if (ret)
12074 				goto fail;
12075 
12076 			dm_new_crtc_state->stream = new_stream;
12077 
12078 			dc_stream_retain(new_stream);
12079 
12080 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
12081 					 crtc->base.id);
12082 
12083 			if (dc_state_add_stream(
12084 					dm->dc,
12085 					dm_state->context,
12086 					dm_new_crtc_state->stream) != DC_OK) {
12087 				ret = -EINVAL;
12088 				goto fail;
12089 			}
12090 
12091 			*lock_and_validation_needed = true;
12092 		}
12093 	}
12094 
12095 skip_modeset:
12096 	/* Release extra reference */
12097 	if (new_stream)
12098 		dc_stream_release(new_stream);
12099 
12100 	/*
12101 	 * We want to do dc stream updates that do not require a
12102 	 * full modeset below.
12103 	 */
12104 	if (!(enable && connector && new_crtc_state->active))
12105 		return 0;
12106 	/*
12107 	 * Given above conditions, the dc state cannot be NULL because:
12108 	 * 1. We're in the process of enabling CRTCs (just been added
12109 	 *    to the dc context, or already is on the context)
12110 	 * 2. Has a valid connector attached, and
12111 	 * 3. Is currently active and enabled.
12112 	 * => The dc stream state currently exists.
12113 	 */
12114 	BUG_ON(dm_new_crtc_state->stream == NULL);
12115 
12116 	/* Scaling or underscan settings */
12117 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
12118 				drm_atomic_crtc_needs_modeset(new_crtc_state))
12119 		update_stream_scaling_settings(adev_to_drm(adev),
12120 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
12121 
12122 	/* ABM settings */
12123 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
12124 
12125 	/*
12126 	 * Color management settings. We also update color properties
12127 	 * when a modeset is needed, to ensure it gets reprogrammed.
12128 	 */
12129 	if (dm_new_crtc_state->base.color_mgmt_changed ||
12130 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
12131 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
12132 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
12133 		if (ret)
12134 			goto fail;
12135 	}
12136 
12137 	/* Update Freesync settings. */
12138 	get_freesync_config_for_crtc(dm_new_crtc_state,
12139 				     dm_new_conn_state);
12140 
12141 	return ret;
12142 
12143 fail:
12144 	if (new_stream)
12145 		dc_stream_release(new_stream);
12146 	return ret;
12147 }
12148 
12149 static bool should_reset_plane(struct drm_atomic_commit *state,
12150 			       struct drm_plane *plane,
12151 			       struct drm_plane_state *old_plane_state,
12152 			       struct drm_plane_state *new_plane_state)
12153 {
12154 	struct drm_plane *other;
12155 	struct drm_plane_state *old_other_state, *new_other_state;
12156 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12157 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
12158 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
12159 	struct drm_connector_state *new_con_state;
12160 	struct drm_connector *connector;
12161 	int i;
12162 
12163 	/*
12164 	 * TODO: Remove this hack for all asics once it proves that the
12165 	 * fast updates works fine on DCN3.2+.
12166 	 */
12167 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
12168 	    state->allow_modeset)
12169 		return true;
12170 
12171 	/* Check for writeback commit */
12172 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
12173 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
12174 			continue;
12175 
12176 		if (new_con_state->writeback_job)
12177 			return true;
12178 	}
12179 
12180 	if (amdgpu_in_reset(adev) && state->allow_modeset)
12181 		return true;
12182 
12183 	/* Exit early if we know that we're adding or removing the plane. */
12184 	if (old_plane_state->crtc != new_plane_state->crtc)
12185 		return true;
12186 
12187 	/* old crtc == new_crtc == NULL, plane not in context. */
12188 	if (!new_plane_state->crtc)
12189 		return false;
12190 
12191 	new_crtc_state =
12192 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
12193 	old_crtc_state =
12194 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
12195 
12196 	if (!new_crtc_state)
12197 		return true;
12198 
12199 	/*
12200 	 * A change in cursor mode means a new dc pipe needs to be acquired or
12201 	 * released from the state
12202 	 */
12203 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
12204 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
12205 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
12206 	    old_dm_crtc_state != NULL &&
12207 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
12208 		return true;
12209 	}
12210 
12211 	/* CRTC Degamma changes currently require us to recreate planes. */
12212 	if (new_crtc_state->color_mgmt_changed)
12213 		return true;
12214 
12215 	/* Plane color pipeline or its colorop changes. */
12216 	if (new_plane_state->color_mgmt_changed)
12217 		return true;
12218 
12219 	/*
12220 	 * On zpos change, planes need to be reordered by removing and re-adding
12221 	 * them one by one to the dc state, in order of descending zpos.
12222 	 *
12223 	 * TODO: We can likely skip bandwidth validation if the only thing that
12224 	 * changed about the plane was it'z z-ordering.
12225 	 */
12226 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
12227 		return true;
12228 
12229 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
12230 		return true;
12231 
12232 	/*
12233 	 * If there are any new primary or overlay planes being added or
12234 	 * removed then the z-order can potentially change. To ensure
12235 	 * correct z-order and pipe acquisition the current DC architecture
12236 	 * requires us to remove and recreate all existing planes.
12237 	 *
12238 	 * TODO: Come up with a more elegant solution for this.
12239 	 */
12240 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
12241 		struct amdgpu_framebuffer *old_afb, *new_afb;
12242 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
12243 
12244 		dm_new_other_state = to_dm_plane_state(new_other_state);
12245 		dm_old_other_state = to_dm_plane_state(old_other_state);
12246 
12247 		if (other->type == DRM_PLANE_TYPE_CURSOR)
12248 			continue;
12249 
12250 		if (old_other_state->crtc != new_plane_state->crtc &&
12251 		    new_other_state->crtc != new_plane_state->crtc)
12252 			continue;
12253 
12254 		if (old_other_state->crtc != new_other_state->crtc)
12255 			return true;
12256 
12257 		/* Src/dst size and scaling updates. */
12258 		if (old_other_state->src_w != new_other_state->src_w ||
12259 		    old_other_state->src_h != new_other_state->src_h ||
12260 		    old_other_state->crtc_w != new_other_state->crtc_w ||
12261 		    old_other_state->crtc_h != new_other_state->crtc_h)
12262 			return true;
12263 
12264 		/* Rotation / mirroring updates. */
12265 		if (old_other_state->rotation != new_other_state->rotation)
12266 			return true;
12267 
12268 		/* Blending updates. */
12269 		if (old_other_state->pixel_blend_mode !=
12270 		    new_other_state->pixel_blend_mode)
12271 			return true;
12272 
12273 		/* Alpha updates. */
12274 		if (old_other_state->alpha != new_other_state->alpha)
12275 			return true;
12276 
12277 		/* Colorspace changes. */
12278 		if (old_other_state->color_range != new_other_state->color_range ||
12279 		    old_other_state->color_encoding != new_other_state->color_encoding)
12280 			return true;
12281 
12282 		/* HDR/Transfer Function changes. */
12283 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
12284 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
12285 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
12286 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
12287 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
12288 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
12289 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
12290 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
12291 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
12292 			return true;
12293 
12294 		/* Framebuffer checks fall at the end. */
12295 		if (!old_other_state->fb || !new_other_state->fb)
12296 			continue;
12297 
12298 		/* Pixel format changes can require bandwidth updates. */
12299 		if (old_other_state->fb->format != new_other_state->fb->format)
12300 			return true;
12301 
12302 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
12303 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
12304 
12305 		/* Tiling and DCC changes also require bandwidth updates. */
12306 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
12307 		    old_afb->base.modifier != new_afb->base.modifier)
12308 			return true;
12309 	}
12310 
12311 	return false;
12312 }
12313 
12314 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
12315 			      struct drm_plane_state *new_plane_state,
12316 			      struct drm_framebuffer *fb)
12317 {
12318 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
12319 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
12320 	unsigned int pitch;
12321 	bool linear;
12322 
12323 	if (fb->width > new_acrtc->max_cursor_width ||
12324 	    fb->height > new_acrtc->max_cursor_height) {
12325 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB size %dx%d\n",
12326 				 new_plane_state->fb->width,
12327 				 new_plane_state->fb->height);
12328 		return -EINVAL;
12329 	}
12330 	if (new_plane_state->src_w != fb->width << 16 ||
12331 	    new_plane_state->src_h != fb->height << 16) {
12332 		drm_dbg_atomic(adev_to_drm(adev), "Cropping not supported for cursor plane\n");
12333 		return -EINVAL;
12334 	}
12335 
12336 	/* Pitch in pixels */
12337 	pitch = fb->pitches[0] / fb->format->cpp[0];
12338 
12339 	if (fb->width != pitch) {
12340 		drm_dbg_atomic(adev_to_drm(adev), "Cursor FB width %d doesn't match pitch %d",
12341 				 fb->width, pitch);
12342 		return -EINVAL;
12343 	}
12344 
12345 	switch (pitch) {
12346 	case 64:
12347 	case 128:
12348 	case 256:
12349 		/* FB pitch is supported by cursor plane */
12350 		break;
12351 	default:
12352 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB pitch %d px\n", pitch);
12353 		return -EINVAL;
12354 	}
12355 
12356 	/* Core DRM takes care of checking FB modifiers, so we only need to
12357 	 * check tiling flags when the FB doesn't have a modifier.
12358 	 */
12359 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
12360 		if (adev->family == AMDGPU_FAMILY_GC_12_0_0) {
12361 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
12362 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
12363 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
12364 		} else {
12365 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
12366 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
12367 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
12368 		}
12369 		if (!linear) {
12370 			drm_dbg_atomic(adev_to_drm(adev), "Cursor FB not linear");
12371 			return -EINVAL;
12372 		}
12373 	}
12374 
12375 	return 0;
12376 }
12377 
12378 /*
12379  * Helper function for checking the cursor in native mode
12380  */
12381 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
12382 					struct drm_plane *plane,
12383 					struct drm_plane_state *new_plane_state,
12384 					bool enable)
12385 {
12386 
12387 	struct amdgpu_crtc *new_acrtc;
12388 	int ret;
12389 
12390 	if (!enable || !new_plane_crtc ||
12391 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
12392 		return 0;
12393 
12394 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
12395 
12396 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
12397 		drm_dbg_atomic(new_plane_crtc->dev, "Cropping not supported for cursor plane\n");
12398 		return -EINVAL;
12399 	}
12400 
12401 	if (new_plane_state->fb) {
12402 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
12403 						new_plane_state->fb);
12404 		if (ret)
12405 			return ret;
12406 	}
12407 
12408 	return 0;
12409 }
12410 
12411 static bool dm_should_update_native_cursor(struct drm_atomic_commit *state,
12412 					   struct drm_crtc *old_plane_crtc,
12413 					   struct drm_crtc *new_plane_crtc,
12414 					   bool enable)
12415 {
12416 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12417 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12418 
12419 	if (!enable) {
12420 		if (old_plane_crtc == NULL)
12421 			return true;
12422 
12423 		old_crtc_state = drm_atomic_get_old_crtc_state(
12424 			state, old_plane_crtc);
12425 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12426 
12427 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12428 	} else {
12429 		if (new_plane_crtc == NULL)
12430 			return true;
12431 
12432 		new_crtc_state = drm_atomic_get_new_crtc_state(
12433 			state, new_plane_crtc);
12434 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12435 
12436 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12437 	}
12438 }
12439 
12440 static int dm_update_plane_state(struct dc *dc,
12441 				 struct drm_atomic_commit *state,
12442 				 struct drm_plane *plane,
12443 				 struct drm_plane_state *old_plane_state,
12444 				 struct drm_plane_state *new_plane_state,
12445 				 bool enable,
12446 				 bool *lock_and_validation_needed,
12447 				 bool *is_top_most_overlay)
12448 {
12449 
12450 	struct dm_atomic_state *dm_state = NULL;
12451 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
12452 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12453 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
12454 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
12455 	bool needs_reset, update_native_cursor;
12456 	int ret = 0;
12457 
12458 
12459 	new_plane_crtc = new_plane_state->crtc;
12460 	old_plane_crtc = old_plane_state->crtc;
12461 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
12462 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
12463 
12464 	update_native_cursor = dm_should_update_native_cursor(state,
12465 							      old_plane_crtc,
12466 							      new_plane_crtc,
12467 							      enable);
12468 
12469 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
12470 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12471 						    new_plane_state, enable);
12472 		if (ret)
12473 			return ret;
12474 
12475 		return 0;
12476 	}
12477 
12478 	needs_reset = should_reset_plane(state, plane, old_plane_state,
12479 					 new_plane_state);
12480 
12481 	/* Remove any changed/removed planes */
12482 	if (!enable) {
12483 		if (!needs_reset)
12484 			return 0;
12485 
12486 		if (!old_plane_crtc)
12487 			return 0;
12488 
12489 		old_crtc_state = drm_atomic_get_old_crtc_state(
12490 				state, old_plane_crtc);
12491 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12492 
12493 		if (!dm_old_crtc_state->stream)
12494 			return 0;
12495 
12496 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
12497 				plane->base.id, old_plane_crtc->base.id);
12498 
12499 		ret = dm_atomic_get_state(state, &dm_state);
12500 		if (ret)
12501 			return ret;
12502 
12503 		if (!dc_state_remove_plane(
12504 				dc,
12505 				dm_old_crtc_state->stream,
12506 				dm_old_plane_state->dc_state,
12507 				dm_state->context)) {
12508 
12509 			return -EINVAL;
12510 		}
12511 
12512 		if (dm_old_plane_state->dc_state)
12513 			dc_plane_state_release(dm_old_plane_state->dc_state);
12514 
12515 		dm_new_plane_state->dc_state = NULL;
12516 
12517 		*lock_and_validation_needed = true;
12518 
12519 	} else { /* Add new planes */
12520 		struct dc_plane_state *dc_new_plane_state;
12521 
12522 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
12523 			return 0;
12524 
12525 		if (!new_plane_crtc)
12526 			return 0;
12527 
12528 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
12529 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12530 
12531 		if (!dm_new_crtc_state->stream)
12532 			return 0;
12533 
12534 		if (!needs_reset)
12535 			return 0;
12536 
12537 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
12538 		if (ret)
12539 			goto out;
12540 
12541 		WARN_ON(dm_new_plane_state->dc_state);
12542 
12543 		dc_new_plane_state = dc_create_plane_state(dc);
12544 		if (!dc_new_plane_state) {
12545 			ret = -ENOMEM;
12546 			goto out;
12547 		}
12548 
12549 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
12550 				 plane->base.id, new_plane_crtc->base.id);
12551 
12552 		ret = fill_dc_plane_attributes(
12553 			drm_to_adev(new_plane_crtc->dev),
12554 			dc_new_plane_state,
12555 			new_plane_state,
12556 			new_crtc_state);
12557 		if (ret) {
12558 			dc_plane_state_release(dc_new_plane_state);
12559 			goto out;
12560 		}
12561 
12562 		ret = dm_atomic_get_state(state, &dm_state);
12563 		if (ret) {
12564 			dc_plane_state_release(dc_new_plane_state);
12565 			goto out;
12566 		}
12567 
12568 		/*
12569 		 * Any atomic check errors that occur after this will
12570 		 * not need a release. The plane state will be attached
12571 		 * to the stream, and therefore part of the atomic
12572 		 * state. It'll be released when the atomic state is
12573 		 * cleaned.
12574 		 */
12575 		if (!dc_state_add_plane(
12576 				dc,
12577 				dm_new_crtc_state->stream,
12578 				dc_new_plane_state,
12579 				dm_state->context)) {
12580 
12581 			dc_plane_state_release(dc_new_plane_state);
12582 			ret = -EINVAL;
12583 			goto out;
12584 		}
12585 
12586 		dm_new_plane_state->dc_state = dc_new_plane_state;
12587 
12588 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
12589 
12590 		/* Tell DC to do a full surface update every time there
12591 		 * is a plane change. Inefficient, but works for now.
12592 		 */
12593 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
12594 
12595 		*lock_and_validation_needed = true;
12596 	}
12597 
12598 out:
12599 	/* If enabling cursor overlay failed, attempt fallback to native mode */
12600 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
12601 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12602 						    new_plane_state, enable);
12603 		if (ret)
12604 			return ret;
12605 
12606 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
12607 	}
12608 
12609 	return ret;
12610 }
12611 
12612 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
12613 				       int *src_w, int *src_h)
12614 {
12615 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
12616 	case DRM_MODE_ROTATE_90:
12617 	case DRM_MODE_ROTATE_270:
12618 		*src_w = plane_state->src_h >> 16;
12619 		*src_h = plane_state->src_w >> 16;
12620 		break;
12621 	case DRM_MODE_ROTATE_0:
12622 	case DRM_MODE_ROTATE_180:
12623 	default:
12624 		*src_w = plane_state->src_w >> 16;
12625 		*src_h = plane_state->src_h >> 16;
12626 		break;
12627 	}
12628 }
12629 
12630 static void
12631 dm_get_plane_scale(struct drm_plane_state *plane_state,
12632 		   int *out_plane_scale_w, int *out_plane_scale_h)
12633 {
12634 	int plane_src_w, plane_src_h;
12635 
12636 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
12637 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
12638 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
12639 }
12640 
12641 /*
12642  * The normalized_zpos value cannot be used by this iterator directly. It's only
12643  * calculated for enabled planes, potentially causing normalized_zpos collisions
12644  * between enabled/disabled planes in the atomic state. We need a unique value
12645  * so that the iterator will not generate the same object twice, or loop
12646  * indefinitely.
12647  */
12648 static inline struct __drm_planes_state *__get_next_zpos(
12649 	struct drm_atomic_commit *state,
12650 	struct __drm_planes_state *prev)
12651 {
12652 	unsigned int highest_zpos = 0, prev_zpos = 256;
12653 	uint32_t highest_id = 0, prev_id = UINT_MAX;
12654 	struct drm_plane_state *new_plane_state;
12655 	struct drm_plane *plane;
12656 	int i, highest_i = -1;
12657 
12658 	if (prev != NULL) {
12659 		prev_zpos = prev->new_state->zpos;
12660 		prev_id = prev->ptr->base.id;
12661 	}
12662 
12663 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
12664 		/* Skip planes with higher zpos than the previously returned */
12665 		if (new_plane_state->zpos > prev_zpos ||
12666 		    (new_plane_state->zpos == prev_zpos &&
12667 		     plane->base.id >= prev_id))
12668 			continue;
12669 
12670 		/* Save the index of the plane with highest zpos */
12671 		if (new_plane_state->zpos > highest_zpos ||
12672 		    (new_plane_state->zpos == highest_zpos &&
12673 		     plane->base.id > highest_id)) {
12674 			highest_zpos = new_plane_state->zpos;
12675 			highest_id = plane->base.id;
12676 			highest_i = i;
12677 		}
12678 	}
12679 
12680 	if (highest_i < 0)
12681 		return NULL;
12682 
12683 	return &state->planes[highest_i];
12684 }
12685 
12686 /*
12687  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
12688  * by descending zpos, as read from the new plane state. This is the same
12689  * ordering as defined by drm_atomic_normalize_zpos().
12690  */
12691 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
12692 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
12693 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
12694 		for_each_if(((plane) = __i->ptr,				\
12695 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
12696 			     (old_plane_state) = __i->old_state,		\
12697 			     (new_plane_state) = __i->new_state, 1))
12698 
12699 static int add_affected_mst_dsc_crtcs(struct drm_atomic_commit *state, struct drm_crtc *crtc)
12700 {
12701 	struct drm_connector *connector;
12702 	struct drm_connector_state *conn_state, *old_conn_state;
12703 	struct amdgpu_dm_connector *aconnector = NULL;
12704 	int i;
12705 
12706 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
12707 		if (!conn_state->crtc)
12708 			conn_state = old_conn_state;
12709 
12710 		if (conn_state->crtc != crtc)
12711 			continue;
12712 
12713 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
12714 			continue;
12715 
12716 		aconnector = to_amdgpu_dm_connector(connector);
12717 		if (!aconnector->mst_output_port || !aconnector->mst_root)
12718 			aconnector = NULL;
12719 		else
12720 			break;
12721 	}
12722 
12723 	if (!aconnector)
12724 		return 0;
12725 
12726 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
12727 }
12728 
12729 /**
12730  * DOC: Cursor Modes - Native vs Overlay
12731  *
12732  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
12733  * plane. It does not require a dedicated hw plane to enable, but it is
12734  * subjected to the same z-order and scaling as the hw plane. It also has format
12735  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
12736  * hw plane.
12737  *
12738  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
12739  * own scaling and z-pos. It also has no blending restrictions. It lends to a
12740  * cursor behavior more akin to a DRM client's expectations. However, it does
12741  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
12742  * available.
12743  */
12744 
12745 /**
12746  * dm_plane_color_pipeline_active() - Check if a plane's color pipeline active.
12747  * @state: DRM atomic state
12748  * @plane: DRM plane to check
12749  * @use_old: if true, inspect the old colorop states; otherwise the new ones
12750  *
12751  * A color pipeline may be selected (color_pipeline != NULL) but still is
12752  * inactive if every colorop in the chain is bypassed.  Only return
12753  * true when at least one colorop has bypass == false, meaning the cursor
12754  * would be subjected to the transformation in native mode.
12755  *
12756  * Return: true if the pipeline modifies pixels, false otherwise.
12757  */
12758 static bool dm_plane_color_pipeline_active(struct drm_atomic_commit *state,
12759 					   struct drm_plane *plane,
12760 					   bool use_old)
12761 {
12762 	struct drm_colorop *colorop;
12763 	struct drm_colorop_state *old_colorop_state, *new_colorop_state;
12764 	int i;
12765 
12766 	for_each_oldnew_colorop_in_state(state, colorop, old_colorop_state, new_colorop_state, i) {
12767 		struct drm_colorop_state *cstate = use_old ? old_colorop_state : new_colorop_state;
12768 
12769 		if (cstate->colorop->plane != plane)
12770 			continue;
12771 		if (!cstate->bypass)
12772 			return true;
12773 	}
12774 	return false;
12775 }
12776 
12777 /**
12778  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
12779  * @adev: amdgpu device
12780  * @state: DRM atomic state
12781  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
12782  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
12783  *
12784  * Get whether the cursor should be enabled in native mode, or overlay mode, on
12785  * the dm_crtc_state.
12786  *
12787  * The cursor should be enabled in overlay mode if there exists an underlying
12788  * plane - on which the cursor may be blended - that is either YUV formatted,
12789  * scaled differently from the cursor, or has a color pipeline active.
12790  *
12791  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
12792  * calling this function.
12793  *
12794  * Return: 0 on success, or an error code if getting the cursor plane state
12795  * failed.
12796  */
12797 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
12798 				   struct drm_atomic_commit *state,
12799 				   struct dm_crtc_state *dm_crtc_state,
12800 				   enum amdgpu_dm_cursor_mode *cursor_mode)
12801 {
12802 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
12803 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
12804 	struct drm_plane *plane;
12805 	bool consider_mode_change = false;
12806 	bool entire_crtc_covered = false;
12807 	bool cursor_changed = false;
12808 	int underlying_scale_w, underlying_scale_h;
12809 	int cursor_scale_w, cursor_scale_h;
12810 	int i;
12811 
12812 	/* Overlay cursor not supported on HW before DCN
12813 	 * DCN401/420 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
12814 	 * as previous DCN generations, so enable native mode on DCN401/420
12815 	 */
12816 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1) ||
12817 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
12818 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 1)) {
12819 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12820 		return 0;
12821 	}
12822 
12823 	/* Init cursor_mode to be the same as current */
12824 	*cursor_mode = dm_crtc_state->cursor_mode;
12825 
12826 	/*
12827 	 * Cursor mode can change if a plane's format changes, scale changes, is
12828 	 * enabled/disabled, z-order changes, or color management properties change.
12829 	 */
12830 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
12831 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
12832 
12833 		/* Only care about planes on this CRTC */
12834 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
12835 			continue;
12836 
12837 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
12838 			cursor_changed = true;
12839 
12840 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
12841 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
12842 		    old_plane_state->fb->format != plane_state->fb->format) {
12843 			consider_mode_change = true;
12844 			break;
12845 		}
12846 
12847 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
12848 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
12849 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
12850 			consider_mode_change = true;
12851 			break;
12852 		}
12853 
12854 		if (dm_plane_color_pipeline_active(state, plane, true) !=
12855 		    dm_plane_color_pipeline_active(state, plane, false)) {
12856 			consider_mode_change = true;
12857 			break;
12858 		}
12859 	}
12860 
12861 	if (!consider_mode_change && !crtc_state->zpos_changed)
12862 		return 0;
12863 
12864 	/*
12865 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
12866 	 * no need to set cursor mode. This avoids needlessly locking the cursor
12867 	 * state.
12868 	 */
12869 	if (!cursor_changed &&
12870 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
12871 		return 0;
12872 	}
12873 
12874 	cursor_state = drm_atomic_get_plane_state(state,
12875 						  crtc_state->crtc->cursor);
12876 	if (IS_ERR(cursor_state))
12877 		return PTR_ERR(cursor_state);
12878 
12879 	/* Cursor is disabled */
12880 	if (!cursor_state->fb)
12881 		return 0;
12882 
12883 	/* For all planes in descending z-order (all of which are below cursor
12884 	 * as per zpos definitions), check their scaling and format
12885 	 */
12886 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
12887 
12888 		/* Only care about non-cursor planes on this CRTC */
12889 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
12890 		    plane->type == DRM_PLANE_TYPE_CURSOR)
12891 			continue;
12892 
12893 		/* Underlying plane is YUV format - use overlay cursor */
12894 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
12895 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12896 			return 0;
12897 		}
12898 
12899 		/* Underlying plane has an active color pipeline - cursor would be transformed */
12900 		if (dm_plane_color_pipeline_active(state, plane, false)) {
12901 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12902 			return 0;
12903 		}
12904 
12905 		dm_get_plane_scale(plane_state,
12906 				   &underlying_scale_w, &underlying_scale_h);
12907 		dm_get_plane_scale(cursor_state,
12908 				   &cursor_scale_w, &cursor_scale_h);
12909 
12910 		/* Underlying plane has different scale - use overlay cursor */
12911 		if (cursor_scale_w != underlying_scale_w &&
12912 		    cursor_scale_h != underlying_scale_h) {
12913 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12914 			return 0;
12915 		}
12916 
12917 		/* If this plane covers the whole CRTC, no need to check planes underneath */
12918 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
12919 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
12920 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
12921 			entire_crtc_covered = true;
12922 			break;
12923 		}
12924 	}
12925 
12926 	/* If planes do not cover the entire CRTC, use overlay mode to enable
12927 	 * cursor over holes
12928 	 */
12929 	if (entire_crtc_covered)
12930 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12931 	else
12932 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12933 
12934 	return 0;
12935 }
12936 
12937 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
12938 					    struct drm_atomic_commit *state,
12939 					    struct drm_crtc_state *crtc_state)
12940 {
12941 	struct drm_plane *plane;
12942 	struct drm_plane_state *new_plane_state, *old_plane_state;
12943 
12944 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
12945 		new_plane_state = drm_atomic_get_plane_state(state, plane);
12946 		old_plane_state = drm_atomic_get_plane_state(state, plane);
12947 
12948 		if (IS_ERR(new_plane_state) || IS_ERR(old_plane_state)) {
12949 			drm_err(dev, "Failed to get plane state for plane %s\n", plane->name);
12950 			return false;
12951 		}
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