xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision a10ea943356b9d70c5616a0a06f6fa97cfdaccb1)
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 /**
584  * dm_crtc_high_irq_handler() - Common OTG vblank/flip event handling
585  * @adev: amdgpu device
586  * @acrtc: the CRTC to service
587  *
588  * Performs writeback completion, vblank event handling, CRC processing, VRR BTR
589  * updates and pageflip completion delivery.
590  *
591  * On DCN this is driven by VUPDATE_NO_LOCK (the register latch point) from
592  * dm_vupdate_high_irq(); on DCE it is driven by VLINE0 at the start of vblank
593  * from dm_crtc_high_irq().
594  */
595 static void dm_crtc_high_irq_handler(struct amdgpu_device *adev,
596 				     struct amdgpu_crtc *acrtc)
597 {
598 	struct drm_writeback_job *job;
599 	unsigned long flags;
600 	int vrr_active;
601 	bool is_dcn = amdgpu_ip_version(adev, DCE_HWIP, 0) != 0;
602 
603 	if (acrtc->wb_conn) {
604 		spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
605 
606 		if (acrtc->wb_pending) {
607 			job = list_first_entry_or_null(&acrtc->wb_conn->job_queue,
608 						       struct drm_writeback_job,
609 						       list_entry);
610 			acrtc->wb_pending = false;
611 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
612 
613 			if (job) {
614 				unsigned int v_total, refresh_hz;
615 				struct dc_stream_state *stream = acrtc->dm_irq_params.stream;
616 
617 				v_total = stream->adjust.v_total_max ?
618 					  stream->adjust.v_total_max : stream->timing.v_total;
619 				refresh_hz = div_u64((uint64_t) stream->timing.pix_clk_100hz *
620 					     100LL, (v_total * stream->timing.h_total));
621 				mdelay(1000 / refresh_hz);
622 
623 				drm_writeback_signal_completion(acrtc->wb_conn, 0);
624 				dc_stream_fc_disable_writeback(adev->dm.dc,
625 							       acrtc->dm_irq_params.stream, 0);
626 			}
627 		} else
628 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
629 	}
630 
631 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
632 
633 	drm_dbg_vbl(adev_to_drm(adev),
634 		    "crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
635 		    vrr_active, acrtc->dm_irq_params.active_planes);
636 
637 	/**
638 	 * Core vblank handling.
639 	 *
640 	 * On DCN this handler runs at VUPDATE_NO_LOCK, the register latch
641 	 * point, which is the correct place to timestamp both VRR and non-VRR
642 	 * vblanks.
643 	 *
644 	 * On DCE this handler runs at the start of front-porch, where only
645 	 * non-VRR timestamping is valid; VRR vblank is deferred to
646 	 * dm_vupdate_high_irq() after end of front-porch.
647 	 */
648 	if (is_dcn || !vrr_active)
649 		amdgpu_dm_crtc_handle_vblank(acrtc);
650 
651 	/**
652 	 * Following stuff must happen at start of vblank, for crc
653 	 * computation and below-the-range btr support in vrr mode.
654 	 */
655 	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
656 
657 	/* BTR updates need to happen before VUPDATE on Vega and above. */
658 	if (adev->family < AMDGPU_FAMILY_AI)
659 		return;
660 
661 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
662 
663 	if (acrtc->dm_irq_params.stream &&
664 		acrtc->dm_irq_params.vrr_params.supported) {
665 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
666 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
667 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state == VRR_STATE_ACTIVE_VARIABLE;
668 
669 		mod_freesync_handle_v_update(adev->dm.freesync_module,
670 					     acrtc->dm_irq_params.stream,
671 					     &acrtc->dm_irq_params.vrr_params);
672 
673 		/* update vmin_vmax only if freesync is enabled, or only if PSR and REPLAY are disabled */
674 		if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
675 			schedule_dc_vmin_vmax(adev, acrtc->dm_irq_params.stream,
676 					&acrtc->dm_irq_params.vrr_params.adjust);
677 		}
678 	}
679 
680 	/*
681 	 * Deliver pageflip completion events (DCN only).
682 	 *
683 	 * Since GRPH_PFLIP is not used, VUPDATE_NO_LOCK is the flip latch
684 	 * point. Deliver any pending pageflip completion event from here,
685 	 * once HW has consumed the new address (the OTG no longer reports a
686 	 * pending flip).
687 	 *
688 	 * Also handle the case here where there aren't any active planes and
689 	 * DCN HUBP may be clock-gated, so the flip-pending status may be
690 	 * undefined.
691 	 */
692 	if (is_dcn && acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
693 	    acrtc->event) {
694 
695 		if (!dc_get_flip_pending_on_otg(adev->dm.dc, acrtc->otg_inst)) {
696 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
697 			acrtc->event = NULL;
698 			drm_crtc_vblank_put(&acrtc->base);
699 			acrtc->pflip_status = AMDGPU_FLIP_NONE;
700 		}
701 		/*
702 		 * If the flip is still pending, leave it armed and
703 		 * retry on the next vupdate.
704 		 */
705 	} else if (is_dcn && acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
706 		   acrtc->dm_irq_params.active_planes == 0) {
707 
708 		if (acrtc->event) {
709 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
710 			acrtc->event = NULL;
711 			drm_crtc_vblank_put(&acrtc->base);
712 		}
713 		acrtc->pflip_status = AMDGPU_FLIP_NONE;
714 	}
715 
716 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
717 }
718 
719 static void dm_vupdate_high_irq(void *interrupt_params)
720 {
721 	struct common_irq_params *irq_params = interrupt_params;
722 	struct amdgpu_device *adev = irq_params->adev;
723 	struct amdgpu_crtc *acrtc;
724 	struct drm_device *drm_dev;
725 	struct drm_vblank_crtc *vblank;
726 	ktime_t frame_duration_ns, previous_timestamp;
727 	unsigned long flags;
728 	int vrr_active;
729 
730 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
731 	if (!acrtc)
732 		return;
733 
734 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
735 	drm_dev = acrtc->base.dev;
736 	vblank = drm_crtc_vblank_crtc(&acrtc->base);
737 	previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
738 	frame_duration_ns = vblank->time - previous_timestamp;
739 
740 	if (frame_duration_ns > 0) {
741 		trace_amdgpu_refresh_rate_track(acrtc->base.index,
742 					frame_duration_ns,
743 					ktime_divns(NSEC_PER_SEC, frame_duration_ns));
744 		atomic64_set(&irq_params->previous_timestamp, vblank->time);
745 	}
746 
747 	drm_dbg_vbl(drm_dev,
748 		    "crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
749 		    vrr_active);
750 
751 	/*
752 	 * On DCN, VUPDATE_NO_LOCK is the single OTG interrupt used to deliver
753 	 * vblank and pageflip completion events; VSTARTUP and GRPH_PFLIP are
754 	 * not used. Run the full handler here.
755 	 */
756 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) != 0) {
757 		dm_crtc_high_irq_handler(adev, acrtc);
758 		return;
759 	}
760 
761 	/* DCE only below. */
762 
763 	/* Core vblank handling is done here after end of front-porch in
764 	 * vrr mode, as vblank timestamping will give valid results
765 	 * while now done after front-porch. This will also deliver
766 	 * page-flip completion events that have been queued to us
767 	 * if a pageflip happened inside front-porch.
768 	 */
769 	if (vrr_active && acrtc->dm_irq_params.stream) {
770 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
771 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
772 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state
773 			== VRR_STATE_ACTIVE_VARIABLE;
774 
775 		amdgpu_dm_crtc_handle_vblank(acrtc);
776 
777 		/* BTR processing for pre-DCE12 ASICs */
778 		if (adev->family < AMDGPU_FAMILY_AI) {
779 			spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
780 			mod_freesync_handle_v_update(
781 				adev->dm.freesync_module,
782 				acrtc->dm_irq_params.stream,
783 				&acrtc->dm_irq_params.vrr_params);
784 
785 			if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
786 				schedule_dc_vmin_vmax(adev,
787 					acrtc->dm_irq_params.stream,
788 					&acrtc->dm_irq_params.vrr_params.adjust);
789 			}
790 			spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
791 		}
792 	}
793 }
794 
795 /**
796  * dm_crtc_high_irq() - Handles CRTC interrupt
797  * @interrupt_params: used for determining the CRTC instance
798  *
799  * Handles the CRTC/VSYNC interrupt by notifying DRM's VBLANK event handler.
800  *
801  * Used on DCE (VLINE0, set to vblank start). On DCN the equivalent handling is
802  * driven by VUPDATE_NO_LOCK in dm_vupdate_high_irq().
803  */
804 static void dm_crtc_high_irq(void *interrupt_params)
805 {
806 	struct common_irq_params *irq_params = interrupt_params;
807 	struct amdgpu_device *adev = irq_params->adev;
808 	struct amdgpu_crtc *acrtc;
809 
810 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
811 	if (!acrtc)
812 		return;
813 
814 	dm_crtc_high_irq_handler(adev, acrtc);
815 }
816 
817 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
818 /**
819  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
820  * DCN generation ASICs
821  * @interrupt_params: interrupt parameters
822  *
823  * Used to set crc window/read out crc value at vertical line 0 position
824  */
825 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
826 {
827 	struct common_irq_params *irq_params = interrupt_params;
828 	struct amdgpu_device *adev = irq_params->adev;
829 	struct amdgpu_crtc *acrtc;
830 
831 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
832 
833 	if (!acrtc)
834 		return;
835 
836 	amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
837 }
838 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
839 
840 /**
841  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
842  * @adev: amdgpu_device pointer
843  * @notify: dmub notification structure
844  *
845  * Dmub AUX or SET_CONFIG command completion processing callback
846  * Copies dmub notification to DM which is to be read by AUX command.
847  * issuing thread and also signals the event to wake up the thread.
848  */
849 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
850 					struct dmub_notification *notify)
851 {
852 	if (adev->dm.dmub_notify)
853 		memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
854 	if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
855 		complete(&adev->dm.dmub_aux_transfer_done);
856 }
857 
858 static void dmub_aux_fused_io_callback(struct amdgpu_device *adev,
859 					struct dmub_notification *notify)
860 {
861 	if (!adev || !notify) {
862 		ASSERT(false);
863 		return;
864 	}
865 
866 	const struct dmub_cmd_fused_request *req = &notify->fused_request;
867 	const uint8_t ddc_line = req->u.aux.ddc_line;
868 
869 	if (ddc_line >= ARRAY_SIZE(adev->dm.fused_io)) {
870 		ASSERT(false);
871 		return;
872 	}
873 
874 	struct fused_io_sync *sync = &adev->dm.fused_io[ddc_line];
875 
876 	static_assert(sizeof(*req) <= sizeof(sync->reply_data), "Size mismatch");
877 	memcpy(sync->reply_data, req, sizeof(*req));
878 	complete(&sync->replied);
879 }
880 
881 /**
882  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
883  * @adev: amdgpu_device pointer
884  * @notify: dmub notification structure
885  *
886  * Dmub Hpd interrupt processing callback. Gets displayindex through the
887  * ink index and calls helper to do the processing.
888  */
889 static void dmub_hpd_callback(struct amdgpu_device *adev,
890 			      struct dmub_notification *notify)
891 {
892 	struct amdgpu_dm_connector *aconnector;
893 	struct amdgpu_dm_connector *hpd_aconnector = NULL;
894 	struct drm_connector *connector;
895 	struct drm_connector_list_iter iter;
896 	struct dc_link *link;
897 	u8 link_index = 0;
898 	struct drm_device *dev;
899 
900 	if (adev == NULL)
901 		return;
902 
903 	if (notify == NULL) {
904 		drm_err(adev_to_drm(adev), "DMUB HPD callback notification was NULL");
905 		return;
906 	}
907 
908 	if (notify->link_index > adev->dm.dc->link_count) {
909 		drm_err(adev_to_drm(adev), "DMUB HPD index (%u)is abnormal", notify->link_index);
910 		return;
911 	}
912 
913 	/* Skip DMUB HPD IRQ in suspend/resume. We will probe them later. */
914 	if (notify->type == DMUB_NOTIFICATION_HPD && adev->in_suspend) {
915 		drm_info(adev_to_drm(adev), "Skip DMUB HPD IRQ callback in suspend/resume\n");
916 		return;
917 	}
918 
919 	link_index = notify->link_index;
920 	link = adev->dm.dc->links[link_index];
921 	dev = adev->dm.ddev;
922 
923 	drm_connector_list_iter_begin(dev, &iter);
924 	drm_for_each_connector_iter(connector, &iter) {
925 
926 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
927 			continue;
928 
929 		aconnector = to_amdgpu_dm_connector(connector);
930 		if (link && aconnector->dc_link == link) {
931 			if (notify->type == DMUB_NOTIFICATION_HPD)
932 				drm_info(adev_to_drm(adev), "DMUB HPD IRQ callback: link_index=%u\n", link_index);
933 			else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
934 				drm_info(adev_to_drm(adev), "DMUB HPD RX IRQ callback: link_index=%u\n", link_index);
935 			else
936 				drm_warn(adev_to_drm(adev), "DMUB Unknown HPD callback type %d, link_index=%u\n",
937 						notify->type, link_index);
938 
939 			hpd_aconnector = aconnector;
940 			break;
941 		}
942 	}
943 	drm_connector_list_iter_end(&iter);
944 
945 	if (hpd_aconnector) {
946 		if (notify->type == DMUB_NOTIFICATION_HPD) {
947 			if (hpd_aconnector->dc_link->hpd_status == (notify->hpd_status == DP_HPD_PLUG))
948 				drm_warn(adev_to_drm(adev), "DMUB reported hpd status unchanged. link_index=%u\n", link_index);
949 			handle_hpd_irq_helper(hpd_aconnector);
950 		} else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ) {
951 			handle_hpd_rx_irq(hpd_aconnector);
952 		}
953 	}
954 }
955 
956 /**
957  * dmub_hpd_sense_callback - DMUB HPD sense processing callback.
958  * @adev: amdgpu_device pointer
959  * @notify: dmub notification structure
960  *
961  * HPD sense changes can occur during low power states and need to be
962  * notified from firmware to driver.
963  */
964 static void dmub_hpd_sense_callback(struct amdgpu_device *adev,
965 			      struct dmub_notification *notify)
966 {
967 	drm_dbg_driver(adev_to_drm(adev), "DMUB HPD SENSE callback.\n");
968 }
969 
970 /**
971  * register_dmub_notify_callback - Sets callback for DMUB notify
972  * @adev: amdgpu_device pointer
973  * @type: Type of dmub notification
974  * @callback: Dmub interrupt callback function
975  * @dmub_int_thread_offload: offload indicator
976  *
977  * API to register a dmub callback handler for a dmub notification
978  * Also sets indicator whether callback processing to be offloaded.
979  * to dmub interrupt handling thread
980  * Return: true if successfully registered, false if there is existing registration
981  */
982 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
983 					  enum dmub_notification_type type,
984 					  dmub_notify_interrupt_callback_t callback,
985 					  bool dmub_int_thread_offload)
986 {
987 	if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
988 		adev->dm.dmub_callback[type] = callback;
989 		adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
990 	} else
991 		return false;
992 
993 	return true;
994 }
995 
996 static void dm_handle_hpd_work(struct work_struct *work)
997 {
998 	struct dmub_hpd_work *dmub_hpd_wrk;
999 
1000 	dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
1001 
1002 	if (!dmub_hpd_wrk->dmub_notify) {
1003 		drm_err(adev_to_drm(dmub_hpd_wrk->adev), "dmub_hpd_wrk dmub_notify is NULL");
1004 		return;
1005 	}
1006 
1007 	if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
1008 		dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
1009 		dmub_hpd_wrk->dmub_notify);
1010 	}
1011 
1012 	kfree(dmub_hpd_wrk->dmub_notify);
1013 	kfree(dmub_hpd_wrk);
1014 
1015 }
1016 
1017 static const char *dmub_notification_type_str(enum dmub_notification_type e)
1018 {
1019 	switch (e) {
1020 	case DMUB_NOTIFICATION_NO_DATA:
1021 		return "NO_DATA";
1022 	case DMUB_NOTIFICATION_AUX_REPLY:
1023 		return "AUX_REPLY";
1024 	case DMUB_NOTIFICATION_HPD:
1025 		return "HPD";
1026 	case DMUB_NOTIFICATION_HPD_IRQ:
1027 		return "HPD_IRQ";
1028 	case DMUB_NOTIFICATION_SET_CONFIG_REPLY:
1029 		return "SET_CONFIG_REPLY";
1030 	case DMUB_NOTIFICATION_DPIA_NOTIFICATION:
1031 		return "DPIA_NOTIFICATION";
1032 	case DMUB_NOTIFICATION_HPD_SENSE_NOTIFY:
1033 		return "HPD_SENSE_NOTIFY";
1034 	case DMUB_NOTIFICATION_FUSED_IO:
1035 		return "FUSED_IO";
1036 	default:
1037 		return "<unknown>";
1038 	}
1039 }
1040 
1041 #define DMUB_TRACE_MAX_READ 64
1042 /**
1043  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
1044  * @interrupt_params: used for determining the Outbox instance
1045  *
1046  * Handles the Outbox Interrupt
1047  * event handler.
1048  */
1049 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
1050 {
1051 	struct dmub_notification notify = {0};
1052 	struct common_irq_params *irq_params = interrupt_params;
1053 	struct amdgpu_device *adev = irq_params->adev;
1054 	struct amdgpu_display_manager *dm = &adev->dm;
1055 	struct dmcub_trace_buf_entry entry = { 0 };
1056 	u32 count = 0;
1057 	struct dmub_hpd_work *dmub_hpd_wrk;
1058 
1059 	do {
1060 		if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
1061 			trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
1062 							entry.param0, entry.param1);
1063 
1064 			drm_dbg_driver(adev_to_drm(adev), "trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
1065 				 entry.trace_code, entry.tick_count, entry.param0, entry.param1);
1066 		} else
1067 			break;
1068 
1069 		count++;
1070 
1071 	} while (count <= DMUB_TRACE_MAX_READ);
1072 
1073 	if (count > DMUB_TRACE_MAX_READ)
1074 		drm_dbg_driver(adev_to_drm(adev), "Warning : count > DMUB_TRACE_MAX_READ");
1075 
1076 	if (dc_enable_dmub_notifications(adev->dm.dc) &&
1077 		irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
1078 
1079 		do {
1080 			dc_stat_get_dmub_notification(adev->dm.dc, &notify);
1081 			if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
1082 				drm_err(adev_to_drm(adev), "DM: notify type %d invalid!", notify.type);
1083 				continue;
1084 			}
1085 			if (!dm->dmub_callback[notify.type]) {
1086 				drm_warn(adev_to_drm(adev), "DMUB notification skipped due to no handler: type=%s\n",
1087 					dmub_notification_type_str(notify.type));
1088 				continue;
1089 			}
1090 			if (dm->dmub_thread_offload[notify.type] == true) {
1091 				dmub_hpd_wrk = kzalloc_obj(*dmub_hpd_wrk,
1092 							   GFP_ATOMIC);
1093 				if (!dmub_hpd_wrk) {
1094 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk");
1095 					return;
1096 				}
1097 				dmub_hpd_wrk->dmub_notify = kmemdup(&notify, sizeof(struct dmub_notification),
1098 								    GFP_ATOMIC);
1099 				if (!dmub_hpd_wrk->dmub_notify) {
1100 					kfree(dmub_hpd_wrk);
1101 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk->dmub_notify");
1102 					return;
1103 				}
1104 				INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
1105 				dmub_hpd_wrk->adev = adev;
1106 				queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
1107 			} else {
1108 				dm->dmub_callback[notify.type](adev, &notify);
1109 			}
1110 		} while (notify.pending_notification);
1111 	}
1112 }
1113 
1114 static int dm_set_clockgating_state(struct amdgpu_ip_block *ip_block,
1115 		  enum amd_clockgating_state state)
1116 {
1117 	return 0;
1118 }
1119 
1120 static int dm_set_powergating_state(struct amdgpu_ip_block *ip_block,
1121 		  enum amd_powergating_state state)
1122 {
1123 	return 0;
1124 }
1125 
1126 /* Prototypes of private functions */
1127 static int dm_early_init(struct amdgpu_ip_block *ip_block);
1128 
1129 /* Allocate memory for FBC compressed data  */
1130 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
1131 {
1132 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
1133 	struct dm_compressor_info *compressor = &adev->dm.compressor;
1134 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
1135 	struct drm_display_mode *mode;
1136 	unsigned long max_size = 0;
1137 
1138 	if (adev->dm.dc->fbc_compressor == NULL)
1139 		return;
1140 
1141 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
1142 		return;
1143 
1144 	if (compressor->bo_ptr)
1145 		return;
1146 
1147 
1148 	list_for_each_entry(mode, &connector->modes, head) {
1149 		if (max_size < (unsigned long) mode->htotal * mode->vtotal)
1150 			max_size = (unsigned long) mode->htotal * mode->vtotal;
1151 	}
1152 
1153 	if (max_size) {
1154 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
1155 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
1156 			    &compressor->gpu_addr, &compressor->cpu_addr);
1157 
1158 		if (r)
1159 			drm_err(adev_to_drm(adev), "DM: Failed to initialize FBC\n");
1160 		else {
1161 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
1162 			drm_info(adev_to_drm(adev), "DM: FBC alloc %lu\n", max_size*4);
1163 		}
1164 
1165 	}
1166 
1167 }
1168 
1169 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
1170 					  int pipe, bool *enabled,
1171 					  unsigned char *buf, int max_bytes)
1172 {
1173 	struct drm_device *dev = dev_get_drvdata(kdev);
1174 	struct amdgpu_device *adev = drm_to_adev(dev);
1175 	struct drm_connector *connector;
1176 	struct drm_connector_list_iter conn_iter;
1177 	struct amdgpu_dm_connector *aconnector;
1178 	int ret = 0;
1179 
1180 	*enabled = false;
1181 
1182 	mutex_lock(&adev->dm.audio_lock);
1183 
1184 	drm_connector_list_iter_begin(dev, &conn_iter);
1185 	drm_for_each_connector_iter(connector, &conn_iter) {
1186 
1187 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1188 			continue;
1189 
1190 		aconnector = to_amdgpu_dm_connector(connector);
1191 		if (aconnector->audio_inst != port)
1192 			continue;
1193 
1194 		*enabled = true;
1195 		mutex_lock(&connector->eld_mutex);
1196 		ret = drm_eld_size(connector->eld);
1197 		memcpy(buf, connector->eld, min(max_bytes, ret));
1198 		mutex_unlock(&connector->eld_mutex);
1199 
1200 		break;
1201 	}
1202 	drm_connector_list_iter_end(&conn_iter);
1203 
1204 	mutex_unlock(&adev->dm.audio_lock);
1205 
1206 	drm_dbg_kms(adev_to_drm(adev), "Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
1207 
1208 	return ret;
1209 }
1210 
1211 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
1212 	.get_eld = amdgpu_dm_audio_component_get_eld,
1213 };
1214 
1215 static int amdgpu_dm_audio_component_bind(struct device *kdev,
1216 				       struct device *hda_kdev, void *data)
1217 {
1218 	struct drm_device *dev = dev_get_drvdata(kdev);
1219 	struct amdgpu_device *adev = drm_to_adev(dev);
1220 	struct drm_audio_component *acomp = data;
1221 
1222 	acomp->ops = &amdgpu_dm_audio_component_ops;
1223 	acomp->dev = kdev;
1224 	adev->dm.audio_component = acomp;
1225 
1226 	return 0;
1227 }
1228 
1229 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
1230 					  struct device *hda_kdev, void *data)
1231 {
1232 	struct amdgpu_device *adev = drm_to_adev(dev_get_drvdata(kdev));
1233 	struct drm_audio_component *acomp = data;
1234 
1235 	acomp->ops = NULL;
1236 	acomp->dev = NULL;
1237 	adev->dm.audio_component = NULL;
1238 }
1239 
1240 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
1241 	.bind	= amdgpu_dm_audio_component_bind,
1242 	.unbind	= amdgpu_dm_audio_component_unbind,
1243 };
1244 
1245 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
1246 {
1247 	int i, ret;
1248 
1249 	if (!amdgpu_audio)
1250 		return 0;
1251 
1252 	adev->mode_info.audio.enabled = true;
1253 
1254 	adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
1255 
1256 	for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
1257 		adev->mode_info.audio.pin[i].channels = -1;
1258 		adev->mode_info.audio.pin[i].rate = -1;
1259 		adev->mode_info.audio.pin[i].bits_per_sample = -1;
1260 		adev->mode_info.audio.pin[i].status_bits = 0;
1261 		adev->mode_info.audio.pin[i].category_code = 0;
1262 		adev->mode_info.audio.pin[i].connected = false;
1263 		adev->mode_info.audio.pin[i].id =
1264 			adev->dm.dc->res_pool->audios[i]->inst;
1265 		adev->mode_info.audio.pin[i].offset = 0;
1266 	}
1267 
1268 	ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1269 	if (ret < 0)
1270 		return ret;
1271 
1272 	adev->dm.audio_registered = true;
1273 
1274 	return 0;
1275 }
1276 
1277 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
1278 {
1279 	if (!amdgpu_audio)
1280 		return;
1281 
1282 	if (!adev->mode_info.audio.enabled)
1283 		return;
1284 
1285 	if (adev->dm.audio_registered) {
1286 		component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1287 		adev->dm.audio_registered = false;
1288 	}
1289 
1290 	/* TODO: Disable audio? */
1291 
1292 	adev->mode_info.audio.enabled = false;
1293 }
1294 
1295 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
1296 {
1297 	struct drm_audio_component *acomp = adev->dm.audio_component;
1298 
1299 	if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
1300 		drm_dbg_kms(adev_to_drm(adev), "Notify ELD: %d\n", pin);
1301 
1302 		acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1303 						 pin, -1);
1304 	}
1305 }
1306 
1307 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1308 {
1309 	const struct dmcub_firmware_header_v1_0 *hdr;
1310 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1311 	struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1312 	const struct firmware *dmub_fw = adev->dm.dmub_fw;
1313 	struct dc *dc = adev->dm.dc;
1314 	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1315 	struct abm *abm = adev->dm.dc->res_pool->abm;
1316 	struct dc_context *ctx = adev->dm.dc->ctx;
1317 	struct dmub_srv_hw_params hw_params;
1318 	enum dmub_status status;
1319 	const unsigned char *fw_inst_const, *fw_bss_data;
1320 	u32 i, fw_inst_const_size, fw_bss_data_size;
1321 	bool has_hw_support;
1322 
1323 	if (!dmub_srv)
1324 		/* DMUB isn't supported on the ASIC. */
1325 		return 0;
1326 
1327 	if (!fb_info) {
1328 		drm_err(adev_to_drm(adev), "No framebuffer info for DMUB service.\n");
1329 		return -EINVAL;
1330 	}
1331 
1332 	if (!dmub_fw) {
1333 		/* Firmware required for DMUB support. */
1334 		drm_err(adev_to_drm(adev), "No firmware provided for DMUB.\n");
1335 		return -EINVAL;
1336 	}
1337 
1338 	/* initialize register offsets for ASICs with runtime initialization available */
1339 	if (dmub_srv->hw_funcs.init_reg_offsets)
1340 		dmub_srv->hw_funcs.init_reg_offsets(dmub_srv, ctx);
1341 
1342 	status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1343 	if (status != DMUB_STATUS_OK) {
1344 		drm_err(adev_to_drm(adev), "Error checking HW support for DMUB: %d\n", status);
1345 		return -EINVAL;
1346 	}
1347 
1348 	if (!has_hw_support) {
1349 		drm_info(adev_to_drm(adev), "DMUB unsupported on ASIC\n");
1350 		return 0;
1351 	}
1352 
1353 	/* Reset DMCUB if it was previously running - before we overwrite its memory. */
1354 	status = dmub_srv_hw_reset(dmub_srv);
1355 	if (status != DMUB_STATUS_OK)
1356 		drm_warn(adev_to_drm(adev), "Error resetting DMUB HW: %d\n", status);
1357 
1358 	hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1359 
1360 	fw_inst_const = dmub_fw->data +
1361 			le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1362 			PSP_HEADER_BYTES_256;
1363 
1364 	fw_bss_data = dmub_fw->data +
1365 		      le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1366 		      le32_to_cpu(hdr->inst_const_bytes);
1367 
1368 	/* Copy firmware and bios info into FB memory. */
1369 	fw_inst_const_size = adev->dm.fw_inst_size;
1370 
1371 	fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1372 
1373 	/* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1374 	 * amdgpu_ucode_init_single_fw will load dmub firmware
1375 	 * fw_inst_const part to cw0; otherwise, the firmware back door load
1376 	 * will be done by dm_dmub_hw_init
1377 	 */
1378 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1379 		memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1380 				fw_inst_const_size);
1381 	}
1382 
1383 	if (fw_bss_data_size)
1384 		memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1385 		       fw_bss_data, fw_bss_data_size);
1386 
1387 	/* Copy firmware bios info into FB memory. */
1388 	memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1389 	       adev->bios_size);
1390 
1391 	/* Reset regions that need to be reset. */
1392 	memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1393 	fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1394 
1395 	memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1396 	       fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1397 
1398 	memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1399 	       fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1400 
1401 	memset(fb_info->fb[DMUB_WINDOW_SHARED_STATE].cpu_addr, 0,
1402 	       fb_info->fb[DMUB_WINDOW_SHARED_STATE].size);
1403 
1404 	/* Initialize hardware. */
1405 	memset(&hw_params, 0, sizeof(hw_params));
1406 	hw_params.soc_fb_info.fb_base = adev->gmc.fb_start;
1407 	hw_params.soc_fb_info.fb_offset = adev->vm_manager.vram_base_offset;
1408 
1409 	/* backdoor load firmware and trigger dmub running */
1410 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1411 		hw_params.load_inst_const = true;
1412 
1413 	if (dmcu)
1414 		hw_params.psp_version = dmcu->psp_version;
1415 
1416 	for (i = 0; i < fb_info->num_fb; ++i)
1417 		hw_params.fb[i] = &fb_info->fb[i];
1418 
1419 	/* Enable usb4 dpia in the FW APU */
1420 	if (dc->caps.is_apu &&
1421 		dc->res_pool->usb4_dpia_count != 0 &&
1422 		!dc->debug.dpia_debug.bits.disable_dpia) {
1423 		hw_params.dpia_supported = true;
1424 		hw_params.disable_dpia = dc->debug.dpia_debug.bits.disable_dpia;
1425 		hw_params.dpia_hpd_int_enable_supported = false;
1426 		hw_params.enable_non_transparent_setconfig = dc->config.consolidated_dpia_dp_lt;
1427 		hw_params.disable_dpia_bw_allocation = !dc->config.usb4_bw_alloc_support;
1428 	}
1429 
1430 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1431 	case IP_VERSION(3, 5, 0):
1432 	case IP_VERSION(3, 5, 1):
1433 	case IP_VERSION(3, 6, 0):
1434 	case IP_VERSION(4, 2, 0):
1435 	case IP_VERSION(4, 2, 1):
1436 		hw_params.ips_sequential_ono = adev->external_rev_id > 0x10;
1437 		hw_params.lower_hbr3_phy_ssc = true;
1438 		break;
1439 	default:
1440 		break;
1441 	}
1442 
1443 	status = dmub_srv_hw_init(dmub_srv, &hw_params);
1444 	if (status != DMUB_STATUS_OK) {
1445 		drm_err(adev_to_drm(adev), "Error initializing DMUB HW: %d\n", status);
1446 		return -EINVAL;
1447 	}
1448 
1449 	/* Wait for firmware load to finish. */
1450 	status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1451 	if (status != DMUB_STATUS_OK)
1452 		drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1453 
1454 	/* Init DMCU and ABM if available. */
1455 	if (dmcu && abm) {
1456 		dmcu->funcs->dmcu_init(dmcu);
1457 		abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1458 	}
1459 
1460 	if (!adev->dm.dc->ctx->dmub_srv)
1461 		adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1462 	if (!adev->dm.dc->ctx->dmub_srv) {
1463 		drm_err(adev_to_drm(adev), "Couldn't allocate DC DMUB server!\n");
1464 		return -ENOMEM;
1465 	}
1466 
1467 	drm_info(adev_to_drm(adev), "DMUB hardware initialized: version=0x%08X\n",
1468 		 adev->dm.dmcub_fw_version);
1469 
1470 	/* Keeping sanity checks off if
1471 	 * DCN31 >= 4.0.59.0
1472 	 * DCN314 >= 8.0.16.0
1473 	 * Otherwise, turn on sanity checks
1474 	 */
1475 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1476 	case IP_VERSION(3, 1, 2):
1477 	case IP_VERSION(3, 1, 3):
1478 		if (adev->dm.dmcub_fw_version &&
1479 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1480 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(4, 0, 59))
1481 				adev->dm.dc->debug.sanity_checks = true;
1482 		break;
1483 	case IP_VERSION(3, 1, 4):
1484 		if (adev->dm.dmcub_fw_version &&
1485 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1486 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(8, 0, 16))
1487 				adev->dm.dc->debug.sanity_checks = true;
1488 		break;
1489 	default:
1490 		break;
1491 	}
1492 
1493 	return 0;
1494 }
1495 
1496 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1497 {
1498 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1499 	enum dmub_status status;
1500 	bool init;
1501 	int r;
1502 
1503 	if (!dmub_srv) {
1504 		/* DMUB isn't supported on the ASIC. */
1505 		return;
1506 	}
1507 
1508 	status = dmub_srv_is_hw_init(dmub_srv, &init);
1509 	if (status != DMUB_STATUS_OK)
1510 		drm_warn(adev_to_drm(adev), "DMUB hardware init check failed: %d\n", status);
1511 
1512 	if (status == DMUB_STATUS_OK && init) {
1513 		/* Wait for firmware load to finish. */
1514 		status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1515 		if (status != DMUB_STATUS_OK)
1516 			drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1517 	} else {
1518 		/* Perform the full hardware initialization. */
1519 		r = dm_dmub_hw_init(adev);
1520 		if (r)
1521 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
1522 	}
1523 }
1524 
1525 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1526 {
1527 	u64 pt_base;
1528 	u32 logical_addr_low;
1529 	u32 logical_addr_high;
1530 	u32 agp_base, agp_bot, agp_top;
1531 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1532 
1533 	memset(pa_config, 0, sizeof(*pa_config));
1534 
1535 	agp_base = 0;
1536 	agp_bot = adev->gmc.agp_start >> 24;
1537 	agp_top = adev->gmc.agp_end >> 24;
1538 
1539 	/* AGP aperture is disabled */
1540 	if (agp_bot > agp_top) {
1541 		logical_addr_low = adev->gmc.fb_start >> 18;
1542 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1543 				       AMD_APU_IS_RENOIR |
1544 				       AMD_APU_IS_GREEN_SARDINE))
1545 			/*
1546 			 * Raven2 has a HW issue that it is unable to use the vram which
1547 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1548 			 * workaround that increase system aperture high address (add 1)
1549 			 * to get rid of the VM fault and hardware hang.
1550 			 */
1551 			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
1552 		else
1553 			logical_addr_high = adev->gmc.fb_end >> 18;
1554 	} else {
1555 		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1556 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1557 				       AMD_APU_IS_RENOIR |
1558 				       AMD_APU_IS_GREEN_SARDINE))
1559 			/*
1560 			 * Raven2 has a HW issue that it is unable to use the vram which
1561 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1562 			 * workaround that increase system aperture high address (add 1)
1563 			 * to get rid of the VM fault and hardware hang.
1564 			 */
1565 			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1566 		else
1567 			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1568 	}
1569 
1570 	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1571 
1572 	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
1573 						   AMDGPU_GPU_PAGE_SHIFT);
1574 	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
1575 						  AMDGPU_GPU_PAGE_SHIFT);
1576 	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
1577 						 AMDGPU_GPU_PAGE_SHIFT);
1578 	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
1579 						AMDGPU_GPU_PAGE_SHIFT);
1580 	page_table_base.high_part = upper_32_bits(pt_base);
1581 	page_table_base.low_part = lower_32_bits(pt_base);
1582 
1583 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1584 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1585 
1586 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
1587 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1588 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1589 
1590 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1591 	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
1592 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1593 
1594 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1595 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1596 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1597 
1598 	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
1599 
1600 }
1601 
1602 static void force_connector_state(
1603 	struct amdgpu_dm_connector *aconnector,
1604 	enum drm_connector_force force_state)
1605 {
1606 	struct drm_connector *connector = &aconnector->base;
1607 
1608 	mutex_lock(&connector->dev->mode_config.mutex);
1609 	aconnector->base.force = force_state;
1610 	mutex_unlock(&connector->dev->mode_config.mutex);
1611 
1612 	mutex_lock(&aconnector->hpd_lock);
1613 	drm_kms_helper_connector_hotplug_event(connector);
1614 	mutex_unlock(&aconnector->hpd_lock);
1615 }
1616 
1617 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1618 {
1619 	struct hpd_rx_irq_offload_work *offload_work;
1620 	struct amdgpu_dm_connector *aconnector;
1621 	struct dc_link *dc_link;
1622 	struct amdgpu_device *adev;
1623 	enum dc_connection_type new_connection_type = dc_connection_none;
1624 	unsigned long flags;
1625 	union test_response test_response;
1626 
1627 	memset(&test_response, 0, sizeof(test_response));
1628 
1629 	offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1630 	aconnector = offload_work->offload_wq->aconnector;
1631 	adev = offload_work->adev;
1632 
1633 	if (!aconnector) {
1634 		drm_err(adev_to_drm(adev), "Can't retrieve aconnector in hpd_rx_irq_offload_work");
1635 		goto skip;
1636 	}
1637 
1638 	dc_link = aconnector->dc_link;
1639 
1640 	mutex_lock(&aconnector->hpd_lock);
1641 	if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
1642 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
1643 	mutex_unlock(&aconnector->hpd_lock);
1644 
1645 	if (new_connection_type == dc_connection_none)
1646 		goto skip;
1647 
1648 	if (amdgpu_in_reset(adev))
1649 		goto skip;
1650 
1651 	if (offload_work->data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
1652 		offload_work->data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
1653 		dm_handle_mst_sideband_msg_ready_event(&aconnector->mst_mgr, DOWN_OR_UP_MSG_RDY_EVENT);
1654 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1655 		offload_work->offload_wq->is_handling_mst_msg_rdy_event = false;
1656 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1657 		goto skip;
1658 	}
1659 
1660 	mutex_lock(&adev->dm.dc_lock);
1661 	if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
1662 		dc_link_dp_handle_automated_test(dc_link);
1663 
1664 		if (aconnector->timing_changed) {
1665 			/* force connector disconnect and reconnect */
1666 			force_connector_state(aconnector, DRM_FORCE_OFF);
1667 			msleep(100);
1668 			force_connector_state(aconnector, DRM_FORCE_UNSPECIFIED);
1669 		}
1670 
1671 		test_response.bits.ACK = 1;
1672 
1673 		core_link_write_dpcd(
1674 		dc_link,
1675 		DP_TEST_RESPONSE,
1676 		&test_response.raw,
1677 		sizeof(test_response));
1678 	} else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1679 			dc_link_check_link_loss_status(dc_link, &offload_work->data) &&
1680 			dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1681 		/* offload_work->data is from handle_hpd_rx_irq->
1682 		 * schedule_hpd_rx_offload_work.this is defer handle
1683 		 * for hpd short pulse. upon here, link status may be
1684 		 * changed, need get latest link status from dpcd
1685 		 * registers. if link status is good, skip run link
1686 		 * training again.
1687 		 */
1688 		union hpd_irq_data irq_data;
1689 
1690 		memset(&irq_data, 0, sizeof(irq_data));
1691 
1692 		/* before dc_link_dp_handle_link_loss, allow new link lost handle
1693 		 * request be added to work queue if link lost at end of dc_link_
1694 		 * dp_handle_link_loss
1695 		 */
1696 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1697 		offload_work->offload_wq->is_handling_link_loss = false;
1698 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1699 
1700 		if ((dc_link_dp_read_hpd_rx_irq_data(dc_link, &irq_data) == DC_OK) &&
1701 			dc_link_check_link_loss_status(dc_link, &irq_data))
1702 			dc_link_dp_handle_link_loss(dc_link);
1703 	}
1704 	mutex_unlock(&adev->dm.dc_lock);
1705 
1706 skip:
1707 	kfree(offload_work);
1708 
1709 }
1710 
1711 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct amdgpu_device *adev)
1712 {
1713 	struct dc *dc = adev->dm.dc;
1714 	int max_caps = dc->caps.max_links;
1715 	int i = 0;
1716 	struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1717 
1718 	hpd_rx_offload_wq = kzalloc_objs(*hpd_rx_offload_wq, max_caps);
1719 
1720 	if (!hpd_rx_offload_wq)
1721 		return NULL;
1722 
1723 
1724 	for (i = 0; i < max_caps; i++) {
1725 		hpd_rx_offload_wq[i].wq =
1726 				    create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1727 
1728 		if (hpd_rx_offload_wq[i].wq == NULL) {
1729 			drm_err(adev_to_drm(adev), "create amdgpu_dm_hpd_rx_offload_wq fail!");
1730 			goto out_err;
1731 		}
1732 
1733 		spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
1734 	}
1735 
1736 	return hpd_rx_offload_wq;
1737 
1738 out_err:
1739 	for (i = 0; i < max_caps; i++) {
1740 		if (hpd_rx_offload_wq[i].wq)
1741 			destroy_workqueue(hpd_rx_offload_wq[i].wq);
1742 	}
1743 	kfree(hpd_rx_offload_wq);
1744 	return NULL;
1745 }
1746 
1747 struct amdgpu_stutter_quirk {
1748 	u16 chip_vendor;
1749 	u16 chip_device;
1750 	u16 subsys_vendor;
1751 	u16 subsys_device;
1752 	u8 revision;
1753 };
1754 
1755 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1756 	/* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1757 	{ 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1758 	{ 0, 0, 0, 0, 0 },
1759 };
1760 
1761 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1762 {
1763 	const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1764 
1765 	while (p && p->chip_device != 0) {
1766 		if (pdev->vendor == p->chip_vendor &&
1767 		    pdev->device == p->chip_device &&
1768 		    pdev->subsystem_vendor == p->subsys_vendor &&
1769 		    pdev->subsystem_device == p->subsys_device &&
1770 		    pdev->revision == p->revision) {
1771 			return true;
1772 		}
1773 		++p;
1774 	}
1775 	return false;
1776 }
1777 
1778 
1779 void*
1780 dm_allocate_gpu_mem(
1781 		struct amdgpu_device *adev,
1782 		enum dc_gpu_mem_alloc_type type,
1783 		size_t size,
1784 		long long *addr)
1785 {
1786 	struct dal_allocation *da;
1787 	u32 domain = (type == DC_MEM_ALLOC_TYPE_GART) ?
1788 		AMDGPU_GEM_DOMAIN_GTT : AMDGPU_GEM_DOMAIN_VRAM;
1789 	int ret;
1790 
1791 	da = kzalloc_obj(struct dal_allocation);
1792 	if (!da)
1793 		return NULL;
1794 
1795 	ret = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
1796 				      domain, &da->bo,
1797 				      &da->gpu_addr, &da->cpu_ptr);
1798 
1799 	*addr = da->gpu_addr;
1800 
1801 	if (ret) {
1802 		kfree(da);
1803 		return NULL;
1804 	}
1805 
1806 	/* add da to list in dm */
1807 	list_add(&da->list, &adev->dm.da_list);
1808 
1809 	return da->cpu_ptr;
1810 }
1811 
1812 void
1813 dm_free_gpu_mem(
1814 		struct amdgpu_device *adev,
1815 		enum dc_gpu_mem_alloc_type type,
1816 		void *pvMem)
1817 {
1818 	struct dal_allocation *da;
1819 
1820 	/* walk the da list in DM */
1821 	list_for_each_entry(da, &adev->dm.da_list, list) {
1822 		if (pvMem == da->cpu_ptr) {
1823 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
1824 			list_del(&da->list);
1825 			kfree(da);
1826 			break;
1827 		}
1828 	}
1829 
1830 }
1831 
1832 static enum dmub_status
1833 dm_dmub_send_vbios_gpint_command(struct amdgpu_device *adev,
1834 				 enum dmub_gpint_command command_code,
1835 				 uint16_t param,
1836 				 uint32_t timeout_us)
1837 {
1838 	union dmub_gpint_data_register reg, test;
1839 	uint32_t i;
1840 
1841 	/* Assume that VBIOS DMUB is ready to take commands */
1842 
1843 	reg.bits.status = 1;
1844 	reg.bits.command_code = command_code;
1845 	reg.bits.param = param;
1846 
1847 	cgs_write_register(adev->dm.cgs_device, 0x34c0 + 0x01f8, reg.all);
1848 
1849 	for (i = 0; i < timeout_us; ++i) {
1850 		udelay(1);
1851 
1852 		/* Check if our GPINT got acked */
1853 		reg.bits.status = 0;
1854 		test = (union dmub_gpint_data_register)
1855 			cgs_read_register(adev->dm.cgs_device, 0x34c0 + 0x01f8);
1856 
1857 		if (test.all == reg.all)
1858 			return DMUB_STATUS_OK;
1859 	}
1860 
1861 	return DMUB_STATUS_TIMEOUT;
1862 }
1863 
1864 static void *dm_dmub_get_vbios_bounding_box(struct amdgpu_device *adev)
1865 {
1866 	void *bb;
1867 	long long addr;
1868 	unsigned int bb_size;
1869 	int i = 0;
1870 	uint16_t chunk;
1871 	enum dmub_gpint_command send_addrs[] = {
1872 		DMUB_GPINT__SET_BB_ADDR_WORD0,
1873 		DMUB_GPINT__SET_BB_ADDR_WORD1,
1874 		DMUB_GPINT__SET_BB_ADDR_WORD2,
1875 		DMUB_GPINT__SET_BB_ADDR_WORD3,
1876 	};
1877 	enum dmub_status ret;
1878 
1879 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1880 	case IP_VERSION(4, 0, 1):
1881 		bb_size = sizeof(struct dml2_soc_bb);
1882 		break;
1883 	case IP_VERSION(4, 2, 0):
1884 	case IP_VERSION(4, 2, 1):
1885 		bb_size = sizeof(struct dml2_soc_bb);
1886 		break;
1887 	default:
1888 		return NULL;
1889 	}
1890 
1891 	bb =  dm_allocate_gpu_mem(adev,
1892 				  DC_MEM_ALLOC_TYPE_GART,
1893 				  bb_size,
1894 				  &addr);
1895 	if (!bb)
1896 		return NULL;
1897 
1898 	for (i = 0; i < 4; i++) {
1899 		/* Extract 16-bit chunk */
1900 		chunk = ((uint64_t) addr >> (i * 16)) & 0xFFFF;
1901 		/* Send the chunk */
1902 		ret = dm_dmub_send_vbios_gpint_command(adev, send_addrs[i], chunk, 30000);
1903 		if (ret != DMUB_STATUS_OK)
1904 			goto free_bb;
1905 	}
1906 
1907 	/* Now ask DMUB to copy the bb */
1908 	ret = dm_dmub_send_vbios_gpint_command(adev, DMUB_GPINT__BB_COPY, 1, 200000);
1909 	if (ret != DMUB_STATUS_OK)
1910 		goto free_bb;
1911 
1912 	return bb;
1913 
1914 free_bb:
1915 	dm_free_gpu_mem(adev, DC_MEM_ALLOC_TYPE_GART, (void *) bb);
1916 	return NULL;
1917 
1918 }
1919 
1920 static enum dmub_ips_disable_type dm_get_default_ips_mode(
1921 	struct amdgpu_device *adev)
1922 {
1923 	enum dmub_ips_disable_type ret = DMUB_IPS_ENABLE;
1924 
1925 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1926 	case IP_VERSION(3, 5, 0):
1927 	case IP_VERSION(3, 6, 0):
1928 	case IP_VERSION(3, 5, 1):
1929 		ret =  DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
1930 		break;
1931 	case IP_VERSION(4, 2, 0):
1932 	case IP_VERSION(4, 2, 1):
1933 		ret =  DMUB_IPS_ENABLE;
1934 		break;
1935 	default:
1936 		/* ASICs older than DCN35 do not have IPSs */
1937 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 5, 0))
1938 			ret = DMUB_IPS_DISABLE_ALL;
1939 		break;
1940 	}
1941 
1942 	return ret;
1943 }
1944 
1945 static int amdgpu_dm_init_power_module(struct amdgpu_display_manager *dm)
1946 {
1947 	struct mod_power_init_params init_data[MAX_NUM_EDP];
1948 
1949 	if (dm->num_of_edps == 0) {
1950 		drm_dbg_driver(
1951 			dm->ddev,
1952 			"amdgpu: No eDP detected, skip initializing power module\n");
1953 		return 0;
1954 	}
1955 
1956 	/* Initialize all the power module parameters */
1957 	for (int i = 0; i < dm->num_of_edps; i++) {
1958 		init_data[i].allow_psr_smu_optimizations =
1959 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_SMU_OPT);
1960 		init_data[i].allow_psr_multi_disp_optimizations =
1961 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_MULTI_DISP_OPT);
1962 		/* See dm_late_init */
1963 		init_data[i].backlight_ramping_override = false;
1964 		init_data[i].backlight_ramping_start = 0xCCCC;
1965 		init_data[i].backlight_ramping_reduction = 0xCCCCCCCC;
1966 		init_data[i].def_varibright_level = 0;
1967 		init_data[i].abm_config_setting = 0;
1968 		init_data[i].num_backlight_levels = 101;
1969 		init_data[i].use_nits_based_brightness = false;
1970 		init_data[i].panel_max_millinits = 0;
1971 		init_data[i].panel_min_millinits = 0;
1972 		init_data[i].disable_fractional_pwm =
1973 			!(amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK);
1974 		init_data[i].use_custom_backlight_caps = false;
1975 		init_data[i].custom_backlight_caps_config_no = 0;
1976 		init_data[i].use_linear_backlight_curve = false;
1977 		init_data[i].def_varibright_enable = 0;
1978 		init_data[i].varibright_level = 0;
1979 		/*
1980 		 * Power module uses 16-bit backlight levels (0xFFFF max) rather
1981 		 * than 8-bit(0XFF max)
1982 		 */
1983 		init_data[i].min_backlight_pwm =
1984 			dm->backlight_caps[i].min_input_signal * 0x101;
1985 		init_data[i].max_backlight_pwm =
1986 			dm->backlight_caps[i].max_input_signal * 0x101;
1987 		init_data[i].min_abm_backlight =
1988 			dm->backlight_caps[i].min_input_signal * 0x101;
1989 
1990 		/* Min backlight level after ABM reduction,  Don't allow below 1%
1991 		 * 0xFFFF x 0.01 = 0x28F
1992 		 */
1993 		init_data[i].min_abm_backlight = (init_data[i].min_abm_backlight < 0x28F) ?
1994 			0x28F : init_data[i].min_abm_backlight;
1995 	}
1996 
1997 	dm->power_module = mod_power_create(dm->dc, init_data, dm->num_of_edps);
1998 	if (!dm->power_module) {
1999 		drm_err(dm->ddev, "amdgpu: Error allocating memory for power module\n");
2000 		return -ENOMEM;
2001 	}
2002 
2003 	mod_power_hw_init(dm->power_module);
2004 	drm_dbg_driver(dm->ddev, "amdgpu: Power module init done\n");
2005 
2006 	return 0;
2007 }
2008 
2009 static void hdmi_frl_status_polling_work(struct work_struct *work)
2010 {
2011 	struct amdgpu_display_manager *dm =
2012 		container_of(to_delayed_work(work), struct amdgpu_display_manager,
2013 				hdmi_frl_status_polling_work);
2014 	struct dc *dc = dm->dc;
2015 	struct dc_link *dc_link;
2016 	bool link_update = false;
2017 
2018 	for (int i = 0; i < MAX_LINKS; i++) {
2019 		dc_link = dc->links[i];
2020 
2021 		if (!dc_link || !dc_link->local_sink)
2022 			continue;
2023 
2024 		if (!dc_is_hdmi_signal(dc_link->connector_signal))
2025 			continue;
2026 
2027 		if (dc_link->connector_signal != SIGNAL_TYPE_HDMI_FRL)
2028 			continue;
2029 
2030 		link_update = dc_link_frl_poll_status_flag(dc_link);
2031 		if (link_update) {
2032 			mutex_lock(&dm->dc_lock);
2033 			dc_link_detect(dc_link, DETECT_REASON_RETRAIN);
2034 			mutex_unlock(&dm->dc_lock);
2035 		}
2036 	}
2037 
2038 	queue_delayed_work(dm->hdmi_frl_status_polling_wq,
2039 			   &dm->hdmi_frl_status_polling_work,
2040 			   msecs_to_jiffies(dm->hdmi_frl_status_polling_delay_ms));
2041 }
2042 
2043 static int amdgpu_dm_init(struct amdgpu_device *adev)
2044 {
2045 	struct dc_init_data init_data;
2046 	struct dc_callback_init init_params;
2047 	int r;
2048 
2049 	adev->dm.ddev = adev_to_drm(adev);
2050 	adev->dm.adev = adev;
2051 
2052 	/* Zero all the fields */
2053 	memset(&init_data, 0, sizeof(init_data));
2054 	memset(&init_params, 0, sizeof(init_params));
2055 
2056 	mutex_init(&adev->dm.dpia_aux_lock);
2057 	mutex_init(&adev->dm.dc_lock);
2058 	mutex_init(&adev->dm.audio_lock);
2059 
2060 	spin_lock_init(&adev->dm.dmub_lock);
2061 
2062 	if (amdgpu_dm_irq_init(adev)) {
2063 		drm_err(adev_to_drm(adev), "failed to initialize DM IRQ support.\n");
2064 		goto error;
2065 	}
2066 
2067 	/* special handling for early revisions of GC 11.5.4 */
2068 	if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(11, 5, 4))
2069 		init_data.asic_id.chip_family = AMDGPU_FAMILY_GC_11_5_4;
2070 	else
2071 		init_data.asic_id.chip_family = adev->family;
2072 
2073 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
2074 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
2075 	init_data.asic_id.chip_id = adev->pdev->device;
2076 
2077 	init_data.asic_id.vram_width = adev->gmc.vram_width;
2078 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
2079 	init_data.asic_id.atombios_base_address =
2080 		adev->mode_info.atom_context->bios;
2081 
2082 	init_data.driver = adev;
2083 
2084 	/* cgs_device was created in dm_sw_init() */
2085 	init_data.cgs_device = adev->dm.cgs_device;
2086 
2087 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
2088 
2089 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2090 	case IP_VERSION(2, 1, 0):
2091 		switch (adev->dm.dmcub_fw_version) {
2092 		case 0: /* development */
2093 		case 0x1: /* linux-firmware.git hash 6d9f399 */
2094 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
2095 			init_data.flags.disable_dmcu = false;
2096 			break;
2097 		default:
2098 			init_data.flags.disable_dmcu = true;
2099 		}
2100 		break;
2101 	case IP_VERSION(2, 0, 3):
2102 		init_data.flags.disable_dmcu = true;
2103 		break;
2104 	default:
2105 		break;
2106 	}
2107 
2108 	/* APU support S/G display by default except:
2109 	 * ASICs before Carrizo,
2110 	 * RAVEN1 (Users reported stability issue)
2111 	 */
2112 
2113 	if (adev->asic_type < CHIP_CARRIZO) {
2114 		init_data.flags.gpu_vm_support = false;
2115 	} else if (adev->asic_type == CHIP_RAVEN) {
2116 		if (adev->apu_flags & AMD_APU_IS_RAVEN)
2117 			init_data.flags.gpu_vm_support = false;
2118 		else
2119 			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
2120 	} else {
2121 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(2, 0, 3))
2122 			init_data.flags.gpu_vm_support = (amdgpu_sg_display == 1);
2123 		else
2124 			init_data.flags.gpu_vm_support =
2125 				(amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
2126 	}
2127 
2128 	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
2129 
2130 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
2131 		init_data.flags.fbc_support = true;
2132 
2133 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
2134 		init_data.flags.multi_mon_pp_mclk_switch = true;
2135 
2136 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
2137 		init_data.flags.disable_fractional_pwm = true;
2138 
2139 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
2140 		init_data.flags.edp_no_power_sequencing = true;
2141 
2142 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
2143 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
2144 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
2145 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
2146 
2147 	if (amdgpu_dc_feature_mask & DC_FRL_MASK)
2148 		init_data.flags.enable_frl = true;
2149 
2150 	init_data.flags.seamless_boot_edp_requested = false;
2151 
2152 	if (amdgpu_device_seamless_boot_supported(adev)) {
2153 		init_data.flags.seamless_boot_edp_requested = true;
2154 		init_data.flags.allow_seamless_boot_optimization = true;
2155 		drm_dbg(adev->dm.ddev, "Seamless boot requested\n");
2156 	}
2157 
2158 	init_data.flags.enable_mipi_converter_optimization = true;
2159 
2160 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
2161 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
2162 	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
2163 
2164 	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
2165 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
2166 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS_DYNAMIC)
2167 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_DYNAMIC;
2168 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS2_DYNAMIC)
2169 		init_data.flags.disable_ips = DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
2170 	else if (amdgpu_dc_debug_mask & DC_FORCE_IPS_ENABLE)
2171 		init_data.flags.disable_ips = DMUB_IPS_ENABLE;
2172 	else
2173 		init_data.flags.disable_ips = dm_get_default_ips_mode(adev);
2174 
2175 	init_data.flags.disable_ips_in_vpb = 0;
2176 
2177 	/* DCN35 and above supports dynamic DTBCLK switch */
2178 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 5, 0))
2179 		init_data.flags.allow_0_dtb_clk = true;
2180 
2181 	/* Enable DWB for tested platforms only */
2182 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
2183 		init_data.num_virtual_links = 1;
2184 
2185 	/* DCN42 and above dpia switch to unified link training path */
2186 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 2, 0)) {
2187 		init_data.flags.consolidated_dpia_dp_lt = true;
2188 		init_data.flags.enable_dpia_pre_training = true;
2189 		init_data.flags.unify_link_enc_assignment = true;
2190 		init_data.flags.usb4_bw_alloc_support = true;
2191 	}
2192 	retrieve_dmi_info(&adev->dm);
2193 	if (adev->dm.edp0_on_dp1_quirk)
2194 		init_data.flags.support_edp0_on_dp1 = true;
2195 
2196 	if (adev->dm.bb_from_dmub)
2197 		init_data.bb_from_dmub = adev->dm.bb_from_dmub;
2198 	else
2199 		init_data.bb_from_dmub = NULL;
2200 
2201 	/* Display Core create. */
2202 	adev->dm.dc = dc_create(&init_data);
2203 
2204 	if (adev->dm.dc) {
2205 		drm_info(adev_to_drm(adev), "Display Core v%s initialized on %s\n", DC_VER,
2206 			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
2207 	} else {
2208 		drm_info(adev_to_drm(adev), "Display Core failed to initialize with v%s!\n", DC_VER);
2209 		goto error;
2210 	}
2211 
2212 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
2213 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
2214 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
2215 	}
2216 
2217 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2218 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2219 	if (dm_should_disable_stutter(adev->pdev))
2220 		adev->dm.dc->debug.disable_stutter = true;
2221 
2222 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
2223 		adev->dm.dc->debug.disable_stutter = true;
2224 
2225 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
2226 		adev->dm.dc->debug.disable_dsc = true;
2227 
2228 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
2229 		adev->dm.dc->debug.disable_clock_gate = true;
2230 
2231 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
2232 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
2233 
2234 	if (amdgpu_dc_debug_mask & DC_DISABLE_SUBVP_FAMS) {
2235 		adev->dm.dc->debug.force_disable_subvp = true;
2236 		adev->dm.dc->debug.fams2_config.bits.enable = false;
2237 	}
2238 
2239 	if (amdgpu_dc_debug_mask & DC_ENABLE_DML2) {
2240 		adev->dm.dc->debug.using_dml2 = true;
2241 		adev->dm.dc->debug.using_dml21 = true;
2242 	}
2243 
2244 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_FORCE_FW_ENABLE)
2245 		adev->dm.dc->debug.hdcp_lc_force_fw_enable = true;
2246 
2247 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_ENABLE_SW_FALLBACK)
2248 		adev->dm.dc->debug.hdcp_lc_enable_sw_fallback = true;
2249 
2250 	if (amdgpu_dc_debug_mask & DC_SKIP_DETECTION_LT)
2251 		adev->dm.dc->debug.skip_detection_link_training = true;
2252 
2253 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
2254 
2255 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
2256 	adev->dm.dc->debug.ignore_cable_id = true;
2257 
2258 	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
2259 		drm_info(adev_to_drm(adev), "DP-HDMI FRL PCON supported\n");
2260 
2261 	r = dm_dmub_hw_init(adev);
2262 	if (r) {
2263 		drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
2264 		goto error;
2265 	}
2266 
2267 	dc_hardware_init(adev->dm.dc);
2268 
2269 	adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev);
2270 	if (!adev->dm.hpd_rx_offload_wq) {
2271 		drm_err(adev_to_drm(adev), "failed to create hpd rx offload workqueue.\n");
2272 		goto error;
2273 	}
2274 
2275 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
2276 		struct dc_phy_addr_space_config pa_config;
2277 
2278 		mmhub_read_system_context(adev, &pa_config);
2279 
2280 		// Call the DC init_memory func
2281 		dc_setup_system_context(adev->dm.dc, &pa_config);
2282 	}
2283 
2284 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
2285 	if (!adev->dm.freesync_module) {
2286 		drm_err(adev_to_drm(adev),
2287 		"failed to initialize freesync_module.\n");
2288 	} else
2289 		drm_dbg_driver(adev_to_drm(adev), "freesync_module init done %p.\n",
2290 				adev->dm.freesync_module);
2291 
2292 	amdgpu_dm_init_color_mod();
2293 
2294 	if (adev->dm.dc->caps.max_links > 0) {
2295 		adev->dm.vblank_control_workqueue =
2296 			create_singlethread_workqueue("dm_vblank_control_workqueue");
2297 		if (!adev->dm.vblank_control_workqueue)
2298 			drm_err(adev_to_drm(adev), "failed to initialize vblank_workqueue.\n");
2299 	}
2300 
2301 	if (adev->dm.dc->caps.ips_support &&
2302 	    adev->dm.dc->config.disable_ips != DMUB_IPS_DISABLE_ALL)
2303 		adev->dm.idle_workqueue = idle_create_workqueue(adev);
2304 
2305 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
2306 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
2307 
2308 		if (!adev->dm.hdcp_workqueue)
2309 			drm_err(adev_to_drm(adev), "failed to initialize hdcp_workqueue.\n");
2310 		else
2311 			drm_dbg_driver(adev_to_drm(adev),
2312 				       "hdcp_workqueue init done %p.\n",
2313 				       adev->dm.hdcp_workqueue);
2314 
2315 		dc_init_callbacks(adev->dm.dc, &init_params);
2316 	}
2317 	if (adev->dm.dc->caps.max_links > 0) {
2318 		adev->dm.hdmi_frl_status_polling_wq =
2319 			create_singlethread_workqueue("hdmi_frl_status_polling_workqueue");
2320 		if (!adev->dm.hdmi_frl_status_polling_wq)
2321 			drm_err(adev_to_drm(adev), "failed to initialize hdmi_frl_status_polling_workqueue\n");
2322 		adev->dm.hdmi_frl_status_polling_delay_ms = 200;
2323 		INIT_DELAYED_WORK(&adev->dm.hdmi_frl_status_polling_work, hdmi_frl_status_polling_work);
2324 	}
2325 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2326 		init_completion(&adev->dm.dmub_aux_transfer_done);
2327 		adev->dm.dmub_notify = kzalloc_obj(struct dmub_notification);
2328 		if (!adev->dm.dmub_notify) {
2329 			drm_info(adev_to_drm(adev), "fail to allocate adev->dm.dmub_notify");
2330 			goto error;
2331 		}
2332 
2333 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
2334 		if (!adev->dm.delayed_hpd_wq) {
2335 			drm_err(adev_to_drm(adev), "failed to create hpd offload workqueue.\n");
2336 			goto error;
2337 		}
2338 
2339 		amdgpu_dm_outbox_init(adev);
2340 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
2341 			dmub_aux_setconfig_callback, false)) {
2342 			drm_err(adev_to_drm(adev), "fail to register dmub aux callback");
2343 			goto error;
2344 		}
2345 
2346 		for (size_t i = 0; i < ARRAY_SIZE(adev->dm.fused_io); i++)
2347 			init_completion(&adev->dm.fused_io[i].replied);
2348 
2349 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_FUSED_IO,
2350 			dmub_aux_fused_io_callback, false)) {
2351 			drm_err(adev_to_drm(adev), "fail to register dmub fused io callback");
2352 			goto error;
2353 		}
2354 		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
2355 		 * It is expected that DMUB will resend any pending notifications at this point. Note
2356 		 * that hpd and hpd_irq handler registration are deferred to register_hpd_handlers() to
2357 		 * align legacy interface initialization sequence. Connection status will be proactivly
2358 		 * detected once in the amdgpu_dm_initialize_drm_device.
2359 		 */
2360 		dc_enable_dmub_outbox(adev->dm.dc);
2361 
2362 		/* DPIA trace goes to dmesg logs only if outbox is enabled */
2363 		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
2364 			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
2365 	}
2366 
2367 	if (amdgpu_dm_initialize_drm_device(adev)) {
2368 		drm_err(adev_to_drm(adev),
2369 		"failed to initialize sw for display support.\n");
2370 		goto error;
2371 	}
2372 
2373 	if (amdgpu_dm_init_power_module(&adev->dm))
2374 		goto error;
2375 
2376 	/* create fake encoders for MST */
2377 	dm_dp_create_fake_mst_encoders(adev);
2378 
2379 	/* TODO: Add_display_info? */
2380 
2381 	/* TODO use dynamic cursor width */
2382 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
2383 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
2384 
2385 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
2386 		drm_err(adev_to_drm(adev),
2387 		"failed to initialize vblank for display support.\n");
2388 		goto error;
2389 	}
2390 
2391 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2392 	amdgpu_dm_crtc_secure_display_create_contexts(adev);
2393 	if (!adev->dm.secure_display_ctx.crtc_ctx)
2394 		drm_err(adev_to_drm(adev), "failed to initialize secure display contexts.\n");
2395 
2396 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))
2397 		adev->dm.secure_display_ctx.support_mul_roi = true;
2398 
2399 #endif
2400 
2401 	drm_dbg_driver(adev_to_drm(adev), "KMS initialized.\n");
2402 
2403 	return 0;
2404 error:
2405 	amdgpu_dm_fini(adev);
2406 
2407 	return -EINVAL;
2408 }
2409 
2410 static int amdgpu_dm_early_fini(struct amdgpu_ip_block *ip_block)
2411 {
2412 	struct amdgpu_device *adev = ip_block->adev;
2413 
2414 	amdgpu_dm_audio_fini(adev);
2415 
2416 	return 0;
2417 }
2418 
2419 static void amdgpu_dm_fini(struct amdgpu_device *adev)
2420 {
2421 	int i;
2422 
2423 	if (adev->dm.vblank_control_workqueue) {
2424 		destroy_workqueue(adev->dm.vblank_control_workqueue);
2425 		adev->dm.vblank_control_workqueue = NULL;
2426 	}
2427 
2428 	if (adev->dm.idle_workqueue) {
2429 		if (adev->dm.idle_workqueue->running) {
2430 			adev->dm.idle_workqueue->enable = false;
2431 			flush_work(&adev->dm.idle_workqueue->work);
2432 		}
2433 
2434 		kfree(adev->dm.idle_workqueue);
2435 		adev->dm.idle_workqueue = NULL;
2436 	}
2437 
2438 	/*
2439 	 * Disable ISM before dc_destroy() invalidates dm->dc.
2440 	 *
2441 	 * Quiesce workers first without dc_lock (they take dc_lock
2442 	 * themselves, so syncing under it would deadlock), then drive the
2443 	 * FSM back to FULL_POWER_RUNNING under dc_lock.
2444 	 */
2445 	amdgpu_dm_ism_disable(&adev->dm);
2446 	scoped_guard(mutex, &adev->dm.dc_lock)
2447 		amdgpu_dm_ism_force_full_power(&adev->dm);
2448 
2449 	amdgpu_dm_destroy_drm_device(&adev->dm);
2450 
2451 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2452 	if (adev->dm.secure_display_ctx.crtc_ctx) {
2453 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
2454 			if (adev->dm.secure_display_ctx.crtc_ctx[i].crtc) {
2455 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].notify_ta_work);
2456 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].forward_roi_work);
2457 			}
2458 		}
2459 		kfree(adev->dm.secure_display_ctx.crtc_ctx);
2460 		adev->dm.secure_display_ctx.crtc_ctx = NULL;
2461 	}
2462 #endif
2463 	if (adev->dm.hdcp_workqueue) {
2464 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
2465 		adev->dm.hdcp_workqueue = NULL;
2466 	}
2467 
2468 	if (adev->dm.dc) {
2469 		dc_deinit_callbacks(adev->dm.dc);
2470 		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
2471 		if (dc_enable_dmub_notifications(adev->dm.dc)) {
2472 			kfree(adev->dm.dmub_notify);
2473 			adev->dm.dmub_notify = NULL;
2474 			destroy_workqueue(adev->dm.delayed_hpd_wq);
2475 			adev->dm.delayed_hpd_wq = NULL;
2476 		}
2477 	}
2478 
2479 	if (adev->dm.dmub_bo)
2480 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
2481 				      &adev->dm.dmub_bo_gpu_addr,
2482 				      &adev->dm.dmub_bo_cpu_addr);
2483 
2484 	if (adev->dm.boot_time_crc_info.bo_ptr)
2485 		amdgpu_bo_free_kernel(&adev->dm.boot_time_crc_info.bo_ptr,
2486 					&adev->dm.boot_time_crc_info.gpu_addr,
2487 					&adev->dm.boot_time_crc_info.cpu_addr);
2488 
2489 	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
2490 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
2491 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
2492 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
2493 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
2494 			}
2495 		}
2496 
2497 		kfree(adev->dm.hpd_rx_offload_wq);
2498 		adev->dm.hpd_rx_offload_wq = NULL;
2499 	}
2500 
2501 	/* DC Destroy TODO: Replace destroy DAL */
2502 	if (adev->dm.dc)
2503 		dc_destroy(&adev->dm.dc);
2504 	/*
2505 	 * TODO: pageflip, vlank interrupt
2506 	 *
2507 	 * amdgpu_dm_irq_fini(adev);
2508 	 */
2509 
2510 	if (adev->dm.cgs_device) {
2511 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
2512 		adev->dm.cgs_device = NULL;
2513 	}
2514 	if (adev->dm.freesync_module) {
2515 		mod_freesync_destroy(adev->dm.freesync_module);
2516 		adev->dm.freesync_module = NULL;
2517 	}
2518 
2519 	if (adev->dm.power_module) {
2520 		mod_power_destroy(adev->dm.power_module);
2521 		adev->dm.power_module = NULL;
2522 	}
2523 	mutex_destroy(&adev->dm.audio_lock);
2524 	mutex_destroy(&adev->dm.dc_lock);
2525 	mutex_destroy(&adev->dm.dpia_aux_lock);
2526 }
2527 
2528 static int load_dmcu_fw(struct amdgpu_device *adev)
2529 {
2530 	const char *fw_name_dmcu = NULL;
2531 	int r;
2532 	const struct dmcu_firmware_header_v1_0 *hdr;
2533 
2534 	switch (adev->asic_type) {
2535 #if defined(CONFIG_DRM_AMD_DC_SI)
2536 	case CHIP_TAHITI:
2537 	case CHIP_PITCAIRN:
2538 	case CHIP_VERDE:
2539 	case CHIP_OLAND:
2540 #endif
2541 	case CHIP_BONAIRE:
2542 	case CHIP_HAWAII:
2543 	case CHIP_KAVERI:
2544 	case CHIP_KABINI:
2545 	case CHIP_MULLINS:
2546 	case CHIP_TONGA:
2547 	case CHIP_FIJI:
2548 	case CHIP_CARRIZO:
2549 	case CHIP_STONEY:
2550 	case CHIP_POLARIS11:
2551 	case CHIP_POLARIS10:
2552 	case CHIP_POLARIS12:
2553 	case CHIP_VEGAM:
2554 	case CHIP_VEGA10:
2555 	case CHIP_VEGA12:
2556 	case CHIP_VEGA20:
2557 		return 0;
2558 	case CHIP_NAVI12:
2559 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
2560 		break;
2561 	case CHIP_RAVEN:
2562 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
2563 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2564 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
2565 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2566 		else
2567 			return 0;
2568 		break;
2569 	default:
2570 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2571 		case IP_VERSION(2, 0, 2):
2572 		case IP_VERSION(2, 0, 3):
2573 		case IP_VERSION(2, 0, 0):
2574 		case IP_VERSION(2, 1, 0):
2575 		case IP_VERSION(3, 0, 0):
2576 		case IP_VERSION(3, 0, 2):
2577 		case IP_VERSION(3, 0, 3):
2578 		case IP_VERSION(3, 0, 1):
2579 		case IP_VERSION(3, 1, 2):
2580 		case IP_VERSION(3, 1, 3):
2581 		case IP_VERSION(3, 1, 4):
2582 		case IP_VERSION(3, 1, 5):
2583 		case IP_VERSION(3, 1, 6):
2584 		case IP_VERSION(3, 2, 0):
2585 		case IP_VERSION(3, 2, 1):
2586 		case IP_VERSION(3, 5, 0):
2587 		case IP_VERSION(3, 5, 1):
2588 		case IP_VERSION(3, 6, 0):
2589 		case IP_VERSION(4, 0, 1):
2590 		case IP_VERSION(4, 2, 0):
2591 		case IP_VERSION(4, 2, 1):
2592 			return 0;
2593 		default:
2594 			break;
2595 		}
2596 		drm_err(adev_to_drm(adev), "Unsupported ASIC type: 0x%X\n", adev->asic_type);
2597 		return -EINVAL;
2598 	}
2599 
2600 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
2601 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not supported on direct or SMU loading\n");
2602 		return 0;
2603 	}
2604 
2605 	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, AMDGPU_UCODE_REQUIRED,
2606 				 "%s", fw_name_dmcu);
2607 	if (r == -ENODEV) {
2608 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
2609 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not found\n");
2610 		adev->dm.fw_dmcu = NULL;
2611 		return 0;
2612 	}
2613 	if (r) {
2614 		drm_err(adev_to_drm(adev), "amdgpu_dm: Can't validate firmware \"%s\"\n",
2615 			fw_name_dmcu);
2616 		amdgpu_ucode_release(&adev->dm.fw_dmcu);
2617 		return r;
2618 	}
2619 
2620 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
2621 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
2622 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
2623 	adev->firmware.fw_size +=
2624 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2625 
2626 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
2627 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
2628 	adev->firmware.fw_size +=
2629 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2630 
2631 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
2632 
2633 	drm_dbg_kms(adev_to_drm(adev), "PSP loading DMCU firmware\n");
2634 
2635 	return 0;
2636 }
2637 
2638 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
2639 {
2640 	struct amdgpu_device *adev = ctx;
2641 
2642 	return dm_read_reg(adev->dm.dc->ctx, address);
2643 }
2644 
2645 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
2646 				     uint32_t value)
2647 {
2648 	struct amdgpu_device *adev = ctx;
2649 
2650 	return dm_write_reg(adev->dm.dc->ctx, address, value);
2651 }
2652 
2653 static int dm_dmub_sw_init(struct amdgpu_device *adev)
2654 {
2655 	struct dmub_srv_create_params create_params;
2656 	struct dmub_srv_fw_meta_info_params fw_meta_info_params;
2657 	struct dmub_srv_region_params region_params;
2658 	struct dmub_srv_region_info region_info;
2659 	struct dmub_srv_memory_params memory_params;
2660 	struct dmub_fw_meta_info fw_info;
2661 	struct dmub_srv_fb_info *fb_info;
2662 	struct dmub_srv *dmub_srv;
2663 	const struct dmcub_firmware_header_v1_0 *hdr;
2664 	enum dmub_asic dmub_asic;
2665 	enum dmub_status status;
2666 	static enum dmub_window_memory_type window_memory_type[DMUB_WINDOW_TOTAL] = {
2667 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_0_INST_CONST
2668 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_1_STACK
2669 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_2_BSS_DATA
2670 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_3_VBIOS
2671 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_4_MAILBOX
2672 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_5_TRACEBUFF
2673 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_6_FW_STATE
2674 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_7_SCRATCH_MEM
2675 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_IB_MEM
2676 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_SHARED_STATE
2677 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_LSDMA_BUFFER
2678 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_CURSOR_OFFLOAD
2679 	};
2680 	int r;
2681 
2682 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2683 	case IP_VERSION(2, 1, 0):
2684 		dmub_asic = DMUB_ASIC_DCN21;
2685 		break;
2686 	case IP_VERSION(3, 0, 0):
2687 		dmub_asic = DMUB_ASIC_DCN30;
2688 		break;
2689 	case IP_VERSION(3, 0, 1):
2690 		dmub_asic = DMUB_ASIC_DCN301;
2691 		break;
2692 	case IP_VERSION(3, 0, 2):
2693 		dmub_asic = DMUB_ASIC_DCN302;
2694 		break;
2695 	case IP_VERSION(3, 0, 3):
2696 		dmub_asic = DMUB_ASIC_DCN303;
2697 		break;
2698 	case IP_VERSION(3, 1, 2):
2699 	case IP_VERSION(3, 1, 3):
2700 		dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
2701 		break;
2702 	case IP_VERSION(3, 1, 4):
2703 		dmub_asic = DMUB_ASIC_DCN314;
2704 		break;
2705 	case IP_VERSION(3, 1, 5):
2706 		dmub_asic = DMUB_ASIC_DCN315;
2707 		break;
2708 	case IP_VERSION(3, 1, 6):
2709 		dmub_asic = DMUB_ASIC_DCN316;
2710 		break;
2711 	case IP_VERSION(3, 2, 0):
2712 		dmub_asic = DMUB_ASIC_DCN32;
2713 		break;
2714 	case IP_VERSION(3, 2, 1):
2715 		dmub_asic = DMUB_ASIC_DCN321;
2716 		break;
2717 	case IP_VERSION(3, 5, 0):
2718 	case IP_VERSION(3, 5, 1):
2719 		dmub_asic = DMUB_ASIC_DCN35;
2720 		break;
2721 	case IP_VERSION(3, 6, 0):
2722 		dmub_asic = DMUB_ASIC_DCN36;
2723 		break;
2724 	case IP_VERSION(4, 0, 1):
2725 		dmub_asic = DMUB_ASIC_DCN401;
2726 		break;
2727 	case IP_VERSION(4, 2, 0):
2728 		dmub_asic = DMUB_ASIC_DCN42;
2729 		break;
2730 	case IP_VERSION(4, 2, 1):
2731 		dmub_asic = DMUB_ASIC_DCN42B;
2732 		break;
2733 	default:
2734 		/* ASIC doesn't support DMUB. */
2735 		return 0;
2736 	}
2737 
2738 	hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
2739 	adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
2740 
2741 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
2742 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
2743 			AMDGPU_UCODE_ID_DMCUB;
2744 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
2745 			adev->dm.dmub_fw;
2746 		adev->firmware.fw_size +=
2747 			ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
2748 
2749 		drm_info(adev_to_drm(adev), "Loading DMUB firmware via PSP: version=0x%08X\n",
2750 			 adev->dm.dmcub_fw_version);
2751 	}
2752 
2753 
2754 	adev->dm.dmub_srv = kzalloc_obj(*adev->dm.dmub_srv);
2755 	dmub_srv = adev->dm.dmub_srv;
2756 
2757 	if (!dmub_srv) {
2758 		drm_err(adev_to_drm(adev), "Failed to allocate DMUB service!\n");
2759 		return -ENOMEM;
2760 	}
2761 
2762 	memset(&create_params, 0, sizeof(create_params));
2763 	create_params.user_ctx = adev;
2764 	create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2765 	create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2766 	create_params.asic = dmub_asic;
2767 
2768 	/* Create the DMUB service. */
2769 	status = dmub_srv_create(dmub_srv, &create_params);
2770 	if (status != DMUB_STATUS_OK) {
2771 		drm_err(adev_to_drm(adev), "Error creating DMUB service: %d\n", status);
2772 		return -EINVAL;
2773 	}
2774 
2775 	/* Extract the FW meta info. */
2776 	memset(&fw_meta_info_params, 0, sizeof(fw_meta_info_params));
2777 
2778 	fw_meta_info_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2779 					      PSP_HEADER_BYTES_256;
2780 	fw_meta_info_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2781 	fw_meta_info_params.fw_inst_const = adev->dm.dmub_fw->data +
2782 					    le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2783 					    PSP_HEADER_BYTES_256;
2784 	fw_meta_info_params.fw_bss_data = fw_meta_info_params.bss_data_size ? adev->dm.dmub_fw->data +
2785 					  le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2786 					  le32_to_cpu(hdr->inst_const_bytes) : NULL;
2787 	fw_meta_info_params.custom_psp_footer_size = 0;
2788 
2789 	status = dmub_srv_get_fw_meta_info_from_raw_fw(&fw_meta_info_params, &fw_info);
2790 	if (status != DMUB_STATUS_OK) {
2791 		/* Skip returning early, just log the error. */
2792 		drm_err(adev_to_drm(adev), "Error getting DMUB FW meta info: %d\n", status);
2793 		// return -EINVAL;
2794 	}
2795 
2796 	/* Calculate the size of all the regions for the DMUB service. */
2797 	memset(&region_params, 0, sizeof(region_params));
2798 
2799 	region_params.inst_const_size = fw_meta_info_params.inst_const_size;
2800 	region_params.bss_data_size = fw_meta_info_params.bss_data_size;
2801 	region_params.vbios_size = adev->bios_size;
2802 	region_params.fw_bss_data = fw_meta_info_params.fw_bss_data;
2803 	region_params.fw_inst_const = fw_meta_info_params.fw_inst_const;
2804 	region_params.window_memory_type = window_memory_type;
2805 	region_params.fw_info = (status == DMUB_STATUS_OK) ? &fw_info : NULL;
2806 
2807 	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2808 					   &region_info);
2809 
2810 	if (status != DMUB_STATUS_OK) {
2811 		drm_err(adev_to_drm(adev), "Error calculating DMUB region info: %d\n", status);
2812 		return -EINVAL;
2813 	}
2814 
2815 	/*
2816 	 * Allocate a framebuffer based on the total size of all the regions.
2817 	 * TODO: Move this into GART.
2818 	 */
2819 	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2820 				    AMDGPU_GEM_DOMAIN_VRAM |
2821 				    AMDGPU_GEM_DOMAIN_GTT,
2822 				    &adev->dm.dmub_bo,
2823 				    &adev->dm.dmub_bo_gpu_addr,
2824 				    &adev->dm.dmub_bo_cpu_addr);
2825 	if (r)
2826 		return r;
2827 
2828 	/* Rebase the regions on the framebuffer address. */
2829 	memset(&memory_params, 0, sizeof(memory_params));
2830 	memory_params.cpu_fb_addr = adev->dm.dmub_bo_cpu_addr;
2831 	memory_params.gpu_fb_addr = adev->dm.dmub_bo_gpu_addr;
2832 	memory_params.region_info = &region_info;
2833 	memory_params.window_memory_type = window_memory_type;
2834 
2835 	adev->dm.dmub_fb_info = kzalloc_obj(*adev->dm.dmub_fb_info);
2836 	fb_info = adev->dm.dmub_fb_info;
2837 
2838 	if (!fb_info) {
2839 		drm_err(adev_to_drm(adev),
2840 			"Failed to allocate framebuffer info for DMUB service!\n");
2841 		return -ENOMEM;
2842 	}
2843 
2844 	status = dmub_srv_calc_mem_info(dmub_srv, &memory_params, fb_info);
2845 	if (status != DMUB_STATUS_OK) {
2846 		drm_err(adev_to_drm(adev), "Error calculating DMUB FB info: %d\n", status);
2847 		return -EINVAL;
2848 	}
2849 
2850 	adev->dm.bb_from_dmub = dm_dmub_get_vbios_bounding_box(adev);
2851 	adev->dm.fw_inst_size = fw_meta_info_params.inst_const_size;
2852 
2853 	return 0;
2854 }
2855 
2856 static int dm_sw_init(struct amdgpu_ip_block *ip_block)
2857 {
2858 	struct amdgpu_device *adev = ip_block->adev;
2859 	int r;
2860 
2861 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
2862 
2863 	if (!adev->dm.cgs_device) {
2864 		drm_err(adev_to_drm(adev), "failed to create cgs device.\n");
2865 		return -EINVAL;
2866 	}
2867 
2868 	/* Moved from dm init since we need to use allocations for storing bounding box data */
2869 	INIT_LIST_HEAD(&adev->dm.da_list);
2870 
2871 	r = dm_dmub_sw_init(adev);
2872 	if (r)
2873 		return r;
2874 
2875 	return load_dmcu_fw(adev);
2876 }
2877 
2878 static int dm_sw_fini(struct amdgpu_ip_block *ip_block)
2879 {
2880 	struct amdgpu_device *adev = ip_block->adev;
2881 	struct dal_allocation *da;
2882 
2883 	list_for_each_entry(da, &adev->dm.da_list, list) {
2884 		if (adev->dm.bb_from_dmub == (void *) da->cpu_ptr) {
2885 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
2886 			list_del(&da->list);
2887 			kfree(da);
2888 			adev->dm.bb_from_dmub = NULL;
2889 			break;
2890 		}
2891 	}
2892 
2893 
2894 	kfree(adev->dm.dmub_fb_info);
2895 	adev->dm.dmub_fb_info = NULL;
2896 
2897 	if (adev->dm.dmub_srv) {
2898 		dmub_srv_destroy(adev->dm.dmub_srv);
2899 		kfree(adev->dm.dmub_srv);
2900 		adev->dm.dmub_srv = NULL;
2901 	}
2902 
2903 	amdgpu_ucode_release(&adev->dm.dmub_fw);
2904 	amdgpu_ucode_release(&adev->dm.fw_dmcu);
2905 
2906 	return 0;
2907 }
2908 
2909 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2910 {
2911 	struct amdgpu_dm_connector *aconnector;
2912 	struct drm_connector *connector;
2913 	struct drm_connector_list_iter iter;
2914 	int ret = 0;
2915 
2916 	drm_connector_list_iter_begin(dev, &iter);
2917 	drm_for_each_connector_iter(connector, &iter) {
2918 
2919 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2920 			continue;
2921 
2922 		aconnector = to_amdgpu_dm_connector(connector);
2923 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
2924 		    aconnector->mst_mgr.aux) {
2925 			drm_dbg_kms(dev, "DM_MST: starting TM on aconnector: %p [id: %d]\n",
2926 					 aconnector,
2927 					 aconnector->base.base.id);
2928 
2929 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2930 			if (ret < 0) {
2931 				drm_err(dev, "DM_MST: Failed to start MST\n");
2932 				aconnector->dc_link->type =
2933 					dc_connection_single;
2934 				ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2935 								     aconnector->dc_link);
2936 				break;
2937 			}
2938 		}
2939 	}
2940 	drm_connector_list_iter_end(&iter);
2941 
2942 	return ret;
2943 }
2944 
2945 static void amdgpu_dm_boot_time_crc_init(struct amdgpu_device *adev)
2946 {
2947 	struct dm_boot_time_crc_info *bootcrc_info = NULL;
2948 	struct dmub_srv *dmub = NULL;
2949 	union dmub_fw_boot_options option = {0};
2950 	int ret = 0;
2951 	const uint32_t fb_size = 3 * 1024 * 1024;	/* 3MB for DCC pattern */
2952 
2953 	if (!adev || !adev->dm.dc || !adev->dm.dc->ctx ||
2954 		!adev->dm.dc->ctx->dmub_srv) {
2955 		return;
2956 	}
2957 
2958 	dmub = adev->dm.dc->ctx->dmub_srv->dmub;
2959 	bootcrc_info = &adev->dm.boot_time_crc_info;
2960 
2961 	if (!dmub || !dmub->hw_funcs.get_fw_boot_option) {
2962 		drm_dbg(adev_to_drm(adev), "failed to init boot time crc buffer\n");
2963 		return;
2964 	}
2965 
2966 	option = dmub->hw_funcs.get_fw_boot_option(dmub);
2967 
2968 	/* Return if boot time CRC is not enabled */
2969 	if (option.bits.bootcrc_en_at_S0i3 == 0)
2970 		return;
2971 
2972 	/* Create a buffer for boot time CRC */
2973 	ret = amdgpu_bo_create_kernel(adev, fb_size, PAGE_SIZE,
2974 		AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT,
2975 		&bootcrc_info->bo_ptr,
2976 		&bootcrc_info->gpu_addr,
2977 		&bootcrc_info->cpu_addr);
2978 
2979 	if (ret) {
2980 		drm_dbg(adev_to_drm(adev), "failed to create boot time crc buffer\n");
2981 	} else {
2982 		bootcrc_info->size = fb_size;
2983 
2984 		drm_dbg(adev_to_drm(adev), "boot time crc buffer created addr 0x%llx, size %u\n",
2985 			bootcrc_info->gpu_addr, bootcrc_info->size);
2986 
2987 		/* Send the buffer info to DMUB */
2988 		dc_dmub_srv_boot_time_crc_init(adev->dm.dc,
2989 			bootcrc_info->gpu_addr, bootcrc_info->size);
2990 	}
2991 }
2992 
2993 static int dm_late_init(struct amdgpu_ip_block *ip_block)
2994 {
2995 	struct amdgpu_device *adev = ip_block->adev;
2996 
2997 	struct dmcu_iram_parameters params;
2998 	unsigned int linear_lut[16];
2999 	int i;
3000 	struct dmcu *dmcu = NULL;
3001 
3002 	dmcu = adev->dm.dc->res_pool->dmcu;
3003 
3004 	/* Init the boot time CRC (skip in resume) */
3005 	if ((adev->in_suspend == 0) &&
3006 		(amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(3, 6, 0)))
3007 		amdgpu_dm_boot_time_crc_init(adev);
3008 
3009 	for (i = 0; i < 16; i++)
3010 		linear_lut[i] = 0xFFFF * i / 15;
3011 
3012 	params.set = 0;
3013 	params.backlight_ramping_override = false;
3014 	params.backlight_ramping_start = 0xCCCC;
3015 	params.backlight_ramping_reduction = 0xCCCCCCCC;
3016 	params.backlight_lut_array_size = 16;
3017 	params.backlight_lut_array = linear_lut;
3018 
3019 	/* Min backlight level after ABM reduction,  Don't allow below 1%
3020 	 * 0xFFFF x 0.01 = 0x28F
3021 	 */
3022 	params.min_abm_backlight = 0x28F;
3023 	/* In the case where abm is implemented on dmcub,
3024 	 * dmcu object will be null.
3025 	 * ABM 2.4 and up are implemented on dmcub.
3026 	 */
3027 	if (dmcu) {
3028 		if (!dmcu_load_iram(dmcu, params))
3029 			return -EINVAL;
3030 	} else if (adev->dm.dc->ctx->dmub_srv) {
3031 		struct dc_link *edp_links[MAX_NUM_EDP];
3032 		int edp_num;
3033 
3034 		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
3035 		for (i = 0; i < edp_num; i++) {
3036 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
3037 				return -EINVAL;
3038 		}
3039 	}
3040 
3041 	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
3042 }
3043 
3044 static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
3045 {
3046 	u8 buf[UUID_SIZE];
3047 	guid_t guid;
3048 	int ret;
3049 
3050 	mutex_lock(&mgr->lock);
3051 	if (!mgr->mst_primary)
3052 		goto out_fail;
3053 
3054 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
3055 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
3056 		goto out_fail;
3057 	}
3058 
3059 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
3060 				 DP_MST_EN |
3061 				 DP_UP_REQ_EN |
3062 				 DP_UPSTREAM_IS_SRC);
3063 	if (ret < 0) {
3064 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
3065 		goto out_fail;
3066 	}
3067 
3068 	/* Some hubs forget their guids after they resume */
3069 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, buf, sizeof(buf));
3070 	if (ret != sizeof(buf)) {
3071 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
3072 		goto out_fail;
3073 	}
3074 
3075 	import_guid(&guid, buf);
3076 
3077 	if (guid_is_null(&guid)) {
3078 		guid_gen(&guid);
3079 		export_guid(buf, &guid);
3080 
3081 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, buf, sizeof(buf));
3082 
3083 		if (ret != sizeof(buf)) {
3084 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
3085 			goto out_fail;
3086 		}
3087 	}
3088 
3089 	guid_copy(&mgr->mst_primary->guid, &guid);
3090 
3091 out_fail:
3092 	mutex_unlock(&mgr->lock);
3093 }
3094 
3095 void hdmi_cec_unset_edid(struct amdgpu_dm_connector *aconnector)
3096 {
3097 	struct cec_notifier *n = aconnector->notifier;
3098 
3099 	if (!n)
3100 		return;
3101 
3102 	cec_notifier_phys_addr_invalidate(n);
3103 }
3104 
3105 void hdmi_cec_set_edid(struct amdgpu_dm_connector *aconnector)
3106 {
3107 	struct drm_connector *connector = &aconnector->base;
3108 	struct cec_notifier *n = aconnector->notifier;
3109 
3110 	if (!n)
3111 		return;
3112 
3113 	cec_notifier_set_phys_addr(n,
3114 				   connector->display_info.source_physical_address);
3115 }
3116 
3117 static void s3_handle_hdmi_cec(struct drm_device *ddev, bool suspend)
3118 {
3119 	struct amdgpu_dm_connector *aconnector;
3120 	struct drm_connector *connector;
3121 	struct drm_connector_list_iter conn_iter;
3122 
3123 	drm_connector_list_iter_begin(ddev, &conn_iter);
3124 	drm_for_each_connector_iter(connector, &conn_iter) {
3125 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3126 			continue;
3127 
3128 		aconnector = to_amdgpu_dm_connector(connector);
3129 		if (suspend)
3130 			hdmi_cec_unset_edid(aconnector);
3131 		else
3132 			hdmi_cec_set_edid(aconnector);
3133 	}
3134 	drm_connector_list_iter_end(&conn_iter);
3135 }
3136 
3137 static void s3_handle_mst(struct drm_device *dev, bool suspend)
3138 {
3139 	struct amdgpu_dm_connector *aconnector;
3140 	struct drm_connector *connector;
3141 	struct drm_connector_list_iter iter;
3142 	struct drm_dp_mst_topology_mgr *mgr;
3143 
3144 	drm_connector_list_iter_begin(dev, &iter);
3145 	drm_for_each_connector_iter(connector, &iter) {
3146 
3147 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3148 			continue;
3149 
3150 		aconnector = to_amdgpu_dm_connector(connector);
3151 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3152 		    aconnector->mst_root)
3153 			continue;
3154 
3155 		mgr = &aconnector->mst_mgr;
3156 
3157 		if (suspend) {
3158 			drm_dp_mst_topology_mgr_suspend(mgr);
3159 		} else {
3160 			/* if extended timeout is supported in hardware,
3161 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
3162 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
3163 			 */
3164 			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
3165 			if (!dp_is_lttpr_present(aconnector->dc_link))
3166 				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
3167 
3168 			/* TODO: move resume_mst_branch_status() into drm mst resume again
3169 			 * once topology probing work is pulled out from mst resume into mst
3170 			 * resume 2nd step. mst resume 2nd step should be called after old
3171 			 * state getting restored (i.e. drm_atomic_helper_resume()).
3172 			 */
3173 			resume_mst_branch_status(mgr);
3174 		}
3175 	}
3176 	drm_connector_list_iter_end(&iter);
3177 }
3178 
3179 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
3180 {
3181 	int ret = 0;
3182 
3183 	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
3184 	 * on window driver dc implementation.
3185 	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
3186 	 * should be passed to smu during boot up and resume from s3.
3187 	 * boot up: dc calculate dcn watermark clock settings within dc_create,
3188 	 * dcn20_resource_construct
3189 	 * then call pplib functions below to pass the settings to smu:
3190 	 * smu_set_watermarks_for_clock_ranges
3191 	 * smu_set_watermarks_table
3192 	 * navi10_set_watermarks_table
3193 	 * smu_write_watermarks_table
3194 	 *
3195 	 * For Renoir, clock settings of dcn watermark are also fixed values.
3196 	 * dc has implemented different flow for window driver:
3197 	 * dc_hardware_init / dc_set_power_state
3198 	 * dcn10_init_hw
3199 	 * notify_wm_ranges
3200 	 * set_wm_ranges
3201 	 * -- Linux
3202 	 * smu_set_watermarks_for_clock_ranges
3203 	 * renoir_set_watermarks_table
3204 	 * smu_write_watermarks_table
3205 	 *
3206 	 * For Linux,
3207 	 * dc_hardware_init -> amdgpu_dm_init
3208 	 * dc_set_power_state --> dm_resume
3209 	 *
3210 	 * therefore, this function apply to navi10/12/14 but not Renoir
3211 	 * *
3212 	 */
3213 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
3214 	case IP_VERSION(2, 0, 2):
3215 	case IP_VERSION(2, 0, 0):
3216 		break;
3217 	default:
3218 		return 0;
3219 	}
3220 
3221 	ret = amdgpu_dpm_write_watermarks_table(adev);
3222 	if (ret) {
3223 		drm_err(adev_to_drm(adev), "Failed to update WMTABLE!\n");
3224 		return ret;
3225 	}
3226 
3227 	return 0;
3228 }
3229 
3230 static int dm_oem_i2c_hw_init(struct amdgpu_device *adev)
3231 {
3232 	struct amdgpu_display_manager *dm = &adev->dm;
3233 	struct amdgpu_i2c_adapter *oem_i2c;
3234 	struct ddc_service *oem_ddc_service;
3235 	int r;
3236 
3237 	oem_ddc_service = dc_get_oem_i2c_device(adev->dm.dc);
3238 	if (oem_ddc_service) {
3239 		oem_i2c = create_i2c(oem_ddc_service, true);
3240 		if (!oem_i2c) {
3241 			drm_info(adev_to_drm(adev), "Failed to create oem i2c adapter data\n");
3242 			return -ENOMEM;
3243 		}
3244 
3245 		r = devm_i2c_add_adapter(adev->dev, &oem_i2c->base);
3246 		if (r) {
3247 			drm_info(adev_to_drm(adev), "Failed to register oem i2c\n");
3248 			kfree(oem_i2c);
3249 			return r;
3250 		}
3251 		dm->oem_i2c = oem_i2c;
3252 	}
3253 
3254 	return 0;
3255 }
3256 
3257 /**
3258  * dm_hw_init() - Initialize DC device
3259  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3260  *
3261  * Initialize the &struct amdgpu_display_manager device. This involves calling
3262  * the initializers of each DM component, then populating the struct with them.
3263  *
3264  * Although the function implies hardware initialization, both hardware and
3265  * software are initialized here. Splitting them out to their relevant init
3266  * hooks is a future TODO item.
3267  *
3268  * Some notable things that are initialized here:
3269  *
3270  * - Display Core, both software and hardware
3271  * - DC modules that we need (freesync and color management)
3272  * - DRM software states
3273  * - Interrupt sources and handlers
3274  * - Vblank support
3275  * - Debug FS entries, if enabled
3276  */
3277 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
3278 {
3279 	struct amdgpu_device *adev = ip_block->adev;
3280 	int r;
3281 
3282 	/* Create DAL display manager */
3283 	r = amdgpu_dm_init(adev);
3284 	if (r)
3285 		return r;
3286 	amdgpu_dm_hpd_init(adev);
3287 
3288 	r = dm_oem_i2c_hw_init(adev);
3289 	if (r)
3290 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
3291 
3292 	return 0;
3293 }
3294 
3295 /**
3296  * dm_hw_fini() - Teardown DC device
3297  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3298  *
3299  * Teardown components within &struct amdgpu_display_manager that require
3300  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
3301  * were loaded. Also flush IRQ workqueues and disable them.
3302  */
3303 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
3304 {
3305 	struct amdgpu_device *adev = ip_block->adev;
3306 
3307 	amdgpu_dm_hpd_fini(adev);
3308 
3309 	amdgpu_dm_irq_fini(adev);
3310 	amdgpu_dm_fini(adev);
3311 	return 0;
3312 }
3313 
3314 
3315 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
3316 				 struct dc_state *state, bool enable)
3317 {
3318 	enum dc_irq_source irq_source;
3319 	struct amdgpu_crtc *acrtc;
3320 	int rc = -EBUSY;
3321 	int i = 0;
3322 
3323 	for (i = 0; i < state->stream_count; i++) {
3324 		acrtc = get_crtc_by_otg_inst(
3325 				adev, state->stream_status[i].primary_otg_inst);
3326 
3327 		if (acrtc && state->stream_status[i].plane_count != 0) {
3328 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
3329 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3330 			if (rc)
3331 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
3332 					 enable ? "enable" : "disable");
3333 
3334 			if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
3335 				if (enable) {
3336 					if (amdgpu_dm_crtc_vrr_active(
3337 							to_dm_crtc_state(acrtc->base.state)))
3338 						rc = amdgpu_dm_crtc_set_vupdate_irq(
3339 							&acrtc->base, true);
3340 				} else
3341 					rc = amdgpu_dm_crtc_set_vupdate_irq(
3342 							&acrtc->base, false);
3343 
3344 				if (rc)
3345 					drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
3346 						enable ? "en" : "dis");
3347 			}
3348 
3349 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3350 			/* During gpu-reset we disable and then enable vblank irq, so
3351 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
3352 			 */
3353 			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
3354 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
3355 
3356 		} else if (acrtc && state->stream_status[i].plane_count != 0) {
3357 			/* DCN only needs to toggle VUPDATE_NO_LOCK */
3358 			rc = amdgpu_dm_crtc_set_vupdate_irq(&acrtc->base, enable);
3359 			if (rc)
3360 				drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
3361 					 enable ? "en" : "dis");
3362 		}
3363 	}
3364 
3365 }
3366 
3367 DEFINE_FREE(state_release, struct dc_state *, if (_T) dc_state_release(_T))
3368 
3369 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
3370 {
3371 	struct dc_state *context __free(state_release) = NULL;
3372 	int i;
3373 	struct dc_stream_state *del_streams[MAX_PIPES];
3374 	int del_streams_count = 0;
3375 	struct dc_commit_streams_params params = {};
3376 
3377 	memset(del_streams, 0, sizeof(del_streams));
3378 
3379 	context = dc_state_create_current_copy(dc);
3380 	if (context == NULL)
3381 		return DC_ERROR_UNEXPECTED;
3382 
3383 	/* First remove from context all streams */
3384 	for (i = 0; i < context->stream_count; i++) {
3385 		struct dc_stream_state *stream = context->streams[i];
3386 
3387 		del_streams[del_streams_count++] = stream;
3388 	}
3389 
3390 	/* Remove all planes for removed streams and then remove the streams */
3391 	for (i = 0; i < del_streams_count; i++) {
3392 		enum dc_status res;
3393 
3394 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
3395 			return DC_FAIL_DETACH_SURFACES;
3396 
3397 		res = dc_state_remove_stream(dc, context, del_streams[i]);
3398 		if (res != DC_OK)
3399 			return res;
3400 	}
3401 
3402 	params.streams = context->streams;
3403 	params.stream_count = context->stream_count;
3404 
3405 	return dc_commit_streams(dc, &params);
3406 }
3407 
3408 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
3409 {
3410 	int i;
3411 
3412 	if (dm->hpd_rx_offload_wq) {
3413 		for (i = 0; i < dm->dc->caps.max_links; i++)
3414 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
3415 	}
3416 }
3417 
3418 static int dm_cache_state(struct amdgpu_device *adev)
3419 {
3420 	int r;
3421 
3422 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
3423 	if (IS_ERR(adev->dm.cached_state)) {
3424 		r = PTR_ERR(adev->dm.cached_state);
3425 		adev->dm.cached_state = NULL;
3426 	}
3427 
3428 	return adev->dm.cached_state ? 0 : r;
3429 }
3430 
3431 static void dm_destroy_cached_state(struct amdgpu_device *adev)
3432 {
3433 	struct amdgpu_display_manager *dm = &adev->dm;
3434 	struct drm_device *ddev = adev_to_drm(adev);
3435 	struct dm_plane_state *dm_new_plane_state;
3436 	struct drm_plane_state *new_plane_state;
3437 	struct dm_crtc_state *dm_new_crtc_state;
3438 	struct drm_crtc_state *new_crtc_state;
3439 	struct drm_plane *plane;
3440 	struct drm_crtc *crtc;
3441 	int i;
3442 
3443 	if (!dm->cached_state)
3444 		return;
3445 
3446 	/* Force mode set in atomic commit */
3447 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3448 		new_crtc_state->active_changed = true;
3449 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3450 		reset_freesync_config_for_crtc(dm_new_crtc_state);
3451 	}
3452 
3453 	/*
3454 	 * atomic_check is expected to create the dc states. We need to release
3455 	 * them here, since they were duplicated as part of the suspend
3456 	 * procedure.
3457 	 */
3458 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3459 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3460 		if (dm_new_crtc_state->stream) {
3461 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
3462 			dc_stream_release(dm_new_crtc_state->stream);
3463 			dm_new_crtc_state->stream = NULL;
3464 		}
3465 		dm_new_crtc_state->base.color_mgmt_changed = true;
3466 	}
3467 
3468 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
3469 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
3470 		if (dm_new_plane_state->dc_state) {
3471 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
3472 			dc_plane_state_release(dm_new_plane_state->dc_state);
3473 			dm_new_plane_state->dc_state = NULL;
3474 		}
3475 	}
3476 
3477 	drm_atomic_helper_resume(ddev, dm->cached_state);
3478 
3479 	dm->cached_state = NULL;
3480 }
3481 
3482 static int dm_suspend(struct amdgpu_ip_block *ip_block)
3483 {
3484 	struct amdgpu_device *adev = ip_block->adev;
3485 	struct amdgpu_display_manager *dm = &adev->dm;
3486 
3487 	if (amdgpu_in_reset(adev)) {
3488 		enum dc_status res;
3489 
3490 		/* Quiesce ISM workers before taking dc_lock (workers take
3491 		 * dc_lock themselves; syncing under it would deadlock).
3492 		 */
3493 		amdgpu_dm_ism_disable(dm);
3494 
3495 		mutex_lock(&dm->dc_lock);
3496 
3497 		amdgpu_dm_ism_force_full_power(dm);
3498 		dc_allow_idle_optimizations(adev->dm.dc, false);
3499 
3500 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
3501 
3502 		if (dm->cached_dc_state)
3503 			dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
3504 
3505 		res = amdgpu_dm_commit_zero_streams(dm->dc);
3506 		if (res != DC_OK) {
3507 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
3508 			return -EINVAL;
3509 		}
3510 
3511 		amdgpu_dm_irq_suspend(adev);
3512 
3513 		hpd_rx_irq_work_suspend(dm);
3514 
3515 		return 0;
3516 	}
3517 
3518 	if (!adev->dm.cached_state) {
3519 		int r = dm_cache_state(adev);
3520 
3521 		if (r)
3522 			return r;
3523 	}
3524 
3525 	s3_handle_hdmi_cec(adev_to_drm(adev), true);
3526 
3527 	s3_handle_mst(adev_to_drm(adev), true);
3528 
3529 	amdgpu_dm_irq_suspend(adev);
3530 
3531 	/*
3532 	 * Quiesce ISM workers before taking dc_lock (workers take dc_lock
3533 	 * themselves; syncing under it would deadlock).
3534 	 */
3535 	amdgpu_dm_ism_disable(dm);
3536 	scoped_guard(mutex, &dm->dc_lock)
3537 		amdgpu_dm_ism_force_full_power(dm);
3538 
3539 	hpd_rx_irq_work_suspend(dm);
3540 
3541 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
3542 
3543 	if (dm->dc->caps.ips_support && adev->in_s0ix)
3544 		dc_allow_idle_optimizations(dm->dc, true);
3545 
3546 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
3547 
3548 	return 0;
3549 }
3550 
3551 struct drm_connector *
3552 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_commit *state,
3553 					     struct drm_crtc *crtc)
3554 {
3555 	u32 i;
3556 	struct drm_connector_state *new_con_state;
3557 	struct drm_connector *connector;
3558 	struct drm_crtc *crtc_from_state;
3559 
3560 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3561 		crtc_from_state = new_con_state->crtc;
3562 
3563 		if (crtc_from_state == crtc)
3564 			return connector;
3565 	}
3566 
3567 	return NULL;
3568 }
3569 
3570 static void emulated_link_detect(struct dc_link *link)
3571 {
3572 	struct dc_sink_init_data sink_init_data = { 0 };
3573 	struct display_sink_capability sink_caps = { 0 };
3574 	enum dc_edid_status edid_status;
3575 	struct dc_context *dc_ctx = link->ctx;
3576 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
3577 	struct dc_sink *sink = NULL;
3578 	struct dc_sink *prev_sink = NULL;
3579 
3580 	link->type = dc_connection_none;
3581 	prev_sink = link->local_sink;
3582 
3583 	if (prev_sink)
3584 		dc_sink_release(prev_sink);
3585 
3586 	switch (link->connector_signal) {
3587 	case SIGNAL_TYPE_HDMI_TYPE_A: {
3588 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3589 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
3590 		break;
3591 	}
3592 
3593 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
3594 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3595 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
3596 		break;
3597 	}
3598 
3599 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
3600 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3601 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
3602 		break;
3603 	}
3604 
3605 	case SIGNAL_TYPE_LVDS: {
3606 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3607 		sink_caps.signal = SIGNAL_TYPE_LVDS;
3608 		break;
3609 	}
3610 
3611 	case SIGNAL_TYPE_EDP: {
3612 		sink_caps.transaction_type =
3613 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3614 		sink_caps.signal = SIGNAL_TYPE_EDP;
3615 		break;
3616 	}
3617 
3618 	case SIGNAL_TYPE_DISPLAY_PORT: {
3619 		sink_caps.transaction_type =
3620 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3621 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
3622 		break;
3623 	}
3624 
3625 	default:
3626 		drm_err(dev, "Invalid connector type! signal:%d\n",
3627 			link->connector_signal);
3628 		return;
3629 	}
3630 
3631 	sink_init_data.link = link;
3632 	sink_init_data.sink_signal = sink_caps.signal;
3633 
3634 	sink = dc_sink_create(&sink_init_data);
3635 	if (!sink) {
3636 		drm_err(dev, "Failed to create sink!\n");
3637 		return;
3638 	}
3639 
3640 	/* dc_sink_create returns a new reference */
3641 	link->local_sink = sink;
3642 
3643 	edid_status = dm_helpers_read_local_edid(
3644 			link->ctx,
3645 			link,
3646 			sink);
3647 
3648 	if (edid_status != EDID_OK)
3649 		drm_err(dev, "Failed to read EDID\n");
3650 
3651 }
3652 
3653 static void dm_gpureset_commit_state(struct dc_state *dc_state,
3654 				     struct amdgpu_display_manager *dm)
3655 {
3656 	struct {
3657 		struct dc_surface_update surface_updates[MAX_SURFACES];
3658 		struct dc_plane_info plane_infos[MAX_SURFACES];
3659 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3660 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3661 		struct dc_stream_update stream_update;
3662 	} *bundle __free(kfree);
3663 	int k, m;
3664 
3665 	bundle = kzalloc_obj(*bundle);
3666 
3667 	if (!bundle) {
3668 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
3669 		return;
3670 	}
3671 
3672 	for (k = 0; k < dc_state->stream_count; k++) {
3673 		bundle->stream_update.stream = dc_state->streams[k];
3674 
3675 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
3676 			bundle->surface_updates[m].surface =
3677 				dc_state->stream_status[k].plane_states[m];
3678 			bundle->surface_updates[m].surface->force_full_update =
3679 				true;
3680 		}
3681 
3682 		update_planes_and_stream_adapter(dm->dc,
3683 					 UPDATE_TYPE_FULL,
3684 					 dc_state->stream_status[k].plane_count,
3685 					 dc_state->streams[k],
3686 					 &bundle->stream_update,
3687 					 bundle->surface_updates);
3688 	}
3689 }
3690 
3691 static void apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
3692 					    struct dc_sink *sink)
3693 {
3694 	struct dc_panel_patch *ppatch = NULL;
3695 
3696 	if (!sink)
3697 		return;
3698 
3699 	ppatch = &sink->edid_caps.panel_patch;
3700 	if (ppatch->wait_after_dpcd_poweroff_ms) {
3701 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
3702 		drm_dbg_driver(adev_to_drm(adev),
3703 			       "%s: adding a %ds delay as w/a for panel\n",
3704 			       __func__,
3705 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
3706 	}
3707 }
3708 
3709 /**
3710  * amdgpu_dm_dump_links_and_sinks - Debug dump of all DC links and their sinks
3711  * @adev: amdgpu device pointer
3712  *
3713  * Iterates through all DC links and dumps information about local and remote
3714  * (MST) sinks. Should be called after connector detection is complete to see
3715  * the final state of all links.
3716  */
3717 static void amdgpu_dm_dump_links_and_sinks(struct amdgpu_device *adev)
3718 {
3719 	struct dc *dc = adev->dm.dc;
3720 	struct drm_device *dev = adev_to_drm(adev);
3721 	int li;
3722 
3723 	if (!dc)
3724 		return;
3725 
3726 	for (li = 0; li < dc->link_count; li++) {
3727 		struct dc_link *l = dc->links[li];
3728 		const char *name = NULL;
3729 		int rs;
3730 
3731 		if (!l)
3732 			continue;
3733 		if (l->local_sink && l->local_sink->edid_caps.display_name[0])
3734 			name = l->local_sink->edid_caps.display_name;
3735 		else
3736 			name = "n/a";
3737 
3738 		drm_dbg_kms(dev,
3739 			"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",
3740 			li,
3741 			l->local_sink,
3742 			l->type,
3743 			l->local_sink ? l->local_sink->sink_signal : SIGNAL_TYPE_NONE,
3744 			l->sink_count,
3745 			name,
3746 			l->dpcd_caps.is_mst_capable,
3747 			l->mst_stream_alloc_table.stream_count);
3748 
3749 		/* Dump remote (MST) sinks if any */
3750 		for (rs = 0; rs < l->sink_count; rs++) {
3751 			struct dc_sink *rsink = l->remote_sinks[rs];
3752 			const char *rname = NULL;
3753 
3754 			if (!rsink)
3755 				continue;
3756 			if (rsink->edid_caps.display_name[0])
3757 				rname = rsink->edid_caps.display_name;
3758 			else
3759 				rname = "n/a";
3760 			drm_dbg_kms(dev,
3761 				"  REMOTE_SINK[%d:%d]: sink=%p signal=%d edid_name=%s\n",
3762 				li, rs,
3763 				rsink,
3764 				rsink->sink_signal,
3765 				rname);
3766 		}
3767 	}
3768 }
3769 
3770 static int dm_resume(struct amdgpu_ip_block *ip_block)
3771 {
3772 	struct amdgpu_device *adev = ip_block->adev;
3773 	struct drm_device *ddev = adev_to_drm(adev);
3774 	struct amdgpu_display_manager *dm = &adev->dm;
3775 	struct amdgpu_dm_connector *aconnector;
3776 	struct drm_connector *connector;
3777 	struct drm_connector_list_iter iter;
3778 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
3779 	enum dc_connection_type new_connection_type = dc_connection_none;
3780 	struct dc_state *dc_state;
3781 	int i, r, j;
3782 	struct dc_commit_streams_params commit_params = {};
3783 
3784 	if (dm->dc->caps.ips_support) {
3785 		if (!amdgpu_in_reset(adev))
3786 			mutex_lock(&dm->dc_lock);
3787 
3788 		/* Need to set POWER_STATE_D0 first or it will not execute
3789 		 * idle_power_optimizations command to DMUB.
3790 		 */
3791 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3792 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
3793 
3794 		if (!amdgpu_in_reset(adev))
3795 			mutex_unlock(&dm->dc_lock);
3796 	}
3797 
3798 	if (amdgpu_in_reset(adev)) {
3799 		dc_state = dm->cached_dc_state;
3800 
3801 		/*
3802 		 * The dc->current_state is backed up into dm->cached_dc_state
3803 		 * before we commit 0 streams.
3804 		 *
3805 		 * DC will clear link encoder assignments on the real state
3806 		 * but the changes won't propagate over to the copy we made
3807 		 * before the 0 streams commit.
3808 		 *
3809 		 * DC expects that link encoder assignments are *not* valid
3810 		 * when committing a state, so as a workaround we can copy
3811 		 * off of the current state.
3812 		 *
3813 		 * We lose the previous assignments, but we had already
3814 		 * commit 0 streams anyway.
3815 		 */
3816 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
3817 
3818 		r = dm_dmub_hw_init(adev);
3819 		if (r) {
3820 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
3821 			return r;
3822 		}
3823 
3824 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3825 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3826 
3827 		dc_resume(dm->dc);
3828 
3829 		amdgpu_dm_ism_enable(dm);
3830 		amdgpu_dm_irq_resume_early(adev);
3831 
3832 		for (i = 0; i < dc_state->stream_count; i++) {
3833 			dc_state->streams[i]->mode_changed = true;
3834 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
3835 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
3836 					= 0xffffffff;
3837 			}
3838 		}
3839 
3840 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3841 			amdgpu_dm_outbox_init(adev);
3842 			dc_enable_dmub_outbox(adev->dm.dc);
3843 		}
3844 
3845 		commit_params.streams = dc_state->streams;
3846 		commit_params.stream_count = dc_state->stream_count;
3847 		dc_exit_ips_for_hw_access(dm->dc);
3848 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
3849 
3850 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
3851 
3852 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
3853 
3854 		dc_state_release(dm->cached_dc_state);
3855 		dm->cached_dc_state = NULL;
3856 
3857 		amdgpu_dm_irq_resume_late(adev);
3858 
3859 		mutex_unlock(&dm->dc_lock);
3860 
3861 		/* set the backlight after a reset */
3862 		for (i = 0; i < dm->num_of_edps; i++) {
3863 			if (dm->backlight_dev[i])
3864 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
3865 		}
3866 
3867 		return 0;
3868 	}
3869 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
3870 	dc_state_release(dm_state->context);
3871 	dm_state->context = dc_state_create(dm->dc, NULL);
3872 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
3873 
3874 	/* Before powering on DC we need to re-initialize DMUB. */
3875 	dm_dmub_hw_resume(adev);
3876 
3877 	/* Re-enable outbox interrupts for DPIA. */
3878 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3879 		amdgpu_dm_outbox_init(adev);
3880 		dc_enable_dmub_outbox(adev->dm.dc);
3881 	}
3882 
3883 	/* power on hardware */
3884 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3885 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3886 
3887 	/* program HPD filter */
3888 	dc_resume(dm->dc);
3889 
3890 	scoped_guard(mutex, &dm->dc_lock)
3891 		amdgpu_dm_ism_enable(dm);
3892 
3893 	/*
3894 	 * early enable HPD Rx IRQ, should be done before set mode as short
3895 	 * pulse interrupts are used for MST
3896 	 */
3897 	amdgpu_dm_irq_resume_early(adev);
3898 
3899 	s3_handle_hdmi_cec(ddev, false);
3900 
3901 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
3902 	s3_handle_mst(ddev, false);
3903 
3904 	/* Do detection*/
3905 	drm_connector_list_iter_begin(ddev, &iter);
3906 	drm_for_each_connector_iter(connector, &iter) {
3907 		bool ret;
3908 
3909 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3910 			continue;
3911 
3912 		aconnector = to_amdgpu_dm_connector(connector);
3913 
3914 		if (!aconnector->dc_link)
3915 			continue;
3916 
3917 		/*
3918 		 * this is the case when traversing through already created end sink
3919 		 * MST connectors, should be skipped
3920 		 */
3921 		if (aconnector->mst_root)
3922 			continue;
3923 
3924 		/* Skip eDP detection, when there is no sink present */
3925 		if (aconnector->dc_link->connector_signal == SIGNAL_TYPE_EDP &&
3926 		    !aconnector->dc_link->edp_sink_present)
3927 			continue;
3928 
3929 		guard(mutex)(&aconnector->hpd_lock);
3930 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3931 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3932 
3933 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3934 			emulated_link_detect(aconnector->dc_link);
3935 		} else {
3936 			guard(mutex)(&dm->dc_lock);
3937 			dc_exit_ips_for_hw_access(dm->dc);
3938 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
3939 			if (ret) {
3940 				/* w/a delay for certain panels */
3941 				apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3942 			}
3943 		}
3944 
3945 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
3946 			aconnector->fake_enable = false;
3947 
3948 		if (aconnector->dc_sink)
3949 			dc_sink_release(aconnector->dc_sink);
3950 		aconnector->dc_sink = NULL;
3951 		amdgpu_dm_update_connector_after_detect(aconnector);
3952 	}
3953 	drm_connector_list_iter_end(&iter);
3954 
3955 	dm_destroy_cached_state(adev);
3956 
3957 	/* Do mst topology probing after resuming cached state*/
3958 	drm_connector_list_iter_begin(ddev, &iter);
3959 	drm_for_each_connector_iter(connector, &iter) {
3960 		bool init = false;
3961 
3962 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3963 			continue;
3964 
3965 		aconnector = to_amdgpu_dm_connector(connector);
3966 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3967 		    aconnector->mst_root)
3968 			continue;
3969 
3970 		scoped_guard(mutex, &aconnector->mst_mgr.lock) {
3971 			init = !aconnector->mst_mgr.mst_primary;
3972 		}
3973 		if (init)
3974 			dm_helpers_dp_mst_start_top_mgr(aconnector->dc_link->ctx,
3975 				aconnector->dc_link, false);
3976 		else
3977 			drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
3978 	}
3979 	drm_connector_list_iter_end(&iter);
3980 
3981 	/* Debug dump: list all DC links and their associated sinks after detection
3982 	 * is complete for all connectors. This provides a comprehensive view of the
3983 	 * final state without repeating the dump for each connector.
3984 	 */
3985 	amdgpu_dm_dump_links_and_sinks(adev);
3986 
3987 	amdgpu_dm_irq_resume_late(adev);
3988 
3989 	amdgpu_dm_smu_write_watermarks_table(adev);
3990 
3991 	drm_kms_helper_hotplug_event(ddev);
3992 
3993 	return 0;
3994 }
3995 
3996 /**
3997  * DOC: DM Lifecycle
3998  *
3999  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
4000  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
4001  * the base driver's device list to be initialized and torn down accordingly.
4002  *
4003  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
4004  */
4005 
4006 static const struct amd_ip_funcs amdgpu_dm_funcs = {
4007 	.name = "dm",
4008 	.early_init = dm_early_init,
4009 	.late_init = dm_late_init,
4010 	.sw_init = dm_sw_init,
4011 	.sw_fini = dm_sw_fini,
4012 	.early_fini = amdgpu_dm_early_fini,
4013 	.hw_init = dm_hw_init,
4014 	.hw_fini = dm_hw_fini,
4015 	.suspend = dm_suspend,
4016 	.resume = dm_resume,
4017 	.is_idle = dm_is_idle,
4018 	.wait_for_idle = dm_wait_for_idle,
4019 	.check_soft_reset = dm_check_soft_reset,
4020 	.soft_reset = dm_soft_reset,
4021 	.set_clockgating_state = dm_set_clockgating_state,
4022 	.set_powergating_state = dm_set_powergating_state,
4023 };
4024 
4025 const struct amdgpu_ip_block_version dm_ip_block = {
4026 	.type = AMD_IP_BLOCK_TYPE_DCE,
4027 	.major = 1,
4028 	.minor = 0,
4029 	.rev = 0,
4030 	.funcs = &amdgpu_dm_funcs,
4031 };
4032 
4033 
4034 /**
4035  * DOC: atomic
4036  *
4037  * *WIP*
4038  */
4039 
4040 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
4041 	.fb_create = amdgpu_display_user_framebuffer_create,
4042 	.get_format_info = amdgpu_dm_plane_get_format_info,
4043 	.atomic_check = amdgpu_dm_atomic_check,
4044 	.atomic_commit = drm_atomic_helper_commit,
4045 };
4046 
4047 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
4048 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
4049 	.atomic_commit_setup = amdgpu_dm_atomic_setup_commit,
4050 };
4051 
4052 #define DDC_MANUFACTURERNAME_SAMSUNG 0x2D4C
4053 
4054 static void dm_set_panel_type(struct amdgpu_dm_connector *aconnector)
4055 {
4056 	struct drm_connector *connector = &aconnector->base;
4057 	struct drm_display_info *display_info = &connector->display_info;
4058 	struct dc_link *link = aconnector->dc_link;
4059 	struct amdgpu_device *adev;
4060 
4061 	adev = drm_to_adev(connector->dev);
4062 
4063 	link->panel_type = PANEL_TYPE_NONE;
4064 
4065 	switch (display_info->amd_vsdb.panel_type) {
4066 	case AMD_VSDB_PANEL_TYPE_OLED:
4067 		link->panel_type = PANEL_TYPE_OLED;
4068 		break;
4069 	case AMD_VSDB_PANEL_TYPE_MINILED:
4070 		link->panel_type = PANEL_TYPE_MINILED;
4071 		break;
4072 	}
4073 
4074 	/* If VSDB didn't determine panel type, check DPCD ext caps */
4075 	if (link->panel_type == PANEL_TYPE_NONE) {
4076 		if (link->dpcd_sink_ext_caps.bits.miniled == 1)
4077 			link->panel_type = PANEL_TYPE_MINILED;
4078 		if (link->dpcd_sink_ext_caps.bits.oled == 1)
4079 			link->panel_type = PANEL_TYPE_OLED;
4080 	}
4081 
4082 	/*
4083 	 * TODO: get panel type from DID2 that has device technology field
4084 	 * to specify if it's OLED or not. But we need to wait for DID2
4085 	 * support in DC and EDID parser to be able to use it here.
4086 	 */
4087 
4088 	if (link->panel_type == PANEL_TYPE_NONE) {
4089 		struct drm_amd_vsdb_info *vsdb = &display_info->amd_vsdb;
4090 		u32 lum1_max = vsdb->luminance_range1.max_luminance;
4091 		u32 lum2_max = vsdb->luminance_range2.max_luminance;
4092 
4093 		if (vsdb->version && link->local_sink &&
4094 		    link->local_sink->edid_caps.manufacturer_id ==
4095 		    DDC_MANUFACTURERNAME_SAMSUNG &&
4096 		    lum1_max >= ((lum2_max * 3) / 2))
4097 			link->panel_type = PANEL_TYPE_MINILED;
4098 	}
4099 
4100 	if (link->panel_type == PANEL_TYPE_OLED)
4101 		drm_object_property_set_value(&connector->base,
4102 		    adev_to_drm(adev)->mode_config.panel_type_property,
4103 		    DRM_MODE_PANEL_TYPE_OLED);
4104 	else
4105 		drm_object_property_set_value(&connector->base,
4106 		    adev_to_drm(adev)->mode_config.panel_type_property,
4107 		    DRM_MODE_PANEL_TYPE_UNKNOWN);
4108 
4109 	drm_dbg_kms(aconnector->base.dev, "Panel type: %d\n", link->panel_type);
4110 }
4111 
4112 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
4113 {
4114 	const struct drm_panel_backlight_quirk *panel_backlight_quirk;
4115 	struct amdgpu_dm_backlight_caps *caps;
4116 	struct drm_connector *conn_base;
4117 	struct amdgpu_device *adev;
4118 	struct drm_luminance_range_info *luminance_range;
4119 	struct drm_device *drm;
4120 
4121 	if (aconnector->bl_idx == -1 ||
4122 	    aconnector->dc_link->connector_signal != SIGNAL_TYPE_EDP)
4123 		return;
4124 
4125 	conn_base = &aconnector->base;
4126 	drm = conn_base->dev;
4127 	adev = drm_to_adev(drm);
4128 
4129 	caps = &adev->dm.backlight_caps[aconnector->bl_idx];
4130 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
4131 	caps->aux_support = false;
4132 
4133 	panel_backlight_quirk = drm_get_panel_backlight_quirk(aconnector->drm_edid);
4134 
4135 	if (caps->ext_caps->bits.oled == 1
4136 	    /*
4137 	     * ||
4138 	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
4139 	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
4140 	     */)
4141 		caps->aux_support = true;
4142 
4143 	if (amdgpu_backlight == 0)
4144 		caps->aux_support = false;
4145 	else if (amdgpu_backlight == 1)
4146 		caps->aux_support = true;
4147 	else if (!IS_ERR_OR_NULL(panel_backlight_quirk) &&
4148 		 panel_backlight_quirk->force_pwm)
4149 		caps->aux_support = false;
4150 	if (caps->aux_support)
4151 		aconnector->dc_link->backlight_control_type = BACKLIGHT_CONTROL_AMD_AUX;
4152 
4153 	luminance_range = &conn_base->display_info.luminance_range;
4154 
4155 	if (luminance_range->max_luminance)
4156 		caps->aux_max_input_signal = luminance_range->max_luminance;
4157 	else
4158 		caps->aux_max_input_signal = 512;
4159 
4160 	if (luminance_range->min_luminance)
4161 		caps->aux_min_input_signal = luminance_range->min_luminance;
4162 	else
4163 		caps->aux_min_input_signal = 1;
4164 
4165 	if (!IS_ERR_OR_NULL(panel_backlight_quirk)) {
4166 		if (panel_backlight_quirk->min_brightness) {
4167 			caps->min_input_signal =
4168 				panel_backlight_quirk->min_brightness - 1;
4169 			drm_info(drm,
4170 				 "Applying panel backlight quirk, min_brightness: %d\n",
4171 				 caps->min_input_signal);
4172 		}
4173 		if (panel_backlight_quirk->brightness_mask) {
4174 			drm_info(drm,
4175 				 "Applying panel backlight quirk, brightness_mask: 0x%X\n",
4176 				 panel_backlight_quirk->brightness_mask);
4177 			caps->brightness_mask =
4178 				panel_backlight_quirk->brightness_mask;
4179 		}
4180 	}
4181 }
4182 
4183 DEFINE_FREE(sink_release, struct dc_sink *, if (_T) dc_sink_release(_T))
4184 
4185 void amdgpu_dm_update_connector_after_detect(
4186 		struct amdgpu_dm_connector *aconnector)
4187 {
4188 	struct drm_connector *connector = &aconnector->base;
4189 	struct dc_sink *sink __free(sink_release) = NULL;
4190 	struct drm_device *dev = connector->dev;
4191 
4192 	/* MST handled by drm_mst framework */
4193 	if (aconnector->mst_mgr.mst_state == true)
4194 		return;
4195 
4196 	sink = aconnector->dc_link->local_sink;
4197 	if (sink)
4198 		dc_sink_retain(sink);
4199 
4200 	/*
4201 	 * Edid mgmt connector gets first update only in mode_valid hook and then
4202 	 * the connector sink is set to either fake or physical sink depends on link status.
4203 	 * Skip if already done during boot.
4204 	 */
4205 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
4206 			&& aconnector->dc_em_sink) {
4207 
4208 		/*
4209 		 * For S3 resume with headless use eml_sink to fake stream
4210 		 * because on resume connector->sink is set to NULL
4211 		 */
4212 		guard(mutex)(&dev->mode_config.mutex);
4213 
4214 		if (sink) {
4215 			if (aconnector->dc_sink) {
4216 				amdgpu_dm_update_freesync_caps(connector, NULL, true);
4217 				/*
4218 				 * retain and release below are used to
4219 				 * bump up refcount for sink because the link doesn't point
4220 				 * to it anymore after disconnect, so on next crtc to connector
4221 				 * reshuffle by UMD we will get into unwanted dc_sink release
4222 				 */
4223 				dc_sink_release(aconnector->dc_sink);
4224 			}
4225 			aconnector->dc_sink = sink;
4226 			dc_sink_retain(aconnector->dc_sink);
4227 			amdgpu_dm_update_freesync_caps(connector,
4228 					aconnector->drm_edid, true);
4229 		} else {
4230 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4231 			if (!aconnector->dc_sink) {
4232 				aconnector->dc_sink = aconnector->dc_em_sink;
4233 				dc_sink_retain(aconnector->dc_sink);
4234 			}
4235 		}
4236 
4237 		return;
4238 	}
4239 
4240 	/*
4241 	 * TODO: temporary guard to look for proper fix
4242 	 * if this sink is MST sink, we should not do anything
4243 	 */
4244 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
4245 		return;
4246 
4247 	if (aconnector->dc_sink == sink) {
4248 		/*
4249 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
4250 		 * Do nothing!!
4251 		 */
4252 		drm_dbg_kms(dev, "DCHPD: connector_id=%d: dc_sink didn't change.\n",
4253 				 aconnector->connector_id);
4254 		return;
4255 	}
4256 
4257 	drm_dbg_kms(dev, "DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
4258 		    aconnector->connector_id, aconnector->dc_sink, sink);
4259 
4260 	/* When polling, DRM has already locked the mutex for us. */
4261 	if (!drm_kms_helper_is_poll_worker())
4262 		mutex_lock(&dev->mode_config.mutex);
4263 
4264 	/*
4265 	 * 1. Update status of the drm connector
4266 	 * 2. Send an event and let userspace tell us what to do
4267 	 */
4268 	if (sink) {
4269 		/*
4270 		 * TODO: check if we still need the S3 mode update workaround.
4271 		 * If yes, put it here.
4272 		 */
4273 		if (aconnector->dc_sink) {
4274 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4275 			dc_sink_release(aconnector->dc_sink);
4276 		}
4277 
4278 		aconnector->dc_sink = sink;
4279 		dc_sink_retain(aconnector->dc_sink);
4280 		drm_edid_free(aconnector->drm_edid);
4281 		aconnector->drm_edid = NULL;
4282 		if (sink->dc_edid.length == 0) {
4283 			hdmi_cec_unset_edid(aconnector);
4284 			if (aconnector->dc_link->aux_mode) {
4285 				drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4286 			}
4287 		} else {
4288 			const struct edid *edid = (const struct edid *)sink->dc_edid.raw_edid;
4289 
4290 			aconnector->drm_edid = drm_edid_alloc(edid, sink->dc_edid.length);
4291 			drm_edid_connector_update(connector, aconnector->drm_edid);
4292 
4293 			hdmi_cec_set_edid(aconnector);
4294 			if (aconnector->dc_link->aux_mode)
4295 				drm_dp_cec_attach(&aconnector->dm_dp_aux.aux,
4296 						  connector->display_info.source_physical_address);
4297 		}
4298 
4299 		if (!aconnector->timing_requested) {
4300 			aconnector->timing_requested =
4301 				kzalloc_obj(struct dc_crtc_timing);
4302 			if (!aconnector->timing_requested)
4303 				drm_err(dev,
4304 					"failed to create aconnector->requested_timing\n");
4305 		}
4306 
4307 		amdgpu_dm_update_freesync_caps(connector, aconnector->drm_edid, true);
4308 		update_connector_ext_caps(aconnector);
4309 		dm_set_panel_type(aconnector);
4310 	} else {
4311 		hdmi_cec_unset_edid(aconnector);
4312 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4313 		amdgpu_dm_update_freesync_caps(connector, NULL, true);
4314 		aconnector->num_modes = 0;
4315 		dc_sink_release(aconnector->dc_sink);
4316 		aconnector->dc_sink = NULL;
4317 		drm_edid_free(aconnector->drm_edid);
4318 		aconnector->drm_edid = NULL;
4319 		kfree(aconnector->timing_requested);
4320 		aconnector->timing_requested = NULL;
4321 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
4322 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
4323 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
4324 	}
4325 
4326 	update_subconnector_property(aconnector);
4327 
4328 	/* When polling, the mutex will be unlocked for us by DRM. */
4329 	if (!drm_kms_helper_is_poll_worker())
4330 		mutex_unlock(&dev->mode_config.mutex);
4331 }
4332 
4333 static bool are_sinks_equal(const struct dc_sink *sink1, const struct dc_sink *sink2)
4334 {
4335 	if (!sink1 || !sink2)
4336 		return false;
4337 	if (sink1->sink_signal != sink2->sink_signal)
4338 		return false;
4339 
4340 	if (sink1->dc_edid.length != sink2->dc_edid.length)
4341 		return false;
4342 
4343 	if (memcmp(sink1->dc_edid.raw_edid, sink2->dc_edid.raw_edid,
4344 		   sink1->dc_edid.length) != 0)
4345 		return false;
4346 	return true;
4347 }
4348 
4349 
4350 /**
4351  * DOC: hdmi_hpd_debounce_work
4352  *
4353  * HDMI HPD debounce delay in milliseconds. When an HDMI display toggles HPD
4354  * (such as during power save transitions), this delay determines how long to
4355  * wait before processing the HPD event. This allows distinguishing between a
4356  * physical unplug (>hdmi_hpd_debounce_delay)
4357  * and a spontaneous RX HPD toggle (<hdmi_hpd_debounce_delay).
4358  *
4359  * If the toggle is less than this delay, the driver compares sink capabilities
4360  * and permits a hotplug event if they changed.
4361  *
4362  * The default value of 1500ms was chosen based on experimental testing with
4363  * various monitors that exhibit spontaneous HPD toggling behavior.
4364  */
4365 static void hdmi_hpd_debounce_work(struct work_struct *work)
4366 {
4367 	struct amdgpu_dm_connector *aconnector =
4368 		container_of(to_delayed_work(work), struct amdgpu_dm_connector,
4369 			     hdmi_hpd_debounce_work);
4370 	struct drm_connector *connector = &aconnector->base;
4371 	struct drm_device *dev = connector->dev;
4372 	struct amdgpu_device *adev = drm_to_adev(dev);
4373 	struct dc *dc = aconnector->dc_link->ctx->dc;
4374 	bool fake_reconnect = false;
4375 	bool reallow_idle = false;
4376 	bool ret = false;
4377 	guard(mutex)(&aconnector->hpd_lock);
4378 
4379 	/* Re-detect the display */
4380 	scoped_guard(mutex, &adev->dm.dc_lock) {
4381 		if (dc->caps.ips_support && dc->ctx->dmub_srv->idle_allowed) {
4382 			dc_allow_idle_optimizations(dc, false);
4383 			reallow_idle = true;
4384 		}
4385 		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4386 	}
4387 
4388 	if (ret) {
4389 		/* Apply workaround delay for certain panels */
4390 		apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4391 		/* Compare sinks to determine if this was a spontaneous HPD toggle */
4392 		if (are_sinks_equal(aconnector->dc_link->local_sink, aconnector->hdmi_prev_sink)) {
4393 			/*
4394 			* Sinks match - this was a spontaneous HDMI HPD toggle.
4395 			*/
4396 			drm_dbg_kms(dev, "HDMI HPD: Sink unchanged after debounce, internal re-enable\n");
4397 			fake_reconnect = true;
4398 		}
4399 
4400 		/* Update connector state */
4401 		amdgpu_dm_update_connector_after_detect(aconnector);
4402 
4403 		drm_modeset_lock_all(dev);
4404 		dm_restore_drm_connector_state(dev, connector);
4405 		drm_modeset_unlock_all(dev);
4406 
4407 		/* Only notify OS if sink actually changed */
4408 		if (!fake_reconnect && aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4409 			drm_kms_helper_hotplug_event(dev);
4410 	}
4411 
4412 	/* Release the cached sink reference */
4413 	if (aconnector->hdmi_prev_sink) {
4414 		dc_sink_release(aconnector->hdmi_prev_sink);
4415 		aconnector->hdmi_prev_sink = NULL;
4416 	}
4417 
4418 	scoped_guard(mutex, &adev->dm.dc_lock) {
4419 		if (reallow_idle && dc->caps.ips_support)
4420 			dc_allow_idle_optimizations(dc, true);
4421 	}
4422 }
4423 
4424 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
4425 {
4426 	struct drm_connector *connector = &aconnector->base;
4427 	struct drm_device *dev = connector->dev;
4428 	enum dc_connection_type new_connection_type = dc_connection_none;
4429 	struct amdgpu_device *adev = drm_to_adev(dev);
4430 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
4431 	struct dc *dc = aconnector->dc_link->ctx->dc;
4432 	bool ret = false;
4433 	bool debounce_required = false;
4434 
4435 	if (adev->dm.disable_hpd_irq)
4436 		return;
4437 
4438 	/*
4439 	 * In case of failure or MST no need to update connector status or notify the OS
4440 	 * since (for MST case) MST does this in its own context.
4441 	 */
4442 	guard(mutex)(&aconnector->hpd_lock);
4443 
4444 	if (adev->dm.hdcp_workqueue) {
4445 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
4446 		dm_con_state->update_hdcp = true;
4447 	}
4448 	if (aconnector->fake_enable)
4449 		aconnector->fake_enable = false;
4450 
4451 	aconnector->timing_changed = false;
4452 
4453 	if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
4454 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4455 
4456 	/*
4457 	 * Check for HDMI disconnect with debounce enabled.
4458 	 */
4459 	debounce_required = (aconnector->hdmi_hpd_debounce_delay_ms > 0 &&
4460 			      dc_is_hdmi_signal(aconnector->dc_link->connector_signal) &&
4461 			      new_connection_type == dc_connection_none &&
4462 			      aconnector->dc_link->local_sink != NULL);
4463 
4464 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
4465 		emulated_link_detect(aconnector->dc_link);
4466 
4467 		drm_modeset_lock_all(dev);
4468 		dm_restore_drm_connector_state(dev, connector);
4469 		drm_modeset_unlock_all(dev);
4470 
4471 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4472 			drm_kms_helper_connector_hotplug_event(connector);
4473 	} else if (debounce_required) {
4474 		/*
4475 		 * HDMI disconnect detected - schedule delayed work instead of
4476 		 * processing immediately. This allows us to coalesce spurious
4477 		 * HDMI signals from physical unplugs.
4478 		 */
4479 		drm_dbg_kms(dev, "HDMI HPD: Disconnect detected, scheduling debounce work (%u ms)\n",
4480 			    aconnector->hdmi_hpd_debounce_delay_ms);
4481 
4482 		/* Cache the current sink for later comparison */
4483 		if (aconnector->hdmi_prev_sink)
4484 			dc_sink_release(aconnector->hdmi_prev_sink);
4485 		aconnector->hdmi_prev_sink = aconnector->dc_link->local_sink;
4486 		if (aconnector->hdmi_prev_sink)
4487 			dc_sink_retain(aconnector->hdmi_prev_sink);
4488 
4489 		/* Schedule delayed detection. */
4490 		if (mod_delayed_work(system_percpu_wq,
4491 				 &aconnector->hdmi_hpd_debounce_work,
4492 				 msecs_to_jiffies(aconnector->hdmi_hpd_debounce_delay_ms)))
4493 			drm_dbg_kms(dev, "HDMI HPD: Re-scheduled debounce work\n");
4494 
4495 	} else {
4496 
4497 		/* If the aconnector->hdmi_hpd_debounce_work is scheduled, exit early */
4498 		if (delayed_work_pending(&aconnector->hdmi_hpd_debounce_work))
4499 			return;
4500 
4501 		scoped_guard(mutex, &adev->dm.dc_lock) {
4502 			dc_exit_ips_for_hw_access(dc);
4503 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4504 		}
4505 		if (ret) {
4506 			/* w/a delay for certain panels */
4507 			apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4508 			amdgpu_dm_update_connector_after_detect(aconnector);
4509 
4510 			drm_modeset_lock_all(dev);
4511 			dm_restore_drm_connector_state(dev, connector);
4512 			drm_modeset_unlock_all(dev);
4513 
4514 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4515 				drm_kms_helper_connector_hotplug_event(connector);
4516 		}
4517 	}
4518 }
4519 
4520 static void handle_hpd_irq(void *param)
4521 {
4522 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4523 
4524 	handle_hpd_irq_helper(aconnector);
4525 
4526 }
4527 
4528 static void schedule_hpd_rx_offload_work(struct amdgpu_device *adev, struct hpd_rx_irq_offload_work_queue *offload_wq,
4529 							union hpd_irq_data hpd_irq_data)
4530 {
4531 	struct hpd_rx_irq_offload_work *offload_work = kzalloc_obj(*offload_work);
4532 
4533 	if (!offload_work) {
4534 		drm_err(adev_to_drm(adev), "Failed to allocate hpd_rx_irq_offload_work.\n");
4535 		return;
4536 	}
4537 
4538 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
4539 	offload_work->data = hpd_irq_data;
4540 	offload_work->offload_wq = offload_wq;
4541 	offload_work->adev = adev;
4542 
4543 	queue_work(offload_wq->wq, &offload_work->work);
4544 	drm_dbg_kms(adev_to_drm(adev), "queue work to handle hpd_rx offload work");
4545 }
4546 
4547 static void handle_hpd_rx_irq(void *param)
4548 {
4549 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4550 	struct drm_connector *connector = &aconnector->base;
4551 	struct drm_device *dev = connector->dev;
4552 	struct dc_link *dc_link = aconnector->dc_link;
4553 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
4554 	bool result = false;
4555 	enum dc_connection_type new_connection_type = dc_connection_none;
4556 	struct amdgpu_device *adev = drm_to_adev(dev);
4557 	union hpd_irq_data hpd_irq_data;
4558 	bool link_loss = false;
4559 	bool has_left_work = false;
4560 	int idx = dc_link->link_index;
4561 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
4562 	struct dc *dc = aconnector->dc_link->ctx->dc;
4563 
4564 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
4565 
4566 	if (adev->dm.disable_hpd_irq)
4567 		return;
4568 
4569 	/*
4570 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
4571 	 * conflict, after implement i2c helper, this mutex should be
4572 	 * retired.
4573 	 */
4574 	mutex_lock(&aconnector->hpd_lock);
4575 
4576 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
4577 						&link_loss, true, &has_left_work);
4578 
4579 	if (!has_left_work)
4580 		goto out;
4581 
4582 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
4583 		schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4584 		goto out;
4585 	}
4586 
4587 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
4588 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
4589 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
4590 			bool skip = false;
4591 
4592 			/*
4593 			 * DOWN_REP_MSG_RDY is also handled by polling method
4594 			 * mgr->cbs->poll_hpd_irq()
4595 			 */
4596 			spin_lock(&offload_wq->offload_lock);
4597 			skip = offload_wq->is_handling_mst_msg_rdy_event;
4598 
4599 			if (!skip)
4600 				offload_wq->is_handling_mst_msg_rdy_event = true;
4601 
4602 			spin_unlock(&offload_wq->offload_lock);
4603 
4604 			if (!skip)
4605 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4606 
4607 			goto out;
4608 		}
4609 
4610 		if (link_loss) {
4611 			bool skip = false;
4612 
4613 			spin_lock(&offload_wq->offload_lock);
4614 			skip = offload_wq->is_handling_link_loss;
4615 
4616 			if (!skip)
4617 				offload_wq->is_handling_link_loss = true;
4618 
4619 			spin_unlock(&offload_wq->offload_lock);
4620 
4621 			if (!skip)
4622 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4623 
4624 			goto out;
4625 		}
4626 	}
4627 
4628 out:
4629 	if (result && !is_mst_root_connector) {
4630 		/* Downstream Port status changed. */
4631 		if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
4632 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4633 
4634 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4635 			emulated_link_detect(dc_link);
4636 
4637 			if (aconnector->fake_enable)
4638 				aconnector->fake_enable = false;
4639 
4640 			amdgpu_dm_update_connector_after_detect(aconnector);
4641 
4642 
4643 			drm_modeset_lock_all(dev);
4644 			dm_restore_drm_connector_state(dev, connector);
4645 			drm_modeset_unlock_all(dev);
4646 
4647 			drm_kms_helper_connector_hotplug_event(connector);
4648 		} else {
4649 			bool ret = false;
4650 
4651 			mutex_lock(&adev->dm.dc_lock);
4652 			dc_exit_ips_for_hw_access(dc);
4653 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
4654 			mutex_unlock(&adev->dm.dc_lock);
4655 
4656 			if (ret) {
4657 				if (aconnector->fake_enable)
4658 					aconnector->fake_enable = false;
4659 
4660 				amdgpu_dm_update_connector_after_detect(aconnector);
4661 
4662 				drm_modeset_lock_all(dev);
4663 				dm_restore_drm_connector_state(dev, connector);
4664 				drm_modeset_unlock_all(dev);
4665 
4666 				drm_kms_helper_connector_hotplug_event(connector);
4667 			}
4668 		}
4669 	}
4670 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
4671 		if (adev->dm.hdcp_workqueue)
4672 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
4673 	}
4674 
4675 	if (dc_link->type != dc_connection_mst_branch)
4676 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
4677 
4678 	mutex_unlock(&aconnector->hpd_lock);
4679 }
4680 
4681 static int register_hpd_handlers(struct amdgpu_device *adev)
4682 {
4683 	struct drm_device *dev = adev_to_drm(adev);
4684 	struct drm_connector *connector;
4685 	struct amdgpu_dm_connector *aconnector;
4686 	const struct dc_link *dc_link;
4687 	struct dc_interrupt_params int_params = {0};
4688 
4689 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4690 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4691 
4692 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
4693 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD,
4694 			dmub_hpd_callback, true)) {
4695 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4696 			return -EINVAL;
4697 		}
4698 
4699 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ,
4700 			dmub_hpd_callback, true)) {
4701 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4702 			return -EINVAL;
4703 		}
4704 
4705 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_SENSE_NOTIFY,
4706 			dmub_hpd_sense_callback, true)) {
4707 			drm_err(adev_to_drm(adev), "fail to register dmub hpd sense callback");
4708 			return -EINVAL;
4709 		}
4710 	}
4711 
4712 	list_for_each_entry(connector,
4713 			&dev->mode_config.connector_list, head)	{
4714 
4715 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
4716 			continue;
4717 
4718 		aconnector = to_amdgpu_dm_connector(connector);
4719 		dc_link = aconnector->dc_link;
4720 
4721 		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
4722 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4723 			int_params.irq_source = dc_link->irq_source_hpd;
4724 
4725 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4726 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1 ||
4727 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6) {
4728 				drm_err(adev_to_drm(adev), "Failed to register hpd irq!\n");
4729 				return -EINVAL;
4730 			}
4731 
4732 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4733 				handle_hpd_irq, (void *) aconnector))
4734 				return -ENOMEM;
4735 		}
4736 
4737 		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
4738 
4739 			/* Also register for DP short pulse (hpd_rx). */
4740 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4741 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
4742 
4743 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4744 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1RX ||
4745 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6RX) {
4746 				drm_err(adev_to_drm(adev), "Failed to register hpd rx irq!\n");
4747 				return -EINVAL;
4748 			}
4749 
4750 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4751 				handle_hpd_rx_irq, (void *) aconnector))
4752 				return -ENOMEM;
4753 		}
4754 	}
4755 	return 0;
4756 }
4757 
4758 /* Register IRQ sources and initialize IRQ callbacks */
4759 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
4760 {
4761 	struct dc *dc = adev->dm.dc;
4762 	struct common_irq_params *c_irq_params;
4763 	struct dc_interrupt_params int_params = {0};
4764 	int r;
4765 	int i;
4766 	unsigned int src_id;
4767 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4768 	/* Use different interrupts for VBLANK on DCE 6 vs. newer. */
4769 	const unsigned int vblank_d1 =
4770 		adev->dm.dc->ctx->dce_version >= DCE_VERSION_8_0
4771 		? VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0 : 1;
4772 
4773 	if (adev->family >= AMDGPU_FAMILY_AI)
4774 		client_id = SOC15_IH_CLIENTID_DCE;
4775 
4776 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4777 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4778 
4779 	/*
4780 	 * Actions of amdgpu_irq_add_id():
4781 	 * 1. Register a set() function with base driver.
4782 	 *    Base driver will call set() function to enable/disable an
4783 	 *    interrupt in DC hardware.
4784 	 * 2. Register amdgpu_dm_irq_handler().
4785 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4786 	 *    coming from DC hardware.
4787 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4788 	 *    for acknowledging and handling.
4789 	 */
4790 
4791 	/* Use VBLANK interrupt */
4792 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
4793 		src_id = vblank_d1 + i;
4794 		r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->crtc_irq);
4795 		if (r) {
4796 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4797 			return r;
4798 		}
4799 
4800 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4801 		int_params.irq_source =
4802 			dc_interrupt_to_irq_source(dc, src_id, 0);
4803 
4804 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4805 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4806 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4807 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4808 			return -EINVAL;
4809 		}
4810 
4811 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4812 
4813 		c_irq_params->adev = adev;
4814 		c_irq_params->irq_src = int_params.irq_source;
4815 
4816 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4817 			dm_crtc_high_irq, c_irq_params))
4818 			return -ENOMEM;
4819 	}
4820 
4821 	if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
4822 		/* Use VUPDATE interrupt */
4823 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
4824 			src_id = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT + i * 2;
4825 			r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->vupdate_irq);
4826 			if (r) {
4827 				drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4828 				return r;
4829 			}
4830 
4831 			int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4832 			int_params.irq_source =
4833 				dc_interrupt_to_irq_source(dc, src_id, 0);
4834 
4835 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4836 				int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4837 				int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4838 				drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4839 				return -EINVAL;
4840 			}
4841 
4842 			c_irq_params = &adev->dm.vupdate_params[
4843 				int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4844 			c_irq_params->adev = adev;
4845 			c_irq_params->irq_src = int_params.irq_source;
4846 
4847 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4848 				dm_vupdate_high_irq, c_irq_params))
4849 				return -ENOMEM;
4850 		}
4851 	}
4852 
4853 	/* Use GRPH_PFLIP interrupt */
4854 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4855 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4856 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4857 		if (r) {
4858 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4859 			return r;
4860 		}
4861 
4862 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4863 		int_params.irq_source =
4864 			dc_interrupt_to_irq_source(dc, i, 0);
4865 
4866 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4867 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4868 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4869 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4870 			return -EINVAL;
4871 		}
4872 
4873 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4874 
4875 		c_irq_params->adev = adev;
4876 		c_irq_params->irq_src = int_params.irq_source;
4877 
4878 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4879 			dm_pflip_high_irq, c_irq_params))
4880 			return -ENOMEM;
4881 	}
4882 
4883 	/* HPD */
4884 	r = amdgpu_irq_add_id(adev, client_id,
4885 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4886 	if (r) {
4887 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4888 		return r;
4889 	}
4890 
4891 	r = register_hpd_handlers(adev);
4892 
4893 	return r;
4894 }
4895 
4896 /* Register IRQ sources and initialize IRQ callbacks */
4897 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
4898 {
4899 	struct dc *dc = adev->dm.dc;
4900 	struct common_irq_params *c_irq_params;
4901 	struct dc_interrupt_params int_params = {0};
4902 	int r;
4903 	int i;
4904 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4905 	static const unsigned int vrtl_int_srcid[] = {
4906 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
4907 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
4908 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
4909 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
4910 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
4911 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
4912 	};
4913 #endif
4914 
4915 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4916 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4917 
4918 	/*
4919 	 * Actions of amdgpu_irq_add_id():
4920 	 * 1. Register a set() function with base driver.
4921 	 *    Base driver will call set() function to enable/disable an
4922 	 *    interrupt in DC hardware.
4923 	 * 2. Register amdgpu_dm_irq_handler().
4924 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4925 	 *    coming from DC hardware.
4926 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4927 	 *    for acknowledging and handling.
4928 	 */
4929 
4930 	/* Use otg vertical line interrupt */
4931 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4932 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
4933 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
4934 				vrtl_int_srcid[i], &adev->vline0_irq);
4935 
4936 		if (r) {
4937 			drm_err(adev_to_drm(adev), "Failed to add vline0 irq id!\n");
4938 			return r;
4939 		}
4940 
4941 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4942 		int_params.irq_source =
4943 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
4944 
4945 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4946 			int_params.irq_source < DC_IRQ_SOURCE_DC1_VLINE0 ||
4947 			int_params.irq_source > DC_IRQ_SOURCE_DC6_VLINE0) {
4948 			drm_err(adev_to_drm(adev), "Failed to register vline0 irq!\n");
4949 			return -EINVAL;
4950 		}
4951 
4952 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
4953 					- DC_IRQ_SOURCE_DC1_VLINE0];
4954 
4955 		c_irq_params->adev = adev;
4956 		c_irq_params->irq_src = int_params.irq_source;
4957 
4958 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4959 			dm_dcn_vertical_interrupt0_high_irq,
4960 			c_irq_params))
4961 			return -ENOMEM;
4962 	}
4963 #endif
4964 
4965 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
4966 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
4967 	 * to trigger at end of each vblank, regardless of state of the lock,
4968 	 * matching DCE behaviour.
4969 	 */
4970 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
4971 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
4972 	     i++) {
4973 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
4974 
4975 		if (r) {
4976 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4977 			return r;
4978 		}
4979 
4980 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4981 		int_params.irq_source =
4982 			dc_interrupt_to_irq_source(dc, i, 0);
4983 
4984 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4985 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4986 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4987 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4988 			return -EINVAL;
4989 		}
4990 
4991 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4992 
4993 		c_irq_params->adev = adev;
4994 		c_irq_params->irq_src = int_params.irq_source;
4995 
4996 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4997 			dm_vupdate_high_irq, c_irq_params))
4998 			return -ENOMEM;
4999 	}
5000 
5001 	/* HPD */
5002 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
5003 			&adev->hpd_irq);
5004 	if (r) {
5005 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
5006 		return r;
5007 	}
5008 
5009 	r = register_hpd_handlers(adev);
5010 
5011 	return r;
5012 }
5013 /* Register Outbox IRQ sources and initialize IRQ callbacks */
5014 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
5015 {
5016 	struct dc *dc = adev->dm.dc;
5017 	struct common_irq_params *c_irq_params;
5018 	struct dc_interrupt_params int_params = {0};
5019 	int r, i;
5020 
5021 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
5022 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
5023 
5024 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
5025 			&adev->dmub_outbox_irq);
5026 	if (r) {
5027 		drm_err(adev_to_drm(adev), "Failed to add outbox irq id!\n");
5028 		return r;
5029 	}
5030 
5031 	if (dc->ctx->dmub_srv) {
5032 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
5033 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
5034 		int_params.irq_source =
5035 		dc_interrupt_to_irq_source(dc, i, 0);
5036 
5037 		c_irq_params = &adev->dm.dmub_outbox_params[0];
5038 
5039 		c_irq_params->adev = adev;
5040 		c_irq_params->irq_src = int_params.irq_source;
5041 
5042 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
5043 			dm_dmub_outbox1_low_irq, c_irq_params))
5044 			return -ENOMEM;
5045 	}
5046 
5047 	return 0;
5048 }
5049 
5050 /*
5051  * Acquires the lock for the atomic state object and returns
5052  * the new atomic state.
5053  *
5054  * This should only be called during atomic check.
5055  */
5056 int dm_atomic_get_state(struct drm_atomic_commit *state,
5057 			struct dm_atomic_state **dm_state)
5058 {
5059 	struct drm_device *dev = state->dev;
5060 	struct amdgpu_device *adev = drm_to_adev(dev);
5061 	struct amdgpu_display_manager *dm = &adev->dm;
5062 	struct drm_private_state *priv_state;
5063 
5064 	if (*dm_state)
5065 		return 0;
5066 
5067 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
5068 	if (IS_ERR(priv_state))
5069 		return PTR_ERR(priv_state);
5070 
5071 	*dm_state = to_dm_atomic_state(priv_state);
5072 
5073 	return 0;
5074 }
5075 
5076 static struct dm_atomic_state *
5077 dm_atomic_get_new_state(struct drm_atomic_commit *state)
5078 {
5079 	struct drm_device *dev = state->dev;
5080 	struct amdgpu_device *adev = drm_to_adev(dev);
5081 	struct amdgpu_display_manager *dm = &adev->dm;
5082 	struct drm_private_obj *obj;
5083 	struct drm_private_state *new_obj_state;
5084 	int i;
5085 
5086 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
5087 		if (obj->funcs == dm->atomic_obj.funcs)
5088 			return to_dm_atomic_state(new_obj_state);
5089 	}
5090 
5091 	return NULL;
5092 }
5093 
5094 static struct drm_private_state *
5095 dm_atomic_duplicate_state(struct drm_private_obj *obj)
5096 {
5097 	struct dm_atomic_state *old_state, *new_state;
5098 
5099 	new_state = kzalloc_obj(*new_state);
5100 	if (!new_state)
5101 		return NULL;
5102 
5103 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
5104 
5105 	old_state = to_dm_atomic_state(obj->state);
5106 
5107 	if (old_state && old_state->context)
5108 		new_state->context = dc_state_create_copy(old_state->context);
5109 
5110 	if (!new_state->context) {
5111 		kfree(new_state);
5112 		return NULL;
5113 	}
5114 
5115 	return &new_state->base;
5116 }
5117 
5118 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
5119 				    struct drm_private_state *state)
5120 {
5121 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
5122 
5123 	if (dm_state && dm_state->context)
5124 		dc_state_release(dm_state->context);
5125 
5126 	kfree(dm_state);
5127 }
5128 
5129 static struct drm_private_state *
5130 dm_atomic_create_state(struct drm_private_obj *obj)
5131 {
5132 	struct amdgpu_device *adev = drm_to_adev(obj->dev);
5133 	struct dm_atomic_state *dm_state;
5134 	struct dc_state *context;
5135 
5136 	dm_state = kzalloc_obj(*dm_state);
5137 	if (!dm_state)
5138 		return ERR_PTR(-ENOMEM);
5139 
5140 	context = dc_state_create_current_copy(adev->dm.dc);
5141 	if (!context) {
5142 		kfree(dm_state);
5143 		return ERR_PTR(-ENOMEM);
5144 	}
5145 
5146 	__drm_atomic_helper_private_obj_create_state(obj, &dm_state->base);
5147 	dm_state->context = context;
5148 
5149 	return &dm_state->base;
5150 }
5151 
5152 static struct drm_private_state_funcs dm_atomic_state_funcs = {
5153 	.atomic_create_state = dm_atomic_create_state,
5154 	.atomic_duplicate_state = dm_atomic_duplicate_state,
5155 	.atomic_destroy_state = dm_atomic_destroy_state,
5156 };
5157 
5158 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
5159 {
5160 	int r;
5161 
5162 	adev->mode_info.mode_config_initialized = true;
5163 
5164 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
5165 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
5166 
5167 	adev_to_drm(adev)->mode_config.max_width = 16384;
5168 	adev_to_drm(adev)->mode_config.max_height = 16384;
5169 
5170 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
5171 	if (adev->asic_type == CHIP_HAWAII)
5172 		/* disable prefer shadow for now due to hibernation issues */
5173 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
5174 	else
5175 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
5176 	/* indicates support for immediate flip */
5177 	adev_to_drm(adev)->mode_config.async_page_flip = true;
5178 
5179 	drm_atomic_private_obj_init(adev_to_drm(adev),
5180 				    &adev->dm.atomic_obj,
5181 				    &dm_atomic_state_funcs);
5182 
5183 	r = amdgpu_display_modeset_create_props(adev);
5184 	if (r)
5185 		return r;
5186 
5187 #ifdef AMD_PRIVATE_COLOR
5188 	if (amdgpu_dm_create_color_properties(adev))
5189 		return -ENOMEM;
5190 #endif
5191 
5192 	r = amdgpu_dm_audio_init(adev);
5193 	if (r)
5194 		return r;
5195 
5196 	return 0;
5197 }
5198 
5199 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
5200 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
5201 #define AMDGPU_DM_MIN_SPREAD ((AMDGPU_DM_DEFAULT_MAX_BACKLIGHT - AMDGPU_DM_DEFAULT_MIN_BACKLIGHT) / 2)
5202 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
5203 
5204 void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
5205 				     int bl_idx)
5206 {
5207 	struct amdgpu_dm_backlight_caps *caps = &dm->backlight_caps[bl_idx];
5208 
5209 	if (caps->caps_valid)
5210 		return;
5211 
5212 #if defined(CONFIG_ACPI)
5213 	amdgpu_acpi_get_backlight_caps(caps);
5214 
5215 	/* validate the firmware value is sane */
5216 	if (caps->caps_valid) {
5217 		int spread = caps->max_input_signal - caps->min_input_signal;
5218 
5219 		if (caps->max_input_signal > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5220 		    caps->min_input_signal < 0 ||
5221 		    spread > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5222 		    spread < AMDGPU_DM_MIN_SPREAD) {
5223 			drm_dbg_kms(adev_to_drm(dm->adev), "DM: Invalid backlight caps: min=%d, max=%d\n",
5224 				      caps->min_input_signal, caps->max_input_signal);
5225 			caps->caps_valid = false;
5226 		}
5227 	}
5228 
5229 	if (!caps->caps_valid) {
5230 		caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5231 		caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5232 		caps->caps_valid = true;
5233 	}
5234 #else
5235 	if (caps->aux_support)
5236 		return;
5237 
5238 	caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5239 	caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5240 	caps->caps_valid = true;
5241 #endif
5242 }
5243 
5244 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
5245 				unsigned int *min, unsigned int *max)
5246 {
5247 	if (!caps)
5248 		return 0;
5249 
5250 	if (caps->aux_support) {
5251 		// Firmware limits are in nits, DC API wants millinits.
5252 		*max = 1000 * caps->aux_max_input_signal;
5253 		*min = 1000 * caps->aux_min_input_signal;
5254 	} else {
5255 		// Firmware limits are 8-bit, PWM control is 16-bit.
5256 		*max = 0x101 * caps->max_input_signal;
5257 		*min = 0x101 * caps->min_input_signal;
5258 	}
5259 	return 1;
5260 }
5261 
5262 /* Rescale from [min..max] to [0..AMDGPU_MAX_BL_LEVEL] */
5263 static inline u32 scale_input_to_fw(int min, int max, u64 input)
5264 {
5265 	return DIV_ROUND_CLOSEST_ULL(input * AMDGPU_MAX_BL_LEVEL, max - min);
5266 }
5267 
5268 /* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [min..max] */
5269 static inline u32 scale_fw_to_input(int min, int max, u64 input)
5270 {
5271 	return min + DIV_ROUND_CLOSEST_ULL(input * (max - min), AMDGPU_MAX_BL_LEVEL);
5272 }
5273 
5274 static void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps,
5275 				      unsigned int min, unsigned int max,
5276 				      uint32_t *user_brightness)
5277 {
5278 	u32 brightness = scale_input_to_fw(min, max, *user_brightness);
5279 	u8 lower_signal, upper_signal, upper_lum, lower_lum, lum;
5280 	int left, right;
5281 
5282 	if (amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)
5283 		return;
5284 
5285 	if (!caps->data_points)
5286 		return;
5287 
5288 	/*
5289 	 * Handle the case where brightness is below the first data point
5290 	 * Interpolate between (0,0) and (first_signal, first_lum)
5291 	 */
5292 	if (brightness < caps->luminance_data[0].input_signal) {
5293 		lum = DIV_ROUND_CLOSEST(caps->luminance_data[0].luminance * brightness,
5294 					caps->luminance_data[0].input_signal);
5295 		goto scale;
5296 	}
5297 
5298 	left = 0;
5299 	right = caps->data_points - 1;
5300 	while (left <= right) {
5301 		int mid = left + (right - left) / 2;
5302 		u8 signal = caps->luminance_data[mid].input_signal;
5303 
5304 		/* Exact match found */
5305 		if (signal == brightness) {
5306 			lum = caps->luminance_data[mid].luminance;
5307 			goto scale;
5308 		}
5309 
5310 		if (signal < brightness)
5311 			left = mid + 1;
5312 		else
5313 			right = mid - 1;
5314 	}
5315 
5316 	/* verify bound */
5317 	if (left >= caps->data_points)
5318 		left = caps->data_points - 1;
5319 
5320 	/* At this point, left > right */
5321 	lower_signal = caps->luminance_data[right].input_signal;
5322 	upper_signal = caps->luminance_data[left].input_signal;
5323 	lower_lum = caps->luminance_data[right].luminance;
5324 	upper_lum = caps->luminance_data[left].luminance;
5325 
5326 	/* interpolate */
5327 	if (right == left || !lower_lum)
5328 		lum = upper_lum;
5329 	else
5330 		lum = lower_lum + DIV_ROUND_CLOSEST((upper_lum - lower_lum) *
5331 						    (brightness - lower_signal),
5332 						    upper_signal - lower_signal);
5333 scale:
5334 	*user_brightness = scale_fw_to_input(min, max,
5335 					     DIV_ROUND_CLOSEST(lum * brightness, 101));
5336 }
5337 
5338 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
5339 					uint32_t brightness)
5340 {
5341 	unsigned int min, max;
5342 
5343 	if (!get_brightness_range(caps, &min, &max))
5344 		return brightness;
5345 
5346 	convert_custom_brightness(caps, min, max, &brightness);
5347 
5348 	// Rescale 0..max to min..max
5349 	return min + DIV_ROUND_CLOSEST_ULL((u64)(max - min) * brightness, max);
5350 }
5351 
5352 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
5353 				      uint32_t brightness)
5354 {
5355 	unsigned int min, max;
5356 
5357 	if (!get_brightness_range(caps, &min, &max))
5358 		return brightness;
5359 
5360 	if (brightness < min)
5361 		return 0;
5362 	// Rescale min..max to 0..max
5363 	return DIV_ROUND_CLOSEST_ULL((u64)max * (brightness - min),
5364 				 max - min);
5365 }
5366 
5367 static struct dc_stream_state *dm_find_stream_with_link(
5368 	struct amdgpu_display_manager *dm,
5369 	struct dc_link *link)
5370 {
5371 	struct dc_state *cur_dc_state = dm->dc->current_state;
5372 	struct dc_stream_state *stream = NULL;
5373 	int i;
5374 
5375 	for (i = 0; i < cur_dc_state->stream_count; i++) {
5376 		stream = cur_dc_state->streams[i];
5377 		if (stream->link == link)
5378 			return stream;
5379 	}
5380 
5381 	return NULL;
5382 }
5383 
5384 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
5385 					 int bl_idx,
5386 					 u32 user_brightness)
5387 {
5388 	struct amdgpu_dm_backlight_caps *caps;
5389 	struct dc_link *link;
5390 	u32 brightness = 0;
5391 	bool rc = false, reallow_idle = false;
5392 	struct drm_connector *connector;
5393 	struct dc_stream_state *stream;
5394 	unsigned int min, max;
5395 
5396 	list_for_each_entry(connector, &dm->ddev->mode_config.connector_list, head) {
5397 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5398 
5399 		if (aconnector->bl_idx != bl_idx)
5400 			continue;
5401 
5402 		/* if connector is off, save the brightness for next time it's on */
5403 		if (!aconnector->base.encoder) {
5404 			dm->brightness[bl_idx] = user_brightness;
5405 			dm->actual_brightness[bl_idx] = 0;
5406 			return;
5407 		}
5408 	}
5409 
5410 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5411 	caps = &dm->backlight_caps[bl_idx];
5412 
5413 	dm->brightness[bl_idx] = user_brightness;
5414 	/* update scratch register */
5415 	if (bl_idx == 0)
5416 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
5417 	brightness = convert_brightness_from_user(caps, dm->brightness[bl_idx]);
5418 	link = (struct dc_link *)dm->backlight_link[bl_idx];
5419 
5420 	/* Apply brightness quirk */
5421 	if (caps->brightness_mask)
5422 		brightness |= caps->brightness_mask;
5423 
5424 	if (trace_amdgpu_dm_brightness_enabled()) {
5425 		trace_amdgpu_dm_brightness(__builtin_return_address(0),
5426 					   user_brightness,
5427 					   brightness,
5428 					   caps->aux_support,
5429 					   power_supply_is_system_supplied() > 0);
5430 	}
5431 
5432 	stream = dm_find_stream_with_link(dm, link);
5433 	if (!stream)
5434 		return;
5435 
5436 	mutex_lock(&dm->dc_lock);
5437 	if (dm->dc->caps.ips_support && dm->dc->ctx->dmub_srv->idle_allowed) {
5438 		dc_allow_idle_optimizations(dm->dc, false);
5439 		reallow_idle = true;
5440 	}
5441 
5442 	if (caps->aux_support) {
5443 		rc = mod_power_set_backlight_nits(dm->power_module, stream, brightness,
5444 			AUX_BL_DEFAULT_TRANSITION_TIME_MS, false, true);
5445 	} else {
5446 		/* power module uses millipercent */
5447 		get_brightness_range(caps, &min, &max);
5448 		brightness = DIV_ROUND_CLOSEST(brightness * 100, (max - min)) * 1000;
5449 		rc = mod_power_set_backlight_percent(dm->power_module, stream,
5450 						     brightness, 0, false);
5451 	}
5452 
5453 	/*
5454 	 * Some kms clients create a ramped backlight transition effect
5455 	 * by rapidly changing the backlight. Yet we must wait on dmcub
5456 	 * fw to exit psr/replay before programming backlight. To
5457 	 * prevent lag, keep disable psr/replay and let the next atomic
5458 	 * flip clear the event.
5459 	 *
5460 	 * ToDo: use ISM to handle rapidly backlight change
5461 	 *
5462 	 * Rapidly backlight change is similar to rapidly cursor events,
5463 	 * which is now handled by ISM. ISM can delay the event until system
5464 	 * is really idle, so we may use ISM to handle backlight change as well.
5465 	 */
5466 	amdgpu_dm_psr_set_event(dm, stream, true,
5467 		psr_event_hw_programming, true);
5468 	amdgpu_dm_replay_set_event(dm, stream, true,
5469 		replay_event_hw_programming, true);
5470 
5471 	if (dm->dc->caps.ips_support && reallow_idle)
5472 		dc_allow_idle_optimizations(dm->dc, true);
5473 
5474 	mutex_unlock(&dm->dc_lock);
5475 
5476 	if (rc)
5477 		dm->actual_brightness[bl_idx] = user_brightness;
5478 }
5479 
5480 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
5481 {
5482 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5483 	int i;
5484 
5485 	for (i = 0; i < dm->num_of_edps; i++) {
5486 		if (bd == dm->backlight_dev[i])
5487 			break;
5488 	}
5489 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5490 		i = 0;
5491 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
5492 
5493 	return 0;
5494 }
5495 
5496 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
5497 					 int bl_idx)
5498 {
5499 	int ret;
5500 	struct amdgpu_dm_backlight_caps caps;
5501 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
5502 
5503 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5504 	caps = dm->backlight_caps[bl_idx];
5505 
5506 	if (caps.aux_support) {
5507 		u32 avg, peak;
5508 
5509 		if (!dc_link_get_backlight_level_nits(link, &avg, &peak))
5510 			return dm->brightness[bl_idx];
5511 		return convert_brightness_to_user(&caps, avg);
5512 	}
5513 
5514 	ret = dc_link_get_backlight_level(link);
5515 
5516 	if (ret == DC_ERROR_UNEXPECTED)
5517 		return dm->brightness[bl_idx];
5518 
5519 	return convert_brightness_to_user(&caps, ret);
5520 }
5521 
5522 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
5523 {
5524 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5525 	int i;
5526 
5527 	for (i = 0; i < dm->num_of_edps; i++) {
5528 		if (bd == dm->backlight_dev[i])
5529 			break;
5530 	}
5531 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5532 		i = 0;
5533 	return amdgpu_dm_backlight_get_level(dm, i);
5534 }
5535 
5536 static const struct backlight_ops amdgpu_dm_backlight_ops = {
5537 	.options = BL_CORE_SUSPENDRESUME,
5538 	.get_brightness = amdgpu_dm_backlight_get_brightness,
5539 	.update_status	= amdgpu_dm_backlight_update_status,
5540 };
5541 
5542 static void
5543 amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector *aconnector)
5544 {
5545 	struct drm_device *drm = aconnector->base.dev;
5546 	struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
5547 	struct backlight_properties props = { 0 };
5548 	struct amdgpu_dm_backlight_caps *caps;
5549 	char bl_name[16];
5550 	int min, max;
5551 	int real_brightness;
5552 	int init_brightness;
5553 
5554 	if (aconnector->bl_idx == -1)
5555 		return;
5556 
5557 	if (!acpi_video_backlight_use_native()) {
5558 		drm_info(drm, "Skipping amdgpu DM backlight registration\n");
5559 		/* Try registering an ACPI video backlight device instead. */
5560 		acpi_video_register_backlight();
5561 		return;
5562 	}
5563 
5564 	caps = &dm->backlight_caps[aconnector->bl_idx];
5565 	if (get_brightness_range(caps, &min, &max)) {
5566 		if (power_supply_is_system_supplied() > 0)
5567 			props.brightness = DIV_ROUND_CLOSEST(max * caps->ac_level, 100);
5568 		else
5569 			props.brightness = DIV_ROUND_CLOSEST(max * caps->dc_level, 100);
5570 		/* min is zero, so max needs to be adjusted */
5571 		props.max_brightness = max;
5572 		drm_dbg(drm, "Backlight caps: min: %d, max: %d, ac %d, dc %d\n", min, max,
5573 			caps->ac_level, caps->dc_level);
5574 	} else
5575 		props.brightness = props.max_brightness = MAX_BACKLIGHT_LEVEL;
5576 
5577 	init_brightness = props.brightness;
5578 
5579 	if (caps->data_points && !(amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)) {
5580 		drm_info(drm, "Using custom brightness curve\n");
5581 		props.scale = BACKLIGHT_SCALE_NON_LINEAR;
5582 	} else
5583 		props.scale = BACKLIGHT_SCALE_LINEAR;
5584 	props.type = BACKLIGHT_RAW;
5585 
5586 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
5587 		 drm->primary->index + aconnector->bl_idx);
5588 
5589 	dm->backlight_dev[aconnector->bl_idx] =
5590 		backlight_device_register(bl_name, aconnector->base.kdev, dm,
5591 					  &amdgpu_dm_backlight_ops, &props);
5592 	dm->brightness[aconnector->bl_idx] = props.brightness;
5593 
5594 	if (IS_ERR(dm->backlight_dev[aconnector->bl_idx])) {
5595 		drm_err(drm, "DM: Backlight registration failed!\n");
5596 		dm->backlight_dev[aconnector->bl_idx] = NULL;
5597 	} else {
5598 		/*
5599 		 * dm->brightness[x] can be inconsistent just after startup until
5600 		 * ops.get_brightness is called.
5601 		 */
5602 		real_brightness =
5603 			amdgpu_dm_backlight_ops.get_brightness(dm->backlight_dev[aconnector->bl_idx]);
5604 
5605 		if (real_brightness != init_brightness) {
5606 			dm->actual_brightness[aconnector->bl_idx] = real_brightness;
5607 			dm->brightness[aconnector->bl_idx] = real_brightness;
5608 		}
5609 		drm_dbg_driver(drm, "DM: Registered Backlight device: %s\n", bl_name);
5610 	}
5611 }
5612 
5613 static int initialize_plane(struct amdgpu_display_manager *dm,
5614 			    struct amdgpu_mode_info *mode_info, int plane_id,
5615 			    enum drm_plane_type plane_type,
5616 			    const struct dc_plane_cap *plane_cap)
5617 {
5618 	struct drm_plane *plane;
5619 	unsigned long possible_crtcs;
5620 	int ret = 0;
5621 
5622 	plane = kzalloc_obj(struct drm_plane);
5623 	if (!plane) {
5624 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
5625 		return -ENOMEM;
5626 	}
5627 	plane->type = plane_type;
5628 
5629 	/*
5630 	 * HACK: IGT tests expect that the primary plane for a CRTC
5631 	 * can only have one possible CRTC. Only expose support for
5632 	 * any CRTC if they're not going to be used as a primary plane
5633 	 * for a CRTC - like overlay or underlay planes.
5634 	 */
5635 	possible_crtcs = 1 << plane_id;
5636 	if (plane_id >= dm->dc->caps.max_streams)
5637 		possible_crtcs = 0xff;
5638 
5639 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
5640 
5641 	if (ret) {
5642 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
5643 		kfree(plane);
5644 		return ret;
5645 	}
5646 
5647 	if (mode_info)
5648 		mode_info->planes[plane_id] = plane;
5649 
5650 	return ret;
5651 }
5652 
5653 
5654 static void setup_backlight_device(struct amdgpu_display_manager *dm,
5655 				   struct amdgpu_dm_connector *aconnector)
5656 {
5657 	struct amdgpu_dm_backlight_caps *caps;
5658 	struct dc_link *link = aconnector->dc_link;
5659 	int bl_idx = dm->num_of_edps;
5660 
5661 	if (!(link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) ||
5662 	    link->type == dc_connection_none)
5663 		return;
5664 
5665 	if (dm->num_of_edps >= AMDGPU_DM_MAX_NUM_EDP) {
5666 		drm_warn(adev_to_drm(dm->adev), "Too much eDP connections, skipping backlight setup for additional eDPs\n");
5667 		return;
5668 	}
5669 
5670 	aconnector->bl_idx = bl_idx;
5671 
5672 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5673 	dm->backlight_link[bl_idx] = link;
5674 	dm->num_of_edps++;
5675 
5676 	update_connector_ext_caps(aconnector);
5677 	caps = &dm->backlight_caps[aconnector->bl_idx];
5678 
5679 	/* Only offer ABM property when non-OLED and user didn't turn off by module parameter */
5680 	if (caps->ext_caps && !caps->ext_caps->bits.oled && amdgpu_dm_abm_level < 0)
5681 		drm_object_attach_property(&aconnector->base.base,
5682 					   dm->adev->mode_info.abm_level_property,
5683 					   ABM_SYSFS_CONTROL);
5684 }
5685 
5686 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
5687 
5688 
5689 
5690 /*
5691  * In this architecture, the association
5692  * connector -> encoder -> crtc
5693  * id not really requried. The crtc and connector will hold the
5694  * display_index as an abstraction to use with DAL component
5695  *
5696  * Returns 0 on success
5697  */
5698 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
5699 {
5700 	struct amdgpu_display_manager *dm = &adev->dm;
5701 	s32 i;
5702 	struct amdgpu_dm_connector *aconnector = NULL;
5703 	struct amdgpu_encoder *aencoder = NULL;
5704 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5705 	u32 link_cnt;
5706 	s32 primary_planes;
5707 	enum dc_connection_type new_connection_type = dc_connection_none;
5708 	const struct dc_plane_cap *plane;
5709 	bool psr_feature_enabled = false;
5710 	bool replay_feature_enabled = false;
5711 	int max_overlay = dm->dc->caps.max_slave_planes;
5712 
5713 	dm->display_indexes_num = dm->dc->caps.max_streams;
5714 	/* Update the actual used number of crtc */
5715 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
5716 
5717 	amdgpu_dm_set_irq_funcs(adev);
5718 
5719 	link_cnt = dm->dc->caps.max_links;
5720 	if (amdgpu_dm_mode_config_init(dm->adev)) {
5721 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
5722 		return -EINVAL;
5723 	}
5724 
5725 	/* There is one primary plane per CRTC */
5726 	primary_planes = dm->dc->caps.max_streams;
5727 	if (primary_planes > AMDGPU_MAX_PLANES) {
5728 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
5729 		return -EINVAL;
5730 	}
5731 
5732 	/*
5733 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
5734 	 * Order is reversed to match iteration order in atomic check.
5735 	 */
5736 	for (i = (primary_planes - 1); i >= 0; i--) {
5737 		plane = &dm->dc->caps.planes[i];
5738 
5739 		if (initialize_plane(dm, mode_info, i,
5740 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
5741 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
5742 			goto fail;
5743 		}
5744 	}
5745 
5746 	/*
5747 	 * Initialize overlay planes, index starting after primary planes.
5748 	 * These planes have a higher DRM index than the primary planes since
5749 	 * they should be considered as having a higher z-order.
5750 	 * Order is reversed to match iteration order in atomic check.
5751 	 *
5752 	 * Only support DCN for now, and only expose one so we don't encourage
5753 	 * userspace to use up all the pipes.
5754 	 */
5755 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
5756 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
5757 
5758 		/* Do not create overlay if MPO disabled */
5759 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
5760 			break;
5761 
5762 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
5763 			continue;
5764 
5765 		if (!plane->pixel_format_support.argb8888)
5766 			continue;
5767 
5768 		if (max_overlay-- == 0)
5769 			break;
5770 
5771 		if (initialize_plane(dm, NULL, primary_planes + i,
5772 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
5773 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
5774 			goto fail;
5775 		}
5776 	}
5777 
5778 	for (i = 0; i < dm->dc->caps.max_streams; i++)
5779 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
5780 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
5781 			goto fail;
5782 		}
5783 
5784 	/* Use Outbox interrupt */
5785 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5786 	case IP_VERSION(3, 0, 0):
5787 	case IP_VERSION(3, 1, 2):
5788 	case IP_VERSION(3, 1, 3):
5789 	case IP_VERSION(3, 1, 4):
5790 	case IP_VERSION(3, 1, 5):
5791 	case IP_VERSION(3, 1, 6):
5792 	case IP_VERSION(3, 2, 0):
5793 	case IP_VERSION(3, 2, 1):
5794 	case IP_VERSION(2, 1, 0):
5795 	case IP_VERSION(3, 5, 0):
5796 	case IP_VERSION(3, 5, 1):
5797 	case IP_VERSION(3, 6, 0):
5798 	case IP_VERSION(4, 0, 1):
5799 	case IP_VERSION(4, 2, 0):
5800 	case IP_VERSION(4, 2, 1):
5801 		if (register_outbox_irq_handlers(dm->adev)) {
5802 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5803 			goto fail;
5804 		}
5805 		break;
5806 	default:
5807 		drm_dbg_kms(adev_to_drm(adev), "Unsupported DCN IP version for outbox: 0x%X\n",
5808 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
5809 	}
5810 
5811 	/* Determine whether to enable PSR support by default. */
5812 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
5813 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5814 		case IP_VERSION(3, 1, 2):
5815 		case IP_VERSION(3, 1, 3):
5816 		case IP_VERSION(3, 1, 4):
5817 		case IP_VERSION(3, 1, 5):
5818 		case IP_VERSION(3, 1, 6):
5819 		case IP_VERSION(3, 2, 0):
5820 		case IP_VERSION(3, 2, 1):
5821 		case IP_VERSION(3, 5, 0):
5822 		case IP_VERSION(3, 5, 1):
5823 		case IP_VERSION(3, 6, 0):
5824 		case IP_VERSION(4, 0, 1):
5825 		case IP_VERSION(4, 2, 0):
5826 		case IP_VERSION(4, 2, 1):
5827 			psr_feature_enabled = true;
5828 			break;
5829 		default:
5830 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
5831 			break;
5832 		}
5833 	}
5834 
5835 	/* Determine whether to enable Replay support by default. */
5836 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
5837 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5838 		case IP_VERSION(3, 1, 4):
5839 		case IP_VERSION(3, 2, 0):
5840 		case IP_VERSION(3, 2, 1):
5841 		case IP_VERSION(3, 5, 0):
5842 		case IP_VERSION(3, 5, 1):
5843 		case IP_VERSION(3, 6, 0):
5844 		case IP_VERSION(4, 2, 0):
5845 		case IP_VERSION(4, 2, 1):
5846 			replay_feature_enabled = true;
5847 			break;
5848 
5849 		default:
5850 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
5851 			break;
5852 		}
5853 	}
5854 
5855 	if (link_cnt > MAX_LINKS) {
5856 		drm_err(adev_to_drm(adev),
5857 			"KMS: Cannot support more than %d display indexes\n",
5858 				MAX_LINKS);
5859 		goto fail;
5860 	}
5861 
5862 	/* loops over all connectors on the board */
5863 	for (i = 0; i < link_cnt; i++) {
5864 		struct dc_link *link = NULL;
5865 
5866 		link = dc_get_link_at_index(dm->dc, i);
5867 
5868 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
5869 			struct amdgpu_dm_wb_connector *wbcon = kzalloc_obj(*wbcon);
5870 
5871 			if (!wbcon) {
5872 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
5873 				continue;
5874 			}
5875 
5876 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
5877 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
5878 				kfree(wbcon);
5879 				continue;
5880 			}
5881 
5882 			link->psr_settings.psr_feature_enabled = false;
5883 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
5884 
5885 			continue;
5886 		}
5887 
5888 		aconnector = kzalloc_obj(*aconnector);
5889 		if (!aconnector)
5890 			goto fail;
5891 
5892 		aencoder = kzalloc_obj(*aencoder);
5893 		if (!aencoder)
5894 			goto fail;
5895 
5896 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
5897 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
5898 			goto fail;
5899 		}
5900 
5901 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
5902 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
5903 			goto fail;
5904 		}
5905 
5906 		if (dm->hpd_rx_offload_wq)
5907 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
5908 				aconnector;
5909 
5910 		if (!dc_link_detect_connection_type(link, &new_connection_type))
5911 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
5912 
5913 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
5914 			emulated_link_detect(link);
5915 			amdgpu_dm_update_connector_after_detect(aconnector);
5916 		} else {
5917 			bool ret = false;
5918 
5919 			mutex_lock(&dm->dc_lock);
5920 			dc_exit_ips_for_hw_access(dm->dc);
5921 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
5922 			mutex_unlock(&dm->dc_lock);
5923 
5924 			if (ret) {
5925 				amdgpu_dm_update_connector_after_detect(aconnector);
5926 				setup_backlight_device(dm, aconnector);
5927 
5928 				/* Disable PSR if Replay can be enabled */
5929 				if (replay_feature_enabled)
5930 					if (amdgpu_dm_set_replay_caps(link, aconnector))
5931 						psr_feature_enabled = false;
5932 
5933 				if (psr_feature_enabled) {
5934 					amdgpu_dm_set_psr_caps(link, aconnector);
5935 					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",
5936 						 aconnector->base.name,
5937 						 link->psr_settings.psr_feature_enabled,
5938 						 link->psr_settings.psr_version,
5939 						 link->dpcd_caps.psr_info.psr_version,
5940 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
5941 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
5942 				}
5943 			}
5944 		}
5945 		amdgpu_set_panel_orientation(&aconnector->base);
5946 	}
5947 
5948 	/* Debug dump: list all DC links and their associated sinks after detection
5949 	 * is complete for all connectors. This provides a comprehensive view of the
5950 	 * final state without repeating the dump for each connector.
5951 	 */
5952 	amdgpu_dm_dump_links_and_sinks(adev);
5953 
5954 	/* Software is initialized. Now we can register interrupt handlers. */
5955 	switch (adev->asic_type) {
5956 #if defined(CONFIG_DRM_AMD_DC_SI)
5957 	case CHIP_TAHITI:
5958 	case CHIP_PITCAIRN:
5959 	case CHIP_VERDE:
5960 	case CHIP_OLAND:
5961 #endif
5962 	case CHIP_BONAIRE:
5963 	case CHIP_HAWAII:
5964 	case CHIP_KAVERI:
5965 	case CHIP_KABINI:
5966 	case CHIP_MULLINS:
5967 	case CHIP_TONGA:
5968 	case CHIP_FIJI:
5969 	case CHIP_CARRIZO:
5970 	case CHIP_STONEY:
5971 	case CHIP_POLARIS11:
5972 	case CHIP_POLARIS10:
5973 	case CHIP_POLARIS12:
5974 	case CHIP_VEGAM:
5975 	case CHIP_VEGA10:
5976 	case CHIP_VEGA12:
5977 	case CHIP_VEGA20:
5978 		if (dce110_register_irq_handlers(dm->adev)) {
5979 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5980 			goto fail;
5981 		}
5982 		break;
5983 	default:
5984 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5985 		case IP_VERSION(1, 0, 0):
5986 		case IP_VERSION(1, 0, 1):
5987 		case IP_VERSION(2, 0, 2):
5988 		case IP_VERSION(2, 0, 3):
5989 		case IP_VERSION(2, 0, 0):
5990 		case IP_VERSION(2, 1, 0):
5991 		case IP_VERSION(3, 0, 0):
5992 		case IP_VERSION(3, 0, 2):
5993 		case IP_VERSION(3, 0, 3):
5994 		case IP_VERSION(3, 0, 1):
5995 		case IP_VERSION(3, 1, 2):
5996 		case IP_VERSION(3, 1, 3):
5997 		case IP_VERSION(3, 1, 4):
5998 		case IP_VERSION(3, 1, 5):
5999 		case IP_VERSION(3, 1, 6):
6000 		case IP_VERSION(3, 2, 0):
6001 		case IP_VERSION(3, 2, 1):
6002 		case IP_VERSION(3, 5, 0):
6003 		case IP_VERSION(3, 5, 1):
6004 		case IP_VERSION(3, 6, 0):
6005 		case IP_VERSION(4, 0, 1):
6006 		case IP_VERSION(4, 2, 0):
6007 		case IP_VERSION(4, 2, 1):
6008 			if (dcn10_register_irq_handlers(dm->adev)) {
6009 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
6010 				goto fail;
6011 			}
6012 			break;
6013 		default:
6014 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
6015 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6016 			goto fail;
6017 		}
6018 		break;
6019 	}
6020 
6021 	return 0;
6022 fail:
6023 	kfree(aencoder);
6024 	kfree(aconnector);
6025 
6026 	return -EINVAL;
6027 }
6028 
6029 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
6030 {
6031 	if (dm->atomic_obj.state)
6032 		drm_atomic_private_obj_fini(&dm->atomic_obj);
6033 }
6034 
6035 /******************************************************************************
6036  * amdgpu_display_funcs functions
6037  *****************************************************************************/
6038 
6039 /*
6040  * dm_bandwidth_update - program display watermarks
6041  *
6042  * @adev: amdgpu_device pointer
6043  *
6044  * Calculate and program the display watermarks and line buffer allocation.
6045  */
6046 static void dm_bandwidth_update(struct amdgpu_device *adev)
6047 {
6048 	/* TODO: implement later */
6049 }
6050 
6051 static const struct amdgpu_display_funcs dm_display_funcs = {
6052 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
6053 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
6054 	.backlight_set_level = NULL, /* never called for DC */
6055 	.backlight_get_level = NULL, /* never called for DC */
6056 	.hpd_sense = NULL,/* called unconditionally */
6057 	.hpd_set_polarity = NULL, /* called unconditionally */
6058 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
6059 	.page_flip_get_scanoutpos =
6060 		dm_crtc_get_scanoutpos,/* called unconditionally */
6061 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
6062 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
6063 };
6064 
6065 #if defined(CONFIG_DEBUG_KERNEL_DC)
6066 
6067 static ssize_t s3_debug_store(struct device *device,
6068 			      struct device_attribute *attr,
6069 			      const char *buf,
6070 			      size_t count)
6071 {
6072 	int ret;
6073 	int s3_state;
6074 	struct drm_device *drm_dev = dev_get_drvdata(device);
6075 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
6076 	struct amdgpu_ip_block *ip_block;
6077 
6078 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
6079 	if (!ip_block)
6080 		return -EINVAL;
6081 
6082 	ret = kstrtoint(buf, 0, &s3_state);
6083 
6084 	if (ret == 0) {
6085 		if (s3_state) {
6086 			dm_resume(ip_block);
6087 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
6088 		} else
6089 			dm_suspend(ip_block);
6090 	}
6091 
6092 	return ret == 0 ? count : 0;
6093 }
6094 
6095 DEVICE_ATTR_WO(s3_debug);
6096 
6097 #endif
6098 
6099 static int dm_init_microcode(struct amdgpu_device *adev)
6100 {
6101 	char *fw_name_dmub;
6102 	int r;
6103 
6104 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6105 	case IP_VERSION(2, 1, 0):
6106 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
6107 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
6108 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
6109 		break;
6110 	case IP_VERSION(3, 0, 0):
6111 		if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(10, 3, 0))
6112 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
6113 		else
6114 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
6115 		break;
6116 	case IP_VERSION(3, 0, 1):
6117 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
6118 		break;
6119 	case IP_VERSION(3, 0, 2):
6120 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
6121 		break;
6122 	case IP_VERSION(3, 0, 3):
6123 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
6124 		break;
6125 	case IP_VERSION(3, 1, 2):
6126 	case IP_VERSION(3, 1, 3):
6127 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
6128 		break;
6129 	case IP_VERSION(3, 1, 4):
6130 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
6131 		break;
6132 	case IP_VERSION(3, 1, 5):
6133 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
6134 		break;
6135 	case IP_VERSION(3, 1, 6):
6136 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
6137 		break;
6138 	case IP_VERSION(3, 2, 0):
6139 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
6140 		break;
6141 	case IP_VERSION(3, 2, 1):
6142 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
6143 		break;
6144 	case IP_VERSION(3, 5, 0):
6145 		fw_name_dmub = FIRMWARE_DCN_35_DMUB;
6146 		break;
6147 	case IP_VERSION(3, 5, 1):
6148 		fw_name_dmub = FIRMWARE_DCN_351_DMUB;
6149 		break;
6150 	case IP_VERSION(3, 6, 0):
6151 		fw_name_dmub = FIRMWARE_DCN_36_DMUB;
6152 		break;
6153 	case IP_VERSION(4, 0, 1):
6154 		fw_name_dmub = FIRMWARE_DCN_401_DMUB;
6155 		break;
6156 	case IP_VERSION(4, 2, 0):
6157 		fw_name_dmub = FIRMWARE_DCN_42_DMUB;
6158 		break;
6159 	case IP_VERSION(4, 2, 1):
6160 		fw_name_dmub = FIRMWARE_DCN_42B_DMUB;
6161 		break;
6162 	default:
6163 		/* ASIC doesn't support DMUB. */
6164 		return 0;
6165 	}
6166 	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, AMDGPU_UCODE_REQUIRED,
6167 				 "%s", fw_name_dmub);
6168 	return r;
6169 }
6170 
6171 static int dm_early_init(struct amdgpu_ip_block *ip_block)
6172 {
6173 	struct amdgpu_device *adev = ip_block->adev;
6174 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
6175 	struct atom_context *ctx = mode_info->atom_context;
6176 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
6177 	u16 data_offset;
6178 
6179 	/* if there is no object header, skip DM */
6180 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
6181 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
6182 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
6183 		return -ENOENT;
6184 	}
6185 
6186 	switch (adev->asic_type) {
6187 #if defined(CONFIG_DRM_AMD_DC_SI)
6188 	case CHIP_TAHITI:
6189 	case CHIP_PITCAIRN:
6190 	case CHIP_VERDE:
6191 		adev->mode_info.num_crtc = 6;
6192 		adev->mode_info.num_hpd = 6;
6193 		adev->mode_info.num_dig = 6;
6194 		break;
6195 	case CHIP_OLAND:
6196 		adev->mode_info.num_crtc = 2;
6197 		adev->mode_info.num_hpd = 2;
6198 		adev->mode_info.num_dig = 2;
6199 		break;
6200 #endif
6201 	case CHIP_BONAIRE:
6202 	case CHIP_HAWAII:
6203 		adev->mode_info.num_crtc = 6;
6204 		adev->mode_info.num_hpd = 6;
6205 		adev->mode_info.num_dig = 6;
6206 		break;
6207 	case CHIP_KAVERI:
6208 		adev->mode_info.num_crtc = 4;
6209 		adev->mode_info.num_hpd = 6;
6210 		adev->mode_info.num_dig = 7;
6211 		break;
6212 	case CHIP_KABINI:
6213 	case CHIP_MULLINS:
6214 		adev->mode_info.num_crtc = 2;
6215 		adev->mode_info.num_hpd = 6;
6216 		adev->mode_info.num_dig = 6;
6217 		break;
6218 	case CHIP_FIJI:
6219 	case CHIP_TONGA:
6220 		adev->mode_info.num_crtc = 6;
6221 		adev->mode_info.num_hpd = 6;
6222 		adev->mode_info.num_dig = 7;
6223 		break;
6224 	case CHIP_CARRIZO:
6225 		adev->mode_info.num_crtc = 3;
6226 		adev->mode_info.num_hpd = 6;
6227 		adev->mode_info.num_dig = 9;
6228 		break;
6229 	case CHIP_STONEY:
6230 		adev->mode_info.num_crtc = 2;
6231 		adev->mode_info.num_hpd = 6;
6232 		adev->mode_info.num_dig = 9;
6233 		break;
6234 	case CHIP_POLARIS11:
6235 	case CHIP_POLARIS12:
6236 		adev->mode_info.num_crtc = 5;
6237 		adev->mode_info.num_hpd = 5;
6238 		adev->mode_info.num_dig = 5;
6239 		break;
6240 	case CHIP_POLARIS10:
6241 	case CHIP_VEGAM:
6242 		adev->mode_info.num_crtc = 6;
6243 		adev->mode_info.num_hpd = 6;
6244 		adev->mode_info.num_dig = 6;
6245 		break;
6246 	case CHIP_VEGA10:
6247 	case CHIP_VEGA12:
6248 	case CHIP_VEGA20:
6249 		adev->mode_info.num_crtc = 6;
6250 		adev->mode_info.num_hpd = 6;
6251 		adev->mode_info.num_dig = 6;
6252 		break;
6253 	default:
6254 
6255 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6256 		case IP_VERSION(2, 0, 2):
6257 		case IP_VERSION(3, 0, 0):
6258 			adev->mode_info.num_crtc = 6;
6259 			adev->mode_info.num_hpd = 6;
6260 			adev->mode_info.num_dig = 6;
6261 			break;
6262 		case IP_VERSION(2, 0, 0):
6263 		case IP_VERSION(3, 0, 2):
6264 			adev->mode_info.num_crtc = 5;
6265 			adev->mode_info.num_hpd = 5;
6266 			adev->mode_info.num_dig = 5;
6267 			break;
6268 		case IP_VERSION(2, 0, 3):
6269 		case IP_VERSION(3, 0, 3):
6270 			adev->mode_info.num_crtc = 2;
6271 			adev->mode_info.num_hpd = 2;
6272 			adev->mode_info.num_dig = 2;
6273 			break;
6274 		case IP_VERSION(1, 0, 0):
6275 		case IP_VERSION(1, 0, 1):
6276 		case IP_VERSION(3, 0, 1):
6277 		case IP_VERSION(2, 1, 0):
6278 		case IP_VERSION(3, 1, 2):
6279 		case IP_VERSION(3, 1, 3):
6280 		case IP_VERSION(3, 1, 4):
6281 		case IP_VERSION(3, 1, 5):
6282 		case IP_VERSION(3, 1, 6):
6283 		case IP_VERSION(3, 2, 0):
6284 		case IP_VERSION(3, 2, 1):
6285 		case IP_VERSION(3, 5, 0):
6286 		case IP_VERSION(3, 5, 1):
6287 		case IP_VERSION(3, 6, 0):
6288 		case IP_VERSION(4, 0, 1):
6289 		case IP_VERSION(4, 2, 0):
6290 		case IP_VERSION(4, 2, 1):
6291 			adev->mode_info.num_crtc = 4;
6292 			adev->mode_info.num_hpd = 4;
6293 			adev->mode_info.num_dig = 4;
6294 			break;
6295 		default:
6296 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
6297 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6298 			return -EINVAL;
6299 		}
6300 		break;
6301 	}
6302 
6303 	if (adev->mode_info.funcs == NULL)
6304 		adev->mode_info.funcs = &dm_display_funcs;
6305 
6306 	/*
6307 	 * Note: Do NOT change adev->reg.audio_endpt.rreg and
6308 	 * adev->reg.audio_endpt.wreg because they are initialised in
6309 	 * amdgpu_device_init()
6310 	 */
6311 #if defined(CONFIG_DEBUG_KERNEL_DC)
6312 	device_create_file(
6313 		adev_to_drm(adev)->dev,
6314 		&dev_attr_s3_debug);
6315 #endif
6316 	adev->dc_enabled = true;
6317 
6318 	return dm_init_microcode(adev);
6319 }
6320 
6321 static bool modereset_required(struct drm_crtc_state *crtc_state)
6322 {
6323 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
6324 }
6325 
6326 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
6327 {
6328 	drm_encoder_cleanup(encoder);
6329 	kfree(encoder);
6330 }
6331 
6332 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
6333 	.destroy = amdgpu_dm_encoder_destroy,
6334 };
6335 
6336 static int
6337 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
6338 			    const enum surface_pixel_format format,
6339 			    enum dc_color_space *color_space)
6340 {
6341 	bool full_range;
6342 
6343 	*color_space = COLOR_SPACE_SRGB;
6344 
6345 	/* Ignore properties when DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE is set */
6346 	if (plane_state->state && plane_state->state->plane_color_pipeline)
6347 		return 0;
6348 
6349 	/* DRM color properties only affect non-RGB formats. */
6350 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
6351 		return 0;
6352 
6353 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
6354 
6355 	switch (plane_state->color_encoding) {
6356 	case DRM_COLOR_YCBCR_BT601:
6357 		if (full_range)
6358 			*color_space = COLOR_SPACE_YCBCR601;
6359 		else
6360 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
6361 		break;
6362 
6363 	case DRM_COLOR_YCBCR_BT709:
6364 		if (full_range)
6365 			*color_space = COLOR_SPACE_YCBCR709;
6366 		else
6367 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
6368 		break;
6369 
6370 	case DRM_COLOR_YCBCR_BT2020:
6371 		if (full_range)
6372 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
6373 		else
6374 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6375 		break;
6376 
6377 	default:
6378 		return -EINVAL;
6379 	}
6380 
6381 	return 0;
6382 }
6383 
6384 static int
6385 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
6386 			    const struct drm_plane_state *plane_state,
6387 			    const u64 tiling_flags,
6388 			    struct dc_plane_info *plane_info,
6389 			    struct dc_plane_address *address,
6390 			    bool tmz_surface)
6391 {
6392 	const struct drm_framebuffer *fb = plane_state->fb;
6393 	const struct amdgpu_framebuffer *afb =
6394 		to_amdgpu_framebuffer(plane_state->fb);
6395 	int ret;
6396 
6397 	memset(plane_info, 0, sizeof(*plane_info));
6398 
6399 	switch (fb->format->format) {
6400 	case DRM_FORMAT_C8:
6401 		plane_info->format =
6402 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
6403 		break;
6404 	case DRM_FORMAT_RGB565:
6405 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
6406 		break;
6407 	case DRM_FORMAT_XRGB8888:
6408 	case DRM_FORMAT_ARGB8888:
6409 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6410 		break;
6411 	case DRM_FORMAT_XRGB2101010:
6412 	case DRM_FORMAT_ARGB2101010:
6413 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
6414 		break;
6415 	case DRM_FORMAT_XBGR2101010:
6416 	case DRM_FORMAT_ABGR2101010:
6417 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
6418 		break;
6419 	case DRM_FORMAT_XBGR8888:
6420 	case DRM_FORMAT_ABGR8888:
6421 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
6422 		break;
6423 	case DRM_FORMAT_NV21:
6424 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
6425 		break;
6426 	case DRM_FORMAT_NV12:
6427 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
6428 		break;
6429 	case DRM_FORMAT_P010:
6430 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
6431 		break;
6432 	case DRM_FORMAT_XRGB16161616F:
6433 	case DRM_FORMAT_ARGB16161616F:
6434 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
6435 		break;
6436 	case DRM_FORMAT_XBGR16161616F:
6437 	case DRM_FORMAT_ABGR16161616F:
6438 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
6439 		break;
6440 	case DRM_FORMAT_XRGB16161616:
6441 	case DRM_FORMAT_ARGB16161616:
6442 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
6443 		break;
6444 	case DRM_FORMAT_XBGR16161616:
6445 	case DRM_FORMAT_ABGR16161616:
6446 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
6447 		break;
6448 	default:
6449 		drm_err(adev_to_drm(adev),
6450 			"Unsupported screen format %p4cc\n",
6451 			&fb->format->format);
6452 		return -EINVAL;
6453 	}
6454 
6455 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
6456 	case DRM_MODE_ROTATE_0:
6457 		plane_info->rotation = ROTATION_ANGLE_0;
6458 		break;
6459 	case DRM_MODE_ROTATE_90:
6460 		plane_info->rotation = ROTATION_ANGLE_90;
6461 		break;
6462 	case DRM_MODE_ROTATE_180:
6463 		plane_info->rotation = ROTATION_ANGLE_180;
6464 		break;
6465 	case DRM_MODE_ROTATE_270:
6466 		plane_info->rotation = ROTATION_ANGLE_270;
6467 		break;
6468 	default:
6469 		plane_info->rotation = ROTATION_ANGLE_0;
6470 		break;
6471 	}
6472 
6473 
6474 	plane_info->visible = true;
6475 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
6476 
6477 	plane_info->layer_index = plane_state->normalized_zpos;
6478 
6479 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
6480 					  &plane_info->color_space);
6481 	if (ret)
6482 		return ret;
6483 
6484 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
6485 					   plane_info->rotation, tiling_flags,
6486 					   &plane_info->tiling_info,
6487 					   &plane_info->plane_size,
6488 					   &plane_info->dcc, address,
6489 					   tmz_surface);
6490 	if (ret)
6491 		return ret;
6492 
6493 	amdgpu_dm_plane_fill_blending_from_plane_state(
6494 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
6495 		&plane_info->global_alpha, &plane_info->global_alpha_value);
6496 
6497 	return 0;
6498 }
6499 
6500 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
6501 				    struct dc_plane_state *dc_plane_state,
6502 				    struct drm_plane_state *plane_state,
6503 				    struct drm_crtc_state *crtc_state)
6504 {
6505 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6506 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
6507 	struct dc_scaling_info scaling_info;
6508 	struct dc_plane_info plane_info;
6509 	int ret;
6510 
6511 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
6512 	if (ret)
6513 		return ret;
6514 
6515 	dc_plane_state->src_rect = scaling_info.src_rect;
6516 	dc_plane_state->dst_rect = scaling_info.dst_rect;
6517 	dc_plane_state->clip_rect = scaling_info.clip_rect;
6518 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
6519 
6520 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
6521 					  afb->tiling_flags,
6522 					  &plane_info,
6523 					  &dc_plane_state->address,
6524 					  afb->tmz_surface);
6525 	if (ret)
6526 		return ret;
6527 
6528 	dc_plane_state->format = plane_info.format;
6529 	dc_plane_state->color_space = plane_info.color_space;
6530 	dc_plane_state->format = plane_info.format;
6531 	dc_plane_state->plane_size = plane_info.plane_size;
6532 	dc_plane_state->rotation = plane_info.rotation;
6533 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
6534 	dc_plane_state->stereo_format = plane_info.stereo_format;
6535 	dc_plane_state->tiling_info = plane_info.tiling_info;
6536 	dc_plane_state->visible = plane_info.visible;
6537 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
6538 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
6539 	dc_plane_state->global_alpha = plane_info.global_alpha;
6540 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
6541 	dc_plane_state->dcc = plane_info.dcc;
6542 	dc_plane_state->layer_index = plane_info.layer_index;
6543 	dc_plane_state->flip_int_enabled = true;
6544 
6545 	/*
6546 	 * Always set input transfer function, since plane state is refreshed
6547 	 * every time.
6548 	 */
6549 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
6550 						plane_state,
6551 						dc_plane_state);
6552 	if (ret)
6553 		return ret;
6554 
6555 	return 0;
6556 }
6557 
6558 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
6559 				      struct rect *dirty_rect, int32_t x,
6560 				      s32 y, s32 width, s32 height,
6561 				      int *i, bool ffu)
6562 {
6563 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
6564 
6565 	dirty_rect->x = x;
6566 	dirty_rect->y = y;
6567 	dirty_rect->width = width;
6568 	dirty_rect->height = height;
6569 
6570 	if (ffu)
6571 		drm_dbg(plane->dev,
6572 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
6573 			plane->base.id, width, height);
6574 	else
6575 		drm_dbg(plane->dev,
6576 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
6577 			plane->base.id, x, y, width, height);
6578 
6579 	(*i)++;
6580 }
6581 
6582 /**
6583  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
6584  *
6585  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
6586  *         remote fb
6587  * @old_plane_state: Old state of @plane
6588  * @new_plane_state: New state of @plane
6589  * @crtc_state: New state of CRTC connected to the @plane
6590  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
6591  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
6592  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
6593  *             that have changed will be updated. If PSR SU is not enabled,
6594  *             or if damage clips are not available, the entire screen will be updated.
6595  * @dirty_regions_changed: dirty regions changed
6596  *
6597  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
6598  * (referred to as "damage clips" in DRM nomenclature) that require updating on
6599  * the eDP remote buffer. The responsibility of specifying the dirty regions is
6600  * amdgpu_dm's.
6601  *
6602  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
6603  * plane with regions that require flushing to the eDP remote buffer. In
6604  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
6605  * implicitly provide damage clips without any client support via the plane
6606  * bounds.
6607  */
6608 static void fill_dc_dirty_rects(struct drm_plane *plane,
6609 				struct drm_plane_state *old_plane_state,
6610 				struct drm_plane_state *new_plane_state,
6611 				struct drm_crtc_state *crtc_state,
6612 				struct dc_flip_addrs *flip_addrs,
6613 				bool is_psr_su,
6614 				bool *dirty_regions_changed)
6615 {
6616 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6617 	struct rect *dirty_rects = flip_addrs->dirty_rects;
6618 	u32 num_clips = 0;
6619 	struct drm_mode_rect *clips = NULL;
6620 	bool bb_changed;
6621 	bool fb_changed;
6622 	u32 i = 0;
6623 	*dirty_regions_changed = false;
6624 
6625 	/*
6626 	 * Cursor plane has it's own dirty rect update interface. See
6627 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
6628 	 */
6629 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
6630 		return;
6631 
6632 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
6633 		goto ffu;
6634 
6635 	if (!new_plane_state->ignore_damage_clips) {
6636 		num_clips = drm_plane_get_damage_clips_count(new_plane_state);
6637 		clips = drm_plane_get_damage_clips(new_plane_state);
6638 	}
6639 
6640 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
6641 						   is_psr_su)))
6642 		goto ffu;
6643 
6644 	if (!dm_crtc_state->mpo_requested) {
6645 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
6646 			goto ffu;
6647 
6648 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
6649 			fill_dc_dirty_rect(new_plane_state->plane,
6650 					   &dirty_rects[flip_addrs->dirty_rect_count],
6651 					   clips->x1, clips->y1,
6652 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
6653 					   &flip_addrs->dirty_rect_count,
6654 					   false);
6655 		return;
6656 	}
6657 
6658 	/*
6659 	 * MPO is requested. Add entire plane bounding box to dirty rects if
6660 	 * flipped to or damaged.
6661 	 *
6662 	 * If plane is moved or resized, also add old bounding box to dirty
6663 	 * rects.
6664 	 */
6665 	fb_changed = old_plane_state->fb->base.id !=
6666 		     new_plane_state->fb->base.id;
6667 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
6668 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
6669 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
6670 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
6671 
6672 	drm_dbg(plane->dev,
6673 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
6674 		new_plane_state->plane->base.id,
6675 		bb_changed, fb_changed, num_clips);
6676 
6677 	*dirty_regions_changed = bb_changed;
6678 
6679 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
6680 		goto ffu;
6681 
6682 	if (bb_changed) {
6683 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6684 				   new_plane_state->crtc_x,
6685 				   new_plane_state->crtc_y,
6686 				   new_plane_state->crtc_w,
6687 				   new_plane_state->crtc_h, &i, false);
6688 
6689 		/* Add old plane bounding-box if plane is moved or resized */
6690 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6691 				   old_plane_state->crtc_x,
6692 				   old_plane_state->crtc_y,
6693 				   old_plane_state->crtc_w,
6694 				   old_plane_state->crtc_h, &i, false);
6695 	}
6696 
6697 	if (num_clips) {
6698 		for (; i < num_clips; clips++)
6699 			fill_dc_dirty_rect(new_plane_state->plane,
6700 					   &dirty_rects[i], clips->x1,
6701 					   clips->y1, clips->x2 - clips->x1,
6702 					   clips->y2 - clips->y1, &i, false);
6703 	} else if (fb_changed && !bb_changed) {
6704 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6705 				   new_plane_state->crtc_x,
6706 				   new_plane_state->crtc_y,
6707 				   new_plane_state->crtc_w,
6708 				   new_plane_state->crtc_h, &i, false);
6709 	}
6710 
6711 	flip_addrs->dirty_rect_count = i;
6712 	return;
6713 
6714 ffu:
6715 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
6716 			   dm_crtc_state->base.mode.crtc_hdisplay,
6717 			   dm_crtc_state->base.mode.crtc_vdisplay,
6718 			   &flip_addrs->dirty_rect_count, true);
6719 }
6720 
6721 static void update_stream_scaling_settings(struct drm_device *dev,
6722 					   const struct drm_display_mode *mode,
6723 					   const struct dm_connector_state *dm_state,
6724 					   struct dc_stream_state *stream)
6725 {
6726 	enum amdgpu_rmx_type rmx_type;
6727 
6728 	struct rect src = { 0 }; /* viewport in composition space*/
6729 	struct rect dst = { 0 }; /* stream addressable area */
6730 
6731 	/* no mode. nothing to be done */
6732 	if (!mode)
6733 		return;
6734 
6735 	/* Full screen scaling by default */
6736 	src.width = mode->hdisplay;
6737 	src.height = mode->vdisplay;
6738 	dst.width = stream->timing.h_addressable;
6739 	dst.height = stream->timing.v_addressable;
6740 
6741 	if (dm_state) {
6742 		rmx_type = dm_state->scaling;
6743 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
6744 			if (src.width * dst.height <
6745 					src.height * dst.width) {
6746 				/* height needs less upscaling/more downscaling */
6747 				dst.width = src.width *
6748 						dst.height / src.height;
6749 			} else {
6750 				/* width needs less upscaling/more downscaling */
6751 				dst.height = src.height *
6752 						dst.width / src.width;
6753 			}
6754 		} else if (rmx_type == RMX_CENTER) {
6755 			dst = src;
6756 		}
6757 
6758 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
6759 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
6760 
6761 		if (dm_state->underscan_enable) {
6762 			dst.x += dm_state->underscan_hborder / 2;
6763 			dst.y += dm_state->underscan_vborder / 2;
6764 			dst.width -= dm_state->underscan_hborder;
6765 			dst.height -= dm_state->underscan_vborder;
6766 		}
6767 	}
6768 
6769 	stream->src = src;
6770 	stream->dst = dst;
6771 
6772 	drm_dbg_kms(dev, "Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
6773 		    dst.x, dst.y, dst.width, dst.height);
6774 
6775 }
6776 
6777 static enum dc_color_depth
6778 convert_color_depth_from_display_info(const struct drm_connector *connector,
6779 				      bool is_y420, int requested_bpc)
6780 {
6781 	u8 bpc;
6782 
6783 	if (is_y420) {
6784 		bpc = 8;
6785 
6786 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
6787 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
6788 			bpc = 16;
6789 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
6790 			bpc = 12;
6791 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
6792 			bpc = 10;
6793 	} else {
6794 		bpc = (uint8_t)connector->display_info.bpc;
6795 		/* Assume 8 bpc by default if no bpc is specified. */
6796 		bpc = bpc ? bpc : 8;
6797 	}
6798 
6799 	if (requested_bpc > 0) {
6800 		/*
6801 		 * Cap display bpc based on the user requested value.
6802 		 *
6803 		 * The value for state->max_bpc may not correctly updated
6804 		 * depending on when the connector gets added to the state
6805 		 * or if this was called outside of atomic check, so it
6806 		 * can't be used directly.
6807 		 */
6808 		bpc = min_t(u8, bpc, requested_bpc);
6809 
6810 		/* Round down to the nearest even number. */
6811 		bpc = bpc - (bpc & 1);
6812 	}
6813 
6814 	switch (bpc) {
6815 	case 0:
6816 		/*
6817 		 * Temporary Work around, DRM doesn't parse color depth for
6818 		 * EDID revision before 1.4
6819 		 * TODO: Fix edid parsing
6820 		 */
6821 		return COLOR_DEPTH_888;
6822 	case 6:
6823 		return COLOR_DEPTH_666;
6824 	case 8:
6825 		return COLOR_DEPTH_888;
6826 	case 10:
6827 		return COLOR_DEPTH_101010;
6828 	case 12:
6829 		return COLOR_DEPTH_121212;
6830 	case 14:
6831 		return COLOR_DEPTH_141414;
6832 	case 16:
6833 		return COLOR_DEPTH_161616;
6834 	default:
6835 		return COLOR_DEPTH_UNDEFINED;
6836 	}
6837 }
6838 
6839 static enum dc_aspect_ratio
6840 get_aspect_ratio(const struct drm_display_mode *mode_in)
6841 {
6842 	/* 1-1 mapping, since both enums follow the HDMI spec. */
6843 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
6844 }
6845 
6846 static enum dc_color_space
6847 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
6848 		       const struct drm_connector_state *connector_state)
6849 {
6850 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
6851 
6852 	switch (connector_state->colorspace) {
6853 	case DRM_MODE_COLORIMETRY_BT601_YCC:
6854 		if (dc_crtc_timing->flags.Y_ONLY)
6855 			color_space = COLOR_SPACE_YCBCR601_LIMITED;
6856 		else
6857 			color_space = COLOR_SPACE_YCBCR601;
6858 		break;
6859 	case DRM_MODE_COLORIMETRY_BT709_YCC:
6860 		if (dc_crtc_timing->flags.Y_ONLY)
6861 			color_space = COLOR_SPACE_YCBCR709_LIMITED;
6862 		else
6863 			color_space = COLOR_SPACE_YCBCR709;
6864 		break;
6865 	case DRM_MODE_COLORIMETRY_OPRGB:
6866 		color_space = COLOR_SPACE_ADOBERGB;
6867 		break;
6868 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
6869 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
6870 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
6871 			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
6872 		else
6873 			color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6874 		break;
6875 	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
6876 	default:
6877 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
6878 			color_space = COLOR_SPACE_SRGB;
6879 			if (connector_state->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_LIMITED)
6880 				color_space = COLOR_SPACE_SRGB_LIMITED;
6881 		/*
6882 		 * 27030khz is the separation point between HDTV and SDTV
6883 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
6884 		 * respectively
6885 		 */
6886 		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
6887 			if (dc_crtc_timing->flags.Y_ONLY)
6888 				color_space =
6889 					COLOR_SPACE_YCBCR709_LIMITED;
6890 			else
6891 				color_space = COLOR_SPACE_YCBCR709;
6892 		} else {
6893 			if (dc_crtc_timing->flags.Y_ONLY)
6894 				color_space =
6895 					COLOR_SPACE_YCBCR601_LIMITED;
6896 			else
6897 				color_space = COLOR_SPACE_YCBCR601;
6898 		}
6899 		break;
6900 	}
6901 
6902 	return color_space;
6903 }
6904 
6905 static enum display_content_type
6906 get_output_content_type(const struct drm_connector_state *connector_state)
6907 {
6908 	switch (connector_state->content_type) {
6909 	default:
6910 	case DRM_MODE_CONTENT_TYPE_NO_DATA:
6911 		return DISPLAY_CONTENT_TYPE_NO_DATA;
6912 	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
6913 		return DISPLAY_CONTENT_TYPE_GRAPHICS;
6914 	case DRM_MODE_CONTENT_TYPE_PHOTO:
6915 		return DISPLAY_CONTENT_TYPE_PHOTO;
6916 	case DRM_MODE_CONTENT_TYPE_CINEMA:
6917 		return DISPLAY_CONTENT_TYPE_CINEMA;
6918 	case DRM_MODE_CONTENT_TYPE_GAME:
6919 		return DISPLAY_CONTENT_TYPE_GAME;
6920 	}
6921 }
6922 
6923 static bool adjust_colour_depth_from_display_info(
6924 	struct dc_crtc_timing *timing_out,
6925 	const struct drm_display_info *info)
6926 {
6927 	enum dc_color_depth depth = timing_out->display_color_depth;
6928 	int normalized_clk;
6929 
6930 	do {
6931 		normalized_clk = timing_out->pix_clk_100hz / 10;
6932 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
6933 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
6934 			normalized_clk /= 2;
6935 		/* Adjusting pix clock following on HDMI spec based on colour depth */
6936 		switch (depth) {
6937 		case COLOR_DEPTH_888:
6938 			break;
6939 		case COLOR_DEPTH_101010:
6940 			normalized_clk = (normalized_clk * 30) / 24;
6941 			break;
6942 		case COLOR_DEPTH_121212:
6943 			normalized_clk = (normalized_clk * 36) / 24;
6944 			break;
6945 		case COLOR_DEPTH_161616:
6946 			normalized_clk = (normalized_clk * 48) / 24;
6947 			break;
6948 		default:
6949 			/* The above depths are the only ones valid for HDMI. */
6950 			return false;
6951 		}
6952 		if (normalized_clk <= info->max_tmds_clock) {
6953 			timing_out->display_color_depth = depth;
6954 			return true;
6955 		}
6956 	} while (--depth > COLOR_DEPTH_666);
6957 	return false;
6958 }
6959 
6960 static void fill_stream_properties_from_drm_display_mode(
6961 	struct dc_stream_state *stream,
6962 	const struct drm_display_mode *mode_in,
6963 	const struct drm_connector *connector,
6964 	const struct drm_connector_state *connector_state,
6965 	const struct dc_stream_state *old_stream,
6966 	int requested_bpc)
6967 {
6968 	struct dc_crtc_timing *timing_out = &stream->timing;
6969 	const struct drm_display_info *info = &connector->display_info;
6970 	struct amdgpu_dm_connector *aconnector = NULL;
6971 	struct hdmi_vendor_infoframe hv_frame;
6972 	struct hdmi_avi_infoframe avi_frame;
6973 	ssize_t err;
6974 
6975 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
6976 		aconnector = to_amdgpu_dm_connector(connector);
6977 
6978 	memset(&hv_frame, 0, sizeof(hv_frame));
6979 	memset(&avi_frame, 0, sizeof(avi_frame));
6980 
6981 	timing_out->h_border_left = 0;
6982 	timing_out->h_border_right = 0;
6983 	timing_out->v_border_top = 0;
6984 	timing_out->v_border_bottom = 0;
6985 	/* TODO: un-hardcode */
6986 	if (drm_mode_is_420_only(info, mode_in)
6987 			&& (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
6988 			    stream->signal == SIGNAL_TYPE_HDMI_FRL)
6989 			&& aconnector
6990 			&& aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR420)
6991 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6992 	else if (drm_mode_is_420_also(info, mode_in)
6993 			&& aconnector
6994 			&& (aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR420
6995 			|| aconnector->force_yuv420_output))
6996 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6997 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR422))
6998 			&& aconnector
6999 			&& (aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR422
7000 			|| aconnector->force_yuv422_output))
7001 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR422;
7002 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR444))
7003 			&& (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7004 			    stream->signal == SIGNAL_TYPE_HDMI_FRL)
7005 			&& aconnector
7006 			&& aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR444)
7007 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
7008 	else
7009 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
7010 
7011 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
7012 	timing_out->display_color_depth = convert_color_depth_from_display_info(
7013 		connector,
7014 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
7015 		requested_bpc);
7016 	timing_out->scan_type = SCANNING_TYPE_NODATA;
7017 	timing_out->hdmi_vic = 0;
7018 
7019 	if (old_stream) {
7020 		timing_out->vic = old_stream->timing.vic;
7021 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
7022 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
7023 	} else {
7024 		timing_out->vic = drm_match_cea_mode(mode_in);
7025 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
7026 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
7027 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
7028 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
7029 	}
7030 
7031 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7032 		stream->signal == SIGNAL_TYPE_HDMI_FRL) {
7033 		err = drm_hdmi_avi_infoframe_from_display_mode(&avi_frame,
7034 							       (struct drm_connector *)connector,
7035 							       mode_in);
7036 		if (err < 0)
7037 			drm_warn_once(connector->dev, "Failed to setup avi infoframe on connector %s: %zd\n",
7038 				      connector->name, err);
7039 		timing_out->vic = avi_frame.video_code;
7040 		err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame,
7041 								  (struct drm_connector *)connector,
7042 								  mode_in);
7043 		if (err < 0)
7044 			drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n",
7045 				      connector->name, err);
7046 		timing_out->hdmi_vic = hv_frame.vic;
7047 	}
7048 
7049 	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
7050 		timing_out->h_addressable = mode_in->hdisplay;
7051 		timing_out->h_total = mode_in->htotal;
7052 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
7053 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
7054 		timing_out->v_total = mode_in->vtotal;
7055 		timing_out->v_addressable = mode_in->vdisplay;
7056 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
7057 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
7058 		timing_out->pix_clk_100hz = mode_in->clock * 10;
7059 	} else {
7060 		timing_out->h_addressable = mode_in->crtc_hdisplay;
7061 		timing_out->h_total = mode_in->crtc_htotal;
7062 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
7063 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
7064 		timing_out->v_total = mode_in->crtc_vtotal;
7065 		timing_out->v_addressable = mode_in->crtc_vdisplay;
7066 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
7067 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
7068 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
7069 	}
7070 
7071 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
7072 
7073 	stream->out_transfer_func.type = TF_TYPE_PREDEFINED;
7074 	stream->out_transfer_func.tf = TRANSFER_FUNCTION_SRGB;
7075 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
7076 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
7077 		    drm_mode_is_420_also(info, mode_in) &&
7078 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
7079 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
7080 			adjust_colour_depth_from_display_info(timing_out, info);
7081 		}
7082 	}
7083 
7084 	stream->output_color_space = get_output_color_space(timing_out, connector_state);
7085 	stream->content_type = get_output_content_type(connector_state);
7086 }
7087 
7088 static void fill_audio_info(struct audio_info *audio_info,
7089 			    const struct drm_connector *drm_connector,
7090 			    const struct dc_sink *dc_sink)
7091 {
7092 	int i = 0;
7093 	int cea_revision = 0;
7094 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
7095 
7096 	audio_info->manufacture_id = edid_caps->manufacturer_id;
7097 	audio_info->product_id = edid_caps->product_id;
7098 
7099 	cea_revision = drm_connector->display_info.cea_rev;
7100 
7101 	strscpy(audio_info->display_name,
7102 		edid_caps->display_name,
7103 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
7104 
7105 	if (cea_revision >= 3) {
7106 		audio_info->mode_count = edid_caps->audio_mode_count;
7107 
7108 		for (i = 0; i < audio_info->mode_count; ++i) {
7109 			audio_info->modes[i].format_code =
7110 					(enum audio_format_code)
7111 					(edid_caps->audio_modes[i].format_code);
7112 			audio_info->modes[i].channel_count =
7113 					edid_caps->audio_modes[i].channel_count;
7114 			audio_info->modes[i].sample_rates.all =
7115 					edid_caps->audio_modes[i].sample_rate;
7116 			audio_info->modes[i].sample_size =
7117 					edid_caps->audio_modes[i].sample_size;
7118 		}
7119 	}
7120 
7121 	audio_info->flags.all = edid_caps->speaker_flags;
7122 
7123 	/* TODO: We only check for the progressive mode, check for interlace mode too */
7124 	if (drm_connector->latency_present[0]) {
7125 		audio_info->video_latency = drm_connector->video_latency[0];
7126 		audio_info->audio_latency = drm_connector->audio_latency[0];
7127 	}
7128 
7129 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
7130 
7131 }
7132 
7133 static void
7134 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
7135 				      struct drm_display_mode *dst_mode)
7136 {
7137 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
7138 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
7139 	dst_mode->crtc_clock = src_mode->crtc_clock;
7140 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
7141 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
7142 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
7143 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
7144 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
7145 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
7146 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
7147 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
7148 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
7149 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
7150 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
7151 }
7152 
7153 static void
7154 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
7155 					const struct drm_display_mode *native_mode,
7156 					bool scale_enabled)
7157 {
7158 	if (scale_enabled || (
7159 	    native_mode->clock == drm_mode->clock &&
7160 	    native_mode->htotal == drm_mode->htotal &&
7161 	    native_mode->vtotal == drm_mode->vtotal)) {
7162 		if (native_mode->crtc_clock)
7163 			copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
7164 	} else {
7165 		/* no scaling nor amdgpu inserted, no need to patch */
7166 	}
7167 }
7168 
7169 static struct dc_sink *
7170 create_fake_sink(struct drm_device *dev, struct dc_link *link)
7171 {
7172 	struct dc_sink_init_data sink_init_data = { 0 };
7173 	struct dc_sink *sink = NULL;
7174 
7175 	sink_init_data.link = link;
7176 	sink_init_data.sink_signal = link->connector_signal;
7177 
7178 	sink = dc_sink_create(&sink_init_data);
7179 	if (!sink) {
7180 		drm_err(dev, "Failed to create sink!\n");
7181 		return NULL;
7182 	}
7183 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
7184 
7185 	return sink;
7186 }
7187 
7188 static void set_multisync_trigger_params(
7189 		struct dc_stream_state *stream)
7190 {
7191 	struct dc_stream_state *master = NULL;
7192 
7193 	if (stream->triggered_crtc_reset.enabled) {
7194 		master = stream->triggered_crtc_reset.event_source;
7195 		stream->triggered_crtc_reset.event =
7196 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
7197 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
7198 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
7199 	}
7200 }
7201 
7202 static void set_master_stream(struct dc_stream_state *stream_set[],
7203 			      int stream_count)
7204 {
7205 	int j, highest_rfr = 0, master_stream = 0;
7206 
7207 	for (j = 0;  j < stream_count; j++) {
7208 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
7209 			int refresh_rate = 0;
7210 
7211 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
7212 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
7213 			if (refresh_rate > highest_rfr) {
7214 				highest_rfr = refresh_rate;
7215 				master_stream = j;
7216 			}
7217 		}
7218 	}
7219 	for (j = 0;  j < stream_count; j++) {
7220 		if (stream_set[j])
7221 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
7222 	}
7223 }
7224 
7225 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
7226 {
7227 	int i = 0;
7228 	struct dc_stream_state *stream;
7229 
7230 	if (context->stream_count < 2)
7231 		return;
7232 	for (i = 0; i < context->stream_count ; i++) {
7233 		if (!context->streams[i])
7234 			continue;
7235 		/*
7236 		 * TODO: add a function to read AMD VSDB bits and set
7237 		 * crtc_sync_master.multi_sync_enabled flag
7238 		 * For now it's set to false
7239 		 */
7240 	}
7241 
7242 	set_master_stream(context->streams, context->stream_count);
7243 
7244 	for (i = 0; i < context->stream_count ; i++) {
7245 		stream = context->streams[i];
7246 
7247 		if (!stream)
7248 			continue;
7249 
7250 		set_multisync_trigger_params(stream);
7251 	}
7252 }
7253 
7254 /**
7255  * DOC: FreeSync Video
7256  *
7257  * When a userspace application wants to play a video, the content follows a
7258  * standard format definition that usually specifies the FPS for that format.
7259  * The below list illustrates some video format and the expected FPS,
7260  * respectively:
7261  *
7262  * - TV/NTSC (23.976 FPS)
7263  * - Cinema (24 FPS)
7264  * - TV/PAL (25 FPS)
7265  * - TV/NTSC (29.97 FPS)
7266  * - TV/NTSC (30 FPS)
7267  * - Cinema HFR (48 FPS)
7268  * - TV/PAL (50 FPS)
7269  * - Commonly used (60 FPS)
7270  * - Multiples of 24 (48,72,96 FPS)
7271  *
7272  * The list of standards video format is not huge and can be added to the
7273  * connector modeset list beforehand. With that, userspace can leverage
7274  * FreeSync to extends the front porch in order to attain the target refresh
7275  * rate. Such a switch will happen seamlessly, without screen blanking or
7276  * reprogramming of the output in any other way. If the userspace requests a
7277  * modesetting change compatible with FreeSync modes that only differ in the
7278  * refresh rate, DC will skip the full update and avoid blink during the
7279  * transition. For example, the video player can change the modesetting from
7280  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
7281  * causing any display blink. This same concept can be applied to a mode
7282  * setting change.
7283  */
7284 static struct drm_display_mode *
7285 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
7286 		bool use_probed_modes)
7287 {
7288 	struct drm_display_mode *m, *m_pref = NULL;
7289 	u16 current_refresh, highest_refresh;
7290 	struct list_head *list_head = use_probed_modes ?
7291 		&aconnector->base.probed_modes :
7292 		&aconnector->base.modes;
7293 
7294 	if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
7295 		return NULL;
7296 
7297 	if (aconnector->freesync_vid_base.clock != 0)
7298 		return &aconnector->freesync_vid_base;
7299 
7300 	/* Find the preferred mode */
7301 	list_for_each_entry(m, list_head, head) {
7302 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
7303 			m_pref = m;
7304 			break;
7305 		}
7306 	}
7307 
7308 	if (!m_pref) {
7309 		/* Probably an EDID with no preferred mode. Fallback to first entry */
7310 		m_pref = list_first_entry_or_null(
7311 				&aconnector->base.modes, struct drm_display_mode, head);
7312 		if (!m_pref) {
7313 			drm_dbg_driver(aconnector->base.dev, "No preferred mode found in EDID\n");
7314 			return NULL;
7315 		}
7316 	}
7317 
7318 	highest_refresh = drm_mode_vrefresh(m_pref);
7319 
7320 	/*
7321 	 * Find the mode with highest refresh rate with same resolution.
7322 	 * For some monitors, preferred mode is not the mode with highest
7323 	 * supported refresh rate.
7324 	 */
7325 	list_for_each_entry(m, list_head, head) {
7326 		current_refresh  = drm_mode_vrefresh(m);
7327 
7328 		if (m->hdisplay == m_pref->hdisplay &&
7329 		    m->vdisplay == m_pref->vdisplay &&
7330 		    highest_refresh < current_refresh) {
7331 			highest_refresh = current_refresh;
7332 			m_pref = m;
7333 		}
7334 	}
7335 
7336 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
7337 	return m_pref;
7338 }
7339 
7340 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
7341 		struct amdgpu_dm_connector *aconnector)
7342 {
7343 	struct drm_display_mode *high_mode;
7344 	int timing_diff;
7345 
7346 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
7347 	if (!high_mode || !mode)
7348 		return false;
7349 
7350 	timing_diff = high_mode->vtotal - mode->vtotal;
7351 
7352 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
7353 	    high_mode->hdisplay != mode->hdisplay ||
7354 	    high_mode->vdisplay != mode->vdisplay ||
7355 	    high_mode->hsync_start != mode->hsync_start ||
7356 	    high_mode->hsync_end != mode->hsync_end ||
7357 	    high_mode->htotal != mode->htotal ||
7358 	    high_mode->hskew != mode->hskew ||
7359 	    high_mode->vscan != mode->vscan ||
7360 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
7361 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
7362 		return false;
7363 	else
7364 		return true;
7365 }
7366 
7367 #if defined(CONFIG_DRM_AMD_DC_FP)
7368 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
7369 			    struct dc_sink *sink, struct dc_stream_state *stream,
7370 			    struct dsc_dec_dpcd_caps *dsc_caps)
7371 {
7372 	stream->timing.flags.DSC = 0;
7373 	dsc_caps->is_dsc_supported = false;
7374 
7375 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
7376 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
7377 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE)
7378 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7379 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7380 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7381 				dsc_caps);
7382 		else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7383 			if (aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.fields.dsc_support.DSC_PASSTHROUGH_SUPPORT &&
7384 					!aconnector->dsc_settings.dsc_force_disable_passthrough &&
7385 					aconnector->dc_link->dpcd_caps.dongle_caps.dp_hdmi_frl_max_link_bw_in_kbps > 0 &&
7386 					sink->edid_caps.frl_dsc_support &&
7387 					sink->edid_caps.max_frl_rate > 0 &&
7388 					sink->edid_caps.frl_dsc_max_frl_rate > 0)
7389 				dc_dsc_parse_dsc_edid(aconnector->dc_link->ctx->dc, &sink->edid_caps, dsc_caps);
7390 			else
7391 				dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7392 				      aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7393 				      aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7394 				      dsc_caps);
7395 		}
7396 	} else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_HDMI_FRL) {
7397 		if (sink->edid_caps.frl_dsc_support &&
7398 				sink->edid_caps.max_frl_rate > 0 &&
7399 				sink->edid_caps.frl_dsc_max_frl_rate > 0)
7400 			dc_dsc_parse_dsc_edid(aconnector->dc_link->ctx->dc, &sink->edid_caps, dsc_caps);
7401 	}
7402 }
7403 
7404 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
7405 				    struct dc_sink *sink, struct dc_stream_state *stream,
7406 				    struct dsc_dec_dpcd_caps *dsc_caps,
7407 				    uint32_t max_dsc_target_bpp_limit_override)
7408 {
7409 	const struct dc_link_settings *verified_link_cap = NULL;
7410 	u32 link_bw_in_kbps;
7411 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
7412 	struct dc *dc = sink->ctx->dc;
7413 	struct dc_dsc_bw_range bw_range = {0};
7414 	struct dc_dsc_config dsc_cfg = {0};
7415 	struct dc_dsc_config_options dsc_options = {0};
7416 
7417 	dc_dsc_get_default_config_option(dc, &dsc_options);
7418 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7419 
7420 	verified_link_cap = dc_link_get_link_cap(stream->link);
7421 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
7422 	edp_min_bpp_x16 = 8 * 16;
7423 	edp_max_bpp_x16 = 8 * 16;
7424 
7425 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
7426 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
7427 
7428 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
7429 		edp_min_bpp_x16 = edp_max_bpp_x16;
7430 
7431 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
7432 				dc->debug.dsc_min_slice_height_override,
7433 				edp_min_bpp_x16, edp_max_bpp_x16,
7434 				dsc_caps,
7435 				&stream->timing,
7436 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7437 				&bw_range)) {
7438 
7439 		if (bw_range.max_kbps < link_bw_in_kbps) {
7440 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7441 					dsc_caps,
7442 					&dsc_options,
7443 					0,
7444 					&stream->timing,
7445 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7446 					&dsc_cfg)) {
7447 				stream->timing.dsc_cfg = dsc_cfg;
7448 				stream->timing.flags.DSC = 1;
7449 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
7450 			}
7451 			return;
7452 		}
7453 	}
7454 
7455 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7456 				dsc_caps,
7457 				&dsc_options,
7458 				link_bw_in_kbps,
7459 				&stream->timing,
7460 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7461 				&dsc_cfg)) {
7462 		stream->timing.dsc_cfg = dsc_cfg;
7463 		stream->timing.flags.DSC = 1;
7464 	}
7465 }
7466 
7467 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
7468 					struct dc_sink *sink, struct dc_stream_state *stream,
7469 					struct dsc_dec_dpcd_caps *dsc_caps)
7470 {
7471 	struct drm_connector *drm_connector = &aconnector->base;
7472 	u32 link_bandwidth_kbps;
7473 	struct dc *dc = sink->ctx->dc;
7474 	const struct dc_hdmi_frl_link_settings *frl_verified_link_cap = NULL;
7475 	u32 converter_bw_in_kbps;
7476 	u32 sink_bw_in_kbps;
7477 	u32 dsc_sink_bw_in_kbps;
7478 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
7479 	u32 dsc_max_supported_bw_in_kbps;
7480 	u32 max_dsc_target_bpp_limit_override =
7481 		drm_connector->display_info.max_dsc_bpp;
7482 	struct dc_dsc_config_options dsc_options = {0};
7483 
7484 	dc_dsc_get_default_config_option(dc, &dsc_options);
7485 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7486 
7487 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
7488 							dc_link_get_link_cap(aconnector->dc_link));
7489 
7490 	/* Set DSC policy according to dsc_clock_en */
7491 	dc_dsc_policy_set_enable_dsc_when_not_needed(
7492 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
7493 
7494 	if (sink->sink_signal == SIGNAL_TYPE_EDP &&
7495 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
7496 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
7497 
7498 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
7499 
7500 	} else if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
7501 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
7502 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7503 						dsc_caps,
7504 						&dsc_options,
7505 						link_bandwidth_kbps,
7506 						&stream->timing,
7507 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7508 						&stream->timing.dsc_cfg)) {
7509 				stream->timing.flags.DSC = 1;
7510 				drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from SST RX\n",
7511 							__func__, drm_connector->name);
7512 			}
7513 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7514 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
7515 					dc_link_get_highest_encoding_format(aconnector->dc_link));
7516 			converter_bw_in_kbps = aconnector->dc_link->dpcd_caps.dongle_caps.dp_hdmi_frl_max_link_bw_in_kbps;
7517 			sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.max_frl_rate);
7518 			dsc_sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.frl_dsc_max_frl_rate);
7519 
7520 			if (dsc_caps->is_frl) {
7521 				max_supported_bw_in_kbps = min(link_bandwidth_kbps, converter_bw_in_kbps);
7522 				max_supported_bw_in_kbps = min(max_supported_bw_in_kbps, sink_bw_in_kbps);
7523 				dsc_max_supported_bw_in_kbps = min(max_supported_bw_in_kbps, dsc_sink_bw_in_kbps);
7524 			} else {
7525 				max_supported_bw_in_kbps = link_bandwidth_kbps;
7526 				dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
7527 			}
7528 
7529 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
7530 					max_supported_bw_in_kbps > 0 &&
7531 					dsc_max_supported_bw_in_kbps > 0)
7532 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7533 						dsc_caps,
7534 						&dsc_options,
7535 						dsc_max_supported_bw_in_kbps,
7536 						&stream->timing,
7537 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7538 						&stream->timing.dsc_cfg)) {
7539 					stream->timing.flags.DSC = 1;
7540 					drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from %s\n",
7541 							__func__, drm_connector->name,
7542 							(dsc_caps->is_frl == 1) ? "HDMI FRL RX" : "DP-HDMI PCON");
7543 				}
7544 		}
7545 	}
7546 	else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_HDMI_FRL) {
7547 		struct dc_dsc_policy dsc_policy = {0};
7548 
7549 		frl_verified_link_cap = dc_link_get_frl_link_cap(stream->link);
7550 		if (frl_verified_link_cap->frl_link_rate != HDMI_FRL_LINK_RATE_DISABLE &&
7551 			aconnector->dc_link->frl_flags.force_frl_dsc) {
7552 			dc_dsc_policy_set_enable_dsc_when_not_needed(true);
7553 			dc_dsc_get_policy_for_timing(&stream->timing, 0, &dsc_policy, dc_link_get_highest_encoding_format(stream->link));
7554 		}
7555 
7556 		timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing, DC_LINK_ENCODING_HDMI_FRL);
7557 		link_bandwidth_kbps = dc_link_frl_bandwidth_kbps(stream->link, frl_verified_link_cap->frl_link_rate);
7558 		dsc_sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.frl_dsc_max_frl_rate);
7559 
7560 		if ((timing_bw_in_kbps > link_bandwidth_kbps && dsc_sink_bw_in_kbps > 0) ||
7561 		    (dsc_policy.enable_dsc_when_not_needed || dsc_options.force_dsc_when_not_needed)) {
7562 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7563 					dsc_caps,
7564 					&dsc_options,
7565 					dsc_sink_bw_in_kbps,
7566 					&stream->timing,
7567 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7568 					&stream->timing.dsc_cfg)) {
7569 				stream->timing.flags.DSC = 1;
7570 				drm_dbg_driver(drm_connector->dev, "%s: HDMI_FRL_DSC [%s] DSC is selected from HDMI FRL RX\n",
7571 						__func__, drm_connector->name);
7572 			}
7573 		}
7574 	}
7575 
7576 	/* Overwrite the stream flag if DSC is enabled through debugfs */
7577 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
7578 		stream->timing.flags.DSC = 1;
7579 
7580 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
7581 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
7582 
7583 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
7584 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
7585 
7586 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
7587 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
7588 }
7589 #endif
7590 
7591 static struct dc_stream_state *
7592 create_stream_for_sink(struct drm_connector *connector,
7593 		       const struct drm_display_mode *drm_mode,
7594 		       const struct dm_connector_state *dm_state,
7595 		       const struct dc_stream_state *old_stream,
7596 		       int requested_bpc)
7597 {
7598 	struct drm_device *dev = connector->dev;
7599 	struct amdgpu_dm_connector *aconnector = NULL;
7600 	struct drm_display_mode *preferred_mode = NULL;
7601 	const struct drm_connector_state *con_state = &dm_state->base;
7602 	struct dc_stream_state *stream = NULL;
7603 	struct drm_display_mode mode;
7604 	struct drm_display_mode saved_mode;
7605 	struct drm_display_mode *freesync_mode = NULL;
7606 	bool native_mode_found = false;
7607 	bool recalculate_timing = false;
7608 	bool scale = dm_state->scaling != RMX_OFF;
7609 	int mode_refresh;
7610 	int preferred_refresh = 0;
7611 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
7612 #if defined(CONFIG_DRM_AMD_DC_FP)
7613 	struct dsc_dec_dpcd_caps dsc_caps = {0};
7614 #endif
7615 	struct dc_link *link = NULL;
7616 	struct dc_sink *sink = NULL;
7617 
7618 	drm_mode_init(&mode, drm_mode);
7619 	memset(&saved_mode, 0, sizeof(saved_mode));
7620 
7621 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK) {
7622 		aconnector = NULL;
7623 		aconnector = to_amdgpu_dm_connector(connector);
7624 		link = aconnector->dc_link;
7625 	} else {
7626 		struct drm_writeback_connector *wbcon = NULL;
7627 		struct amdgpu_dm_wb_connector *dm_wbcon = NULL;
7628 
7629 		wbcon = drm_connector_to_writeback(connector);
7630 		dm_wbcon = to_amdgpu_dm_wb_connector(wbcon);
7631 		link = dm_wbcon->link;
7632 	}
7633 
7634 	if (!aconnector || !aconnector->dc_sink) {
7635 		sink = create_fake_sink(dev, link);
7636 		if (!sink)
7637 			return stream;
7638 
7639 	} else {
7640 		sink = aconnector->dc_sink;
7641 		dc_sink_retain(sink);
7642 	}
7643 
7644 	stream = dc_create_stream_for_sink(sink);
7645 
7646 	if (stream == NULL) {
7647 		drm_err(dev, "Failed to create stream for sink!\n");
7648 		goto finish;
7649 	}
7650 
7651 	/* We leave this NULL for writeback connectors */
7652 	stream->dm_stream_context = aconnector;
7653 
7654 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
7655 		connector->display_info.hdmi.scdc.scrambling.low_rates;
7656 
7657 	list_for_each_entry(preferred_mode, &connector->modes, head) {
7658 		/* Search for preferred mode */
7659 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
7660 			native_mode_found = true;
7661 			break;
7662 		}
7663 	}
7664 	if (!native_mode_found)
7665 		preferred_mode = list_first_entry_or_null(
7666 				&connector->modes,
7667 				struct drm_display_mode,
7668 				head);
7669 
7670 	mode_refresh = drm_mode_vrefresh(&mode);
7671 
7672 	if (preferred_mode == NULL) {
7673 		/*
7674 		 * This may not be an error, the use case is when we have no
7675 		 * usermode calls to reset and set mode upon hotplug. In this
7676 		 * case, we call set mode ourselves to restore the previous mode
7677 		 * and the modelist may not be filled in time.
7678 		 */
7679 		drm_dbg_driver(dev, "No preferred mode found\n");
7680 	} else if (aconnector) {
7681 		recalculate_timing = amdgpu_freesync_vid_mode &&
7682 				 is_freesync_video_mode(&mode, aconnector);
7683 		if (recalculate_timing) {
7684 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
7685 			drm_mode_copy(&saved_mode, &mode);
7686 			saved_mode.picture_aspect_ratio = mode.picture_aspect_ratio;
7687 			drm_mode_copy(&mode, freesync_mode);
7688 			mode.picture_aspect_ratio = saved_mode.picture_aspect_ratio;
7689 		} else {
7690 			decide_crtc_timing_for_drm_display_mode(
7691 					&mode, preferred_mode, scale);
7692 
7693 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
7694 		}
7695 	}
7696 
7697 	if (recalculate_timing)
7698 		drm_mode_set_crtcinfo(&saved_mode, 0);
7699 
7700 	/*
7701 	 * If scaling is enabled and refresh rate didn't change
7702 	 * we copy the vic and polarities of the old timings
7703 	 */
7704 	if (!scale || mode_refresh != preferred_refresh)
7705 		fill_stream_properties_from_drm_display_mode(
7706 			stream, &mode, connector, con_state, NULL,
7707 			requested_bpc);
7708 	else
7709 		fill_stream_properties_from_drm_display_mode(
7710 			stream, &mode, connector, con_state, old_stream,
7711 			requested_bpc);
7712 
7713 	/* The rest isn't needed for writeback connectors */
7714 	if (!aconnector)
7715 		goto finish;
7716 
7717 	if (aconnector->timing_changed) {
7718 		drm_dbg(aconnector->base.dev,
7719 			"overriding timing for automated test, bpc %d, changing to %d\n",
7720 			stream->timing.display_color_depth,
7721 			aconnector->timing_requested->display_color_depth);
7722 		stream->timing = *aconnector->timing_requested;
7723 	}
7724 
7725 #if defined(CONFIG_DRM_AMD_DC_FP)
7726 	/* SST DSC determination policy */
7727 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
7728 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
7729 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
7730 #endif
7731 
7732 	update_stream_scaling_settings(dev, &mode, dm_state, stream);
7733 
7734 	fill_audio_info(
7735 		&stream->audio_info,
7736 		connector,
7737 		sink);
7738 
7739 	update_stream_signal(stream, sink);
7740 
7741 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7742 	    stream->signal == SIGNAL_TYPE_HDMI_FRL)
7743 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket, false, false);
7744 
7745 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT ||
7746 	    stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
7747 	    stream->signal == SIGNAL_TYPE_EDP) {
7748 		const struct dc_edid_caps *edid_caps;
7749 		unsigned int disable_colorimetry = 0;
7750 
7751 		if (aconnector->dc_sink) {
7752 			edid_caps = &aconnector->dc_sink->edid_caps;
7753 			disable_colorimetry = edid_caps->panel_patch.disable_colorimetry;
7754 		}
7755 
7756 		//
7757 		// should decide stream support vsc sdp colorimetry capability
7758 		// before building vsc info packet
7759 		//
7760 		stream->use_vsc_sdp_for_colorimetry = stream->link->dpcd_caps.dpcd_rev.raw >= 0x14 &&
7761 						      stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED &&
7762 						      !disable_colorimetry;
7763 
7764 		if (stream->out_transfer_func.tf == TRANSFER_FUNCTION_GAMMA22)
7765 			tf = TRANSFER_FUNC_GAMMA_22;
7766 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
7767 		aconnector->sr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
7768 
7769 	}
7770 finish:
7771 	dc_sink_release(sink);
7772 
7773 	return stream;
7774 }
7775 
7776 /**
7777  * amdgpu_dm_connector_poll - Poll a connector to see if it's connected to a display
7778  * @aconnector: DM connector to poll (owns @base drm_connector and @dc_link)
7779  * @force: if true, force polling even when DAC load detection was used
7780  *
7781  * Used for connectors that don't support HPD (hotplug detection) to
7782  * periodically check whether the connector is connected to a display.
7783  *
7784  * When connection was determined via DAC load detection, we avoid
7785  * re-running it on normal polls to prevent visible glitches, unless
7786  * @force is set.
7787  *
7788  * Return: The probed connector status (connected/disconnected/unknown).
7789  */
7790 static enum drm_connector_status
7791 amdgpu_dm_connector_poll(struct amdgpu_dm_connector *aconnector, bool force)
7792 {
7793 	struct drm_connector *connector = &aconnector->base;
7794 	struct drm_device *dev = connector->dev;
7795 	struct amdgpu_device *adev = drm_to_adev(dev);
7796 	struct dc_link *link = aconnector->dc_link;
7797 	enum dc_connection_type conn_type = dc_connection_none;
7798 	enum drm_connector_status status = connector_status_disconnected;
7799 
7800 	/* When we determined the connection using DAC load detection,
7801 	 * do NOT poll the connector do detect disconnect because
7802 	 * that would run DAC load detection again which can cause
7803 	 * visible visual glitches.
7804 	 *
7805 	 * Only allow to poll such a connector again when forcing.
7806 	 */
7807 	if (!force && link->local_sink && link->type == dc_connection_analog_load)
7808 		return connector->status;
7809 
7810 	mutex_lock(&aconnector->hpd_lock);
7811 
7812 	if (dc_link_detect_connection_type(aconnector->dc_link, &conn_type) &&
7813 	    conn_type != dc_connection_none) {
7814 		mutex_lock(&adev->dm.dc_lock);
7815 
7816 		/* Only call full link detection when a sink isn't created yet,
7817 		 * ie. just when the display is plugged in, otherwise we risk flickering.
7818 		 */
7819 		if (link->local_sink ||
7820 			dc_link_detect(link, DETECT_REASON_HPD))
7821 			status = connector_status_connected;
7822 
7823 		mutex_unlock(&adev->dm.dc_lock);
7824 	}
7825 
7826 	if (connector->status != status) {
7827 		if (status == connector_status_disconnected) {
7828 			if (link->local_sink)
7829 				dc_sink_release(link->local_sink);
7830 
7831 			link->local_sink = NULL;
7832 			link->dpcd_sink_count = 0;
7833 			link->type = dc_connection_none;
7834 		}
7835 
7836 		amdgpu_dm_update_connector_after_detect(aconnector);
7837 	}
7838 
7839 	mutex_unlock(&aconnector->hpd_lock);
7840 	return status;
7841 }
7842 
7843 /**
7844  * amdgpu_dm_connector_detect() - Detect whether a DRM connector is connected to a display
7845  *
7846  * A connector is considered connected when it has a sink that is not NULL.
7847  * For connectors that support HPD (hotplug detection), the connection is
7848  * handled in the HPD interrupt.
7849  * For connectors that may not support HPD, such as analog connectors,
7850  * DRM will call this function repeatedly to poll them.
7851  *
7852  * Notes:
7853  * 1. This interface is NOT called in context of HPD irq.
7854  * 2. This interface *is called* in context of user-mode ioctl. Which
7855  *    makes it a bad place for *any* MST-related activity.
7856  *
7857  * @connector: The DRM connector we are checking. We convert it to
7858  *             amdgpu_dm_connector so we can read the DC link and state.
7859  * @force:     If true, do a full detect again. This is used even when
7860  *             a lighter check would normally be used to avoid flicker.
7861  *
7862  * Return: The connector status (connected, disconnected, or unknown).
7863  *
7864  */
7865 static enum drm_connector_status
7866 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
7867 {
7868 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7869 
7870 	update_subconnector_property(aconnector);
7871 
7872 	if (aconnector->base.force == DRM_FORCE_ON ||
7873 		aconnector->base.force == DRM_FORCE_ON_DIGITAL)
7874 		return connector_status_connected;
7875 	else if (aconnector->base.force == DRM_FORCE_OFF)
7876 		return connector_status_disconnected;
7877 
7878 	/* Poll analog connectors and only when either
7879 	 * disconnected or connected to an analog display.
7880 	 */
7881 	if (drm_kms_helper_is_poll_worker() &&
7882 		dc_connector_supports_analog(aconnector->dc_link->link_id.id) &&
7883 		(!aconnector->dc_sink || aconnector->dc_sink->edid_caps.analog))
7884 		return amdgpu_dm_connector_poll(aconnector, force);
7885 
7886 	return (aconnector->dc_sink ? connector_status_connected :
7887 			connector_status_disconnected);
7888 }
7889 
7890 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
7891 					    struct drm_connector_state *connector_state,
7892 					    struct drm_property *property,
7893 					    uint64_t val)
7894 {
7895 	struct drm_device *dev = connector->dev;
7896 	struct amdgpu_device *adev = drm_to_adev(dev);
7897 	struct dm_connector_state *dm_old_state =
7898 		to_dm_connector_state(connector->state);
7899 	struct dm_connector_state *dm_new_state =
7900 		to_dm_connector_state(connector_state);
7901 
7902 	int ret = -EINVAL;
7903 
7904 	if (property == dev->mode_config.scaling_mode_property) {
7905 		enum amdgpu_rmx_type rmx_type;
7906 
7907 		switch (val) {
7908 		case DRM_MODE_SCALE_CENTER:
7909 			rmx_type = RMX_CENTER;
7910 			break;
7911 		case DRM_MODE_SCALE_ASPECT:
7912 			rmx_type = RMX_ASPECT;
7913 			break;
7914 		case DRM_MODE_SCALE_FULLSCREEN:
7915 			rmx_type = RMX_FULL;
7916 			break;
7917 		case DRM_MODE_SCALE_NONE:
7918 		default:
7919 			rmx_type = RMX_OFF;
7920 			break;
7921 		}
7922 
7923 		if (dm_old_state->scaling == rmx_type)
7924 			return 0;
7925 
7926 		dm_new_state->scaling = rmx_type;
7927 		ret = 0;
7928 	} else if (property == adev->mode_info.underscan_hborder_property) {
7929 		dm_new_state->underscan_hborder = val;
7930 		ret = 0;
7931 	} else if (property == adev->mode_info.underscan_vborder_property) {
7932 		dm_new_state->underscan_vborder = val;
7933 		ret = 0;
7934 	} else if (property == adev->mode_info.underscan_property) {
7935 		dm_new_state->underscan_enable = val;
7936 		ret = 0;
7937 	} else if (property == adev->mode_info.abm_level_property) {
7938 		switch (val) {
7939 		case ABM_SYSFS_CONTROL:
7940 			dm_new_state->abm_sysfs_forbidden = false;
7941 			break;
7942 		case ABM_LEVEL_OFF:
7943 			dm_new_state->abm_sysfs_forbidden = true;
7944 			dm_new_state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7945 			break;
7946 		default:
7947 			dm_new_state->abm_sysfs_forbidden = true;
7948 			dm_new_state->abm_level = val;
7949 		}
7950 		ret = 0;
7951 	}
7952 
7953 	return ret;
7954 }
7955 
7956 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
7957 					    const struct drm_connector_state *state,
7958 					    struct drm_property *property,
7959 					    uint64_t *val)
7960 {
7961 	struct drm_device *dev = connector->dev;
7962 	struct amdgpu_device *adev = drm_to_adev(dev);
7963 	struct dm_connector_state *dm_state =
7964 		to_dm_connector_state(state);
7965 	int ret = -EINVAL;
7966 
7967 	if (property == dev->mode_config.scaling_mode_property) {
7968 		switch (dm_state->scaling) {
7969 		case RMX_CENTER:
7970 			*val = DRM_MODE_SCALE_CENTER;
7971 			break;
7972 		case RMX_ASPECT:
7973 			*val = DRM_MODE_SCALE_ASPECT;
7974 			break;
7975 		case RMX_FULL:
7976 			*val = DRM_MODE_SCALE_FULLSCREEN;
7977 			break;
7978 		case RMX_OFF:
7979 		default:
7980 			*val = DRM_MODE_SCALE_NONE;
7981 			break;
7982 		}
7983 		ret = 0;
7984 	} else if (property == adev->mode_info.underscan_hborder_property) {
7985 		*val = dm_state->underscan_hborder;
7986 		ret = 0;
7987 	} else if (property == adev->mode_info.underscan_vborder_property) {
7988 		*val = dm_state->underscan_vborder;
7989 		ret = 0;
7990 	} else if (property == adev->mode_info.underscan_property) {
7991 		*val = dm_state->underscan_enable;
7992 		ret = 0;
7993 	} else if (property == adev->mode_info.abm_level_property) {
7994 		if (!dm_state->abm_sysfs_forbidden)
7995 			*val = ABM_SYSFS_CONTROL;
7996 		else
7997 			*val = (dm_state->abm_level != ABM_LEVEL_IMMEDIATE_DISABLE) ?
7998 				dm_state->abm_level : 0;
7999 		ret = 0;
8000 	}
8001 
8002 	return ret;
8003 }
8004 
8005 /**
8006  * DOC: panel power savings
8007  *
8008  * The display manager allows you to set your desired **panel power savings**
8009  * level (between 0-4, with 0 representing off), e.g. using the following::
8010  *
8011  *   # echo 3 > /sys/class/drm/card0-eDP-1/amdgpu/panel_power_savings
8012  *
8013  * Modifying this value can have implications on color accuracy, so tread
8014  * carefully.
8015  */
8016 
8017 static ssize_t panel_power_savings_show(struct device *device,
8018 					struct device_attribute *attr,
8019 					char *buf)
8020 {
8021 	struct drm_connector *connector = dev_get_drvdata(device);
8022 	struct drm_device *dev = connector->dev;
8023 	u8 val;
8024 
8025 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
8026 	val = to_dm_connector_state(connector->state)->abm_level ==
8027 		ABM_LEVEL_IMMEDIATE_DISABLE ? 0 :
8028 		to_dm_connector_state(connector->state)->abm_level;
8029 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
8030 
8031 	return sysfs_emit(buf, "%u\n", val);
8032 }
8033 
8034 static ssize_t panel_power_savings_store(struct device *device,
8035 					 struct device_attribute *attr,
8036 					 const char *buf, size_t count)
8037 {
8038 	struct drm_connector *connector = dev_get_drvdata(device);
8039 	struct drm_device *dev = connector->dev;
8040 	long val;
8041 	int ret;
8042 
8043 	ret = kstrtol(buf, 0, &val);
8044 
8045 	if (ret)
8046 		return ret;
8047 
8048 	if (val < 0 || val > 4)
8049 		return -EINVAL;
8050 
8051 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
8052 	if (to_dm_connector_state(connector->state)->abm_sysfs_forbidden)
8053 		ret = -EBUSY;
8054 	else
8055 		to_dm_connector_state(connector->state)->abm_level = val ?:
8056 			ABM_LEVEL_IMMEDIATE_DISABLE;
8057 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
8058 
8059 	if (ret)
8060 		return ret;
8061 
8062 	drm_kms_helper_hotplug_event(dev);
8063 
8064 	return count;
8065 }
8066 
8067 static DEVICE_ATTR_RW(panel_power_savings);
8068 
8069 static struct attribute *amdgpu_attrs[] = {
8070 	&dev_attr_panel_power_savings.attr,
8071 	NULL
8072 };
8073 
8074 static const struct attribute_group amdgpu_group = {
8075 	.name = "amdgpu",
8076 	.attrs = amdgpu_attrs
8077 };
8078 
8079 static bool
8080 amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector *amdgpu_dm_connector)
8081 {
8082 	if (amdgpu_dm_abm_level >= 0)
8083 		return false;
8084 
8085 	if (amdgpu_dm_connector->base.connector_type != DRM_MODE_CONNECTOR_eDP)
8086 		return false;
8087 
8088 	/* check for OLED panels */
8089 	if (amdgpu_dm_connector->bl_idx >= 0) {
8090 		struct drm_device *drm = amdgpu_dm_connector->base.dev;
8091 		struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
8092 		struct amdgpu_dm_backlight_caps *caps;
8093 
8094 		caps = &dm->backlight_caps[amdgpu_dm_connector->bl_idx];
8095 		if (caps->aux_support)
8096 			return false;
8097 	}
8098 
8099 	return true;
8100 }
8101 
8102 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
8103 {
8104 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
8105 
8106 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector))
8107 		sysfs_remove_group(&connector->kdev->kobj, &amdgpu_group);
8108 
8109 	cec_notifier_conn_unregister(amdgpu_dm_connector->notifier);
8110 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
8111 }
8112 
8113 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
8114 {
8115 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8116 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8117 	struct amdgpu_display_manager *dm = &adev->dm;
8118 
8119 	/*
8120 	 * Call only if mst_mgr was initialized before since it's not done
8121 	 * for all connector types.
8122 	 */
8123 	if (aconnector->mst_mgr.dev)
8124 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
8125 
8126 	/* Cancel and flush any pending HDMI HPD debounce work */
8127 	if (aconnector->hdmi_hpd_debounce_delay_ms) {
8128 		cancel_delayed_work_sync(&aconnector->hdmi_hpd_debounce_work);
8129 		if (aconnector->hdmi_prev_sink) {
8130 			dc_sink_release(aconnector->hdmi_prev_sink);
8131 			aconnector->hdmi_prev_sink = NULL;
8132 		}
8133 	}
8134 
8135 	if (aconnector->bl_idx != -1) {
8136 		backlight_device_unregister(dm->backlight_dev[aconnector->bl_idx]);
8137 		dm->backlight_dev[aconnector->bl_idx] = NULL;
8138 	}
8139 
8140 	if (aconnector->dc_em_sink)
8141 		dc_sink_release(aconnector->dc_em_sink);
8142 	aconnector->dc_em_sink = NULL;
8143 	if (aconnector->dc_sink)
8144 		dc_sink_release(aconnector->dc_sink);
8145 	aconnector->dc_sink = NULL;
8146 
8147 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
8148 	drm_connector_unregister(connector);
8149 	drm_connector_cleanup(connector);
8150 	kfree(aconnector->dm_dp_aux.aux.name);
8151 
8152 	kfree(connector);
8153 }
8154 
8155 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
8156 {
8157 	struct dm_connector_state *state =
8158 		to_dm_connector_state(connector->state);
8159 
8160 	if (connector->state)
8161 		__drm_atomic_helper_connector_destroy_state(connector->state);
8162 
8163 	kfree(state);
8164 
8165 	state = kzalloc_obj(*state);
8166 
8167 	if (state) {
8168 		state->scaling = RMX_OFF;
8169 		state->underscan_enable = false;
8170 		state->underscan_hborder = 0;
8171 		state->underscan_vborder = 0;
8172 		state->base.max_requested_bpc = 8;
8173 		state->vcpi_slots = 0;
8174 		state->pbn = 0;
8175 
8176 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) {
8177 			if (amdgpu_dm_abm_level <= 0)
8178 				state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
8179 			else
8180 				state->abm_level = amdgpu_dm_abm_level;
8181 		}
8182 
8183 		__drm_atomic_helper_connector_reset(connector, &state->base);
8184 	}
8185 }
8186 
8187 struct drm_connector_state *
8188 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
8189 {
8190 	struct dm_connector_state *state =
8191 		to_dm_connector_state(connector->state);
8192 
8193 	struct dm_connector_state *new_state =
8194 			kmemdup(state, sizeof(*state), GFP_KERNEL);
8195 
8196 	if (!new_state)
8197 		return NULL;
8198 
8199 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
8200 
8201 	new_state->freesync_capable = state->freesync_capable;
8202 	new_state->abm_level = state->abm_level;
8203 	new_state->scaling = state->scaling;
8204 	new_state->underscan_enable = state->underscan_enable;
8205 	new_state->underscan_hborder = state->underscan_hborder;
8206 	new_state->underscan_vborder = state->underscan_vborder;
8207 	new_state->vcpi_slots = state->vcpi_slots;
8208 	new_state->pbn = state->pbn;
8209 	return &new_state->base;
8210 }
8211 
8212 static int
8213 amdgpu_dm_connector_late_register(struct drm_connector *connector)
8214 {
8215 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8216 		to_amdgpu_dm_connector(connector);
8217 	int r;
8218 
8219 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector)) {
8220 		r = sysfs_create_group(&connector->kdev->kobj,
8221 				       &amdgpu_group);
8222 		if (r)
8223 			return r;
8224 	}
8225 
8226 	amdgpu_dm_register_backlight_device(amdgpu_dm_connector);
8227 
8228 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
8229 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
8230 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
8231 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
8232 		if (r)
8233 			return r;
8234 	}
8235 
8236 #if defined(CONFIG_DEBUG_FS)
8237 	connector_debugfs_init(amdgpu_dm_connector);
8238 #endif
8239 
8240 	return 0;
8241 }
8242 
8243 static void amdgpu_dm_connector_funcs_force(struct drm_connector *connector)
8244 {
8245 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8246 	struct dc_link *dc_link = aconnector->dc_link;
8247 	struct dc_sink *dc_em_sink = aconnector->dc_em_sink;
8248 	const struct drm_edid *drm_edid;
8249 	struct i2c_adapter *ddc;
8250 	struct drm_device *dev = connector->dev;
8251 
8252 	if (dc_link && dc_link->aux_mode)
8253 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8254 	else
8255 		ddc = &aconnector->i2c->base;
8256 
8257 	drm_edid = drm_edid_read_ddc(connector, ddc);
8258 	drm_edid_connector_update(connector, drm_edid);
8259 	if (!drm_edid) {
8260 		drm_err(dev, "No EDID found on connector: %s.\n", connector->name);
8261 		return;
8262 	}
8263 
8264 	aconnector->drm_edid = drm_edid;
8265 	/* Update emulated (virtual) sink's EDID */
8266 	if (dc_em_sink && dc_link) {
8267 		// FIXME: Get rid of drm_edid_raw()
8268 		const struct edid *edid = drm_edid_raw(drm_edid);
8269 
8270 		memset(&dc_em_sink->edid_caps, 0, sizeof(struct dc_edid_caps));
8271 		memmove(dc_em_sink->dc_edid.raw_edid, edid,
8272 			(edid->extensions + 1) * EDID_LENGTH);
8273 		dm_helpers_parse_edid_caps(
8274 			dc_link,
8275 			&dc_em_sink->dc_edid,
8276 			&dc_em_sink->edid_caps);
8277 	}
8278 }
8279 
8280 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
8281 	.reset = amdgpu_dm_connector_funcs_reset,
8282 	.detect = amdgpu_dm_connector_detect,
8283 	.fill_modes = drm_helper_probe_single_connector_modes,
8284 	.destroy = amdgpu_dm_connector_destroy,
8285 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
8286 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
8287 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
8288 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
8289 	.late_register = amdgpu_dm_connector_late_register,
8290 	.early_unregister = amdgpu_dm_connector_unregister,
8291 	.force = amdgpu_dm_connector_funcs_force
8292 };
8293 
8294 static int get_modes(struct drm_connector *connector)
8295 {
8296 	return amdgpu_dm_connector_get_modes(connector);
8297 }
8298 
8299 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
8300 {
8301 	struct drm_connector *connector = &aconnector->base;
8302 	struct dc_link *dc_link = aconnector->dc_link;
8303 	struct dc_sink_init_data init_params = {
8304 			.link = aconnector->dc_link,
8305 			.sink_signal = SIGNAL_TYPE_VIRTUAL
8306 	};
8307 	const struct drm_edid *drm_edid;
8308 	const struct edid *edid;
8309 	struct i2c_adapter *ddc;
8310 
8311 	if (dc_link && dc_link->aux_mode)
8312 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8313 	else
8314 		ddc = &aconnector->i2c->base;
8315 
8316 	drm_edid = drm_edid_read_ddc(connector, ddc);
8317 	drm_edid_connector_update(connector, drm_edid);
8318 	if (!drm_edid) {
8319 		drm_err(connector->dev, "No EDID found on connector: %s.\n", connector->name);
8320 		return;
8321 	}
8322 
8323 	if (connector->display_info.is_hdmi)
8324 		init_params.sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
8325 
8326 	aconnector->drm_edid = drm_edid;
8327 
8328 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
8329 	aconnector->dc_em_sink = dc_link_add_remote_sink(
8330 		aconnector->dc_link,
8331 		(uint8_t *)edid,
8332 		(edid->extensions + 1) * EDID_LENGTH,
8333 		&init_params);
8334 
8335 	if (aconnector->base.force == DRM_FORCE_ON) {
8336 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
8337 		aconnector->dc_link->local_sink :
8338 		aconnector->dc_em_sink;
8339 		if (aconnector->dc_sink)
8340 			dc_sink_retain(aconnector->dc_sink);
8341 	}
8342 }
8343 
8344 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
8345 {
8346 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
8347 
8348 	/*
8349 	 * In case of headless boot with force on for DP managed connector
8350 	 * Those settings have to be != 0 to get initial modeset
8351 	 */
8352 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
8353 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
8354 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
8355 	}
8356 
8357 	create_eml_sink(aconnector);
8358 }
8359 
8360 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
8361 						struct dc_stream_state *stream)
8362 {
8363 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
8364 	struct dc_plane_state *dc_plane_state = NULL;
8365 	struct dc_state *dc_state = NULL;
8366 
8367 	if (!stream)
8368 		goto cleanup;
8369 
8370 	dc_plane_state = dc_create_plane_state(dc);
8371 	if (!dc_plane_state)
8372 		goto cleanup;
8373 
8374 	dc_state = dc_state_create(dc, NULL);
8375 	if (!dc_state)
8376 		goto cleanup;
8377 
8378 	/* populate stream to plane */
8379 	dc_plane_state->src_rect.height  = stream->src.height;
8380 	dc_plane_state->src_rect.width   = stream->src.width;
8381 	dc_plane_state->dst_rect.height  = stream->src.height;
8382 	dc_plane_state->dst_rect.width   = stream->src.width;
8383 	dc_plane_state->clip_rect.height = stream->src.height;
8384 	dc_plane_state->clip_rect.width  = stream->src.width;
8385 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
8386 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
8387 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
8388 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
8389 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
8390 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
8391 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
8392 	dc_plane_state->rotation = ROTATION_ANGLE_0;
8393 	dc_plane_state->is_tiling_rotated = false;
8394 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
8395 
8396 	dc_result = dc_validate_stream(dc, stream);
8397 	if (dc_result == DC_OK)
8398 		dc_result = dc_validate_plane(dc, dc_plane_state);
8399 
8400 	if (dc_result == DC_OK)
8401 		dc_result = dc_state_add_stream(dc, dc_state, stream);
8402 
8403 	if (dc_result == DC_OK && !dc_state_add_plane(
8404 						dc,
8405 						stream,
8406 						dc_plane_state,
8407 						dc_state))
8408 		dc_result = DC_FAIL_ATTACH_SURFACES;
8409 
8410 	if (dc_result == DC_OK)
8411 		dc_result = dc_validate_global_state(dc, dc_state, DC_VALIDATE_MODE_ONLY);
8412 
8413 cleanup:
8414 	if (dc_state)
8415 		dc_state_release(dc_state);
8416 
8417 	if (dc_plane_state)
8418 		dc_plane_state_release(dc_plane_state);
8419 
8420 	return dc_result;
8421 }
8422 
8423 struct dc_stream_state *
8424 create_validate_stream_for_sink(struct drm_connector *connector,
8425 				const struct drm_display_mode *drm_mode,
8426 				const struct dm_connector_state *dm_state,
8427 				const struct dc_stream_state *old_stream)
8428 {
8429 	struct amdgpu_dm_connector *aconnector = NULL;
8430 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8431 	struct dc_stream_state *stream;
8432 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
8433 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
8434 	enum dc_status dc_result = DC_OK;
8435 	uint8_t bpc_limit = 6;
8436 
8437 	if (!dm_state)
8438 		return NULL;
8439 
8440 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
8441 		aconnector = to_amdgpu_dm_connector(connector);
8442 
8443 	if (aconnector &&
8444 	    (aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
8445 	     aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_FRL ||
8446 	     aconnector->dc_link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER))
8447 		bpc_limit = 8;
8448 
8449 	do {
8450 		drm_dbg_kms(connector->dev, "Trying with %d bpc\n", requested_bpc);
8451 		stream = create_stream_for_sink(connector, drm_mode,
8452 						dm_state, old_stream,
8453 						requested_bpc);
8454 		if (stream == NULL) {
8455 			drm_err(adev_to_drm(adev), "Failed to create stream for sink!\n");
8456 			break;
8457 		}
8458 
8459 		dc_result = dc_validate_stream(adev->dm.dc, stream);
8460 
8461 		if (!aconnector) /* writeback connector */
8462 			return stream;
8463 
8464 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
8465 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
8466 
8467 		if (dc_result == DC_OK)
8468 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
8469 
8470 		if (dc_result != DC_OK) {
8471 			drm_dbg_kms(connector->dev, "Pruned mode %d x %d (clk %d) %s %s -- %s\n",
8472 				      drm_mode->hdisplay,
8473 				      drm_mode->vdisplay,
8474 				      drm_mode->clock,
8475 				      dc_pixel_encoding_to_str(stream->timing.pixel_encoding),
8476 				      dc_color_depth_to_str(stream->timing.display_color_depth),
8477 				      dc_status_to_str(dc_result));
8478 
8479 			dc_stream_release(stream);
8480 			stream = NULL;
8481 			requested_bpc -= 2; /* lower bpc to retry validation */
8482 		}
8483 
8484 	} while (stream == NULL && requested_bpc >= bpc_limit);
8485 
8486 	switch (dc_result) {
8487 	/*
8488 	 * If we failed to validate DP bandwidth stream with the requested RGB color depth,
8489 	 * we try to fallback and configure in order:
8490 	 * YUV422 (8bpc, 6bpc)
8491 	 * YUV420 (8bpc, 6bpc)
8492 	 */
8493 	case DC_FAIL_ENC_VALIDATE:
8494 	case DC_EXCEED_DONGLE_CAP:
8495 	case DC_NO_DP_LINK_BANDWIDTH:
8496 		/* recursively entered twice and already tried both YUV422 and YUV420 */
8497 		if (aconnector->force_yuv422_output && aconnector->force_yuv420_output)
8498 			break;
8499 		/* first failure; try YUV422 */
8500 		if (!aconnector->force_yuv422_output) {
8501 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV422\n",
8502 				    __func__, __LINE__, dc_result);
8503 			aconnector->force_yuv422_output = true;
8504 		/* recursively entered and YUV422 failed, try YUV420 */
8505 		} else if (!aconnector->force_yuv420_output) {
8506 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV420\n",
8507 				    __func__, __LINE__, dc_result);
8508 			aconnector->force_yuv420_output = true;
8509 		}
8510 		stream = create_validate_stream_for_sink(connector, drm_mode,
8511 							 dm_state, old_stream);
8512 		aconnector->force_yuv422_output = false;
8513 		aconnector->force_yuv420_output = false;
8514 		break;
8515 	case DC_OK:
8516 		break;
8517 	default:
8518 		drm_dbg_kms(connector->dev, "%s:%d Unhandled validation failure %d\n",
8519 			    __func__, __LINE__, dc_result);
8520 		break;
8521 	}
8522 
8523 	return stream;
8524 }
8525 
8526 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
8527 				   const struct drm_display_mode *mode)
8528 {
8529 	int result = MODE_ERROR;
8530 	struct dc_sink *dc_sink;
8531 	struct drm_display_mode *test_mode;
8532 	/* TODO: Unhardcode stream count */
8533 	struct dc_stream_state *stream;
8534 	/* we always have an amdgpu_dm_connector here since we got
8535 	 * here via the amdgpu_dm_connector_helper_funcs
8536 	 */
8537 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8538 
8539 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
8540 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
8541 		return result;
8542 
8543 	/*
8544 	 * Only run this the first time mode_valid is called to initilialize
8545 	 * EDID mgmt
8546 	 */
8547 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
8548 		!aconnector->dc_em_sink)
8549 		handle_edid_mgmt(aconnector);
8550 
8551 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
8552 
8553 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
8554 				aconnector->base.force != DRM_FORCE_ON) {
8555 		drm_err(connector->dev, "dc_sink is NULL!\n");
8556 		goto fail;
8557 	}
8558 
8559 	test_mode = drm_mode_duplicate(connector->dev, mode);
8560 	if (!test_mode)
8561 		goto fail;
8562 
8563 	drm_mode_set_crtcinfo(test_mode, 0);
8564 
8565 	stream = create_validate_stream_for_sink(connector, test_mode,
8566 						 to_dm_connector_state(connector->state),
8567 						 NULL);
8568 	drm_mode_destroy(connector->dev, test_mode);
8569 	if (stream) {
8570 		dc_stream_release(stream);
8571 		result = MODE_OK;
8572 	}
8573 
8574 fail:
8575 	/* TODO: error handling*/
8576 	return result;
8577 }
8578 
8579 static int fill_hdr_info_packet(const struct drm_connector_state *state,
8580 				struct dc_info_packet *out)
8581 {
8582 	struct hdmi_drm_infoframe frame;
8583 	unsigned char buf[30]; /* 26 + 4 */
8584 	ssize_t len;
8585 	int ret, i;
8586 
8587 	memset(out, 0, sizeof(*out));
8588 
8589 	if (!state->hdr_output_metadata)
8590 		return 0;
8591 
8592 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
8593 	if (ret)
8594 		return ret;
8595 
8596 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
8597 	if (len < 0)
8598 		return (int)len;
8599 
8600 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
8601 	if (len != 30)
8602 		return -EINVAL;
8603 
8604 	/* Prepare the infopacket for DC. */
8605 	switch (state->connector->connector_type) {
8606 	case DRM_MODE_CONNECTOR_HDMIA:
8607 		out->hb0 = 0x87; /* type */
8608 		out->hb1 = 0x01; /* version */
8609 		out->hb2 = 0x1A; /* length */
8610 		out->sb[0] = buf[3]; /* checksum */
8611 		i = 1;
8612 		break;
8613 
8614 	case DRM_MODE_CONNECTOR_DisplayPort:
8615 	case DRM_MODE_CONNECTOR_eDP:
8616 		out->hb0 = 0x00; /* sdp id, zero */
8617 		out->hb1 = 0x87; /* type */
8618 		out->hb2 = 0x1D; /* payload len - 1 */
8619 		out->hb3 = (0x13 << 2); /* sdp version */
8620 		out->sb[0] = 0x01; /* version */
8621 		out->sb[1] = 0x1A; /* length */
8622 		i = 2;
8623 		break;
8624 
8625 	default:
8626 		return -EINVAL;
8627 	}
8628 
8629 	memcpy(&out->sb[i], &buf[4], 26);
8630 	out->valid = true;
8631 
8632 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
8633 		       sizeof(out->sb), false);
8634 
8635 	return 0;
8636 }
8637 
8638 static int
8639 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
8640 				 struct drm_atomic_commit *state)
8641 {
8642 	struct drm_connector_state *new_con_state =
8643 		drm_atomic_get_new_connector_state(state, conn);
8644 	struct drm_connector_state *old_con_state =
8645 		drm_atomic_get_old_connector_state(state, conn);
8646 	struct drm_crtc *crtc = new_con_state->crtc;
8647 	struct drm_crtc_state *new_crtc_state;
8648 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
8649 	int ret;
8650 
8651 	if (WARN_ON(unlikely(!old_con_state || !new_con_state)))
8652 		return -EINVAL;
8653 
8654 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
8655 
8656 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
8657 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
8658 		if (ret < 0)
8659 			return ret;
8660 	}
8661 
8662 	if (!crtc)
8663 		return 0;
8664 
8665 	if (new_con_state->privacy_screen_sw_state != old_con_state->privacy_screen_sw_state) {
8666 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8667 		if (IS_ERR(new_crtc_state))
8668 			return PTR_ERR(new_crtc_state);
8669 
8670 		new_crtc_state->mode_changed = true;
8671 	}
8672 
8673 	if (new_con_state->colorspace != old_con_state->colorspace) {
8674 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8675 		if (IS_ERR(new_crtc_state))
8676 			return PTR_ERR(new_crtc_state);
8677 
8678 		new_crtc_state->mode_changed = true;
8679 	}
8680 
8681 	if (new_con_state->content_type != old_con_state->content_type) {
8682 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8683 		if (IS_ERR(new_crtc_state))
8684 			return PTR_ERR(new_crtc_state);
8685 
8686 		new_crtc_state->mode_changed = true;
8687 	}
8688 
8689 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
8690 		struct dc_info_packet hdr_infopacket;
8691 
8692 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
8693 		if (ret)
8694 			return ret;
8695 
8696 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8697 		if (IS_ERR(new_crtc_state))
8698 			return PTR_ERR(new_crtc_state);
8699 
8700 		/*
8701 		 * DC considers the stream backends changed if the
8702 		 * static metadata changes. Forcing the modeset also
8703 		 * gives a simple way for userspace to switch from
8704 		 * 8bpc to 10bpc when setting the metadata to enter
8705 		 * or exit HDR.
8706 		 *
8707 		 * Changing the static metadata after it's been
8708 		 * set is permissible, however. So only force a
8709 		 * modeset if we're entering or exiting HDR.
8710 		 */
8711 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
8712 			!old_con_state->hdr_output_metadata ||
8713 			!new_con_state->hdr_output_metadata;
8714 	}
8715 
8716 	return 0;
8717 }
8718 
8719 static const struct drm_connector_helper_funcs
8720 amdgpu_dm_connector_helper_funcs = {
8721 	/*
8722 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
8723 	 * modes will be filtered by drm_mode_validate_size(), and those modes
8724 	 * are missing after user start lightdm. So we need to renew modes list.
8725 	 * in get_modes call back, not just return the modes count
8726 	 */
8727 	.get_modes = get_modes,
8728 	.mode_valid = amdgpu_dm_connector_mode_valid,
8729 	.atomic_check = amdgpu_dm_connector_atomic_check,
8730 };
8731 
8732 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
8733 {
8734 
8735 }
8736 
8737 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
8738 {
8739 	switch (display_color_depth) {
8740 	case COLOR_DEPTH_666:
8741 		return 6;
8742 	case COLOR_DEPTH_888:
8743 		return 8;
8744 	case COLOR_DEPTH_101010:
8745 		return 10;
8746 	case COLOR_DEPTH_121212:
8747 		return 12;
8748 	case COLOR_DEPTH_141414:
8749 		return 14;
8750 	case COLOR_DEPTH_161616:
8751 		return 16;
8752 	default:
8753 		break;
8754 	}
8755 	return 0;
8756 }
8757 
8758 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
8759 					  struct drm_crtc_state *crtc_state,
8760 					  struct drm_connector_state *conn_state)
8761 {
8762 	struct drm_atomic_commit *state = crtc_state->state;
8763 	struct drm_connector *connector = conn_state->connector;
8764 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8765 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
8766 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
8767 	struct drm_dp_mst_topology_mgr *mst_mgr;
8768 	struct drm_dp_mst_port *mst_port;
8769 	struct drm_dp_mst_topology_state *mst_state;
8770 	enum dc_color_depth color_depth;
8771 	int clock, bpp = 0;
8772 	bool is_y420 = false;
8773 
8774 	if ((connector->connector_type == DRM_MODE_CONNECTOR_eDP) ||
8775 	    (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)) {
8776 		struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8777 		struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8778 		enum drm_mode_status result;
8779 
8780 		result = drm_crtc_helper_mode_valid_fixed(encoder->crtc, adjusted_mode, native_mode);
8781 		if (result != MODE_OK && dm_new_connector_state->scaling == RMX_OFF) {
8782 			drm_dbg_driver(encoder->dev,
8783 				       "mode %dx%d@%dHz is not native, enabling scaling\n",
8784 				       adjusted_mode->hdisplay, adjusted_mode->vdisplay,
8785 				       drm_mode_vrefresh(adjusted_mode));
8786 			dm_new_connector_state->scaling = RMX_ASPECT;
8787 		}
8788 		return 0;
8789 	}
8790 
8791 	if (!aconnector->mst_output_port)
8792 		return 0;
8793 
8794 	mst_port = aconnector->mst_output_port;
8795 	mst_mgr = &aconnector->mst_root->mst_mgr;
8796 
8797 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
8798 		return 0;
8799 
8800 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
8801 	if (IS_ERR(mst_state))
8802 		return PTR_ERR(mst_state);
8803 
8804 	mst_state->pbn_div.full = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
8805 
8806 	if (!state->duplicated) {
8807 		int max_bpc = conn_state->max_requested_bpc;
8808 
8809 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
8810 			  aconnector->force_yuv420_output;
8811 		color_depth = convert_color_depth_from_display_info(connector,
8812 								    is_y420,
8813 								    max_bpc);
8814 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
8815 		clock = adjusted_mode->clock;
8816 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
8817 	}
8818 
8819 	dm_new_connector_state->vcpi_slots =
8820 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
8821 					      dm_new_connector_state->pbn);
8822 	if (dm_new_connector_state->vcpi_slots < 0) {
8823 		drm_dbg_atomic(connector->dev, "failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
8824 		return dm_new_connector_state->vcpi_slots;
8825 	}
8826 	return 0;
8827 }
8828 
8829 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
8830 	.disable = dm_encoder_helper_disable,
8831 	.atomic_check = dm_encoder_helper_atomic_check
8832 };
8833 
8834 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_commit *state,
8835 					    struct dc_state *dc_state,
8836 					    struct dsc_mst_fairness_vars *vars)
8837 {
8838 	struct dc_stream_state *stream = NULL;
8839 	struct drm_connector *connector;
8840 	struct drm_connector_state *new_con_state;
8841 	struct amdgpu_dm_connector *aconnector;
8842 	struct dm_connector_state *dm_conn_state;
8843 	int i, j, ret;
8844 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
8845 
8846 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8847 
8848 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
8849 			continue;
8850 
8851 		aconnector = to_amdgpu_dm_connector(connector);
8852 
8853 		if (!aconnector->mst_output_port)
8854 			continue;
8855 
8856 		if (!new_con_state || !new_con_state->crtc)
8857 			continue;
8858 
8859 		dm_conn_state = to_dm_connector_state(new_con_state);
8860 
8861 		for (j = 0; j < dc_state->stream_count; j++) {
8862 			stream = dc_state->streams[j];
8863 			if (!stream)
8864 				continue;
8865 
8866 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
8867 				break;
8868 
8869 			stream = NULL;
8870 		}
8871 
8872 		if (!stream)
8873 			continue;
8874 
8875 		pbn_div = dm_mst_get_pbn_divider(stream->link);
8876 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
8877 		for (j = 0; j < dc_state->stream_count; j++) {
8878 			if (vars[j].aconnector == aconnector) {
8879 				pbn = vars[j].pbn;
8880 				break;
8881 			}
8882 		}
8883 
8884 		if (j == dc_state->stream_count || pbn_div == 0)
8885 			continue;
8886 
8887 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
8888 
8889 		if (stream->timing.flags.DSC != 1) {
8890 			dm_conn_state->pbn = pbn;
8891 			dm_conn_state->vcpi_slots = slot_num;
8892 
8893 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
8894 							   dm_conn_state->pbn, false);
8895 			if (ret < 0)
8896 				return ret;
8897 
8898 			continue;
8899 		}
8900 
8901 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
8902 		if (vcpi < 0)
8903 			return vcpi;
8904 
8905 		dm_conn_state->pbn = pbn;
8906 		dm_conn_state->vcpi_slots = vcpi;
8907 	}
8908 	return 0;
8909 }
8910 
8911 static int to_drm_connector_type(enum signal_type st, uint32_t connector_id)
8912 {
8913 	switch (st) {
8914 	case SIGNAL_TYPE_HDMI_TYPE_A:
8915 		return DRM_MODE_CONNECTOR_HDMIA;
8916 	case SIGNAL_TYPE_EDP:
8917 		return DRM_MODE_CONNECTOR_eDP;
8918 	case SIGNAL_TYPE_LVDS:
8919 		return DRM_MODE_CONNECTOR_LVDS;
8920 	case SIGNAL_TYPE_RGB:
8921 		return DRM_MODE_CONNECTOR_VGA;
8922 	case SIGNAL_TYPE_DISPLAY_PORT:
8923 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
8924 		/* External DP bridges have a different connector type. */
8925 		if (connector_id == CONNECTOR_ID_VGA)
8926 			return DRM_MODE_CONNECTOR_VGA;
8927 		else if (connector_id == CONNECTOR_ID_LVDS)
8928 			return DRM_MODE_CONNECTOR_LVDS;
8929 
8930 		return DRM_MODE_CONNECTOR_DisplayPort;
8931 	case SIGNAL_TYPE_DVI_DUAL_LINK:
8932 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
8933 		if (connector_id == CONNECTOR_ID_SINGLE_LINK_DVII ||
8934 			connector_id == CONNECTOR_ID_DUAL_LINK_DVII)
8935 			return DRM_MODE_CONNECTOR_DVII;
8936 
8937 		return DRM_MODE_CONNECTOR_DVID;
8938 	case SIGNAL_TYPE_VIRTUAL:
8939 		return DRM_MODE_CONNECTOR_VIRTUAL;
8940 
8941 	default:
8942 		return DRM_MODE_CONNECTOR_Unknown;
8943 	}
8944 }
8945 
8946 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
8947 {
8948 	struct drm_encoder *encoder;
8949 
8950 	/* There is only one encoder per connector */
8951 	drm_connector_for_each_possible_encoder(connector, encoder)
8952 		return encoder;
8953 
8954 	return NULL;
8955 }
8956 
8957 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
8958 {
8959 	struct drm_encoder *encoder;
8960 	struct amdgpu_encoder *amdgpu_encoder;
8961 
8962 	encoder = amdgpu_dm_connector_to_encoder(connector);
8963 
8964 	if (encoder == NULL)
8965 		return;
8966 
8967 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8968 
8969 	amdgpu_encoder->native_mode.clock = 0;
8970 
8971 	if (!list_empty(&connector->probed_modes)) {
8972 		struct drm_display_mode *preferred_mode = NULL;
8973 
8974 		list_for_each_entry(preferred_mode,
8975 				    &connector->probed_modes,
8976 				    head) {
8977 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
8978 				amdgpu_encoder->native_mode = *preferred_mode;
8979 
8980 			break;
8981 		}
8982 
8983 	}
8984 }
8985 
8986 static struct drm_display_mode *
8987 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
8988 			     const char *name,
8989 			     int hdisplay, int vdisplay)
8990 {
8991 	struct drm_device *dev = encoder->dev;
8992 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8993 	struct drm_display_mode *mode = NULL;
8994 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8995 
8996 	mode = drm_mode_duplicate(dev, native_mode);
8997 
8998 	if (mode == NULL)
8999 		return NULL;
9000 
9001 	mode->hdisplay = hdisplay;
9002 	mode->vdisplay = vdisplay;
9003 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
9004 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
9005 
9006 	return mode;
9007 
9008 }
9009 
9010 static const struct amdgpu_dm_mode_size {
9011 	char name[DRM_DISPLAY_MODE_LEN];
9012 	int w;
9013 	int h;
9014 } common_modes[] = {
9015 	{  "640x480",  640,  480},
9016 	{  "800x600",  800,  600},
9017 	{ "1024x768", 1024,  768},
9018 	{ "1280x720", 1280,  720},
9019 	{ "1280x800", 1280,  800},
9020 	{"1280x1024", 1280, 1024},
9021 	{ "1440x900", 1440,  900},
9022 	{"1680x1050", 1680, 1050},
9023 	{"1600x1200", 1600, 1200},
9024 	{"1920x1080", 1920, 1080},
9025 	{"1920x1200", 1920, 1200}
9026 };
9027 
9028 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
9029 						 struct drm_connector *connector)
9030 {
9031 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
9032 	struct drm_display_mode *mode = NULL;
9033 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
9034 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9035 				to_amdgpu_dm_connector(connector);
9036 	int i;
9037 	int n;
9038 
9039 	if ((connector->connector_type != DRM_MODE_CONNECTOR_eDP) &&
9040 	    (connector->connector_type != DRM_MODE_CONNECTOR_LVDS))
9041 		return;
9042 
9043 	n = ARRAY_SIZE(common_modes);
9044 
9045 	for (i = 0; i < n; i++) {
9046 		struct drm_display_mode *curmode = NULL;
9047 		bool mode_existed = false;
9048 
9049 		if (common_modes[i].w > native_mode->hdisplay ||
9050 		    common_modes[i].h > native_mode->vdisplay ||
9051 		   (common_modes[i].w == native_mode->hdisplay &&
9052 		    common_modes[i].h == native_mode->vdisplay))
9053 			continue;
9054 
9055 		list_for_each_entry(curmode, &connector->probed_modes, head) {
9056 			if (common_modes[i].w == curmode->hdisplay &&
9057 			    common_modes[i].h == curmode->vdisplay) {
9058 				mode_existed = true;
9059 				break;
9060 			}
9061 		}
9062 
9063 		if (mode_existed)
9064 			continue;
9065 
9066 		mode = amdgpu_dm_create_common_mode(encoder,
9067 				common_modes[i].name, common_modes[i].w,
9068 				common_modes[i].h);
9069 		if (!mode)
9070 			continue;
9071 
9072 		drm_mode_probed_add(connector, mode);
9073 		amdgpu_dm_connector->num_modes++;
9074 	}
9075 }
9076 
9077 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
9078 {
9079 	struct drm_encoder *encoder;
9080 	struct amdgpu_encoder *amdgpu_encoder;
9081 	const struct drm_display_mode *native_mode;
9082 
9083 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
9084 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
9085 		return;
9086 
9087 	mutex_lock(&connector->dev->mode_config.mutex);
9088 	amdgpu_dm_connector_get_modes(connector);
9089 	mutex_unlock(&connector->dev->mode_config.mutex);
9090 
9091 	encoder = amdgpu_dm_connector_to_encoder(connector);
9092 	if (!encoder)
9093 		return;
9094 
9095 	amdgpu_encoder = to_amdgpu_encoder(encoder);
9096 
9097 	native_mode = &amdgpu_encoder->native_mode;
9098 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
9099 		return;
9100 
9101 	drm_connector_set_panel_orientation_with_quirk(connector,
9102 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
9103 						       native_mode->hdisplay,
9104 						       native_mode->vdisplay);
9105 }
9106 
9107 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
9108 					      const struct drm_edid *drm_edid)
9109 {
9110 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9111 			to_amdgpu_dm_connector(connector);
9112 
9113 	if (drm_edid) {
9114 		/* empty probed_modes */
9115 		INIT_LIST_HEAD(&connector->probed_modes);
9116 		amdgpu_dm_connector->num_modes =
9117 				drm_edid_connector_add_modes(connector);
9118 
9119 		/* sorting the probed modes before calling function
9120 		 * amdgpu_dm_get_native_mode() since EDID can have
9121 		 * more than one preferred mode. The modes that are
9122 		 * later in the probed mode list could be of higher
9123 		 * and preferred resolution. For example, 3840x2160
9124 		 * resolution in base EDID preferred timing and 4096x2160
9125 		 * preferred resolution in DID extension block later.
9126 		 */
9127 		drm_mode_sort(&connector->probed_modes);
9128 		amdgpu_dm_get_native_mode(connector);
9129 
9130 		/* Freesync capabilities are reset by calling
9131 		 * drm_edid_connector_add_modes() and need to be
9132 		 * restored here.
9133 		 */
9134 		amdgpu_dm_update_freesync_caps(connector, drm_edid, false);
9135 	} else {
9136 		amdgpu_dm_connector->num_modes = 0;
9137 	}
9138 }
9139 
9140 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
9141 			      struct drm_display_mode *mode)
9142 {
9143 	struct drm_display_mode *m;
9144 
9145 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
9146 		if (drm_mode_equal(m, mode))
9147 			return true;
9148 	}
9149 
9150 	return false;
9151 }
9152 
9153 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
9154 {
9155 	const struct drm_display_mode *m;
9156 	struct drm_display_mode *new_mode;
9157 	uint i;
9158 	u32 new_modes_count = 0;
9159 
9160 	/* Standard FPS values
9161 	 *
9162 	 * 23.976       - TV/NTSC
9163 	 * 24           - Cinema
9164 	 * 25           - TV/PAL
9165 	 * 29.97        - TV/NTSC
9166 	 * 30           - TV/NTSC
9167 	 * 48           - Cinema HFR
9168 	 * 50           - TV/PAL
9169 	 * 60           - Commonly used
9170 	 * 48,72,96,120 - Multiples of 24
9171 	 */
9172 	static const u32 common_rates[] = {
9173 		23976, 24000, 25000, 29970, 30000,
9174 		48000, 50000, 60000, 72000, 96000, 120000
9175 	};
9176 
9177 	/*
9178 	 * Find mode with highest refresh rate with the same resolution
9179 	 * as the preferred mode. Some monitors report a preferred mode
9180 	 * with lower resolution than the highest refresh rate supported.
9181 	 */
9182 
9183 	m = get_highest_refresh_rate_mode(aconnector, true);
9184 	if (!m)
9185 		return 0;
9186 
9187 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
9188 		u64 target_vtotal, target_vtotal_diff;
9189 		u64 num, den;
9190 
9191 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
9192 			continue;
9193 
9194 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
9195 		    common_rates[i] > aconnector->max_vfreq * 1000)
9196 			continue;
9197 
9198 		num = (unsigned long long)m->clock * 1000 * 1000;
9199 		den = common_rates[i] * (unsigned long long)m->htotal;
9200 		target_vtotal = div_u64(num, den);
9201 		target_vtotal_diff = target_vtotal - m->vtotal;
9202 
9203 		/* Check for illegal modes */
9204 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
9205 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
9206 		    m->vtotal + target_vtotal_diff < m->vsync_end)
9207 			continue;
9208 
9209 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
9210 		if (!new_mode)
9211 			goto out;
9212 
9213 		new_mode->vtotal += (u16)target_vtotal_diff;
9214 		new_mode->vsync_start += (u16)target_vtotal_diff;
9215 		new_mode->vsync_end += (u16)target_vtotal_diff;
9216 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
9217 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
9218 
9219 		if (!is_duplicate_mode(aconnector, new_mode)) {
9220 			drm_mode_probed_add(&aconnector->base, new_mode);
9221 			new_modes_count += 1;
9222 		} else
9223 			drm_mode_destroy(aconnector->base.dev, new_mode);
9224 	}
9225  out:
9226 	return new_modes_count;
9227 }
9228 
9229 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
9230 						   const struct drm_edid *drm_edid)
9231 {
9232 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9233 		to_amdgpu_dm_connector(connector);
9234 
9235 	if (!(amdgpu_freesync_vid_mode && drm_edid))
9236 		return;
9237 
9238 	if (!amdgpu_dm_connector->dc_sink || !amdgpu_dm_connector->dc_link)
9239 		return;
9240 
9241 	if (!dc_supports_vrr(amdgpu_dm_connector->dc_sink->ctx->dce_version))
9242 		return;
9243 
9244 	if (dc_connector_supports_analog(amdgpu_dm_connector->dc_link->link_id.id) &&
9245 	    amdgpu_dm_connector->dc_sink->edid_caps.analog)
9246 		return;
9247 
9248 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
9249 		amdgpu_dm_connector->num_modes +=
9250 			add_fs_modes(amdgpu_dm_connector);
9251 }
9252 
9253 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
9254 {
9255 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9256 			to_amdgpu_dm_connector(connector);
9257 	struct dc_link *dc_link = amdgpu_dm_connector->dc_link;
9258 	struct drm_encoder *encoder;
9259 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
9260 	struct dc_link_settings *verified_link_cap = &dc_link->verified_link_cap;
9261 	const struct dc *dc = dc_link->dc;
9262 
9263 	encoder = amdgpu_dm_connector_to_encoder(connector);
9264 
9265 	if (!drm_edid) {
9266 		amdgpu_dm_connector->num_modes =
9267 				drm_add_modes_noedid(connector, 640, 480);
9268 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
9269 			amdgpu_dm_connector->num_modes +=
9270 				drm_add_modes_noedid(connector, 1920, 1080);
9271 
9272 		if (amdgpu_dm_connector->dc_sink &&
9273 		    amdgpu_dm_connector->dc_sink->edid_caps.analog &&
9274 		    dc_connector_supports_analog(dc_link->link_id.id)) {
9275 			/* Analog monitor connected by DAC load detection.
9276 			 * Add common modes. It will be up to the user to select one that works.
9277 			 */
9278 			for (int i = 0; i < ARRAY_SIZE(common_modes); i++)
9279 				amdgpu_dm_connector->num_modes += drm_add_modes_noedid(
9280 					connector, common_modes[i].w, common_modes[i].h);
9281 		}
9282 	} else {
9283 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
9284 		if (encoder)
9285 			amdgpu_dm_connector_add_common_modes(encoder, connector);
9286 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
9287 	}
9288 	amdgpu_dm_fbc_init(connector);
9289 
9290 	return amdgpu_dm_connector->num_modes;
9291 }
9292 
9293 static const u32 supported_colorspaces =
9294 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
9295 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
9296 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
9297 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
9298 
9299 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
9300 				     struct amdgpu_dm_connector *aconnector,
9301 				     int connector_type,
9302 				     struct dc_link *link,
9303 				     int link_index)
9304 {
9305 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
9306 
9307 	/*
9308 	 * Some of the properties below require access to state, like bpc.
9309 	 * Allocate some default initial connector state with our reset helper.
9310 	 */
9311 	if (aconnector->base.funcs->reset)
9312 		aconnector->base.funcs->reset(&aconnector->base);
9313 
9314 	aconnector->connector_id = link_index;
9315 	aconnector->bl_idx = -1;
9316 	aconnector->dc_link = link;
9317 	aconnector->base.interlace_allowed = false;
9318 	aconnector->base.doublescan_allowed = false;
9319 	aconnector->base.stereo_allowed = false;
9320 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
9321 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
9322 	aconnector->audio_inst = -1;
9323 	aconnector->pack_sdp_v1_3 = false;
9324 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
9325 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
9326 	mutex_init(&aconnector->hpd_lock);
9327 	mutex_init(&aconnector->handle_mst_msg_ready);
9328 
9329 	/*
9330 	 * If HDMI HPD debounce delay is set, use the minimum between selected
9331 	 * value and AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS
9332 	 */
9333 	if (amdgpu_hdmi_hpd_debounce_delay_ms) {
9334 		aconnector->hdmi_hpd_debounce_delay_ms = min(amdgpu_hdmi_hpd_debounce_delay_ms,
9335 							     AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS);
9336 		INIT_DELAYED_WORK(&aconnector->hdmi_hpd_debounce_work, hdmi_hpd_debounce_work);
9337 		aconnector->hdmi_prev_sink = NULL;
9338 	} else {
9339 		aconnector->hdmi_hpd_debounce_delay_ms = 0;
9340 	}
9341 
9342 	/*
9343 	 * configure support HPD hot plug connector_>polled default value is 0
9344 	 * which means HPD hot plug not supported
9345 	 */
9346 	switch (connector_type) {
9347 	case DRM_MODE_CONNECTOR_HDMIA:
9348 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9349 		aconnector->base.ycbcr_420_allowed =
9350 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
9351 		break;
9352 	case DRM_MODE_CONNECTOR_DisplayPort:
9353 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9354 		link->link_enc = link_enc_cfg_get_link_enc(link);
9355 		ASSERT(link->link_enc);
9356 		if (link->link_enc)
9357 			aconnector->base.ycbcr_420_allowed =
9358 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
9359 		break;
9360 	case DRM_MODE_CONNECTOR_DVID:
9361 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9362 		break;
9363 	case DRM_MODE_CONNECTOR_DVII:
9364 	case DRM_MODE_CONNECTOR_VGA:
9365 		aconnector->base.polled =
9366 			DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT;
9367 		break;
9368 	default:
9369 		break;
9370 	}
9371 
9372 	drm_object_attach_property(&aconnector->base.base,
9373 				dm->ddev->mode_config.scaling_mode_property,
9374 				DRM_MODE_SCALE_NONE);
9375 
9376 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA
9377 		|| (connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root))
9378 		drm_connector_attach_broadcast_rgb_property(&aconnector->base);
9379 
9380 	drm_object_attach_property(&aconnector->base.base,
9381 				adev->mode_info.underscan_property,
9382 				UNDERSCAN_OFF);
9383 	drm_object_attach_property(&aconnector->base.base,
9384 				adev->mode_info.underscan_hborder_property,
9385 				0);
9386 	drm_object_attach_property(&aconnector->base.base,
9387 				adev->mode_info.underscan_vborder_property,
9388 				0);
9389 
9390 	if (!aconnector->mst_root)
9391 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
9392 
9393 	aconnector->base.state->max_bpc = 16;
9394 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
9395 
9396 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9397 		/* Content Type is currently only implemented for HDMI. */
9398 		drm_connector_attach_content_type_property(&aconnector->base);
9399 	}
9400 
9401 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9402 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
9403 			drm_connector_attach_colorspace_property(&aconnector->base);
9404 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
9405 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
9406 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
9407 			drm_connector_attach_colorspace_property(&aconnector->base);
9408 	}
9409 
9410 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9411 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
9412 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
9413 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
9414 
9415 		if (!aconnector->mst_root)
9416 			drm_connector_attach_vrr_capable_property(&aconnector->base);
9417 
9418 		if (adev->dm.hdcp_workqueue)
9419 			drm_connector_attach_content_protection_property(&aconnector->base, true);
9420 	}
9421 
9422 	if (connector_type == DRM_MODE_CONNECTOR_eDP) {
9423 		struct drm_privacy_screen *privacy_screen;
9424 
9425 		drm_connector_attach_panel_type_property(&aconnector->base);
9426 
9427 		privacy_screen = drm_privacy_screen_get(adev_to_drm(adev)->dev, NULL);
9428 		if (!IS_ERR(privacy_screen)) {
9429 			drm_connector_attach_privacy_screen_provider(&aconnector->base,
9430 								     privacy_screen);
9431 		} else if (PTR_ERR(privacy_screen) != -ENODEV) {
9432 			drm_warn(adev_to_drm(adev), "Error getting privacy-screen\n");
9433 		}
9434 	}
9435 }
9436 
9437 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
9438 			      struct i2c_msg *msgs, int num)
9439 {
9440 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
9441 	struct ddc_service *ddc_service = i2c->ddc_service;
9442 	struct i2c_command cmd;
9443 	int i;
9444 	int result = -EIO;
9445 
9446 	if (!ddc_service->ddc_pin)
9447 		return result;
9448 
9449 	cmd.payloads = kzalloc_objs(struct i2c_payload, num);
9450 
9451 	if (!cmd.payloads)
9452 		return result;
9453 
9454 	cmd.number_of_payloads = num;
9455 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
9456 	cmd.speed = 100;
9457 
9458 	for (i = 0; i < num; i++) {
9459 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
9460 		cmd.payloads[i].address = msgs[i].addr;
9461 		cmd.payloads[i].length = msgs[i].len;
9462 		cmd.payloads[i].data = msgs[i].buf;
9463 	}
9464 
9465 	if (i2c->oem) {
9466 		if (dc_submit_i2c_oem(
9467 			    ddc_service->ctx->dc,
9468 			    &cmd))
9469 			result = num;
9470 	} else {
9471 		if (dc_submit_i2c(
9472 			    ddc_service->ctx->dc,
9473 			    ddc_service->link->link_index,
9474 			    &cmd))
9475 			result = num;
9476 	}
9477 
9478 	kfree(cmd.payloads);
9479 	return result;
9480 }
9481 
9482 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
9483 {
9484 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
9485 }
9486 
9487 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
9488 	.master_xfer = amdgpu_dm_i2c_xfer,
9489 	.functionality = amdgpu_dm_i2c_func,
9490 };
9491 
9492 static struct amdgpu_i2c_adapter *
9493 create_i2c(struct ddc_service *ddc_service, bool oem)
9494 {
9495 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
9496 	struct amdgpu_i2c_adapter *i2c;
9497 
9498 	i2c = kzalloc_obj(struct amdgpu_i2c_adapter);
9499 	if (!i2c)
9500 		return NULL;
9501 	i2c->base.owner = THIS_MODULE;
9502 	i2c->base.dev.parent = &adev->pdev->dev;
9503 	i2c->base.algo = &amdgpu_dm_i2c_algo;
9504 	if (oem)
9505 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c OEM bus");
9506 	else
9507 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d",
9508 			 ddc_service->link->link_index);
9509 	i2c_set_adapdata(&i2c->base, i2c);
9510 	i2c->ddc_service = ddc_service;
9511 	i2c->oem = oem;
9512 
9513 	return i2c;
9514 }
9515 
9516 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
9517 {
9518 	struct cec_connector_info conn_info;
9519 	struct drm_device *ddev = aconnector->base.dev;
9520 	struct device *hdmi_dev = ddev->dev;
9521 
9522 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
9523 		drm_info(ddev, "HDMI-CEC feature masked\n");
9524 		return -EINVAL;
9525 	}
9526 
9527 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
9528 	aconnector->notifier =
9529 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
9530 	if (!aconnector->notifier) {
9531 		drm_err(ddev, "Failed to create cec notifier\n");
9532 		return -ENOMEM;
9533 	}
9534 
9535 	return 0;
9536 }
9537 
9538 /*
9539  * Note: this function assumes that dc_link_detect() was called for the
9540  * dc_link which will be represented by this aconnector.
9541  */
9542 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
9543 				    struct amdgpu_dm_connector *aconnector,
9544 				    u32 link_index,
9545 				    struct amdgpu_encoder *aencoder)
9546 {
9547 	int res = 0;
9548 	int connector_type;
9549 	struct dc *dc = dm->dc;
9550 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
9551 	struct amdgpu_i2c_adapter *i2c;
9552 
9553 	/* Not needed for writeback connector */
9554 	link->priv = aconnector;
9555 
9556 
9557 	i2c = create_i2c(link->ddc, false);
9558 	if (!i2c) {
9559 		drm_err(adev_to_drm(dm->adev), "Failed to create i2c adapter data\n");
9560 		return -ENOMEM;
9561 	}
9562 
9563 	aconnector->i2c = i2c;
9564 	res = devm_i2c_add_adapter(dm->adev->dev, &i2c->base);
9565 
9566 	if (res) {
9567 		drm_err(adev_to_drm(dm->adev), "Failed to register hw i2c %d\n", link->link_index);
9568 		goto out_free;
9569 	}
9570 
9571 	connector_type = to_drm_connector_type(link->connector_signal, link->link_id.id);
9572 
9573 	res = drm_connector_init_with_ddc(
9574 			dm->ddev,
9575 			&aconnector->base,
9576 			&amdgpu_dm_connector_funcs,
9577 			connector_type,
9578 			&i2c->base);
9579 
9580 	if (res) {
9581 		drm_err(adev_to_drm(dm->adev), "connector_init failed\n");
9582 		aconnector->connector_id = -1;
9583 		goto out_free;
9584 	}
9585 
9586 	drm_connector_helper_add(
9587 			&aconnector->base,
9588 			&amdgpu_dm_connector_helper_funcs);
9589 
9590 	amdgpu_dm_connector_init_helper(
9591 		dm,
9592 		aconnector,
9593 		connector_type,
9594 		link,
9595 		link_index);
9596 
9597 	drm_connector_attach_encoder(
9598 		&aconnector->base, &aencoder->base);
9599 
9600 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9601 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
9602 		amdgpu_dm_initialize_hdmi_connector(aconnector);
9603 
9604 	if (dc_is_dp_signal(link->connector_signal))
9605 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
9606 
9607 out_free:
9608 	if (res) {
9609 		kfree(i2c);
9610 		aconnector->i2c = NULL;
9611 	}
9612 	return res;
9613 }
9614 
9615 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
9616 {
9617 	switch (adev->mode_info.num_crtc) {
9618 	case 1:
9619 		return 0x1;
9620 	case 2:
9621 		return 0x3;
9622 	case 3:
9623 		return 0x7;
9624 	case 4:
9625 		return 0xf;
9626 	case 5:
9627 		return 0x1f;
9628 	case 6:
9629 	default:
9630 		return 0x3f;
9631 	}
9632 }
9633 
9634 static int amdgpu_dm_encoder_init(struct drm_device *dev,
9635 				  struct amdgpu_encoder *aencoder,
9636 				  uint32_t link_index)
9637 {
9638 	struct amdgpu_device *adev = drm_to_adev(dev);
9639 
9640 	int res = drm_encoder_init(dev,
9641 				   &aencoder->base,
9642 				   &amdgpu_dm_encoder_funcs,
9643 				   DRM_MODE_ENCODER_TMDS,
9644 				   NULL);
9645 
9646 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
9647 
9648 	if (!res)
9649 		aencoder->encoder_id = link_index;
9650 	else
9651 		aencoder->encoder_id = -1;
9652 
9653 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
9654 
9655 	return res;
9656 }
9657 
9658 static void manage_dm_interrupts(struct amdgpu_device *adev,
9659 				 struct amdgpu_crtc *acrtc,
9660 				 struct dm_crtc_state *acrtc_state)
9661 {	/*
9662 	 * We cannot be sure that the frontend index maps to the same
9663 	 * backend index - some even map to more than one.
9664 	 * So we have to go through the CRTC to find the right IRQ.
9665 	 */
9666 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
9667 			adev,
9668 			acrtc->crtc_id);
9669 	struct drm_device *dev = adev_to_drm(adev);
9670 
9671 	struct drm_vblank_crtc_config config = {0};
9672 	struct dc_crtc_timing *timing;
9673 	int offdelay;
9674 
9675 	if (acrtc_state) {
9676 		timing = &acrtc_state->stream->timing;
9677 
9678 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
9679 			   IP_VERSION(3, 5, 0) ||
9680 			   !(adev->flags & AMD_IS_APU)) {
9681 			/*
9682 			 * Older HW and DGPU have issues with instant off;
9683 			 * use a 2 frame offdelay.
9684 			 */
9685 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
9686 						      timing->v_total *
9687 						      timing->h_total,
9688 						      timing->pix_clk_100hz);
9689 
9690 			config.offdelay_ms = offdelay ?: 30;
9691 		} else {
9692 			/* offdelay_ms = 0 will never disable vblank */
9693 			config.offdelay_ms = 1;
9694 			config.disable_immediate = true;
9695 		}
9696 
9697 		drm_crtc_vblank_on_config(&acrtc->base,
9698 					  &config);
9699 		/*
9700 		 * Since pflip_high_irq is no longer registered for DCN, grab an
9701 		 * extra reference to vupdate irq instead to workaround this
9702 		 * issue:
9703 		 * https://gitlab.freedesktop.org/drm/amd/-/work_items/3936
9704 		 *
9705 		 * The callbacks to drm_vblank_on/off should really take care of
9706 		 * this though.
9707 		 */
9708 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9709 		case IP_VERSION(3, 0, 0):
9710 		case IP_VERSION(3, 0, 2):
9711 		case IP_VERSION(3, 0, 3):
9712 		case IP_VERSION(3, 2, 0):
9713 			if (amdgpu_irq_get(adev, &adev->vupdate_irq, irq_type))
9714 				drm_err(dev, "DM_IRQ: Cannot get vupdate irq!\n");
9715 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9716 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
9717 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
9718 #endif
9719 		}
9720 
9721 	} else {
9722 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
9723 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9724 		case IP_VERSION(3, 0, 0):
9725 		case IP_VERSION(3, 0, 2):
9726 		case IP_VERSION(3, 0, 3):
9727 		case IP_VERSION(3, 2, 0):
9728 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9729 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
9730 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
9731 #endif
9732 			if (amdgpu_irq_put(adev, &adev->vupdate_irq, irq_type))
9733 				drm_err(dev, "DM_IRQ: Cannot put vupdate irq!\n");
9734 		}
9735 
9736 		drm_crtc_vblank_off(&acrtc->base);
9737 	}
9738 }
9739 
9740 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
9741 				      struct amdgpu_crtc *acrtc)
9742 {
9743 	int irq_type =
9744 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
9745 
9746 	/* GRPH_PFLIP is not used on DCN; nothing to reapply. */
9747 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) != 0)
9748 		return;
9749 
9750 	/**
9751 	 * This reads the current state for the IRQ and force reapplies
9752 	 * the setting to hardware.
9753 	 */
9754 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
9755 }
9756 
9757 static bool
9758 is_scaling_state_different(const struct dm_connector_state *dm_state,
9759 			   const struct dm_connector_state *old_dm_state)
9760 {
9761 	if (dm_state->scaling != old_dm_state->scaling)
9762 		return true;
9763 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
9764 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
9765 			return true;
9766 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
9767 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
9768 			return true;
9769 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
9770 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
9771 		return true;
9772 	return false;
9773 }
9774 
9775 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
9776 					    struct drm_crtc_state *old_crtc_state,
9777 					    struct drm_connector_state *new_conn_state,
9778 					    struct drm_connector_state *old_conn_state,
9779 					    const struct drm_connector *connector,
9780 					    struct hdcp_workqueue *hdcp_w)
9781 {
9782 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
9783 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
9784 
9785 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
9786 		connector->index, connector->status, connector->dpms);
9787 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
9788 		old_conn_state->content_protection, new_conn_state->content_protection);
9789 
9790 	if (old_crtc_state)
9791 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9792 		old_crtc_state->enable,
9793 		old_crtc_state->active,
9794 		old_crtc_state->mode_changed,
9795 		old_crtc_state->active_changed,
9796 		old_crtc_state->connectors_changed);
9797 
9798 	if (new_crtc_state)
9799 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9800 		new_crtc_state->enable,
9801 		new_crtc_state->active,
9802 		new_crtc_state->mode_changed,
9803 		new_crtc_state->active_changed,
9804 		new_crtc_state->connectors_changed);
9805 
9806 	/* hdcp content type change */
9807 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
9808 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
9809 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9810 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
9811 		return true;
9812 	}
9813 
9814 	/* CP is being re enabled, ignore this */
9815 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
9816 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9817 		if (new_crtc_state && new_crtc_state->mode_changed) {
9818 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9819 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
9820 			return true;
9821 		}
9822 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
9823 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
9824 		return false;
9825 	}
9826 
9827 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
9828 	 *
9829 	 * Handles:	UNDESIRED -> ENABLED
9830 	 */
9831 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
9832 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
9833 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9834 
9835 	/* Stream removed and re-enabled
9836 	 *
9837 	 * Can sometimes overlap with the HPD case,
9838 	 * thus set update_hdcp to false to avoid
9839 	 * setting HDCP multiple times.
9840 	 *
9841 	 * Handles:	DESIRED -> DESIRED (Special case)
9842 	 */
9843 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
9844 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
9845 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9846 		dm_con_state->update_hdcp = false;
9847 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
9848 			__func__);
9849 		return true;
9850 	}
9851 
9852 	/* Hot-plug, headless s3, dpms
9853 	 *
9854 	 * Only start HDCP if the display is connected/enabled.
9855 	 * update_hdcp flag will be set to false until the next
9856 	 * HPD comes in.
9857 	 *
9858 	 * Handles:	DESIRED -> DESIRED (Special case)
9859 	 */
9860 	if (dm_con_state->update_hdcp &&
9861 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
9862 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
9863 		dm_con_state->update_hdcp = false;
9864 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
9865 			__func__);
9866 		return true;
9867 	}
9868 
9869 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
9870 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9871 			if (new_crtc_state && new_crtc_state->mode_changed) {
9872 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
9873 					__func__);
9874 				return true;
9875 			}
9876 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
9877 				__func__);
9878 			return false;
9879 		}
9880 
9881 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
9882 		return false;
9883 	}
9884 
9885 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9886 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
9887 			__func__);
9888 		return true;
9889 	}
9890 
9891 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
9892 	return false;
9893 }
9894 
9895 static void remove_stream(struct amdgpu_device *adev,
9896 			  struct amdgpu_crtc *acrtc,
9897 			  struct dc_stream_state *stream)
9898 {
9899 	/* this is the update mode case */
9900 
9901 	acrtc->otg_inst = -1;
9902 	acrtc->enabled = false;
9903 }
9904 
9905 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
9906 {
9907 
9908 	assert_spin_locked(&acrtc->base.dev->event_lock);
9909 	WARN_ON(acrtc->event);
9910 
9911 	acrtc->event = acrtc->base.state->event;
9912 
9913 	/* Set the flip status */
9914 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
9915 
9916 	/* Mark this event as consumed */
9917 	acrtc->base.state->event = NULL;
9918 
9919 	drm_dbg_state(acrtc->base.dev,
9920 		      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
9921 		      acrtc->crtc_id);
9922 }
9923 
9924 static void update_freesync_state_on_stream(
9925 	struct amdgpu_display_manager *dm,
9926 	struct dm_crtc_state *new_crtc_state,
9927 	struct dc_stream_state *new_stream,
9928 	struct dc_plane_state *surface,
9929 	u32 flip_timestamp_in_us)
9930 {
9931 	struct mod_vrr_params vrr_params;
9932 	struct dc_info_packet vrr_infopacket = {0};
9933 	struct amdgpu_device *adev = dm->adev;
9934 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9935 	unsigned long flags;
9936 	bool pack_sdp_v1_3 = false;
9937 	struct amdgpu_dm_connector *aconn;
9938 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
9939 
9940 	if (!new_stream)
9941 		return;
9942 
9943 	/*
9944 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9945 	 * For now it's sufficient to just guard against these conditions.
9946 	 */
9947 
9948 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9949 		return;
9950 
9951 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9952 	vrr_params = acrtc->dm_irq_params.vrr_params;
9953 
9954 	if (surface) {
9955 		mod_freesync_handle_preflip(
9956 			dm->freesync_module,
9957 			surface,
9958 			new_stream,
9959 			flip_timestamp_in_us,
9960 			&vrr_params);
9961 
9962 		if (adev->family < AMDGPU_FAMILY_AI &&
9963 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
9964 			mod_freesync_handle_v_update(dm->freesync_module,
9965 						     new_stream, &vrr_params);
9966 
9967 			/* Need to call this before the frame ends. */
9968 			dc_stream_adjust_vmin_vmax(dm->dc,
9969 						   new_crtc_state->stream,
9970 						   &vrr_params.adjust);
9971 		}
9972 	}
9973 
9974 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
9975 
9976 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
9977 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
9978 
9979 		if (aconn->vsdb_info.amd_vsdb_version == 1)
9980 			packet_type = PACKET_TYPE_FS_V1;
9981 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
9982 			packet_type = PACKET_TYPE_FS_V2;
9983 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
9984 			packet_type = PACKET_TYPE_FS_V3;
9985 
9986 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
9987 					&new_stream->adaptive_sync_infopacket);
9988 	}
9989 
9990 	mod_freesync_build_vrr_infopacket(
9991 		dm->freesync_module,
9992 		new_stream,
9993 		&vrr_params,
9994 		packet_type,
9995 		TRANSFER_FUNC_UNKNOWN,
9996 		&vrr_infopacket,
9997 		pack_sdp_v1_3);
9998 
9999 	new_crtc_state->freesync_vrr_info_changed |=
10000 		(memcmp(&new_crtc_state->vrr_infopacket,
10001 			&vrr_infopacket,
10002 			sizeof(vrr_infopacket)) != 0);
10003 
10004 	acrtc->dm_irq_params.vrr_params = vrr_params;
10005 	new_crtc_state->vrr_infopacket = vrr_infopacket;
10006 
10007 	new_stream->vrr_infopacket = vrr_infopacket;
10008 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
10009 
10010 	if (new_crtc_state->freesync_vrr_info_changed)
10011 		drm_dbg_kms(adev_to_drm(adev), "VRR packet update: crtc=%u enabled=%d state=%d",
10012 			      new_crtc_state->base.crtc->base.id,
10013 			      (int)new_crtc_state->base.vrr_enabled,
10014 			      (int)vrr_params.state);
10015 
10016 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10017 }
10018 
10019 static void update_stream_irq_parameters(
10020 	struct amdgpu_display_manager *dm,
10021 	struct dm_crtc_state *new_crtc_state)
10022 {
10023 	struct dc_stream_state *new_stream = new_crtc_state->stream;
10024 	struct mod_vrr_params vrr_params;
10025 	struct mod_freesync_config config = new_crtc_state->freesync_config;
10026 	struct amdgpu_device *adev = dm->adev;
10027 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
10028 	unsigned long flags;
10029 
10030 	if (!new_stream)
10031 		return;
10032 
10033 	/*
10034 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
10035 	 * For now it's sufficient to just guard against these conditions.
10036 	 */
10037 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
10038 		return;
10039 
10040 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
10041 	vrr_params = acrtc->dm_irq_params.vrr_params;
10042 
10043 	if (new_crtc_state->vrr_supported &&
10044 	    config.min_refresh_in_uhz &&
10045 	    config.max_refresh_in_uhz) {
10046 		/*
10047 		 * if freesync compatible mode was set, config.state will be set
10048 		 * in atomic check
10049 		 */
10050 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
10051 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
10052 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
10053 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
10054 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
10055 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
10056 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
10057 		} else {
10058 			config.state = new_crtc_state->base.vrr_enabled ?
10059 						     VRR_STATE_ACTIVE_VARIABLE :
10060 						     VRR_STATE_INACTIVE;
10061 		}
10062 	} else {
10063 		config.state = VRR_STATE_UNSUPPORTED;
10064 	}
10065 
10066 	mod_freesync_build_vrr_params(dm->freesync_module,
10067 				      new_stream,
10068 				      &config, &vrr_params);
10069 
10070 	new_crtc_state->freesync_config = config;
10071 	/* Copy state for access from DM IRQ handler */
10072 	acrtc->dm_irq_params.freesync_config = config;
10073 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
10074 	acrtc->dm_irq_params.vrr_params = vrr_params;
10075 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10076 }
10077 
10078 static void amdgpu_dm_handle_vrr_transition(struct amdgpu_display_manager *dm,
10079 					    struct dm_crtc_state *old_state,
10080 					    struct dm_crtc_state *new_state)
10081 {
10082 	struct amdgpu_device *adev = drm_to_adev(new_state->base.crtc->dev);
10083 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
10084 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
10085 
10086 	/* Only DCE gates vupdate on VRR, keep it enabled for DCN */
10087 	bool vrr_gates_vupdate = amdgpu_ip_version(adev, DCE_HWIP, 0) == 0;
10088 
10089 	if (!old_vrr_active && new_vrr_active) {
10090 		/* Transition VRR inactive -> active:
10091 		 * While VRR is active, we must not disable vblank irq, as a
10092 		 * reenable after disable would compute bogus vblank/pflip
10093 		 * timestamps if it likely happened inside display front-porch.
10094 		 *
10095 		 * We also need vupdate irq for the actual core vblank handling
10096 		 * at end of vblank.
10097 		 */
10098 		if (vrr_gates_vupdate)
10099 			WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
10100 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
10101 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR off->on: Get vblank ref\n",
10102 				 __func__, new_state->base.crtc->base.id);
10103 
10104 		scoped_guard(mutex, &dm->dc_lock) {
10105 			dc_exit_ips_for_hw_access(dm->dc);
10106 			amdgpu_dm_psr_set_event(dm, new_state->stream, true,
10107 				psr_event_vrr_transition, true);
10108 			amdgpu_dm_replay_set_event(dm, new_state->stream, true,
10109 				replay_event_vrr, true);
10110 		}
10111 	} else if (old_vrr_active && !new_vrr_active) {
10112 		/* Transition VRR active -> inactive:
10113 		 * Allow vblank irq disable again for fixed refresh rate.
10114 		 */
10115 		if (vrr_gates_vupdate)
10116 			WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
10117 		drm_crtc_vblank_put(new_state->base.crtc);
10118 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR on->off: Drop vblank ref\n",
10119 				 __func__, new_state->base.crtc->base.id);
10120 
10121 		scoped_guard(mutex, &dm->dc_lock) {
10122 			dc_exit_ips_for_hw_access(dm->dc);
10123 			amdgpu_dm_psr_set_event(dm, new_state->stream, false,
10124 				psr_event_vrr_transition, false);
10125 			amdgpu_dm_replay_set_event(dm, new_state->stream, false,
10126 				replay_event_vrr, false);
10127 		}
10128 	}
10129 }
10130 
10131 static void amdgpu_dm_commit_cursors(struct drm_atomic_commit *state)
10132 {
10133 	struct drm_plane *plane;
10134 	struct drm_plane_state *old_plane_state;
10135 	int i;
10136 
10137 	/*
10138 	 * TODO: Make this per-stream so we don't issue redundant updates for
10139 	 * commits with multiple streams.
10140 	 */
10141 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
10142 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
10143 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
10144 }
10145 
10146 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
10147 {
10148 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
10149 
10150 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
10151 }
10152 
10153 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
10154 				    struct drm_plane_state *old_plane_state,
10155 				    struct dc_stream_update *update)
10156 {
10157 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
10158 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
10159 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
10160 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
10161 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
10162 	uint64_t address = afb ? afb->address : 0;
10163 	struct dc_cursor_position position = {0};
10164 	struct dc_cursor_attributes attributes;
10165 	int ret;
10166 
10167 	if (!plane->state->fb && !old_plane_state->fb)
10168 		return;
10169 
10170 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
10171 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
10172 		       plane->state->crtc_h);
10173 
10174 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
10175 	if (ret)
10176 		return;
10177 
10178 	if (!position.enable) {
10179 		/* turn off cursor */
10180 		if (crtc_state && crtc_state->stream) {
10181 			dc_stream_set_cursor_position(crtc_state->stream,
10182 						      &position);
10183 			update->cursor_position = &crtc_state->stream->cursor_position;
10184 		}
10185 		return;
10186 	}
10187 
10188 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
10189 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
10190 
10191 	memset(&attributes, 0, sizeof(attributes));
10192 	attributes.address.high_part = upper_32_bits(address);
10193 	attributes.address.low_part  = lower_32_bits(address);
10194 	attributes.width             = plane->state->crtc_w;
10195 	attributes.height            = plane->state->crtc_h;
10196 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
10197 	attributes.rotation_angle    = 0;
10198 	attributes.attribute_flags.value = 0;
10199 
10200 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
10201 	 * legacy gamma setup.
10202 	 */
10203 	if (crtc_state->cm_is_degamma_srgb &&
10204 	    adev->dm.dc->caps.color.dpp.gamma_corr)
10205 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
10206 
10207 	if (afb)
10208 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
10209 
10210 	if (crtc_state->stream) {
10211 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
10212 						     &attributes))
10213 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
10214 
10215 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
10216 
10217 		if (!dc_stream_set_cursor_position(crtc_state->stream,
10218 						   &position))
10219 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
10220 
10221 		update->cursor_position = &crtc_state->stream->cursor_position;
10222 	}
10223 }
10224 
10225 static void amdgpu_dm_enable_self_refresh(struct amdgpu_display_manager *dm,
10226 					  struct amdgpu_crtc *acrtc_attach,
10227 					  const struct dm_crtc_state *acrtc_state,
10228 					  const u64 current_ts)
10229 {
10230 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
10231 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
10232 	struct amdgpu_dm_connector *aconn =
10233 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
10234 
10235 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
10236 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
10237 	    (psr->psr_feature_enabled || pr->replay_feature_enabled)) {
10238 		if (aconn->sr_skip_count > 0)
10239 			aconn->sr_skip_count--;
10240 
10241 		/* Allow SR when skip count is 0. */
10242 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
10243 
10244 		/*
10245 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
10246 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
10247 		 * can be enabled immediately once OS demonstrates an
10248 		 * adequate number of fast atomic commits to notify KMD
10249 		 * of update events.
10250 		 * See `amdgpu_dm_crtc_vblank_control_worker()`.
10251 		 */
10252 		if (acrtc_attach->dm_irq_params.allow_sr_entry &&
10253 			(current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
10254 			amdgpu_dm_psr_set_event(dm, acrtc_state->stream, false,
10255 				psr_event_hw_programming, false);
10256 
10257 			amdgpu_dm_replay_set_event(dm, acrtc_state->stream, false,
10258 				replay_event_hw_programming, false);
10259 		}
10260 	} else {
10261 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
10262 	}
10263 }
10264 
10265 static void dm_arm_vblank_event(struct amdgpu_crtc *acrtc,
10266 				struct dm_crtc_state *acrtc_state,
10267 				bool pflip_update,
10268 				bool cursor_update)
10269 {
10270 	assert_spin_locked(&acrtc->base.dev->event_lock);
10271 
10272 	if (!acrtc->base.state->event || acrtc_state->active_planes == 0)
10273 		return;
10274 
10275 	if (pflip_update) {
10276 		drm_crtc_vblank_get(&acrtc->base);
10277 		WARN_ON(acrtc->pflip_status != AMDGPU_FLIP_NONE);
10278 		/* Arm flip completion handling and event delivery after programming. */
10279 		prepare_flip_isr(acrtc);
10280 	} else if (cursor_update) {
10281 		drm_crtc_vblank_get(&acrtc->base);
10282 		acrtc->event = acrtc->base.state->event;
10283 		acrtc->base.state->event = NULL;
10284 	}
10285 }
10286 
10287 static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state,
10288 				    struct drm_device *dev,
10289 				    struct amdgpu_display_manager *dm,
10290 				    struct drm_crtc *pcrtc,
10291 				    bool wait_for_vblank)
10292 {
10293 	u32 i;
10294 	u64 timestamp_ns = ktime_get_ns();
10295 	struct drm_plane *plane;
10296 	struct drm_plane_state *old_plane_state, *new_plane_state;
10297 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
10298 	struct drm_crtc_state *new_pcrtc_state =
10299 			drm_atomic_get_new_crtc_state(state, pcrtc);
10300 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
10301 	struct dm_crtc_state *dm_old_crtc_state =
10302 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
10303 	int planes_count = 0, vpos, hpos;
10304 	unsigned long flags;
10305 	u32 target_vblank, last_flip_vblank;
10306 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
10307 	bool cursor_update = false;
10308 	bool pflip_present = false;
10309 	bool immediate_flip = false;
10310 	bool flip_latched_during_prog = false;
10311 	bool dirty_rects_changed = false;
10312 	bool updated_planes_and_streams = false;
10313 	struct {
10314 		struct dc_surface_update surface_updates[MAX_SURFACES];
10315 		struct dc_plane_info plane_infos[MAX_SURFACES];
10316 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
10317 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
10318 		struct dc_stream_update stream_update;
10319 	} *bundle;
10320 
10321 	bundle = kzalloc_obj(*bundle);
10322 
10323 	if (!bundle) {
10324 		drm_err(dev, "Failed to allocate update bundle\n");
10325 		goto cleanup;
10326 	}
10327 
10328 	/*
10329 	 * Disable the cursor first if we're disabling all the planes.
10330 	 * It'll remain on the screen after the planes are re-enabled
10331 	 * if we don't.
10332 	 *
10333 	 * If the cursor is transitioning from native to overlay mode, the
10334 	 * native cursor needs to be disabled first.
10335 	 */
10336 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
10337 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10338 		struct dc_cursor_position cursor_position = {0};
10339 
10340 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
10341 						   &cursor_position))
10342 			drm_err(dev, "DC failed to disable native cursor\n");
10343 
10344 		bundle->stream_update.cursor_position =
10345 				&acrtc_state->stream->cursor_position;
10346 	}
10347 
10348 	if (acrtc_state->active_planes == 0 &&
10349 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10350 		amdgpu_dm_commit_cursors(state);
10351 
10352 	/* update planes when needed */
10353 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
10354 		struct drm_crtc *crtc = new_plane_state->crtc;
10355 		struct drm_crtc_state *new_crtc_state;
10356 		struct drm_framebuffer *fb = new_plane_state->fb;
10357 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
10358 		bool plane_needs_flip;
10359 		struct dc_plane_state *dc_plane;
10360 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
10361 
10362 		/* Cursor plane is handled after stream updates */
10363 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
10364 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10365 			if ((fb && crtc == pcrtc) ||
10366 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
10367 				cursor_update = true;
10368 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
10369 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
10370 			}
10371 
10372 			continue;
10373 		}
10374 
10375 		if (!fb || !crtc || pcrtc != crtc)
10376 			continue;
10377 
10378 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
10379 		if (!new_crtc_state->active)
10380 			continue;
10381 
10382 		dc_plane = dm_new_plane_state->dc_state;
10383 		if (!dc_plane)
10384 			continue;
10385 
10386 		bundle->surface_updates[planes_count].surface = dc_plane;
10387 		if (new_pcrtc_state->color_mgmt_changed || new_plane_state->color_mgmt_changed) {
10388 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
10389 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
10390 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
10391 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
10392 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
10393 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
10394 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
10395 		}
10396 
10397 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
10398 				     &bundle->scaling_infos[planes_count]);
10399 
10400 		bundle->surface_updates[planes_count].scaling_info =
10401 			&bundle->scaling_infos[planes_count];
10402 
10403 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
10404 
10405 		pflip_present = pflip_present || plane_needs_flip;
10406 
10407 		if (!plane_needs_flip) {
10408 			planes_count += 1;
10409 			continue;
10410 		}
10411 
10412 		fill_dc_plane_info_and_addr(
10413 			dm->adev, new_plane_state,
10414 			afb->tiling_flags,
10415 			&bundle->plane_infos[planes_count],
10416 			&bundle->flip_addrs[planes_count].address,
10417 			afb->tmz_surface);
10418 
10419 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
10420 				 new_plane_state->plane->index,
10421 				 bundle->plane_infos[planes_count].dcc.enable);
10422 
10423 		bundle->surface_updates[planes_count].plane_info =
10424 			&bundle->plane_infos[planes_count];
10425 
10426 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
10427 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
10428 			fill_dc_dirty_rects(plane, old_plane_state,
10429 					    new_plane_state, new_crtc_state,
10430 					    &bundle->flip_addrs[planes_count],
10431 					    acrtc_state->stream->link->psr_settings.psr_version ==
10432 					    DC_PSR_VERSION_SU_1,
10433 					    &dirty_rects_changed);
10434 
10435 			/*
10436 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
10437 			 * and enabled it again after dirty regions are stable to avoid video glitch.
10438 			 * PSR-SU will be enabled in
10439 			 * amdgpu_dm_crtc_vblank_control_worker() if user
10440 			 * pause the video during the PSR-SU was disabled.
10441 			 */
10442 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
10443 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
10444 			    dirty_rects_changed) {
10445 				mutex_lock(&dm->dc_lock);
10446 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
10447 				timestamp_ns;
10448 				dc_exit_ips_for_hw_access(dm->dc);
10449 				amdgpu_dm_psr_set_event(dm, acrtc_state->stream, true,
10450 					psr_event_hw_programming, true);
10451 				mutex_unlock(&dm->dc_lock);
10452 			}
10453 		}
10454 
10455 		/*
10456 		 * Only allow immediate flips for fast updates that don't
10457 		 * change memory domain, FB pitch, DCC state, rotation or
10458 		 * mirroring.
10459 		 *
10460 		 * dm_crtc_helper_atomic_check() only accepts async flips with
10461 		 * fast updates.
10462 		 */
10463 		if (crtc->state->async_flip &&
10464 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
10465 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
10466 			drm_warn_once(state->dev,
10467 				      "[PLANE:%d:%s] async flip with non-fast update\n",
10468 				      plane->base.id, plane->name);
10469 
10470 		bundle->flip_addrs[planes_count].flip_immediate =
10471 			crtc->state->async_flip &&
10472 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
10473 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
10474 
10475 		immediate_flip |= bundle->flip_addrs[planes_count].flip_immediate;
10476 
10477 		timestamp_ns = ktime_get_ns();
10478 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
10479 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
10480 		bundle->surface_updates[planes_count].surface = dc_plane;
10481 
10482 		if (!bundle->surface_updates[planes_count].surface) {
10483 			drm_err(dev, "No surface for CRTC: id=%d\n",
10484 					acrtc_attach->crtc_id);
10485 			continue;
10486 		}
10487 
10488 		if (plane == pcrtc->primary)
10489 			update_freesync_state_on_stream(
10490 				dm,
10491 				acrtc_state,
10492 				acrtc_state->stream,
10493 				dc_plane,
10494 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
10495 
10496 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
10497 				 __func__,
10498 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
10499 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
10500 
10501 		planes_count += 1;
10502 
10503 	}
10504 
10505 	if (pflip_present) {
10506 		if (!vrr_active) {
10507 			/* Use old throttling in non-vrr fixed refresh rate mode
10508 			 * to keep flip scheduling based on target vblank counts
10509 			 * working in a backwards compatible way, e.g., for
10510 			 * clients using the GLX_OML_sync_control extension or
10511 			 * DRI3/Present extension with defined target_msc.
10512 			 */
10513 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
10514 		} else {
10515 			/* For variable refresh rate mode only:
10516 			 * Get vblank of last completed flip to avoid > 1 vrr
10517 			 * flips per video frame by use of throttling, but allow
10518 			 * flip programming anywhere in the possibly large
10519 			 * variable vrr vblank interval for fine-grained flip
10520 			 * timing control and more opportunity to avoid stutter
10521 			 * on late submission of flips.
10522 			 */
10523 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10524 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
10525 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10526 		}
10527 
10528 		target_vblank = last_flip_vblank + wait_for_vblank;
10529 
10530 		/*
10531 		 * Wait until we're out of the vertical blank period before the one
10532 		 * targeted by the flip
10533 		 */
10534 		while ((acrtc_attach->enabled &&
10535 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
10536 							    0, &vpos, &hpos, NULL,
10537 							    NULL, &pcrtc->hwmode)
10538 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
10539 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
10540 			(int)(target_vblank -
10541 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
10542 			usleep_range(1000, 1100);
10543 		}
10544 
10545 		if (acrtc_state->stream) {
10546 			if (acrtc_state->freesync_vrr_info_changed)
10547 				bundle->stream_update.vrr_infopacket =
10548 					&acrtc_state->stream->vrr_infopacket;
10549 		}
10550 	}
10551 
10552 	/*
10553 	 * DCE depends on a combination of GRPH_FLIP, VLINE0, and VUPDATE for
10554 	 * event delivery. Only GRPH_FLIP handler can send pflip events, and it
10555 	 * only fires if HW latched to the flip. Maintain legacy behavior by
10556 	 * arming event before programming.
10557 	 */
10558 	if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) {
10559 		scoped_guard(spinlock_irqsave, &pcrtc->dev->event_lock) {
10560 			dm_arm_vblank_event(acrtc_attach, acrtc_state,
10561 					pflip_present, cursor_update);
10562 		}
10563 	}
10564 
10565 	/* Update the planes if changed or disable if we don't have any. */
10566 	if ((planes_count || acrtc_state->active_planes == 0) &&
10567 		acrtc_state->stream) {
10568 		/*
10569 		 * If PSR or idle optimizations are enabled then flush out
10570 		 * any pending work before hardware programming.
10571 		 */
10572 		if (dm->vblank_control_workqueue)
10573 			flush_workqueue(dm->vblank_control_workqueue);
10574 
10575 		bundle->stream_update.stream = acrtc_state->stream;
10576 		if (new_pcrtc_state->mode_changed) {
10577 			bundle->stream_update.src = acrtc_state->stream->src;
10578 			bundle->stream_update.dst = acrtc_state->stream->dst;
10579 		}
10580 
10581 		if (new_pcrtc_state->color_mgmt_changed) {
10582 			/*
10583 			 * TODO: This isn't fully correct since we've actually
10584 			 * already modified the stream in place.
10585 			 */
10586 			bundle->stream_update.gamut_remap =
10587 				&acrtc_state->stream->gamut_remap_matrix;
10588 			bundle->stream_update.output_csc_transform =
10589 				&acrtc_state->stream->csc_color_matrix;
10590 			bundle->stream_update.out_transfer_func =
10591 				&acrtc_state->stream->out_transfer_func;
10592 			bundle->stream_update.lut3d_func =
10593 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
10594 			bundle->stream_update.func_shaper =
10595 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
10596 		}
10597 
10598 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
10599 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
10600 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
10601 
10602 		/*
10603 		 * If FreeSync state on the stream has changed then we need to
10604 		 * re-adjust the min/max bounds now that DC doesn't handle this
10605 		 * as part of commit.
10606 		 */
10607 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
10608 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10609 			dc_stream_adjust_vmin_vmax(
10610 				dm->dc, acrtc_state->stream,
10611 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
10612 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10613 		}
10614 		mutex_lock(&dm->dc_lock);
10615 		update_planes_and_stream_adapter(dm->dc,
10616 					 acrtc_state->update_type,
10617 					 planes_count,
10618 					 acrtc_state->stream,
10619 					 &bundle->stream_update,
10620 					 bundle->surface_updates);
10621 		updated_planes_and_streams = true;
10622 
10623 		/**
10624 		 * Enable or disable the interrupts on the backend.
10625 		 *
10626 		 * Most pipes are put into power gating when unused.
10627 		 *
10628 		 * When power gating is enabled on a pipe we lose the
10629 		 * interrupt enablement state when power gating is disabled.
10630 		 *
10631 		 * So we need to update the IRQ control state in hardware
10632 		 * whenever the pipe turns on (since it could be previously
10633 		 * power gated) or off (since some pipes can't be power gated
10634 		 * on some ASICs).
10635 		 */
10636 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
10637 			dm_update_pflip_irq_state(drm_to_adev(dev),
10638 						  acrtc_attach);
10639 		amdgpu_dm_enable_self_refresh(dm, acrtc_attach, acrtc_state,
10640 					      timestamp_ns);
10641 		mutex_unlock(&dm->dc_lock);
10642 	}
10643 
10644 	/*
10645 	 * Update cursor state *after* programming all the planes.
10646 	 * This avoids redundant programming in the case where we're going
10647 	 * to be disabling a single plane - those pipes are being disabled.
10648 	 */
10649 	if (acrtc_state->active_planes &&
10650 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
10651 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10652 		amdgpu_dm_commit_cursors(state);
10653 
10654 	/*
10655 	 * DCN specific vblank handling
10656 	 * ============================
10657 	 *
10658 	 * With the event_lock held, arm the vblank event, and determine whether
10659 	 * deliver it immediately, or in VUPDATE_NO_LOCK IRQ (i.e. HW latch
10660 	 * point) handler. Do this *after* programming so that the IRQ handler
10661 	 * will not deliver the event before HW laches onto the programmed
10662 	 * values:
10663 	 *
10664 	 *     Commit thread      IRQ handler                       HW
10665 	 *     -----------------------------------------------------------------
10666 	 *     arm_vblank_event()
10667 	 *                                                          vupdate()
10668 	 *                        vupdate_handler()
10669 	 *                          cook_timestamp()
10670 	 *                          # prev flip already latched,
10671 	 *                          # so flip_latched == true.
10672 	 *                          if event_armed && flip_latched:
10673 	 *                            send_vblank_event()
10674 	 *                            # sent before latch, **BAD!**
10675 	 *     hw_program()
10676 	 *                                                          vupdate()
10677 	 *                                                          **latch**
10678 	 *
10679 	 * There's a consequence of arming after: it's possible for HW to latch
10680 	 * between start of HW programming and acrtc->event/pflip_status arming.
10681 	 * When this happens, the IRQ handler will send the event on the next
10682 	 * immediate latch point, even though HW has already latched. This is
10683 	 * handled by optimistically checking for HW latch after programming,
10684 	 * and if latched, send the event immediately:
10685 	 *
10686 	 *     Commit thread             IRQ handler                HW
10687 	 *     -----------------------------------------------------------------
10688 	 *     hw_program()
10689 	 *                                                          vupdate()
10690 	 *                                                          **latch**
10691 	 *                               vupdate_handler()
10692 	 *                                 cook_timestamp()
10693 	 *                                 # event_armed == false
10694 	 *                                 # **no event sent!**
10695 	 *     arm_vblank_event()
10696 	 *     if flip_latched:
10697 	 *       **send_vblank_event()**
10698 	 *       disarm_vblank_event()
10699 	 *
10700 	 * The IRQ handler is expected to cook the timestamp, but we need to
10701 	 * cook the timestamp before optimistic sending as well. That's because
10702 	 * the following sequence is possible:
10703 	 *
10704 	 *     Commit thread              IRQ handler              HW
10705 	 *     -----------------------------------------------------------------
10706 	 *     hw_program()
10707 	 *     arm_vblank_event()
10708 	 *                                                         vupdate()
10709 	 *                                                         **latch**
10710 	 *     if flip_latched:
10711 	 *       # Need cook before send!
10712 	 *       **cook_timestamp()**
10713 	 *       send_vblank_event()
10714 	 *       disarm_vblank_event()
10715 	 *                                vupdate_handler()
10716 	 *                                  cook_timestamp()
10717 	 *                                  # event_armed == false
10718 	 *                                  # no event sent!
10719 	 *
10720 	 * Cooking twice is OK, since DRM scanout accurate timestamps report A)
10721 	 * the previous vactive start if currently in vactive, or B) the next
10722 	 * vactive start if currently in vblank (see &get_vblank_counter). 'A)'
10723 	 * is what we want for the optimistic send, and for 'B)', we'll cook a
10724 	 * timestamp no later than the next IRQ handler run.
10725 	 *
10726 	 * The more correct fix is to wrap programming and arming with the
10727 	 * event_lock and thus serializing it with the IRQ handler. However,
10728 	 * there are various sleep-waits within
10729 	 * update_planes_and_stream_adapter() that makes spin locking illegal.
10730 	 * And on full updates, it can take 1-2 frame-times to return (see
10731 	 * commit_planes_for_stream).
10732 	 *
10733 	 * On DCE, GRPH_PFLIP IRQ is used and takes care of this.
10734 	 */
10735 	if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0) {
10736 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10737 
10738 		if (updated_planes_and_streams) {
10739 			flip_latched_during_prog =
10740 				!dc_get_flip_pending_on_otg(dm->dc, acrtc_attach->otg_inst);
10741 		}
10742 
10743 		dm_arm_vblank_event(acrtc_attach, acrtc_state,
10744 				    pflip_present, cursor_update);
10745 
10746 		/*
10747 		 * Deliver the event immediately on immediate flip, or on a
10748 		 * update that has already latched.
10749 		 */
10750 		if ((immediate_flip || flip_latched_during_prog) &&
10751 		    acrtc_attach->pflip_status == AMDGPU_FLIP_SUBMITTED &&
10752 		    acrtc_attach->event) {
10753 			drm_crtc_accurate_vblank_count(&acrtc_attach->base);
10754 			drm_crtc_send_vblank_event(&acrtc_attach->base,
10755 						   acrtc_attach->event);
10756 			acrtc_attach->event = NULL;
10757 			drm_crtc_vblank_put(&acrtc_attach->base);
10758 			acrtc_attach->pflip_status = AMDGPU_FLIP_NONE;
10759 		}
10760 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10761 	}
10762 
10763 cleanup:
10764 	kfree(bundle);
10765 }
10766 
10767 static void amdgpu_dm_commit_audio(struct drm_device *dev,
10768 				   struct drm_atomic_commit *state)
10769 {
10770 	struct amdgpu_device *adev = drm_to_adev(dev);
10771 	struct amdgpu_dm_connector *aconnector;
10772 	struct drm_connector *connector;
10773 	struct drm_connector_state *old_con_state, *new_con_state;
10774 	struct drm_crtc_state *new_crtc_state;
10775 	struct dm_crtc_state *new_dm_crtc_state;
10776 	const struct dc_stream_status *status;
10777 	int i, inst;
10778 
10779 	/* Notify device removals. */
10780 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10781 		if (old_con_state->crtc != new_con_state->crtc) {
10782 			/* CRTC changes require notification. */
10783 			goto notify;
10784 		}
10785 
10786 		if (!new_con_state->crtc)
10787 			continue;
10788 
10789 		new_crtc_state = drm_atomic_get_new_crtc_state(
10790 			state, new_con_state->crtc);
10791 
10792 		if (!new_crtc_state)
10793 			continue;
10794 
10795 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10796 			continue;
10797 
10798 notify:
10799 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10800 			continue;
10801 
10802 		aconnector = to_amdgpu_dm_connector(connector);
10803 
10804 		mutex_lock(&adev->dm.audio_lock);
10805 		inst = aconnector->audio_inst;
10806 		aconnector->audio_inst = -1;
10807 		mutex_unlock(&adev->dm.audio_lock);
10808 
10809 		amdgpu_dm_audio_eld_notify(adev, inst);
10810 	}
10811 
10812 	/* Notify audio device additions. */
10813 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10814 		if (!new_con_state->crtc)
10815 			continue;
10816 
10817 		new_crtc_state = drm_atomic_get_new_crtc_state(
10818 			state, new_con_state->crtc);
10819 
10820 		if (!new_crtc_state)
10821 			continue;
10822 
10823 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10824 			continue;
10825 
10826 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
10827 		if (!new_dm_crtc_state->stream)
10828 			continue;
10829 
10830 		status = dc_stream_get_status(new_dm_crtc_state->stream);
10831 		if (!status)
10832 			continue;
10833 
10834 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10835 			continue;
10836 
10837 		aconnector = to_amdgpu_dm_connector(connector);
10838 
10839 		mutex_lock(&adev->dm.audio_lock);
10840 		inst = status->audio_inst;
10841 		aconnector->audio_inst = inst;
10842 		mutex_unlock(&adev->dm.audio_lock);
10843 
10844 		amdgpu_dm_audio_eld_notify(adev, inst);
10845 	}
10846 }
10847 
10848 /*
10849  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
10850  * @crtc_state: the DRM CRTC state
10851  * @stream_state: the DC stream state.
10852  *
10853  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
10854  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
10855  */
10856 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
10857 						struct dc_stream_state *stream_state)
10858 {
10859 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
10860 }
10861 
10862 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
10863 			      struct dm_crtc_state *crtc_state)
10864 {
10865 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
10866 }
10867 
10868 /**
10869  * amdgpu_dm_mod_power_update_streams - update mod_power stream state on modeset
10870  * @state: the drm atomic state
10871  * @dm: the display manager to update mod_power on
10872  *
10873  * Notify mod_power of stream changes on modeset events, and disable PSR/Replay
10874  * in preparation for hardware programming. See also
10875  * amdgpu_dm_mod_power_setup_streams() for post-modeset mod_power setup.
10876  */
10877 static void amdgpu_dm_mod_power_update_streams(struct drm_atomic_commit *state,
10878 					       struct amdgpu_display_manager *dm)
10879 {
10880 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10881 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10882 	struct amdgpu_dm_connector *aconnector;
10883 	struct drm_crtc *crtc;
10884 	int i = 0;
10885 
10886 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10887 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10888 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10889 
10890 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10891 			continue;
10892 
10893 		/*
10894 		 * Update mod_power on modeset event in preparation for hw
10895 		 * programming. Always use the old stream, since it would have
10896 		 * been previously added to mod_power. If old stream is null (on
10897 		 * crtc enable, for example), mod_power will no-op, which is the
10898 		 * desried behavior.
10899 		 */
10900 		if (old_crtc_state->active) {
10901 			scoped_guard(mutex, &dm->dc_lock) {
10902 				dc_exit_ips_for_hw_access(dm->dc);
10903 				amdgpu_dm_psr_set_event(dm, dm_old_crtc_state->stream, true,
10904 					psr_event_hw_programming, true);
10905 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, true,
10906 					replay_event_hw_programming, true);
10907 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, false,
10908 					replay_event_general_ui, false);
10909 			}
10910 		}
10911 
10912 		if (new_crtc_state->active) {
10913 			aconnector = (struct amdgpu_dm_connector *)
10914 				dm_new_crtc_state->stream->dm_stream_context;
10915 			if (old_crtc_state->active) {
10916 				mod_power_replace_stream(dm->power_module,
10917 					dm_old_crtc_state->stream,
10918 					dm_new_crtc_state->stream,
10919 					&aconnector->psr_caps);
10920 			} else {
10921 				mod_power_add_stream(dm->power_module,
10922 					dm_new_crtc_state->stream,
10923 					&aconnector->psr_caps);
10924 			}
10925 		} else if (old_crtc_state->active) {
10926 			mod_power_remove_stream(dm->power_module,
10927 				dm_old_crtc_state->stream);
10928 		}
10929 	}
10930 }
10931 
10932 /**
10933  * amdgpu_dm_mod_power_setup_streams - setup mod_power stream state post modeset
10934  * @state: the drm atomic state
10935  * @dm: the display manager to update mod_power on
10936  *
10937  * Notify mod_power of mode_change. This needs to be done after dc_stream
10938  * updates have been committed, and VRR parameters have been updated.
10939  */
10940 static void amdgpu_dm_mod_power_setup_streams(struct drm_atomic_commit *state,
10941 					      struct amdgpu_display_manager *dm)
10942 {
10943 	struct dm_crtc_state *dm_new_crtc_state;
10944 	struct drm_crtc_state *new_crtc_state;
10945 	struct amdgpu_crtc *acrtc;
10946 	struct drm_crtc *crtc;
10947 	int i = 0;
10948 
10949 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10950 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10951 		acrtc = to_amdgpu_crtc(crtc);
10952 
10953 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10954 			continue;
10955 
10956 		if (new_crtc_state->active) {
10957 			amdgpu_dm_link_setup_replay(dm_new_crtc_state->stream,
10958 					&acrtc->dm_irq_params.vrr_params);
10959 			mod_power_notify_mode_change(dm->power_module,
10960 						dm_new_crtc_state->stream,
10961 						false);
10962 
10963 			/*
10964 			 * Block PSR / Replay on the new stream until display settles post-modeset.
10965 			 * These events will be cleared by amdgpu_dm_enable_self_refresh() once
10966 			 * allow_sr_entry becomes true.
10967 			 */
10968 			amdgpu_dm_psr_set_event(dm, dm_new_crtc_state->stream, true,
10969 				psr_event_hw_programming, true);
10970 
10971 			amdgpu_dm_replay_set_event(dm, dm_new_crtc_state->stream, true,
10972 				replay_event_hw_programming | replay_event_general_ui,
10973 				true);
10974 		}
10975 	}
10976 
10977 }
10978 
10979 static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state,
10980 					struct dc_state *dc_state)
10981 {
10982 	struct drm_device *dev = state->dev;
10983 	struct amdgpu_device *adev = drm_to_adev(dev);
10984 	struct amdgpu_display_manager *dm = &adev->dm;
10985 	struct drm_crtc *crtc;
10986 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10987 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10988 	struct drm_connector_state *old_con_state;
10989 	struct drm_connector *connector;
10990 	bool mode_set_reset_required = false;
10991 	u32 i;
10992 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
10993 	bool set_backlight_level = false;
10994 
10995 	/* Disable writeback */
10996 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
10997 		struct dm_connector_state *dm_old_con_state;
10998 		struct amdgpu_crtc *acrtc;
10999 
11000 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11001 			continue;
11002 
11003 		old_crtc_state = NULL;
11004 
11005 		dm_old_con_state = to_dm_connector_state(old_con_state);
11006 		if (!dm_old_con_state->base.crtc)
11007 			continue;
11008 
11009 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
11010 		if (acrtc)
11011 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11012 
11013 		if (!acrtc || !acrtc->wb_enabled)
11014 			continue;
11015 
11016 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11017 
11018 		dm_clear_writeback(dm, dm_old_crtc_state);
11019 		acrtc->wb_enabled = false;
11020 	}
11021 
11022 	amdgpu_dm_mod_power_update_streams(state, dm);
11023 
11024 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
11025 				      new_crtc_state, i) {
11026 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11027 
11028 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11029 
11030 		if (old_crtc_state->active &&
11031 		    (!new_crtc_state->active ||
11032 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11033 			manage_dm_interrupts(adev, acrtc, NULL);
11034 			dc_stream_release(dm_old_crtc_state->stream);
11035 		}
11036 	}
11037 
11038 	drm_atomic_helper_calc_timestamping_constants(state);
11039 
11040 	/* update changed items */
11041 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11042 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11043 
11044 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11045 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11046 
11047 		drm_dbg_state(state->dev,
11048 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
11049 			acrtc->crtc_id,
11050 			new_crtc_state->enable,
11051 			new_crtc_state->active,
11052 			new_crtc_state->planes_changed,
11053 			new_crtc_state->mode_changed,
11054 			new_crtc_state->active_changed,
11055 			new_crtc_state->connectors_changed);
11056 
11057 		/* Disable cursor if disabling crtc */
11058 		if (old_crtc_state->active && !new_crtc_state->active) {
11059 			struct dc_cursor_position position;
11060 
11061 			memset(&position, 0, sizeof(position));
11062 			mutex_lock(&dm->dc_lock);
11063 			dc_exit_ips_for_hw_access(dm->dc);
11064 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
11065 			mutex_unlock(&dm->dc_lock);
11066 		}
11067 
11068 		/* Copy all transient state flags into dc state */
11069 		if (dm_new_crtc_state->stream) {
11070 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
11071 							    dm_new_crtc_state->stream);
11072 		}
11073 
11074 		/* handles headless hotplug case, updating new_state and
11075 		 * aconnector as needed
11076 		 */
11077 
11078 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
11079 
11080 			drm_dbg_atomic(dev,
11081 				       "Atomic commit: SET crtc id %d: [%p]\n",
11082 				       acrtc->crtc_id, acrtc);
11083 
11084 			if (!dm_new_crtc_state->stream) {
11085 				/*
11086 				 * this could happen because of issues with
11087 				 * userspace notifications delivery.
11088 				 * In this case userspace tries to set mode on
11089 				 * display which is disconnected in fact.
11090 				 * dc_sink is NULL in this case on aconnector.
11091 				 * We expect reset mode will come soon.
11092 				 *
11093 				 * This can also happen when unplug is done
11094 				 * during resume sequence ended
11095 				 *
11096 				 * In this case, we want to pretend we still
11097 				 * have a sink to keep the pipe running so that
11098 				 * hw state is consistent with the sw state
11099 				 */
11100 				drm_dbg_atomic(dev,
11101 					       "Failed to create new stream for crtc %d\n",
11102 						acrtc->base.base.id);
11103 				continue;
11104 			}
11105 
11106 			if (dm_old_crtc_state->stream)
11107 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
11108 
11109 			pm_runtime_get_noresume(dev->dev);
11110 
11111 			acrtc->enabled = true;
11112 			acrtc->hw_mode = new_crtc_state->mode;
11113 			crtc->hwmode = new_crtc_state->mode;
11114 			mode_set_reset_required = true;
11115 			set_backlight_level = true;
11116 		} else if (modereset_required(new_crtc_state)) {
11117 			drm_dbg_atomic(dev,
11118 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
11119 				       acrtc->crtc_id, acrtc);
11120 			/* i.e. reset mode */
11121 			if (dm_old_crtc_state->stream)
11122 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
11123 
11124 			mode_set_reset_required = true;
11125 		}
11126 	} /* for_each_crtc_in_state() */
11127 
11128 	/* if there mode set or reset, flush vblank work queue */
11129 	if (mode_set_reset_required) {
11130 		if (dm->vblank_control_workqueue)
11131 			flush_workqueue(dm->vblank_control_workqueue);
11132 	}
11133 
11134 	dm_enable_per_frame_crtc_master_sync(dc_state);
11135 	mutex_lock(&dm->dc_lock);
11136 	dc_exit_ips_for_hw_access(dm->dc);
11137 	WARN_ON(!dc_commit_streams(dm->dc, &params));
11138 
11139 	bool frl_stream_found = false;
11140 
11141 	for (i = 0; i < params.stream_count; i++) {
11142 		struct dc_stream_state *stream = params.streams[i];
11143 
11144 		if (stream->signal == SIGNAL_TYPE_HDMI_FRL) {
11145 			frl_stream_found = true;
11146 			break;
11147 		}
11148 	}
11149 	if (frl_stream_found) {
11150 		if (queue_delayed_work(dm->hdmi_frl_status_polling_wq,
11151 				       &dm->hdmi_frl_status_polling_work,
11152 				       msecs_to_jiffies(dm->hdmi_frl_status_polling_delay_ms)))
11153 			drm_dbg_kms(dev, "200ms frl status polling starts ...\n");
11154 	} else {
11155 		if (cancel_delayed_work_sync(&dm->hdmi_frl_status_polling_work))
11156 			drm_dbg_kms(dev, "200ms frl status polling stops ...\n");
11157 	}
11158 	/* Allow idle optimization when vblank count is 0 for display off */
11159 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
11160 		dc_allow_idle_optimizations(dm->dc, true);
11161 	mutex_unlock(&dm->dc_lock);
11162 
11163 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11164 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11165 
11166 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11167 
11168 		if (dm_new_crtc_state->stream != NULL) {
11169 			const struct dc_stream_status *status =
11170 					dc_stream_get_status(dm_new_crtc_state->stream);
11171 
11172 			if (!status)
11173 				status = dc_state_get_stream_status(dc_state,
11174 									 dm_new_crtc_state->stream);
11175 			if (!status)
11176 				drm_err(dev,
11177 					"got no status for stream %p on acrtc%p\n",
11178 					dm_new_crtc_state->stream, acrtc);
11179 			else
11180 				acrtc->otg_inst = status->primary_otg_inst;
11181 		}
11182 	}
11183 
11184 	/* During boot up and resume the DC layer will reset the panel brightness
11185 	 * to fix a flicker issue.
11186 	 * It will cause the dm->actual_brightness is not the current panel brightness
11187 	 * level. (the dm->brightness is the correct panel level)
11188 	 * So we set the backlight level with dm->brightness value after set mode
11189 	 */
11190 	if (set_backlight_level) {
11191 		for (i = 0; i < dm->num_of_edps; i++) {
11192 			if (dm->backlight_dev[i])
11193 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11194 		}
11195 	}
11196 }
11197 
11198 static void dm_set_writeback(struct amdgpu_display_manager *dm,
11199 			      struct dm_crtc_state *crtc_state,
11200 			      struct drm_connector *connector,
11201 			      struct drm_connector_state *new_con_state)
11202 {
11203 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
11204 	struct amdgpu_device *adev = dm->adev;
11205 	struct amdgpu_crtc *acrtc;
11206 	struct dc_writeback_info *wb_info;
11207 	struct pipe_ctx *pipe = NULL;
11208 	struct amdgpu_framebuffer *afb;
11209 	int i = 0;
11210 
11211 	wb_info = kzalloc_obj(*wb_info);
11212 	if (!wb_info) {
11213 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
11214 		return;
11215 	}
11216 
11217 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
11218 	if (!acrtc) {
11219 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
11220 		kfree(wb_info);
11221 		return;
11222 	}
11223 
11224 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
11225 	if (!afb) {
11226 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
11227 		kfree(wb_info);
11228 		return;
11229 	}
11230 
11231 	for (i = 0; i < MAX_PIPES; i++) {
11232 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
11233 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
11234 			break;
11235 		}
11236 	}
11237 
11238 	/* fill in wb_info */
11239 	wb_info->wb_enabled = true;
11240 
11241 	wb_info->dwb_pipe_inst = 0;
11242 	wb_info->dwb_params.dwbscl_black_color = 0;
11243 	wb_info->dwb_params.hdr_mult = 0x1F000;
11244 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
11245 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
11246 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
11247 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
11248 
11249 	/* width & height from crtc */
11250 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
11251 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
11252 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
11253 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
11254 
11255 	wb_info->dwb_params.cnv_params.crop_en = false;
11256 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
11257 
11258 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
11259 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
11260 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
11261 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
11262 
11263 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
11264 
11265 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
11266 
11267 	wb_info->dwb_params.scaler_taps.h_taps = 1;
11268 	wb_info->dwb_params.scaler_taps.v_taps = 1;
11269 	wb_info->dwb_params.scaler_taps.h_taps_c = 1;
11270 	wb_info->dwb_params.scaler_taps.v_taps_c = 1;
11271 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
11272 
11273 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
11274 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
11275 
11276 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
11277 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
11278 		wb_info->mcif_buf_params.chroma_address[i] = 0;
11279 	}
11280 
11281 	wb_info->mcif_buf_params.p_vmid = 1;
11282 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
11283 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
11284 		wb_info->mcif_warmup_params.region_size =
11285 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
11286 	}
11287 	wb_info->mcif_warmup_params.p_vmid = 1;
11288 	wb_info->writeback_source_plane = pipe->plane_state;
11289 
11290 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
11291 
11292 	acrtc->wb_pending = true;
11293 	acrtc->wb_conn = wb_conn;
11294 	drm_writeback_queue_job(wb_conn, new_con_state);
11295 }
11296 
11297 static void amdgpu_dm_update_hdcp(struct drm_atomic_commit *state)
11298 {
11299 	struct drm_connector_state *old_con_state, *new_con_state;
11300 	struct drm_device *dev = state->dev;
11301 	struct drm_connector *connector;
11302 	struct amdgpu_device *adev = drm_to_adev(dev);
11303 	int i;
11304 
11305 	if (!adev->dm.hdcp_workqueue)
11306 		return;
11307 
11308 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11309 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11310 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11311 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11312 		struct dm_crtc_state *dm_new_crtc_state;
11313 		struct amdgpu_dm_connector *aconnector;
11314 
11315 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11316 			continue;
11317 
11318 		aconnector = to_amdgpu_dm_connector(connector);
11319 
11320 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
11321 
11322 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
11323 			connector->index, connector->status, connector->dpms);
11324 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
11325 			old_con_state->content_protection, new_con_state->content_protection);
11326 
11327 		if (aconnector->dc_sink) {
11328 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
11329 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
11330 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
11331 				aconnector->dc_sink->edid_caps.display_name);
11332 			}
11333 		}
11334 
11335 		new_crtc_state = NULL;
11336 		old_crtc_state = NULL;
11337 
11338 		if (acrtc) {
11339 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11340 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11341 		}
11342 
11343 		if (old_crtc_state)
11344 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11345 			old_crtc_state->enable,
11346 			old_crtc_state->active,
11347 			old_crtc_state->mode_changed,
11348 			old_crtc_state->active_changed,
11349 			old_crtc_state->connectors_changed);
11350 
11351 		if (new_crtc_state)
11352 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11353 			new_crtc_state->enable,
11354 			new_crtc_state->active,
11355 			new_crtc_state->mode_changed,
11356 			new_crtc_state->active_changed,
11357 			new_crtc_state->connectors_changed);
11358 
11359 
11360 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11361 
11362 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
11363 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
11364 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
11365 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
11366 			dm_new_con_state->update_hdcp = true;
11367 			continue;
11368 		}
11369 
11370 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
11371 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
11372 			/* when display is unplugged from mst hub, connctor will
11373 			 * be destroyed within dm_dp_mst_connector_destroy. connector
11374 			 * hdcp perperties, like type, undesired, desired, enabled,
11375 			 * will be lost. So, save hdcp properties into hdcp_work within
11376 			 * amdgpu_dm_atomic_commit_tail. if the same display is
11377 			 * plugged back with same display index, its hdcp properties
11378 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
11379 			 */
11380 
11381 			bool enable_encryption = false;
11382 
11383 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
11384 				enable_encryption = true;
11385 
11386 			if (aconnector->dc_link && aconnector->dc_sink &&
11387 				aconnector->dc_link->type == dc_connection_mst_branch) {
11388 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
11389 				struct hdcp_workqueue *hdcp_w =
11390 					&hdcp_work[aconnector->dc_link->link_index];
11391 
11392 				hdcp_w->hdcp_content_type[connector->index] =
11393 					new_con_state->hdcp_content_type;
11394 				hdcp_w->content_protection[connector->index] =
11395 					new_con_state->content_protection;
11396 			}
11397 
11398 			if (new_crtc_state && new_crtc_state->mode_changed &&
11399 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
11400 				enable_encryption = true;
11401 
11402 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
11403 
11404 			if (aconnector->dc_link)
11405 				hdcp_update_display(
11406 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
11407 					new_con_state->hdcp_content_type, enable_encryption);
11408 		}
11409 	}
11410 }
11411 
11412 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state)
11413 {
11414 	struct drm_crtc *crtc;
11415 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11416 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11417 	int i, ret;
11418 
11419 	ret = drm_dp_mst_atomic_setup_commit(state);
11420 	if (ret)
11421 		return ret;
11422 
11423 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11424 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11425 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11426 		/*
11427 		 * Color management settings. We also update color properties
11428 		 * when a modeset is needed, to ensure it gets reprogrammed.
11429 		 */
11430 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
11431 		    (dm_new_crtc_state->base.color_mgmt_changed ||
11432 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11433 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11434 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
11435 			if (ret) {
11436 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
11437 				return ret;
11438 			}
11439 		}
11440 	}
11441 
11442 	return 0;
11443 }
11444 
11445 /**
11446  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
11447  * @state: The atomic state to commit
11448  *
11449  * This will tell DC to commit the constructed DC state from atomic_check,
11450  * programming the hardware. Any failures here implies a hardware failure, since
11451  * atomic check should have filtered anything non-kosher.
11452  */
11453 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state)
11454 {
11455 	struct drm_device *dev = state->dev;
11456 	struct amdgpu_device *adev = drm_to_adev(dev);
11457 	struct amdgpu_display_manager *dm = &adev->dm;
11458 	struct dm_atomic_state *dm_state;
11459 	struct dc_state *dc_state = NULL;
11460 	u32 i, j;
11461 	struct drm_crtc *crtc;
11462 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11463 	unsigned long flags;
11464 	bool wait_for_vblank = true;
11465 	struct drm_connector *connector;
11466 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
11467 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11468 	int crtc_disable_count = 0;
11469 
11470 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
11471 
11472 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
11473 	drm_dp_mst_atomic_wait_for_dependencies(state);
11474 
11475 	dm_state = dm_atomic_get_new_state(state);
11476 	if (dm_state && dm_state->context) {
11477 		dc_state = dm_state->context;
11478 		amdgpu_dm_commit_streams(state, dc_state);
11479 	}
11480 
11481 	amdgpu_dm_update_hdcp(state);
11482 
11483 	/* Handle connector state changes */
11484 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11485 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11486 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
11487 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11488 		struct dc_surface_update *dummy_updates;
11489 		struct dc_stream_update stream_update;
11490 		struct dc_info_packet hdr_packet;
11491 		struct dc_stream_status *status = NULL;
11492 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
11493 
11494 		memset(&stream_update, 0, sizeof(stream_update));
11495 
11496 		if (acrtc) {
11497 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11498 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11499 		}
11500 
11501 		/* Skip any modesets/resets */
11502 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
11503 			continue;
11504 
11505 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11506 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11507 
11508 		scaling_changed = is_scaling_state_different(dm_new_con_state,
11509 							     dm_old_con_state);
11510 
11511 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
11512 			(dm_old_crtc_state->stream->output_color_space !=
11513 				get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
11514 			output_color_space_changed = true;
11515 
11516 		abm_changed = dm_new_crtc_state->abm_level !=
11517 			      dm_old_crtc_state->abm_level;
11518 
11519 		hdr_changed =
11520 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
11521 
11522 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
11523 			continue;
11524 
11525 		stream_update.stream = dm_new_crtc_state->stream;
11526 		if (scaling_changed) {
11527 			update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
11528 					dm_new_con_state, dm_new_crtc_state->stream);
11529 
11530 			stream_update.src = dm_new_crtc_state->stream->src;
11531 			stream_update.dst = dm_new_crtc_state->stream->dst;
11532 		}
11533 
11534 		if (output_color_space_changed) {
11535 			dm_new_crtc_state->stream->output_color_space
11536 				= get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
11537 
11538 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
11539 		}
11540 
11541 		if (abm_changed) {
11542 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
11543 
11544 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
11545 		}
11546 
11547 		if (hdr_changed) {
11548 			fill_hdr_info_packet(new_con_state, &hdr_packet);
11549 			stream_update.hdr_static_metadata = &hdr_packet;
11550 		}
11551 
11552 		status = dc_stream_get_status(dm_new_crtc_state->stream);
11553 
11554 		if (WARN_ON(!status))
11555 			continue;
11556 
11557 		WARN_ON(!status->plane_count);
11558 
11559 		/*
11560 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
11561 		 * Here we create an empty update on each plane.
11562 		 * To fix this, DC should permit updating only stream properties.
11563 		 */
11564 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
11565 		if (!dummy_updates) {
11566 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
11567 			continue;
11568 		}
11569 		for (j = 0; j < status->plane_count; j++)
11570 			dummy_updates[j].surface = status->plane_states[j];
11571 
11572 		sort(dummy_updates, status->plane_count,
11573 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
11574 
11575 		mutex_lock(&dm->dc_lock);
11576 		dc_exit_ips_for_hw_access(dm->dc);
11577 		dc_update_planes_and_stream(dm->dc,
11578 					    dummy_updates,
11579 					    status->plane_count,
11580 					    dm_new_crtc_state->stream,
11581 					    &stream_update);
11582 		mutex_unlock(&dm->dc_lock);
11583 		kfree(dummy_updates);
11584 
11585 		drm_connector_update_privacy_screen(new_con_state);
11586 	}
11587 
11588 	/**
11589 	 * Enable interrupts for CRTCs that are newly enabled or went through
11590 	 * a modeset. It was intentionally deferred until after the front end
11591 	 * state was modified to wait until the OTG was on and so the IRQ
11592 	 * handlers didn't access stale or invalid state.
11593 	 */
11594 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11595 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11596 #ifdef CONFIG_DEBUG_FS
11597 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
11598 #endif
11599 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
11600 		if (old_crtc_state->active && !new_crtc_state->active)
11601 			crtc_disable_count++;
11602 
11603 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11604 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11605 
11606 		/* For freesync config update on crtc state and params for irq */
11607 		update_stream_irq_parameters(dm, dm_new_crtc_state);
11608 
11609 #ifdef CONFIG_DEBUG_FS
11610 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11611 		cur_crc_src = acrtc->dm_irq_params.crc_src;
11612 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11613 #endif
11614 
11615 		if (new_crtc_state->active &&
11616 		    (!old_crtc_state->active ||
11617 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11618 			dc_stream_retain(dm_new_crtc_state->stream);
11619 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
11620 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
11621 		}
11622 		/* Handle vrr on->off / off->on transitions */
11623 		amdgpu_dm_handle_vrr_transition(dm, dm_old_crtc_state, dm_new_crtc_state);
11624 
11625 #ifdef CONFIG_DEBUG_FS
11626 		if (new_crtc_state->active &&
11627 		    (!old_crtc_state->active ||
11628 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11629 			/**
11630 			 * Frontend may have changed so reapply the CRC capture
11631 			 * settings for the stream.
11632 			 */
11633 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
11634 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
11635 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
11636 					uint8_t cnt;
11637 
11638 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11639 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
11640 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
11641 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
11642 
11643 							/**
11644 							 * It takes 2 frames for HW to stably generate CRC when
11645 							 * resuming from suspend, so we set skip_frame_cnt 2.
11646 							 */
11647 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
11648 						}
11649 					}
11650 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11651 				}
11652 #endif
11653 				if (amdgpu_dm_crtc_configure_crc_source(
11654 					crtc, dm_new_crtc_state, cur_crc_src))
11655 					drm_dbg_atomic(dev, "Failed to configure crc source");
11656 			}
11657 		}
11658 #endif
11659 	}
11660 
11661 	amdgpu_dm_mod_power_setup_streams(state, dm);
11662 
11663 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
11664 		if (new_crtc_state->async_flip)
11665 			wait_for_vblank = false;
11666 
11667 	/* update planes when needed per crtc*/
11668 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
11669 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11670 
11671 		if (dm_new_crtc_state->stream)
11672 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
11673 	}
11674 
11675 	/* Enable writeback */
11676 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11677 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11678 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11679 
11680 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11681 			continue;
11682 
11683 		if (!new_con_state->writeback_job)
11684 			continue;
11685 
11686 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11687 
11688 		if (!new_crtc_state)
11689 			continue;
11690 
11691 		if (acrtc->wb_enabled)
11692 			continue;
11693 
11694 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11695 
11696 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
11697 		acrtc->wb_enabled = true;
11698 	}
11699 
11700 	/* Update audio instances for each connector. */
11701 	amdgpu_dm_commit_audio(dev, state);
11702 
11703 	/* restore the backlight level */
11704 	for (i = 0; i < dm->num_of_edps; i++) {
11705 		if (dm->backlight_dev[i] &&
11706 		    (dm->actual_brightness[i] != dm->brightness[i]))
11707 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11708 	}
11709 
11710 	/*
11711 	 * send vblank event on all events not handled in flip and
11712 	 * mark consumed event for drm_atomic_helper_commit_hw_done
11713 	 */
11714 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11715 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11716 
11717 		if (new_crtc_state->event)
11718 			drm_send_event_locked(dev, &new_crtc_state->event->base);
11719 
11720 		new_crtc_state->event = NULL;
11721 	}
11722 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11723 
11724 	/* Signal HW programming completion */
11725 	drm_atomic_helper_commit_hw_done(state);
11726 
11727 	if (wait_for_vblank)
11728 		drm_atomic_helper_wait_for_flip_done(dev, state);
11729 
11730 	drm_atomic_helper_cleanup_planes(dev, state);
11731 
11732 	/* Don't free the memory if we are hitting this as part of suspend.
11733 	 * This way we don't free any memory during suspend; see
11734 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
11735 	 * non-suspend modeset or when the driver is torn down.
11736 	 */
11737 	if (!adev->in_suspend) {
11738 		/* return the stolen vga memory back to VRAM */
11739 		if (!adev->mman.keep_stolen_vga_memory)
11740 			amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_VGA);
11741 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_EXTENDED);
11742 	}
11743 
11744 	/*
11745 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
11746 	 * so we can put the GPU into runtime suspend if we're not driving any
11747 	 * displays anymore
11748 	 */
11749 	for (i = 0; i < crtc_disable_count; i++)
11750 		pm_runtime_put_autosuspend(dev->dev);
11751 	pm_runtime_mark_last_busy(dev->dev);
11752 
11753 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
11754 }
11755 
11756 static int dm_force_atomic_commit(struct drm_connector *connector)
11757 {
11758 	int ret = 0;
11759 	struct drm_device *ddev = connector->dev;
11760 	struct drm_atomic_commit *state = drm_atomic_commit_alloc(ddev);
11761 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11762 	struct drm_plane *plane = disconnected_acrtc->base.primary;
11763 	struct drm_connector_state *conn_state;
11764 	struct drm_crtc_state *crtc_state;
11765 	struct drm_plane_state *plane_state;
11766 
11767 	if (!state)
11768 		return -ENOMEM;
11769 
11770 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
11771 
11772 	/* Construct an atomic state to restore previous display setting */
11773 
11774 	/*
11775 	 * Attach connectors to drm_atomic_commit
11776 	 */
11777 	conn_state = drm_atomic_get_connector_state(state, connector);
11778 
11779 	/* Check for error in getting connector state */
11780 	if (IS_ERR(conn_state)) {
11781 		ret = PTR_ERR(conn_state);
11782 		goto out;
11783 	}
11784 
11785 	/* Attach crtc to drm_atomic_commit*/
11786 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
11787 
11788 	/* Check for error in getting crtc state */
11789 	if (IS_ERR(crtc_state)) {
11790 		ret = PTR_ERR(crtc_state);
11791 		goto out;
11792 	}
11793 
11794 	/* force a restore */
11795 	crtc_state->mode_changed = true;
11796 
11797 	/* Attach plane to drm_atomic_commit */
11798 	plane_state = drm_atomic_get_plane_state(state, plane);
11799 
11800 	/* Check for error in getting plane state */
11801 	if (IS_ERR(plane_state)) {
11802 		ret = PTR_ERR(plane_state);
11803 		goto out;
11804 	}
11805 
11806 	/* Call commit internally with the state we just constructed */
11807 	ret = drm_atomic_commit(state);
11808 
11809 out:
11810 	drm_atomic_commit_put(state);
11811 	if (ret)
11812 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
11813 
11814 	return ret;
11815 }
11816 
11817 /*
11818  * This function handles all cases when set mode does not come upon hotplug.
11819  * This includes when a display is unplugged then plugged back into the
11820  * same port and when running without usermode desktop manager supprot
11821  */
11822 void dm_restore_drm_connector_state(struct drm_device *dev,
11823 				    struct drm_connector *connector)
11824 {
11825 	struct amdgpu_dm_connector *aconnector;
11826 	struct amdgpu_crtc *disconnected_acrtc;
11827 	struct dm_crtc_state *acrtc_state;
11828 
11829 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11830 		return;
11831 
11832 	aconnector = to_amdgpu_dm_connector(connector);
11833 
11834 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
11835 		return;
11836 
11837 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11838 	if (!disconnected_acrtc)
11839 		return;
11840 
11841 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
11842 	if (!acrtc_state->stream)
11843 		return;
11844 
11845 	/*
11846 	 * If the previous sink is not released and different from the current,
11847 	 * we deduce we are in a state where we can not rely on usermode call
11848 	 * to turn on the display, so we do it here
11849 	 */
11850 	if (acrtc_state->stream->sink != aconnector->dc_sink)
11851 		dm_force_atomic_commit(&aconnector->base);
11852 }
11853 
11854 /*
11855  * Grabs all modesetting locks to serialize against any blocking commits,
11856  * Waits for completion of all non blocking commits.
11857  */
11858 static int do_aquire_global_lock(struct drm_device *dev,
11859 				 struct drm_atomic_commit *state)
11860 {
11861 	struct drm_crtc *crtc;
11862 	struct drm_crtc_commit *commit;
11863 	long ret;
11864 
11865 	/*
11866 	 * Adding all modeset locks to aquire_ctx will
11867 	 * ensure that when the framework release it the
11868 	 * extra locks we are locking here will get released to
11869 	 */
11870 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
11871 	if (ret)
11872 		return ret;
11873 
11874 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
11875 		spin_lock(&crtc->commit_lock);
11876 		commit = list_first_entry_or_null(&crtc->commit_list,
11877 				struct drm_crtc_commit, commit_entry);
11878 		if (commit)
11879 			drm_crtc_commit_get(commit);
11880 		spin_unlock(&crtc->commit_lock);
11881 
11882 		if (!commit)
11883 			continue;
11884 
11885 		/*
11886 		 * Make sure all pending HW programming completed and
11887 		 * page flips done
11888 		 */
11889 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
11890 
11891 		if (ret > 0)
11892 			ret = wait_for_completion_interruptible_timeout(
11893 					&commit->flip_done, 10*HZ);
11894 
11895 		if (ret == 0)
11896 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
11897 				  crtc->base.id, crtc->name);
11898 
11899 		drm_crtc_commit_put(commit);
11900 	}
11901 
11902 	return ret < 0 ? ret : 0;
11903 }
11904 
11905 static void get_freesync_config_for_crtc(
11906 	struct dm_crtc_state *new_crtc_state,
11907 	struct dm_connector_state *new_con_state)
11908 {
11909 	struct mod_freesync_config config = {0};
11910 	struct amdgpu_dm_connector *aconnector;
11911 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
11912 	int vrefresh = drm_mode_vrefresh(mode);
11913 	bool fs_vid_mode = false;
11914 
11915 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11916 		return;
11917 
11918 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
11919 
11920 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
11921 					vrefresh >= aconnector->min_vfreq &&
11922 					vrefresh <= aconnector->max_vfreq;
11923 
11924 	if (new_crtc_state->vrr_supported) {
11925 		new_crtc_state->stream->ignore_msa_timing_param = true;
11926 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
11927 
11928 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
11929 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
11930 		config.vsif_supported = true;
11931 		config.btr = true;
11932 
11933 		if (fs_vid_mode) {
11934 			config.state = VRR_STATE_ACTIVE_FIXED;
11935 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
11936 			goto out;
11937 		} else if (new_crtc_state->base.vrr_enabled) {
11938 			config.state = VRR_STATE_ACTIVE_VARIABLE;
11939 		} else {
11940 			config.state = VRR_STATE_INACTIVE;
11941 		}
11942 	} else {
11943 		config.state = VRR_STATE_UNSUPPORTED;
11944 	}
11945 out:
11946 	new_crtc_state->freesync_config = config;
11947 }
11948 
11949 static void reset_freesync_config_for_crtc(
11950 	struct dm_crtc_state *new_crtc_state)
11951 {
11952 	new_crtc_state->vrr_supported = false;
11953 
11954 	memset(&new_crtc_state->vrr_infopacket, 0,
11955 	       sizeof(new_crtc_state->vrr_infopacket));
11956 }
11957 
11958 static bool
11959 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
11960 				 struct drm_crtc_state *new_crtc_state)
11961 {
11962 	const struct drm_display_mode *old_mode, *new_mode;
11963 
11964 	if (!old_crtc_state || !new_crtc_state)
11965 		return false;
11966 
11967 	old_mode = &old_crtc_state->mode;
11968 	new_mode = &new_crtc_state->mode;
11969 
11970 	if (old_mode->clock       == new_mode->clock &&
11971 	    old_mode->hdisplay    == new_mode->hdisplay &&
11972 	    old_mode->vdisplay    == new_mode->vdisplay &&
11973 	    old_mode->htotal      == new_mode->htotal &&
11974 	    old_mode->vtotal      != new_mode->vtotal &&
11975 	    old_mode->hsync_start == new_mode->hsync_start &&
11976 	    old_mode->vsync_start != new_mode->vsync_start &&
11977 	    old_mode->hsync_end   == new_mode->hsync_end &&
11978 	    old_mode->vsync_end   != new_mode->vsync_end &&
11979 	    old_mode->hskew       == new_mode->hskew &&
11980 	    old_mode->vscan       == new_mode->vscan &&
11981 	    (old_mode->vsync_end - old_mode->vsync_start) ==
11982 	    (new_mode->vsync_end - new_mode->vsync_start))
11983 		return true;
11984 
11985 	return false;
11986 }
11987 
11988 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
11989 {
11990 	u64 num, den, res;
11991 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
11992 
11993 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
11994 
11995 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
11996 	den = (unsigned long long)new_crtc_state->mode.htotal *
11997 	      (unsigned long long)new_crtc_state->mode.vtotal;
11998 
11999 	res = div_u64(num, den);
12000 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
12001 }
12002 
12003 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
12004 			 struct drm_atomic_commit *state,
12005 			 struct drm_crtc *crtc,
12006 			 struct drm_crtc_state *old_crtc_state,
12007 			 struct drm_crtc_state *new_crtc_state,
12008 			 bool enable,
12009 			 bool *lock_and_validation_needed)
12010 {
12011 	struct dm_atomic_state *dm_state = NULL;
12012 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12013 	struct dc_stream_state *new_stream;
12014 	struct amdgpu_device *adev = dm->adev;
12015 	int ret = 0;
12016 
12017 	/*
12018 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
12019 	 * update changed items
12020 	 */
12021 	struct amdgpu_crtc *acrtc = NULL;
12022 	struct drm_connector *connector = NULL;
12023 	struct amdgpu_dm_connector *aconnector = NULL;
12024 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
12025 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
12026 
12027 	new_stream = NULL;
12028 
12029 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12030 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12031 	acrtc = to_amdgpu_crtc(crtc);
12032 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
12033 	if (connector)
12034 		aconnector = to_amdgpu_dm_connector(connector);
12035 
12036 	/* TODO This hack should go away */
12037 	if (connector && enable) {
12038 		/* Make sure fake sink is created in plug-in scenario */
12039 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
12040 									connector);
12041 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
12042 									connector);
12043 
12044 		if (WARN_ON(!drm_new_conn_state)) {
12045 			ret = -EINVAL;
12046 			goto fail;
12047 		}
12048 
12049 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
12050 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
12051 
12052 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
12053 			goto skip_modeset;
12054 
12055 		new_stream = create_validate_stream_for_sink(connector,
12056 							     &new_crtc_state->mode,
12057 							     dm_new_conn_state,
12058 							     dm_old_crtc_state->stream);
12059 
12060 		/*
12061 		 * we can have no stream on ACTION_SET if a display
12062 		 * was disconnected during S3, in this case it is not an
12063 		 * error, the OS will be updated after detection, and
12064 		 * will do the right thing on next atomic commit
12065 		 */
12066 
12067 		if (!new_stream) {
12068 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
12069 					__func__, acrtc->base.base.id);
12070 			ret = -ENOMEM;
12071 			goto fail;
12072 		}
12073 
12074 		/*
12075 		 * TODO: Check VSDB bits to decide whether this should
12076 		 * be enabled or not.
12077 		 */
12078 		new_stream->triggered_crtc_reset.enabled =
12079 			dm->force_timing_sync;
12080 
12081 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
12082 
12083 		ret = fill_hdr_info_packet(drm_new_conn_state,
12084 					   &new_stream->hdr_static_metadata);
12085 		if (ret)
12086 			goto fail;
12087 
12088 		/*
12089 		 * If we already removed the old stream from the context
12090 		 * (and set the new stream to NULL) then we can't reuse
12091 		 * the old stream even if the stream and scaling are unchanged.
12092 		 * We'll hit the BUG_ON and black screen.
12093 		 *
12094 		 * TODO: Refactor this function to allow this check to work
12095 		 * in all conditions.
12096 		 */
12097 		if (amdgpu_freesync_vid_mode &&
12098 		    dm_new_crtc_state->stream &&
12099 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
12100 			goto skip_modeset;
12101 
12102 		if (dm_new_crtc_state->stream &&
12103 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
12104 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
12105 			new_crtc_state->mode_changed = false;
12106 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
12107 					 new_crtc_state->mode_changed);
12108 		}
12109 	}
12110 
12111 	/* mode_changed flag may get updated above, need to check again */
12112 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
12113 		goto skip_modeset;
12114 
12115 	drm_dbg_state(state->dev,
12116 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
12117 		acrtc->crtc_id,
12118 		new_crtc_state->enable,
12119 		new_crtc_state->active,
12120 		new_crtc_state->planes_changed,
12121 		new_crtc_state->mode_changed,
12122 		new_crtc_state->active_changed,
12123 		new_crtc_state->connectors_changed);
12124 
12125 	/* Remove stream for any changed/disabled CRTC */
12126 	if (!enable) {
12127 
12128 		if (!dm_old_crtc_state->stream)
12129 			goto skip_modeset;
12130 
12131 		/* Unset freesync video if it was active before */
12132 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
12133 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
12134 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
12135 		}
12136 
12137 		/* Now check if we should set freesync video mode */
12138 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
12139 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
12140 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
12141 		    is_timing_unchanged_for_freesync(new_crtc_state,
12142 						     old_crtc_state)) {
12143 			new_crtc_state->mode_changed = false;
12144 			drm_dbg_driver(adev_to_drm(adev),
12145 				"Mode change not required for front porch change, setting mode_changed to %d",
12146 				new_crtc_state->mode_changed);
12147 
12148 			set_freesync_fixed_config(dm_new_crtc_state);
12149 
12150 			goto skip_modeset;
12151 		} else if (amdgpu_freesync_vid_mode && aconnector &&
12152 			   is_freesync_video_mode(&new_crtc_state->mode,
12153 						  aconnector)) {
12154 			struct drm_display_mode *high_mode;
12155 
12156 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
12157 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
12158 				set_freesync_fixed_config(dm_new_crtc_state);
12159 		}
12160 
12161 		ret = dm_atomic_get_state(state, &dm_state);
12162 		if (ret)
12163 			goto fail;
12164 
12165 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
12166 				crtc->base.id);
12167 
12168 		/* i.e. reset mode */
12169 		if (dc_state_remove_stream(
12170 				dm->dc,
12171 				dm_state->context,
12172 				dm_old_crtc_state->stream) != DC_OK) {
12173 			ret = -EINVAL;
12174 			goto fail;
12175 		}
12176 
12177 		dc_stream_release(dm_old_crtc_state->stream);
12178 		dm_new_crtc_state->stream = NULL;
12179 
12180 		reset_freesync_config_for_crtc(dm_new_crtc_state);
12181 
12182 		*lock_and_validation_needed = true;
12183 
12184 	} else {/* Add stream for any updated/enabled CRTC */
12185 		/*
12186 		 * Quick fix to prevent NULL pointer on new_stream when
12187 		 * added MST connectors not found in existing crtc_state in the chained mode
12188 		 * TODO: need to dig out the root cause of that
12189 		 */
12190 		if (!connector)
12191 			goto skip_modeset;
12192 
12193 		if (modereset_required(new_crtc_state))
12194 			goto skip_modeset;
12195 
12196 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
12197 				     dm_old_crtc_state->stream)) {
12198 
12199 			WARN_ON(dm_new_crtc_state->stream);
12200 
12201 			ret = dm_atomic_get_state(state, &dm_state);
12202 			if (ret)
12203 				goto fail;
12204 
12205 			dm_new_crtc_state->stream = new_stream;
12206 
12207 			dc_stream_retain(new_stream);
12208 
12209 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
12210 					 crtc->base.id);
12211 
12212 			if (dc_state_add_stream(
12213 					dm->dc,
12214 					dm_state->context,
12215 					dm_new_crtc_state->stream) != DC_OK) {
12216 				ret = -EINVAL;
12217 				goto fail;
12218 			}
12219 
12220 			*lock_and_validation_needed = true;
12221 		}
12222 	}
12223 
12224 skip_modeset:
12225 	/* Release extra reference */
12226 	if (new_stream)
12227 		dc_stream_release(new_stream);
12228 	new_stream = NULL;
12229 
12230 	/*
12231 	 * We want to do dc stream updates that do not require a
12232 	 * full modeset below.
12233 	 */
12234 	if (!(enable && connector && new_crtc_state->active))
12235 		return 0;
12236 	/*
12237 	 * Given above conditions, the dc state cannot be NULL because:
12238 	 * 1. We're in the process of enabling CRTCs (just been added
12239 	 *    to the dc context, or already is on the context)
12240 	 * 2. Has a valid connector attached, and
12241 	 * 3. Is currently active and enabled.
12242 	 * => The dc stream state currently exists.
12243 	 */
12244 	BUG_ON(dm_new_crtc_state->stream == NULL);
12245 
12246 	/* Scaling or underscan settings */
12247 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
12248 				drm_atomic_crtc_needs_modeset(new_crtc_state))
12249 		update_stream_scaling_settings(adev_to_drm(adev),
12250 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
12251 
12252 	/* ABM settings */
12253 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
12254 
12255 	/*
12256 	 * Color management settings. We also update color properties
12257 	 * when a modeset is needed, to ensure it gets reprogrammed.
12258 	 */
12259 	if (dm_new_crtc_state->base.color_mgmt_changed ||
12260 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
12261 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
12262 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
12263 		if (ret)
12264 			goto fail;
12265 	}
12266 
12267 	/* Update Freesync settings. */
12268 	get_freesync_config_for_crtc(dm_new_crtc_state,
12269 				     dm_new_conn_state);
12270 
12271 	return ret;
12272 
12273 fail:
12274 	if (new_stream)
12275 		dc_stream_release(new_stream);
12276 	return ret;
12277 }
12278 
12279 static bool should_reset_plane(struct drm_atomic_commit *state,
12280 			       struct drm_plane *plane,
12281 			       struct drm_plane_state *old_plane_state,
12282 			       struct drm_plane_state *new_plane_state)
12283 {
12284 	struct drm_plane *other;
12285 	struct drm_plane_state *old_other_state, *new_other_state;
12286 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12287 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
12288 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
12289 	struct drm_connector_state *new_con_state;
12290 	struct drm_connector *connector;
12291 	int i;
12292 
12293 	/*
12294 	 * TODO: Remove this hack for all asics once it proves that the
12295 	 * fast updates works fine on DCN3.2+.
12296 	 */
12297 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
12298 	    state->allow_modeset)
12299 		return true;
12300 
12301 	/* Check for writeback commit */
12302 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
12303 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
12304 			continue;
12305 
12306 		if (new_con_state->writeback_job)
12307 			return true;
12308 	}
12309 
12310 	if (amdgpu_in_reset(adev) && state->allow_modeset)
12311 		return true;
12312 
12313 	/* Exit early if we know that we're adding or removing the plane. */
12314 	if (old_plane_state->crtc != new_plane_state->crtc)
12315 		return true;
12316 
12317 	/* old crtc == new_crtc == NULL, plane not in context. */
12318 	if (!new_plane_state->crtc)
12319 		return false;
12320 
12321 	new_crtc_state =
12322 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
12323 	old_crtc_state =
12324 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
12325 
12326 	if (!new_crtc_state)
12327 		return true;
12328 
12329 	/*
12330 	 * A change in cursor mode means a new dc pipe needs to be acquired or
12331 	 * released from the state
12332 	 */
12333 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
12334 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
12335 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
12336 	    old_dm_crtc_state != NULL &&
12337 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
12338 		return true;
12339 	}
12340 
12341 	/* CRTC Degamma changes currently require us to recreate planes. */
12342 	if (new_crtc_state->color_mgmt_changed)
12343 		return true;
12344 
12345 	/* Plane color pipeline or its colorop changes. */
12346 	if (new_plane_state->color_mgmt_changed)
12347 		return true;
12348 
12349 	/*
12350 	 * On zpos change, planes need to be reordered by removing and re-adding
12351 	 * them one by one to the dc state, in order of descending zpos.
12352 	 *
12353 	 * TODO: We can likely skip bandwidth validation if the only thing that
12354 	 * changed about the plane was it'z z-ordering.
12355 	 */
12356 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
12357 		return true;
12358 
12359 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
12360 		return true;
12361 
12362 	/*
12363 	 * If there are any new primary or overlay planes being added or
12364 	 * removed then the z-order can potentially change. To ensure
12365 	 * correct z-order and pipe acquisition the current DC architecture
12366 	 * requires us to remove and recreate all existing planes.
12367 	 *
12368 	 * TODO: Come up with a more elegant solution for this.
12369 	 */
12370 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
12371 		struct amdgpu_framebuffer *old_afb, *new_afb;
12372 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
12373 
12374 		dm_new_other_state = to_dm_plane_state(new_other_state);
12375 		dm_old_other_state = to_dm_plane_state(old_other_state);
12376 
12377 		if (other->type == DRM_PLANE_TYPE_CURSOR)
12378 			continue;
12379 
12380 		if (old_other_state->crtc != new_plane_state->crtc &&
12381 		    new_other_state->crtc != new_plane_state->crtc)
12382 			continue;
12383 
12384 		if (old_other_state->crtc != new_other_state->crtc)
12385 			return true;
12386 
12387 		/* Src/dst size and scaling updates. */
12388 		if (old_other_state->src_w != new_other_state->src_w ||
12389 		    old_other_state->src_h != new_other_state->src_h ||
12390 		    old_other_state->crtc_w != new_other_state->crtc_w ||
12391 		    old_other_state->crtc_h != new_other_state->crtc_h)
12392 			return true;
12393 
12394 		/* Rotation / mirroring updates. */
12395 		if (old_other_state->rotation != new_other_state->rotation)
12396 			return true;
12397 
12398 		/* Blending updates. */
12399 		if (old_other_state->pixel_blend_mode !=
12400 		    new_other_state->pixel_blend_mode)
12401 			return true;
12402 
12403 		/* Alpha updates. */
12404 		if (old_other_state->alpha != new_other_state->alpha)
12405 			return true;
12406 
12407 		/* Colorspace changes. */
12408 		if (old_other_state->color_range != new_other_state->color_range ||
12409 		    old_other_state->color_encoding != new_other_state->color_encoding)
12410 			return true;
12411 
12412 		/* HDR/Transfer Function changes. */
12413 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
12414 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
12415 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
12416 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
12417 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
12418 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
12419 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
12420 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
12421 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
12422 			return true;
12423 
12424 		/* Framebuffer checks fall at the end. */
12425 		if (!old_other_state->fb || !new_other_state->fb)
12426 			continue;
12427 
12428 		/* Pixel format changes can require bandwidth updates. */
12429 		if (old_other_state->fb->format != new_other_state->fb->format)
12430 			return true;
12431 
12432 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
12433 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
12434 
12435 		/* Tiling and DCC changes also require bandwidth updates. */
12436 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
12437 		    old_afb->base.modifier != new_afb->base.modifier)
12438 			return true;
12439 	}
12440 
12441 	return false;
12442 }
12443 
12444 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
12445 			      struct drm_plane_state *new_plane_state,
12446 			      struct drm_framebuffer *fb)
12447 {
12448 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
12449 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
12450 	unsigned int pitch;
12451 	bool linear;
12452 
12453 	if (fb->width > new_acrtc->max_cursor_width ||
12454 	    fb->height > new_acrtc->max_cursor_height) {
12455 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB size %dx%d\n",
12456 				 new_plane_state->fb->width,
12457 				 new_plane_state->fb->height);
12458 		return -EINVAL;
12459 	}
12460 	if (new_plane_state->src_w != fb->width << 16 ||
12461 	    new_plane_state->src_h != fb->height << 16) {
12462 		drm_dbg_atomic(adev_to_drm(adev), "Cropping not supported for cursor plane\n");
12463 		return -EINVAL;
12464 	}
12465 
12466 	/* Pitch in pixels */
12467 	pitch = fb->pitches[0] / fb->format->cpp[0];
12468 
12469 	if (fb->width != pitch) {
12470 		drm_dbg_atomic(adev_to_drm(adev), "Cursor FB width %d doesn't match pitch %d",
12471 				 fb->width, pitch);
12472 		return -EINVAL;
12473 	}
12474 
12475 	switch (pitch) {
12476 	case 64:
12477 	case 128:
12478 	case 256:
12479 		/* FB pitch is supported by cursor plane */
12480 		break;
12481 	default:
12482 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB pitch %d px\n", pitch);
12483 		return -EINVAL;
12484 	}
12485 
12486 	/* Core DRM takes care of checking FB modifiers, so we only need to
12487 	 * check tiling flags when the FB doesn't have a modifier.
12488 	 */
12489 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
12490 		if (adev->family == AMDGPU_FAMILY_GC_12_0_0) {
12491 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
12492 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
12493 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
12494 		} else {
12495 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
12496 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
12497 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
12498 		}
12499 		if (!linear) {
12500 			drm_dbg_atomic(adev_to_drm(adev), "Cursor FB not linear");
12501 			return -EINVAL;
12502 		}
12503 	}
12504 
12505 	return 0;
12506 }
12507 
12508 /*
12509  * Helper function for checking the cursor in native mode
12510  */
12511 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
12512 					struct drm_plane *plane,
12513 					struct drm_plane_state *new_plane_state,
12514 					bool enable)
12515 {
12516 
12517 	struct amdgpu_crtc *new_acrtc;
12518 	int ret;
12519 
12520 	if (!enable || !new_plane_crtc ||
12521 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
12522 		return 0;
12523 
12524 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
12525 
12526 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
12527 		drm_dbg_atomic(new_plane_crtc->dev, "Cropping not supported for cursor plane\n");
12528 		return -EINVAL;
12529 	}
12530 
12531 	if (new_plane_state->fb) {
12532 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
12533 						new_plane_state->fb);
12534 		if (ret)
12535 			return ret;
12536 	}
12537 
12538 	return 0;
12539 }
12540 
12541 static bool dm_should_update_native_cursor(struct drm_atomic_commit *state,
12542 					   struct drm_crtc *old_plane_crtc,
12543 					   struct drm_crtc *new_plane_crtc,
12544 					   bool enable)
12545 {
12546 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12547 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12548 
12549 	if (!enable) {
12550 		if (old_plane_crtc == NULL)
12551 			return true;
12552 
12553 		old_crtc_state = drm_atomic_get_old_crtc_state(
12554 			state, old_plane_crtc);
12555 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12556 
12557 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12558 	} else {
12559 		if (new_plane_crtc == NULL)
12560 			return true;
12561 
12562 		new_crtc_state = drm_atomic_get_new_crtc_state(
12563 			state, new_plane_crtc);
12564 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12565 
12566 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12567 	}
12568 }
12569 
12570 static int dm_update_plane_state(struct dc *dc,
12571 				 struct drm_atomic_commit *state,
12572 				 struct drm_plane *plane,
12573 				 struct drm_plane_state *old_plane_state,
12574 				 struct drm_plane_state *new_plane_state,
12575 				 bool enable,
12576 				 bool *lock_and_validation_needed,
12577 				 bool *is_top_most_overlay)
12578 {
12579 
12580 	struct dm_atomic_state *dm_state = NULL;
12581 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
12582 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12583 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
12584 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
12585 	bool needs_reset, update_native_cursor;
12586 	int ret = 0;
12587 
12588 
12589 	new_plane_crtc = new_plane_state->crtc;
12590 	old_plane_crtc = old_plane_state->crtc;
12591 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
12592 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
12593 
12594 	update_native_cursor = dm_should_update_native_cursor(state,
12595 							      old_plane_crtc,
12596 							      new_plane_crtc,
12597 							      enable);
12598 
12599 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
12600 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12601 						    new_plane_state, enable);
12602 		if (ret)
12603 			return ret;
12604 
12605 		return 0;
12606 	}
12607 
12608 	needs_reset = should_reset_plane(state, plane, old_plane_state,
12609 					 new_plane_state);
12610 
12611 	/* Remove any changed/removed planes */
12612 	if (!enable) {
12613 		if (!needs_reset)
12614 			return 0;
12615 
12616 		if (!old_plane_crtc)
12617 			return 0;
12618 
12619 		old_crtc_state = drm_atomic_get_old_crtc_state(
12620 				state, old_plane_crtc);
12621 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12622 
12623 		if (!dm_old_crtc_state->stream)
12624 			return 0;
12625 
12626 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
12627 				plane->base.id, old_plane_crtc->base.id);
12628 
12629 		ret = dm_atomic_get_state(state, &dm_state);
12630 		if (ret)
12631 			return ret;
12632 
12633 		if (!dc_state_remove_plane(
12634 				dc,
12635 				dm_old_crtc_state->stream,
12636 				dm_old_plane_state->dc_state,
12637 				dm_state->context)) {
12638 
12639 			return -EINVAL;
12640 		}
12641 
12642 		if (dm_old_plane_state->dc_state)
12643 			dc_plane_state_release(dm_old_plane_state->dc_state);
12644 
12645 		dm_new_plane_state->dc_state = NULL;
12646 
12647 		*lock_and_validation_needed = true;
12648 
12649 	} else { /* Add new planes */
12650 		struct dc_plane_state *dc_new_plane_state;
12651 
12652 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
12653 			return 0;
12654 
12655 		if (!new_plane_crtc)
12656 			return 0;
12657 
12658 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
12659 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12660 
12661 		if (!dm_new_crtc_state->stream)
12662 			return 0;
12663 
12664 		if (!needs_reset)
12665 			return 0;
12666 
12667 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
12668 		if (ret)
12669 			goto out;
12670 
12671 		WARN_ON(dm_new_plane_state->dc_state);
12672 
12673 		dc_new_plane_state = dc_create_plane_state(dc);
12674 		if (!dc_new_plane_state) {
12675 			ret = -ENOMEM;
12676 			goto out;
12677 		}
12678 
12679 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
12680 				 plane->base.id, new_plane_crtc->base.id);
12681 
12682 		ret = fill_dc_plane_attributes(
12683 			drm_to_adev(new_plane_crtc->dev),
12684 			dc_new_plane_state,
12685 			new_plane_state,
12686 			new_crtc_state);
12687 		if (ret) {
12688 			dc_plane_state_release(dc_new_plane_state);
12689 			goto out;
12690 		}
12691 
12692 		ret = dm_atomic_get_state(state, &dm_state);
12693 		if (ret) {
12694 			dc_plane_state_release(dc_new_plane_state);
12695 			goto out;
12696 		}
12697 
12698 		/*
12699 		 * Any atomic check errors that occur after this will
12700 		 * not need a release. The plane state will be attached
12701 		 * to the stream, and therefore part of the atomic
12702 		 * state. It'll be released when the atomic state is
12703 		 * cleaned.
12704 		 */
12705 		if (!dc_state_add_plane(
12706 				dc,
12707 				dm_new_crtc_state->stream,
12708 				dc_new_plane_state,
12709 				dm_state->context)) {
12710 
12711 			dc_plane_state_release(dc_new_plane_state);
12712 			ret = -EINVAL;
12713 			goto out;
12714 		}
12715 
12716 		dm_new_plane_state->dc_state = dc_new_plane_state;
12717 
12718 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
12719 
12720 		/* Tell DC to do a full surface update every time there
12721 		 * is a plane change. Inefficient, but works for now.
12722 		 */
12723 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
12724 
12725 		*lock_and_validation_needed = true;
12726 	}
12727 
12728 out:
12729 	/* If enabling cursor overlay failed, attempt fallback to native mode */
12730 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
12731 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12732 						    new_plane_state, enable);
12733 		if (ret)
12734 			return ret;
12735 
12736 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
12737 	}
12738 
12739 	return ret;
12740 }
12741 
12742 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
12743 				       int *src_w, int *src_h)
12744 {
12745 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
12746 	case DRM_MODE_ROTATE_90:
12747 	case DRM_MODE_ROTATE_270:
12748 		*src_w = plane_state->src_h >> 16;
12749 		*src_h = plane_state->src_w >> 16;
12750 		break;
12751 	case DRM_MODE_ROTATE_0:
12752 	case DRM_MODE_ROTATE_180:
12753 	default:
12754 		*src_w = plane_state->src_w >> 16;
12755 		*src_h = plane_state->src_h >> 16;
12756 		break;
12757 	}
12758 }
12759 
12760 static void
12761 dm_get_plane_scale(struct drm_plane_state *plane_state,
12762 		   int *out_plane_scale_w, int *out_plane_scale_h)
12763 {
12764 	int plane_src_w, plane_src_h;
12765 
12766 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
12767 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
12768 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
12769 }
12770 
12771 /*
12772  * The normalized_zpos value cannot be used by this iterator directly. It's only
12773  * calculated for enabled planes, potentially causing normalized_zpos collisions
12774  * between enabled/disabled planes in the atomic state. We need a unique value
12775  * so that the iterator will not generate the same object twice, or loop
12776  * indefinitely.
12777  */
12778 static inline struct __drm_planes_state *__get_next_zpos(
12779 	struct drm_atomic_commit *state,
12780 	struct __drm_planes_state *prev)
12781 {
12782 	unsigned int highest_zpos = 0, prev_zpos = 256;
12783 	uint32_t highest_id = 0, prev_id = UINT_MAX;
12784 	struct drm_plane_state *new_plane_state;
12785 	struct drm_plane *plane;
12786 	int i, highest_i = -1;
12787 
12788 	if (prev != NULL) {
12789 		prev_zpos = prev->new_state->zpos;
12790 		prev_id = prev->ptr->base.id;
12791 	}
12792 
12793 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
12794 		/* Skip planes with higher zpos than the previously returned */
12795 		if (new_plane_state->zpos > prev_zpos ||
12796 		    (new_plane_state->zpos == prev_zpos &&
12797 		     plane->base.id >= prev_id))
12798 			continue;
12799 
12800 		/* Save the index of the plane with highest zpos */
12801 		if (new_plane_state->zpos > highest_zpos ||
12802 		    (new_plane_state->zpos == highest_zpos &&
12803 		     plane->base.id > highest_id)) {
12804 			highest_zpos = new_plane_state->zpos;
12805 			highest_id = plane->base.id;
12806 			highest_i = i;
12807 		}
12808 	}
12809 
12810 	if (highest_i < 0)
12811 		return NULL;
12812 
12813 	return &state->planes[highest_i];
12814 }
12815 
12816 /*
12817  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
12818  * by descending zpos, as read from the new plane state. This is the same
12819  * ordering as defined by drm_atomic_normalize_zpos().
12820  */
12821 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
12822 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
12823 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
12824 		for_each_if(((plane) = __i->ptr,				\
12825 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
12826 			     (old_plane_state) = __i->old_state,		\
12827 			     (new_plane_state) = __i->new_state, 1))
12828 
12829 static int add_affected_mst_dsc_crtcs(struct drm_atomic_commit *state, struct drm_crtc *crtc)
12830 {
12831 	struct drm_connector *connector;
12832 	struct drm_connector_state *conn_state, *old_conn_state;
12833 	struct amdgpu_dm_connector *aconnector = NULL;
12834 	int i;
12835 
12836 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
12837 		if (!conn_state->crtc)
12838 			conn_state = old_conn_state;
12839 
12840 		if (conn_state->crtc != crtc)
12841 			continue;
12842 
12843 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
12844 			continue;
12845 
12846 		aconnector = to_amdgpu_dm_connector(connector);
12847 		if (!aconnector->mst_output_port || !aconnector->mst_root)
12848 			aconnector = NULL;
12849 		else
12850 			break;
12851 	}
12852 
12853 	if (!aconnector)
12854 		return 0;
12855 
12856 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
12857 }
12858 
12859 /**
12860  * DOC: Cursor Modes - Native vs Overlay
12861  *
12862  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
12863  * plane. It does not require a dedicated hw plane to enable, but it is
12864  * subjected to the same z-order and scaling as the hw plane. It also has format
12865  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
12866  * hw plane.
12867  *
12868  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
12869  * own scaling and z-pos. It also has no blending restrictions. It lends to a
12870  * cursor behavior more akin to a DRM client's expectations. However, it does
12871  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
12872  * available.
12873  */
12874 
12875 /**
12876  * dm_plane_color_pipeline_active() - Check if a plane's color pipeline active.
12877  * @state: DRM atomic state
12878  * @plane: DRM plane to check
12879  * @use_old: if true, inspect the old colorop states; otherwise the new ones
12880  *
12881  * A color pipeline may be selected (color_pipeline != NULL) but still is
12882  * inactive if every colorop in the chain is bypassed.  Only return
12883  * true when at least one colorop has bypass == false, meaning the cursor
12884  * would be subjected to the transformation in native mode.
12885  *
12886  * Return: true if the pipeline modifies pixels, false otherwise.
12887  */
12888 static bool dm_plane_color_pipeline_active(struct drm_atomic_commit *state,
12889 					   struct drm_plane *plane,
12890 					   bool use_old)
12891 {
12892 	struct drm_colorop *colorop;
12893 	struct drm_colorop_state *old_colorop_state, *new_colorop_state;
12894 	int i;
12895 
12896 	for_each_oldnew_colorop_in_state(state, colorop, old_colorop_state, new_colorop_state, i) {
12897 		struct drm_colorop_state *cstate = use_old ? old_colorop_state : new_colorop_state;
12898 
12899 		if (cstate->colorop->plane != plane)
12900 			continue;
12901 		if (!cstate->bypass)
12902 			return true;
12903 	}
12904 	return false;
12905 }
12906 
12907 /**
12908  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
12909  * @adev: amdgpu device
12910  * @state: DRM atomic state
12911  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
12912  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
12913  *
12914  * Get whether the cursor should be enabled in native mode, or overlay mode, on
12915  * the dm_crtc_state.
12916  *
12917  * The cursor should be enabled in overlay mode if there exists an underlying
12918  * plane - on which the cursor may be blended - that is either YUV formatted,
12919  * scaled differently from the cursor, or has a color pipeline active.
12920  *
12921  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
12922  * calling this function.
12923  *
12924  * Return: 0 on success, or an error code if getting the cursor plane state
12925  * failed.
12926  */
12927 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
12928 				   struct drm_atomic_commit *state,
12929 				   struct dm_crtc_state *dm_crtc_state,
12930 				   enum amdgpu_dm_cursor_mode *cursor_mode)
12931 {
12932 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
12933 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
12934 	struct drm_plane *plane;
12935 	bool consider_mode_change = false;
12936 	bool entire_crtc_covered = false;
12937 	bool cursor_changed = false;
12938 	int underlying_scale_w, underlying_scale_h;
12939 	int cursor_scale_w, cursor_scale_h;
12940 	int i;
12941 
12942 	/* Overlay cursor not supported on HW before DCN
12943 	 * DCN401/420 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
12944 	 * as previous DCN generations, so enable native mode on DCN401/420
12945 	 *
12946 	 * Always set native cursor mode when the CRTC is disabled,
12947 	 * to make sure it doesn't cause atomic commits to fail when
12948 	 * they are trying to disable the CRTC.
12949 	 */
12950 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1) ||
12951 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
12952 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 1) ||
12953 	    !dm_crtc_state->base.enable) {
12954 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12955 		return 0;
12956 	}
12957 
12958 	/* Init cursor_mode to be the same as current */
12959 	*cursor_mode = dm_crtc_state->cursor_mode;
12960 
12961 	/*
12962 	 * Cursor mode can change if a plane's format changes, scale changes, is
12963 	 * enabled/disabled, z-order changes, or color management properties change.
12964 	 */
12965 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
12966 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
12967 
12968 		/* Only care about planes on this CRTC */
12969 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
12970 			continue;
12971 
12972 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
12973 			cursor_changed = true;
12974 
12975 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
12976 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
12977 		    old_plane_state->fb->format != plane_state->fb->format) {
12978 			consider_mode_change = true;
12979 			break;
12980 		}
12981 
12982 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
12983 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
12984 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
12985 			consider_mode_change = true;
12986 			break;
12987 		}
12988 
12989 		if (dm_plane_color_pipeline_active(state, plane, true) !=
12990 		    dm_plane_color_pipeline_active(state, plane, false)) {
12991 			consider_mode_change = true;
12992 			break;
12993 		}
12994 	}
12995 
12996 	if (!consider_mode_change && !crtc_state->zpos_changed)
12997 		return 0;
12998 
12999 	/*
13000 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
13001 	 * no need to set cursor mode. This avoids needlessly locking the cursor
13002 	 * state.
13003 	 */
13004 	if (!cursor_changed &&
13005 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
13006 		return 0;
13007 	}
13008 
13009 	cursor_state = drm_atomic_get_plane_state(state,
13010 						  crtc_state->crtc->cursor);
13011 	if (IS_ERR(cursor_state))
13012 		return PTR_ERR(cursor_state);
13013 
13014 	/* Cursor is disabled */
13015 	if (!cursor_state->fb)
13016 		return 0;
13017 
13018 	/* For all planes in descending z-order (all of which are below cursor
13019 	 * as per zpos definitions), check their scaling and format
13020 	 */
13021 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
13022 
13023 		/* Only care about non-cursor planes on this CRTC */
13024 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
13025 		    plane->type == DRM_PLANE_TYPE_CURSOR)
13026 			continue;
13027 
13028 		/* Underlying plane is YUV format - use overlay cursor */
13029 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
13030 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
13031 			return 0;
13032 		}
13033 
13034 		/* Underlying plane has an active color pipeline - cursor would be transformed */
13035 		if (dm_plane_color_pipeline_active(state, plane, false)) {
13036 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
13037 			return 0;
13038 		}
13039 
13040 		dm_get_plane_scale(plane_state,
13041 				   &underlying_scale_w, &underlying_scale_h);
13042 		dm_get_plane_scale(cursor_state,
13043 				   &cursor_scale_w, &cursor_scale_h);
13044 
13045 		/* Underlying plane has different scale - use overlay cursor */
13046 		if (cursor_scale_w != underlying_scale_w &&
13047 		    cursor_scale_h != underlying_scale_h) {
13048 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
13049 			return 0;
13050 		}
13051 
13052 		/* If this plane covers the whole CRTC, no need to check planes underneath */
13053 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
13054 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
13055 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
13056 			entire_crtc_covered = true;
13057 			break;
13058 		}
13059 	}
13060 
13061 	/* If planes do not cover the entire CRTC, use overlay mode to enable
13062 	 * cursor over holes
13063 	 */
13064 	if (entire_crtc_covered)
13065 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
13066 	else
13067 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
13068 
13069 	return 0;
13070 }
13071 
13072 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
13073 					    struct drm_atomic_commit *state,
13074 					    struct drm_crtc_state *crtc_state)
13075 {
13076 	struct drm_plane *plane;
13077 	struct drm_plane_state *new_plane_state, *old_plane_state;
13078 
13079 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
13080 		new_plane_state = drm_atomic_get_new_plane_state(state, plane);
13081 		old_plane_state = drm_atomic_get_old_plane_state(state, plane);
13082 
13083 		if (!old_plane_state || !new_plane_state)
13084 			continue;
13085 
13086 		if (old_plane_state->fb && new_plane_state->fb &&
13087 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
13088 			return true;
13089 	}
13090 
13091 	return false;
13092 }
13093 
13094 /**
13095  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
13096  *
13097  * @dev: The DRM device
13098  * @state: The atomic state to commit
13099  *
13100  * Validate that the given atomic state is programmable by DC into hardware.
13101  * This involves constructing a &struct dc_state reflecting the new hardware
13102  * state we wish to commit, then querying DC to see if it is programmable. It's
13103  * important not to modify the existing DC state. Otherwise, atomic_check
13104  * may unexpectedly commit hardware changes.
13105  *
13106  * When validating the DC state, it's important that the right locks are
13107  * acquired. For full updates case which removes/adds/updates streams on one
13108  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
13109  * that any such full update commit will wait for completion of any outstanding
13110  * flip using DRMs synchronization events.
13111  *
13112  * Note that DM adds the affected connectors for all CRTCs in state, when that
13113  * might not seem necessary. This is because DC stream creation requires the
13114  * DC sink, which is tied to the DRM connector state. Cleaning this up should
13115  * be possible but non-trivial - a possible TODO item.
13116  *
13117  * Return: -Error code if validation failed.
13118  */
13119 static int amdgpu_dm_atomic_check(struct drm_device *dev,
13120 				  struct drm_atomic_commit *state)
13121 {
13122 	struct amdgpu_device *adev = drm_to_adev(dev);
13123 	struct dm_atomic_state *dm_state = NULL;
13124 	struct dc *dc = adev->dm.dc;
13125 	struct drm_connector *connector;
13126 	struct drm_connector_state *old_con_state, *new_con_state;
13127 	struct drm_crtc *crtc;
13128 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13129 	struct drm_plane *plane;
13130 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
13131 	enum dc_status status;
13132 	int ret, i;
13133 	bool lock_and_validation_needed = false;
13134 	bool is_top_most_overlay = true;
13135 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
13136 	struct drm_dp_mst_topology_mgr *mgr;
13137 	struct drm_dp_mst_topology_state *mst_state;
13138 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
13139 
13140 	trace_amdgpu_dm_atomic_check_begin(state);
13141 
13142 	ret = drm_atomic_helper_check_modeset(dev, state);
13143 	if (ret) {
13144 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
13145 		goto fail;
13146 	}
13147 
13148 	/* Check connector changes */
13149 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
13150 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
13151 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
13152 
13153 		/* Skip connectors that are disabled or part of modeset already. */
13154 		if (!new_con_state->crtc)
13155 			continue;
13156 
13157 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
13158 		if (IS_ERR(new_crtc_state)) {
13159 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
13160 			ret = PTR_ERR(new_crtc_state);
13161 			goto fail;
13162 		}
13163 
13164 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
13165 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
13166 			new_crtc_state->connectors_changed = true;
13167 	}
13168 
13169 	if (dc_resource_is_dsc_encoding_supported(dc)) {
13170 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13171 			dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13172 			dm_new_crtc_state->mode_changed_independent_from_dsc = new_crtc_state->mode_changed;
13173 		}
13174 
13175 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13176 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
13177 				ret = add_affected_mst_dsc_crtcs(state, crtc);
13178 				if (ret) {
13179 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
13180 					goto fail;
13181 				}
13182 			}
13183 		}
13184 	}
13185 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13186 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
13187 
13188 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
13189 		    !new_crtc_state->color_mgmt_changed &&
13190 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
13191 			dm_old_crtc_state->dsc_force_changed == false)
13192 			continue;
13193 
13194 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
13195 		if (ret) {
13196 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
13197 			goto fail;
13198 		}
13199 
13200 		if (!new_crtc_state->enable)
13201 			continue;
13202 
13203 		ret = drm_atomic_add_affected_connectors(state, crtc);
13204 		if (ret) {
13205 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
13206 			goto fail;
13207 		}
13208 
13209 		ret = drm_atomic_add_affected_planes(state, crtc);
13210 		if (ret) {
13211 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
13212 			goto fail;
13213 		}
13214 
13215 		if (dm_old_crtc_state->dsc_force_changed)
13216 			new_crtc_state->mode_changed = true;
13217 	}
13218 
13219 	/*
13220 	 * Add all primary and overlay planes on the CRTC to the state
13221 	 * whenever a plane is enabled to maintain correct z-ordering
13222 	 * and to enable fast surface updates.
13223 	 */
13224 	drm_for_each_crtc(crtc, dev) {
13225 		bool modified = false;
13226 
13227 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
13228 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
13229 				continue;
13230 
13231 			if (new_plane_state->crtc == crtc ||
13232 			    old_plane_state->crtc == crtc) {
13233 				modified = true;
13234 				break;
13235 			}
13236 		}
13237 
13238 		if (!modified)
13239 			continue;
13240 
13241 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
13242 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
13243 				continue;
13244 
13245 			new_plane_state =
13246 				drm_atomic_get_plane_state(state, plane);
13247 
13248 			if (IS_ERR(new_plane_state)) {
13249 				ret = PTR_ERR(new_plane_state);
13250 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
13251 				goto fail;
13252 			}
13253 		}
13254 	}
13255 
13256 	/*
13257 	 * DC consults the zpos (layer_index in DC terminology) to determine the
13258 	 * hw plane on which to enable the hw cursor (see
13259 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
13260 	 * atomic state, so call drm helper to normalize zpos.
13261 	 */
13262 	ret = drm_atomic_normalize_zpos(dev, state);
13263 	if (ret) {
13264 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
13265 		goto fail;
13266 	}
13267 
13268 	/*
13269 	 * Determine whether cursors on each CRTC should be enabled in native or
13270 	 * overlay mode.
13271 	 */
13272 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13273 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13274 
13275 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
13276 					      &dm_new_crtc_state->cursor_mode);
13277 		if (ret) {
13278 			drm_dbg(dev, "Failed to determine cursor mode\n");
13279 			goto fail;
13280 		}
13281 
13282 		/*
13283 		 * If overlay cursor is needed, DC cannot go through the
13284 		 * native cursor update path. All enabled planes on the CRTC
13285 		 * need to be added for DC to not disable a plane by mistake
13286 		 */
13287 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
13288 			if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
13289 				drm_dbg(dev, "Overlay cursor not supported on DCE\n");
13290 				ret = -EINVAL;
13291 				goto fail;
13292 			}
13293 
13294 			ret = drm_atomic_add_affected_planes(state, crtc);
13295 			if (ret)
13296 				goto fail;
13297 		}
13298 	}
13299 
13300 	/* Remove exiting planes if they are modified */
13301 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13302 
13303 		ret = dm_update_plane_state(dc, state, plane,
13304 					    old_plane_state,
13305 					    new_plane_state,
13306 					    false,
13307 					    &lock_and_validation_needed,
13308 					    &is_top_most_overlay);
13309 		if (ret) {
13310 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13311 			goto fail;
13312 		}
13313 	}
13314 
13315 	/* Disable all crtcs which require disable */
13316 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13317 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
13318 					   old_crtc_state,
13319 					   new_crtc_state,
13320 					   false,
13321 					   &lock_and_validation_needed);
13322 		if (ret) {
13323 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
13324 			goto fail;
13325 		}
13326 	}
13327 
13328 	/* Enable all crtcs which require enable */
13329 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13330 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
13331 					   old_crtc_state,
13332 					   new_crtc_state,
13333 					   true,
13334 					   &lock_and_validation_needed);
13335 		if (ret) {
13336 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
13337 			goto fail;
13338 		}
13339 	}
13340 
13341 	/* Add new/modified planes */
13342 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13343 		ret = dm_update_plane_state(dc, state, plane,
13344 					    old_plane_state,
13345 					    new_plane_state,
13346 					    true,
13347 					    &lock_and_validation_needed,
13348 					    &is_top_most_overlay);
13349 		if (ret) {
13350 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13351 			goto fail;
13352 		}
13353 	}
13354 
13355 #if defined(CONFIG_DRM_AMD_DC_FP)
13356 	if (dc_resource_is_dsc_encoding_supported(dc)) {
13357 		ret = pre_validate_dsc(state, &dm_state, vars);
13358 		if (ret != 0)
13359 			goto fail;
13360 	}
13361 #endif
13362 
13363 	/* Run this here since we want to validate the streams we created */
13364 	ret = drm_atomic_helper_check_planes(dev, state);
13365 	if (ret) {
13366 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
13367 		goto fail;
13368 	}
13369 
13370 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13371 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13372 		if (dm_new_crtc_state->mpo_requested)
13373 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
13374 	}
13375 
13376 	/* Check cursor restrictions */
13377 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13378 		enum amdgpu_dm_cursor_mode required_cursor_mode;
13379 		int is_rotated, is_scaled;
13380 
13381 		/* Overlay cusor not subject to native cursor restrictions */
13382 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13383 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
13384 			continue;
13385 
13386 		/* Check if rotation or scaling is enabled on DCN401 */
13387 		if ((drm_plane_mask(crtc->cursor) &
13388 		     new_crtc_state->plane_mask) &&
13389 		    (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 1) ||
13390 		     amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
13391 		     amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1))) {
13392 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
13393 
13394 			is_rotated = new_cursor_state &&
13395 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
13396 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
13397 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
13398 
13399 			if (is_rotated || is_scaled) {
13400 				drm_dbg_driver(
13401 					crtc->dev,
13402 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
13403 					crtc->base.id, crtc->name);
13404 				ret = -EINVAL;
13405 				goto fail;
13406 			}
13407 		}
13408 
13409 		/* If HW can only do native cursor, check restrictions again */
13410 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
13411 					      &required_cursor_mode);
13412 		if (ret) {
13413 			drm_dbg_driver(crtc->dev,
13414 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
13415 				       crtc->base.id, crtc->name);
13416 			goto fail;
13417 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
13418 			drm_dbg_driver(crtc->dev,
13419 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling, YUV, or color pipeline restrictions\n",
13420 				       crtc->base.id, crtc->name);
13421 			ret = -EINVAL;
13422 			goto fail;
13423 		}
13424 	}
13425 
13426 	if (state->legacy_cursor_update) {
13427 		/*
13428 		 * This is a fast cursor update coming from the plane update
13429 		 * helper, check if it can be done asynchronously for better
13430 		 * performance.
13431 		 */
13432 		state->async_update =
13433 			!drm_atomic_helper_async_check(dev, state);
13434 
13435 		/*
13436 		 * Skip the remaining global validation if this is an async
13437 		 * update. Cursor updates can be done without affecting
13438 		 * state or bandwidth calcs and this avoids the performance
13439 		 * penalty of locking the private state object and
13440 		 * allocating a new dc_state.
13441 		 */
13442 		if (state->async_update)
13443 			return 0;
13444 	}
13445 
13446 	/* Check scaling and underscan changes*/
13447 	/* TODO Removed scaling changes validation due to inability to commit
13448 	 * new stream into context w\o causing full reset. Need to
13449 	 * decide how to handle.
13450 	 */
13451 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
13452 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
13453 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
13454 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
13455 
13456 		/* Skip any modesets/resets */
13457 		if (!acrtc || drm_atomic_crtc_needs_modeset(
13458 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
13459 			continue;
13460 
13461 		/* Skip any thing not scale or underscan changes */
13462 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
13463 			continue;
13464 
13465 		lock_and_validation_needed = true;
13466 	}
13467 
13468 	/* set the slot info for each mst_state based on the link encoding format */
13469 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
13470 		struct amdgpu_dm_connector *aconnector;
13471 		struct drm_connector *connector;
13472 		struct drm_connector_list_iter iter;
13473 		u8 link_coding_cap;
13474 
13475 		drm_connector_list_iter_begin(dev, &iter);
13476 		drm_for_each_connector_iter(connector, &iter) {
13477 			if (connector->index == mst_state->mgr->conn_base_id) {
13478 				aconnector = to_amdgpu_dm_connector(connector);
13479 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
13480 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
13481 
13482 				break;
13483 			}
13484 		}
13485 		drm_connector_list_iter_end(&iter);
13486 	}
13487 
13488 	/**
13489 	 * Streams and planes are reset when there are changes that affect
13490 	 * bandwidth. Anything that affects bandwidth needs to go through
13491 	 * DC global validation to ensure that the configuration can be applied
13492 	 * to hardware.
13493 	 *
13494 	 * We have to currently stall out here in atomic_check for outstanding
13495 	 * commits to finish in this case because our IRQ handlers reference
13496 	 * DRM state directly - we can end up disabling interrupts too early
13497 	 * if we don't.
13498 	 *
13499 	 * TODO: Remove this stall and drop DM state private objects.
13500 	 */
13501 	if (lock_and_validation_needed) {
13502 		ret = dm_atomic_get_state(state, &dm_state);
13503 		if (ret) {
13504 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
13505 			goto fail;
13506 		}
13507 
13508 		ret = do_aquire_global_lock(dev, state);
13509 		if (ret) {
13510 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
13511 			goto fail;
13512 		}
13513 
13514 #if defined(CONFIG_DRM_AMD_DC_FP)
13515 		if (dc_resource_is_dsc_encoding_supported(dc)) {
13516 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
13517 			if (ret) {
13518 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
13519 				ret = -EINVAL;
13520 				goto fail;
13521 			}
13522 		}
13523 #endif
13524 
13525 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
13526 		if (ret) {
13527 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
13528 			goto fail;
13529 		}
13530 
13531 		/*
13532 		 * Perform validation of MST topology in the state:
13533 		 * We need to perform MST atomic check before calling
13534 		 * dc_validate_global_state(), or there is a chance
13535 		 * to get stuck in an infinite loop and hang eventually.
13536 		 */
13537 		ret = drm_dp_mst_atomic_check(state);
13538 		if (ret) {
13539 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
13540 			goto fail;
13541 		}
13542 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
13543 		if (status != DC_OK) {
13544 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
13545 				       dc_status_to_str(status), status);
13546 			ret = -EINVAL;
13547 			goto fail;
13548 		}
13549 	} else {
13550 		/*
13551 		 * The commit is a fast update. Fast updates shouldn't change
13552 		 * the DC context, affect global validation, and can have their
13553 		 * commit work done in parallel with other commits not touching
13554 		 * the same resource. If we have a new DC context as part of
13555 		 * the DM atomic state from validation we need to free it and
13556 		 * retain the existing one instead.
13557 		 *
13558 		 * Furthermore, since the DM atomic state only contains the DC
13559 		 * context and can safely be annulled, we can free the state
13560 		 * and clear the associated private object now to free
13561 		 * some memory and avoid a possible use-after-free later.
13562 		 */
13563 
13564 		for (i = 0; i < state->num_private_objs; i++) {
13565 			struct drm_private_obj *obj = state->private_objs[i].ptr;
13566 
13567 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
13568 				int j = state->num_private_objs-1;
13569 
13570 				dm_atomic_destroy_state(obj,
13571 						state->private_objs[i].state_to_destroy);
13572 
13573 				/* If i is not at the end of the array then the
13574 				 * last element needs to be moved to where i was
13575 				 * before the array can safely be truncated.
13576 				 */
13577 				if (i != j)
13578 					state->private_objs[i] =
13579 						state->private_objs[j];
13580 
13581 				state->private_objs[j].ptr = NULL;
13582 				state->private_objs[j].state_to_destroy = NULL;
13583 				state->private_objs[j].old_state = NULL;
13584 				state->private_objs[j].new_state = NULL;
13585 
13586 				state->num_private_objs = j;
13587 				break;
13588 			}
13589 		}
13590 	}
13591 
13592 	/* Store the overall update type for use later in atomic check. */
13593 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13594 		struct dm_crtc_state *dm_new_crtc_state =
13595 			to_dm_crtc_state(new_crtc_state);
13596 
13597 		/*
13598 		 * Only allow async flips for fast updates that don't change
13599 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
13600 		 */
13601 		if (new_crtc_state->async_flip &&
13602 		    (lock_and_validation_needed ||
13603 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
13604 			drm_dbg_atomic(crtc->dev,
13605 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
13606 				       crtc->base.id, crtc->name);
13607 			ret = -EINVAL;
13608 			goto fail;
13609 		}
13610 
13611 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
13612 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
13613 	}
13614 
13615 	/* Must be success */
13616 	WARN_ON(ret);
13617 
13618 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13619 
13620 	return ret;
13621 
13622 fail:
13623 	if (ret == -EDEADLK)
13624 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
13625 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
13626 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
13627 	else
13628 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
13629 
13630 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13631 
13632 	return ret;
13633 }
13634 
13635 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
13636 		unsigned int offset,
13637 		unsigned int total_length,
13638 		u8 *data,
13639 		unsigned int length,
13640 		struct amdgpu_hdmi_vsdb_info *vsdb)
13641 {
13642 	bool res;
13643 	union dmub_rb_cmd cmd;
13644 	struct dmub_cmd_send_edid_cea *input;
13645 	struct dmub_cmd_edid_cea_output *output;
13646 
13647 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
13648 		return false;
13649 
13650 	memset(&cmd, 0, sizeof(cmd));
13651 
13652 	input = &cmd.edid_cea.data.input;
13653 
13654 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
13655 	cmd.edid_cea.header.sub_type = 0;
13656 	cmd.edid_cea.header.payload_bytes =
13657 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
13658 	input->offset = offset;
13659 	input->length = length;
13660 	input->cea_total_length = total_length;
13661 	memcpy(input->payload, data, length);
13662 
13663 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
13664 	if (!res) {
13665 		drm_err(adev_to_drm(dm->adev), "EDID CEA parser failed\n");
13666 		return false;
13667 	}
13668 
13669 	output = &cmd.edid_cea.data.output;
13670 
13671 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
13672 		if (!output->ack.success) {
13673 			drm_err(adev_to_drm(dm->adev), "EDID CEA ack failed at offset %d\n",
13674 					output->ack.offset);
13675 		}
13676 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
13677 		if (!output->amd_vsdb.vsdb_found)
13678 			return false;
13679 
13680 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
13681 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
13682 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
13683 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
13684 		vsdb->freesync_mccs_vcp_code = output->amd_vsdb.freesync_mccs_vcp_code;
13685 	} else {
13686 		drm_warn(adev_to_drm(dm->adev), "Unknown EDID CEA parser results\n");
13687 		return false;
13688 	}
13689 
13690 	return true;
13691 }
13692 
13693 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
13694 		u8 *edid_ext, int len,
13695 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13696 {
13697 	int i;
13698 
13699 	/* send extension block to DMCU for parsing */
13700 	for (i = 0; i < len; i += 8) {
13701 		bool res;
13702 		int offset;
13703 
13704 		/* send 8 bytes a time */
13705 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
13706 			return false;
13707 
13708 		if (i+8 == len) {
13709 			/* EDID block sent completed, expect result */
13710 			int version, min_rate, max_rate;
13711 
13712 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
13713 			if (res) {
13714 				/* amd vsdb found */
13715 				vsdb_info->freesync_supported = 1;
13716 				vsdb_info->amd_vsdb_version = version;
13717 				vsdb_info->min_refresh_rate_hz = min_rate;
13718 				vsdb_info->max_refresh_rate_hz = max_rate;
13719 				/* Not enabled on DMCU*/
13720 				vsdb_info->freesync_mccs_vcp_code = 0;
13721 				return true;
13722 			}
13723 			/* not amd vsdb */
13724 			return false;
13725 		}
13726 
13727 		/* check for ack*/
13728 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
13729 		if (!res)
13730 			return false;
13731 	}
13732 
13733 	return false;
13734 }
13735 
13736 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
13737 		u8 *edid_ext, int len,
13738 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13739 {
13740 	int i;
13741 
13742 	/* send extension block to DMCU for parsing */
13743 	for (i = 0; i < len; i += 8) {
13744 		/* send 8 bytes a time */
13745 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
13746 			return false;
13747 	}
13748 
13749 	return vsdb_info->freesync_supported;
13750 }
13751 
13752 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
13753 		u8 *edid_ext, int len,
13754 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13755 {
13756 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
13757 	bool ret;
13758 
13759 	mutex_lock(&adev->dm.dc_lock);
13760 	if (adev->dm.dmub_srv)
13761 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
13762 	else
13763 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
13764 	mutex_unlock(&adev->dm.dc_lock);
13765 	return ret;
13766 }
13767 
13768 static void parse_edid_displayid_vrr(struct drm_connector *connector,
13769 				     const struct edid *edid)
13770 {
13771 	u8 *edid_ext = NULL;
13772 	int i;
13773 	int j = 0;
13774 	u16 min_vfreq;
13775 	u16 max_vfreq;
13776 
13777 	if (!edid || !edid->extensions)
13778 		return;
13779 
13780 	/* Find DisplayID extension */
13781 	for (i = 0; i < edid->extensions; i++) {
13782 		edid_ext = (void *)(edid + (i + 1));
13783 		if (edid_ext[0] == DISPLAYID_EXT)
13784 			break;
13785 	}
13786 
13787 	if (i == edid->extensions)
13788 		return;
13789 
13790 	while (j < EDID_LENGTH) {
13791 		/* Get dynamic video timing range from DisplayID if available */
13792 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
13793 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
13794 			min_vfreq = edid_ext[j+9];
13795 			if (edid_ext[j+1] & 7)
13796 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
13797 			else
13798 				max_vfreq = edid_ext[j+10];
13799 
13800 			if (max_vfreq && min_vfreq) {
13801 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
13802 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
13803 
13804 				return;
13805 			}
13806 		}
13807 		j++;
13808 	}
13809 }
13810 
13811 static int get_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13812 			struct amdgpu_hdmi_vsdb_info *vsdb_info)
13813 {
13814 	struct drm_connector *connector = &aconnector->base;
13815 
13816 	vsdb_info->replay_mode = connector->display_info.amd_vsdb.replay_mode;
13817 	vsdb_info->amd_vsdb_version = connector->display_info.amd_vsdb.version;
13818 
13819 	return connector->display_info.amd_vsdb.version != 0;
13820 }
13821 
13822 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13823 			       const struct edid *edid,
13824 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
13825 {
13826 	u8 *edid_ext = NULL;
13827 	int i;
13828 	bool valid_vsdb_found = false;
13829 
13830 	/*----- drm_find_cea_extension() -----*/
13831 	/* No EDID or EDID extensions */
13832 	if (edid == NULL || edid->extensions == 0)
13833 		return -ENODEV;
13834 
13835 	/* Find CEA extension */
13836 	for (i = 0; i < edid->extensions; i++) {
13837 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
13838 		if (edid_ext[0] == CEA_EXT)
13839 			break;
13840 	}
13841 
13842 	if (i == edid->extensions)
13843 		return -ENODEV;
13844 
13845 	/*----- cea_db_offsets() -----*/
13846 	if (edid_ext[0] != CEA_EXT)
13847 		return -ENODEV;
13848 
13849 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
13850 
13851 	return valid_vsdb_found ? i : -ENODEV;
13852 }
13853 
13854 /**
13855  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
13856  *
13857  * @connector: Connector to query.
13858  * @drm_edid: DRM EDID from monitor
13859  * @do_mccs: Controls whether MCCS (Monitor Control Command Set) over
13860  *	      DDC (Display Data Channel) transactions are performed. When true,
13861  *	      the driver queries the monitor to get or update additional FreeSync
13862  *	      capability information. When false, these transactions are skipped.
13863  *
13864  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
13865  * track of some of the display information in the internal data struct used by
13866  * amdgpu_dm. This function checks which type of connector we need to set the
13867  * FreeSync parameters.
13868  */
13869 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
13870 				    const struct drm_edid *drm_edid, bool do_mccs)
13871 {
13872 	int i = 0;
13873 	struct amdgpu_dm_connector *amdgpu_dm_connector =
13874 			to_amdgpu_dm_connector(connector);
13875 	struct dm_connector_state *dm_con_state = NULL;
13876 	struct dc_sink *sink;
13877 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
13878 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
13879 	const struct edid *edid;
13880 	bool freesync_capable = false;
13881 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
13882 
13883 	if (!connector->state) {
13884 		drm_err(adev_to_drm(adev), "%s - Connector has no state", __func__);
13885 		goto update;
13886 	}
13887 
13888 	sink = amdgpu_dm_connector->dc_sink ?
13889 		amdgpu_dm_connector->dc_sink :
13890 		amdgpu_dm_connector->dc_em_sink;
13891 
13892 	drm_edid_connector_update(connector, drm_edid);
13893 
13894 	if (!drm_edid || !sink) {
13895 		dm_con_state = to_dm_connector_state(connector->state);
13896 
13897 		amdgpu_dm_connector->min_vfreq = 0;
13898 		amdgpu_dm_connector->max_vfreq = 0;
13899 		freesync_capable = false;
13900 
13901 		goto update;
13902 	}
13903 
13904 	dm_con_state = to_dm_connector_state(connector->state);
13905 
13906 	if (!adev->dm.freesync_module || !dc_supports_vrr(sink->ctx->dce_version))
13907 		goto update;
13908 
13909 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
13910 
13911 	/* Some eDP panels only have the refresh rate range info in DisplayID */
13912 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
13913 	     connector->display_info.monitor_range.max_vfreq == 0))
13914 		parse_edid_displayid_vrr(connector, edid);
13915 
13916 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
13917 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
13918 		if (amdgpu_dm_connector->dc_link &&
13919 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
13920 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
13921 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
13922 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13923 				freesync_capable = true;
13924 		}
13925 
13926 		get_amd_vsdb(amdgpu_dm_connector, &vsdb_info);
13927 
13928 		if (vsdb_info.replay_mode) {
13929 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
13930 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
13931 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
13932 		}
13933 
13934 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
13935 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13936 		if (i >= 0) {
13937 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13938 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13939 
13940 			if (vsdb_info.freesync_supported) {
13941 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13942 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13943 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13944 					freesync_capable = true;
13945 
13946 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13947 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13948 			}
13949 		}
13950 	}
13951 
13952 	if (amdgpu_dm_connector->dc_link)
13953 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
13954 
13955 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
13956 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13957 		if (i >= 0) {
13958 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13959 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13960 
13961 			if (vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
13962 				amdgpu_dm_connector->pack_sdp_v1_3 = true;
13963 				amdgpu_dm_connector->as_type = as_type;
13964 
13965 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13966 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13967 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13968 					freesync_capable = true;
13969 
13970 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13971 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13972 			}
13973 		}
13974 	}
13975 
13976 	/* Handle MCCS */
13977 	if (do_mccs) {
13978 		dm_helpers_read_mccs_caps(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13979 
13980 		if (sink->edid_caps.freesync_vcp_code && !sink->mccs_caps.freesync_supported)
13981 			freesync_capable = false;
13982 
13983 		if (sink->mccs_caps.freesync_supported && freesync_capable)
13984 			dm_helpers_mccs_vcp_set(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13985 	}
13986 
13987 update:
13988 	if (dm_con_state)
13989 		dm_con_state->freesync_capable = freesync_capable;
13990 
13991 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
13992 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
13993 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
13994 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
13995 	}
13996 
13997 	if (connector->vrr_capable_property)
13998 		drm_connector_set_vrr_capable_property(connector,
13999 						       freesync_capable);
14000 }
14001 
14002 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
14003 {
14004 	struct amdgpu_device *adev = drm_to_adev(dev);
14005 	struct dc *dc = adev->dm.dc;
14006 	int i;
14007 
14008 	mutex_lock(&adev->dm.dc_lock);
14009 	if (dc->current_state) {
14010 		for (i = 0; i < dc->current_state->stream_count; ++i)
14011 			dc->current_state->streams[i]
14012 				->triggered_crtc_reset.enabled =
14013 				adev->dm.force_timing_sync;
14014 
14015 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
14016 		dc_trigger_sync(dc, dc->current_state);
14017 	}
14018 	mutex_unlock(&adev->dm.dc_lock);
14019 }
14020 
14021 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
14022 {
14023 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
14024 		dc_exit_ips_for_hw_access(dc);
14025 }
14026 
14027 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
14028 		       u32 value, const char *func_name)
14029 {
14030 #ifdef DM_CHECK_ADDR_0
14031 	if (address == 0) {
14032 		drm_err(adev_to_drm(ctx->driver_context),
14033 			"invalid register write. address = 0");
14034 		return;
14035 	}
14036 #endif
14037 
14038 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
14039 	cgs_write_register(ctx->cgs_device, address, value);
14040 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
14041 }
14042 
14043 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
14044 			  const char *func_name)
14045 {
14046 	u32 value;
14047 #ifdef DM_CHECK_ADDR_0
14048 	if (address == 0) {
14049 		drm_err(adev_to_drm(ctx->driver_context),
14050 			"invalid register read; address = 0\n");
14051 		return 0;
14052 	}
14053 #endif
14054 
14055 	if (ctx->dmub_srv &&
14056 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
14057 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
14058 		ASSERT(false);
14059 		return 0;
14060 	}
14061 
14062 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
14063 
14064 	value = cgs_read_register(ctx->cgs_device, address);
14065 
14066 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
14067 
14068 	return value;
14069 }
14070 
14071 int amdgpu_dm_process_dmub_aux_transfer_sync(
14072 		struct dc_context *ctx,
14073 		unsigned int link_index,
14074 		struct aux_payload *payload,
14075 		enum aux_return_code_type *operation_result)
14076 {
14077 	struct amdgpu_device *adev = ctx->driver_context;
14078 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
14079 	int ret = -1;
14080 
14081 	mutex_lock(&adev->dm.dpia_aux_lock);
14082 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
14083 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
14084 		goto out;
14085 	}
14086 
14087 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
14088 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
14089 		*operation_result = AUX_RET_ERROR_TIMEOUT;
14090 		goto out;
14091 	}
14092 
14093 	if (p_notify->result != AUX_RET_SUCCESS) {
14094 		/*
14095 		 * Transient states before tunneling is enabled could
14096 		 * lead to this error. We can ignore this for now.
14097 		 */
14098 		if (p_notify->result == AUX_RET_ERROR_PROTOCOL_ERROR) {
14099 			drm_warn(adev_to_drm(adev), "DPIA AUX failed on 0x%x(%d), error %d\n",
14100 					payload->address, payload->length,
14101 					p_notify->result);
14102 		}
14103 		*operation_result = p_notify->result;
14104 		goto out;
14105 	}
14106 
14107 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command & 0xF;
14108 	if (adev->dm.dmub_notify->aux_reply.command & 0xF0)
14109 		/* The reply is stored in the top nibble of the command. */
14110 		payload->reply[0] = (adev->dm.dmub_notify->aux_reply.command >> 4) & 0xF;
14111 
14112 	/*write req may receive a byte indicating partially written number as well*/
14113 	if (p_notify->aux_reply.length)
14114 		memcpy(payload->data, p_notify->aux_reply.data,
14115 				p_notify->aux_reply.length);
14116 
14117 	/* success */
14118 	ret = p_notify->aux_reply.length;
14119 	*operation_result = p_notify->result;
14120 out:
14121 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
14122 	mutex_unlock(&adev->dm.dpia_aux_lock);
14123 	return ret;
14124 }
14125 
14126 static void abort_fused_io(
14127 		struct dc_context *ctx,
14128 		const struct dmub_cmd_fused_request *request
14129 )
14130 {
14131 	union dmub_rb_cmd command = { 0 };
14132 	struct dmub_rb_cmd_fused_io *io = &command.fused_io;
14133 
14134 	io->header.type = DMUB_CMD__FUSED_IO;
14135 	io->header.sub_type = DMUB_CMD__FUSED_IO_ABORT;
14136 	io->header.payload_bytes = sizeof(*io) - sizeof(io->header);
14137 	io->request = *request;
14138 	dm_execute_dmub_cmd(ctx, &command, DM_DMUB_WAIT_TYPE_NO_WAIT);
14139 }
14140 
14141 static bool execute_fused_io(
14142 		struct amdgpu_device *dev,
14143 		struct dc_context *ctx,
14144 		union dmub_rb_cmd *commands,
14145 		uint8_t count,
14146 		uint32_t timeout_us
14147 )
14148 {
14149 	const uint8_t ddc_line = commands[0].fused_io.request.u.aux.ddc_line;
14150 
14151 	if (ddc_line >= ARRAY_SIZE(dev->dm.fused_io))
14152 		return false;
14153 
14154 	struct fused_io_sync *sync = &dev->dm.fused_io[ddc_line];
14155 	struct dmub_rb_cmd_fused_io *first = &commands[0].fused_io;
14156 	const bool result = dm_execute_dmub_cmd_list(ctx, count, commands, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY)
14157 			&& first->header.ret_status
14158 			&& first->request.status == FUSED_REQUEST_STATUS_SUCCESS;
14159 
14160 	if (!result)
14161 		return false;
14162 
14163 	while (wait_for_completion_timeout(&sync->replied, usecs_to_jiffies(timeout_us))) {
14164 		reinit_completion(&sync->replied);
14165 
14166 		struct dmub_cmd_fused_request *reply = (struct dmub_cmd_fused_request *) sync->reply_data;
14167 
14168 		static_assert(sizeof(*reply) <= sizeof(sync->reply_data), "Size mismatch");
14169 
14170 		if (reply->identifier == first->request.identifier) {
14171 			first->request = *reply;
14172 			return true;
14173 		}
14174 	}
14175 
14176 	reinit_completion(&sync->replied);
14177 	first->request.status = FUSED_REQUEST_STATUS_TIMEOUT;
14178 	abort_fused_io(ctx, &first->request);
14179 	return false;
14180 }
14181 
14182 bool amdgpu_dm_execute_fused_io(
14183 		struct amdgpu_device *dev,
14184 		struct dc_link *link,
14185 		union dmub_rb_cmd *commands,
14186 		uint8_t count,
14187 		uint32_t timeout_us)
14188 {
14189 	struct amdgpu_display_manager *dm = &dev->dm;
14190 
14191 	mutex_lock(&dm->dpia_aux_lock);
14192 
14193 	const bool result = execute_fused_io(dev, link->ctx, commands, count, timeout_us);
14194 
14195 	mutex_unlock(&dm->dpia_aux_lock);
14196 	return result;
14197 }
14198 
14199 int amdgpu_dm_process_dmub_set_config_sync(
14200 		struct dc_context *ctx,
14201 		unsigned int link_index,
14202 		struct set_config_cmd_payload *payload,
14203 		enum set_config_status *operation_result)
14204 {
14205 	struct amdgpu_device *adev = ctx->driver_context;
14206 	bool is_cmd_complete;
14207 	int ret;
14208 
14209 	mutex_lock(&adev->dm.dpia_aux_lock);
14210 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
14211 			link_index, payload, adev->dm.dmub_notify);
14212 
14213 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
14214 		ret = 0;
14215 		*operation_result = adev->dm.dmub_notify->sc_status;
14216 	} else {
14217 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
14218 		ret = -1;
14219 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
14220 	}
14221 
14222 	if (!is_cmd_complete)
14223 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
14224 	mutex_unlock(&adev->dm.dpia_aux_lock);
14225 	return ret;
14226 }
14227 
14228 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
14229 {
14230 	struct amdgpu_device *adev = ctx->driver_context;
14231 
14232 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
14233 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
14234 }
14235 
14236 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)
14237 {
14238 	struct amdgpu_device *adev = ctx->driver_context;
14239 
14240 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
14241 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
14242 }
14243 
14244 void dm_acpi_process_phy_transition_interlock(
14245 	const struct dc_context *ctx,
14246 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
14247 {
14248 	// Not yet implemented
14249 }
14250