xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision 547cc004c3c180cbf9da2089ddbde5bc430663eb)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright 2015-2026 Advanced Micro Devices, Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  * Authors: AMD
24  *
25  */
26 
27 /* The caprices of the preprocessor require that this be declared right here */
28 #define CREATE_TRACE_POINTS
29 
30 #include "dm_services_types.h"
31 #include "dc.h"
32 #include "link_enc_cfg.h"
33 #include "dc/inc/core_types.h"
34 #include "dal_asic_id.h"
35 #include "dmub/dmub_srv.h"
36 #include "dc/inc/hw/dmcu.h"
37 #include "dc/inc/hw/abm.h"
38 #include "dc/dc_dmub_srv.h"
39 #include "dc/dc_edid_parser.h"
40 #include "dc/dc_stat.h"
41 #include "dc/dc_state.h"
42 #include "amdgpu_dm_trace.h"
43 #include "link/protocols/link_dpcd.h"
44 #include "link_service_types.h"
45 #include "link/protocols/link_dp_capability.h"
46 #include "link/protocols/link_ddc.h"
47 
48 #include "amdgpu.h"
49 #include "amdgpu_display.h"
50 #include "amdgpu_ucode.h"
51 #include "atom.h"
52 #include "amdgpu_dm.h"
53 #include "amdgpu_dm_plane.h"
54 #include "amdgpu_dm_crtc.h"
55 #include "amdgpu_dm_hdcp.h"
56 #include <drm/display/drm_hdcp_helper.h>
57 #include "amdgpu_dm_wb.h"
58 #include "amdgpu_atombios.h"
59 
60 #include "amd_shared.h"
61 #include "amdgpu_dm_irq.h"
62 #include "dm_helpers.h"
63 #include "amdgpu_dm_mst_types.h"
64 #if defined(CONFIG_DEBUG_FS)
65 #include "amdgpu_dm_debugfs.h"
66 #endif
67 #include "amdgpu_dm_psr.h"
68 #include "amdgpu_dm_replay.h"
69 
70 #include "ivsrcid/ivsrcid_vislands30.h"
71 
72 #include <linux/backlight.h>
73 #include <linux/module.h>
74 #include <linux/moduleparam.h>
75 #include <linux/types.h>
76 #include <linux/pm_runtime.h>
77 #include <linux/pci.h>
78 #include <linux/power_supply.h>
79 #include <linux/firmware.h>
80 #include <linux/component.h>
81 #include <linux/sort.h>
82 
83 #include <drm/drm_privacy_screen_consumer.h>
84 #include <drm/display/drm_dp_mst_helper.h>
85 #include <drm/display/drm_hdmi_helper.h>
86 #include <drm/drm_atomic.h>
87 #include <drm/drm_atomic_uapi.h>
88 #include <drm/drm_atomic_helper.h>
89 #include <drm/drm_blend.h>
90 #include <drm/drm_fixed.h>
91 #include <drm/drm_fourcc.h>
92 #include <drm/drm_edid.h>
93 #include <drm/drm_eld.h>
94 #include <drm/drm_mode.h>
95 #include <drm/drm_utils.h>
96 #include <drm/drm_vblank.h>
97 #include <drm/drm_audio_component.h>
98 #include <drm/drm_colorop.h>
99 #include <drm/drm_gem_atomic_helper.h>
100 
101 #include <media/cec-notifier.h>
102 #include <acpi/video.h>
103 
104 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
105 
106 #include "modules/inc/mod_freesync.h"
107 #include "modules/inc/mod_power.h"
108 #include "modules/power/power_helpers.h"
109 
110 static_assert(AMDGPU_DMUB_NOTIFICATION_MAX == DMUB_NOTIFICATION_MAX, "AMDGPU_DMUB_NOTIFICATION_MAX mismatch");
111 
112 #define FIRMWARE_RENOIR_DMUB "amdgpu/renoir_dmcub.bin"
113 MODULE_FIRMWARE(FIRMWARE_RENOIR_DMUB);
114 #define FIRMWARE_SIENNA_CICHLID_DMUB "amdgpu/sienna_cichlid_dmcub.bin"
115 MODULE_FIRMWARE(FIRMWARE_SIENNA_CICHLID_DMUB);
116 #define FIRMWARE_NAVY_FLOUNDER_DMUB "amdgpu/navy_flounder_dmcub.bin"
117 MODULE_FIRMWARE(FIRMWARE_NAVY_FLOUNDER_DMUB);
118 #define FIRMWARE_GREEN_SARDINE_DMUB "amdgpu/green_sardine_dmcub.bin"
119 MODULE_FIRMWARE(FIRMWARE_GREEN_SARDINE_DMUB);
120 #define FIRMWARE_VANGOGH_DMUB "amdgpu/vangogh_dmcub.bin"
121 MODULE_FIRMWARE(FIRMWARE_VANGOGH_DMUB);
122 #define FIRMWARE_DIMGREY_CAVEFISH_DMUB "amdgpu/dimgrey_cavefish_dmcub.bin"
123 MODULE_FIRMWARE(FIRMWARE_DIMGREY_CAVEFISH_DMUB);
124 #define FIRMWARE_BEIGE_GOBY_DMUB "amdgpu/beige_goby_dmcub.bin"
125 MODULE_FIRMWARE(FIRMWARE_BEIGE_GOBY_DMUB);
126 #define FIRMWARE_YELLOW_CARP_DMUB "amdgpu/yellow_carp_dmcub.bin"
127 MODULE_FIRMWARE(FIRMWARE_YELLOW_CARP_DMUB);
128 #define FIRMWARE_DCN_314_DMUB "amdgpu/dcn_3_1_4_dmcub.bin"
129 MODULE_FIRMWARE(FIRMWARE_DCN_314_DMUB);
130 #define FIRMWARE_DCN_315_DMUB "amdgpu/dcn_3_1_5_dmcub.bin"
131 MODULE_FIRMWARE(FIRMWARE_DCN_315_DMUB);
132 #define FIRMWARE_DCN316_DMUB "amdgpu/dcn_3_1_6_dmcub.bin"
133 MODULE_FIRMWARE(FIRMWARE_DCN316_DMUB);
134 
135 #define FIRMWARE_DCN_V3_2_0_DMCUB "amdgpu/dcn_3_2_0_dmcub.bin"
136 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_0_DMCUB);
137 #define FIRMWARE_DCN_V3_2_1_DMCUB "amdgpu/dcn_3_2_1_dmcub.bin"
138 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_1_DMCUB);
139 
140 #define FIRMWARE_RAVEN_DMCU		"amdgpu/raven_dmcu.bin"
141 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
142 
143 #define FIRMWARE_NAVI12_DMCU            "amdgpu/navi12_dmcu.bin"
144 MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
145 
146 #define FIRMWARE_DCN_35_DMUB "amdgpu/dcn_3_5_dmcub.bin"
147 MODULE_FIRMWARE(FIRMWARE_DCN_35_DMUB);
148 
149 #define FIRMWARE_DCN_351_DMUB "amdgpu/dcn_3_5_1_dmcub.bin"
150 MODULE_FIRMWARE(FIRMWARE_DCN_351_DMUB);
151 
152 #define FIRMWARE_DCN_36_DMUB "amdgpu/dcn_3_6_dmcub.bin"
153 MODULE_FIRMWARE(FIRMWARE_DCN_36_DMUB);
154 
155 #define FIRMWARE_DCN_401_DMUB "amdgpu/dcn_4_0_1_dmcub.bin"
156 MODULE_FIRMWARE(FIRMWARE_DCN_401_DMUB);
157 
158 #define FIRMWARE_DCN_42_DMUB "amdgpu/dcn_4_2_dmcub.bin"
159 MODULE_FIRMWARE(FIRMWARE_DCN_42_DMUB);
160 
161 #define FIRMWARE_DCN_42B_DMUB "amdgpu/dcn_4_2_1_dmcub.bin"
162 MODULE_FIRMWARE(FIRMWARE_DCN_42B_DMUB);
163 
164 /**
165  * DOC: overview
166  *
167  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
168  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
169  * requests into DC requests, and DC responses into DRM responses.
170  *
171  * The root control structure is &struct amdgpu_display_manager.
172  */
173 
174 /* basic init/fini API */
175 static int amdgpu_dm_init(struct amdgpu_device *adev);
176 static void amdgpu_dm_fini(struct amdgpu_device *adev);
177 static bool is_freesync_video_mode(const struct drm_display_mode *mode, struct amdgpu_dm_connector *aconnector);
178 static void reset_freesync_config_for_crtc(struct dm_crtc_state *new_crtc_state);
179 static struct amdgpu_i2c_adapter *
180 create_i2c(struct ddc_service *ddc_service, bool oem);
181 
182 static enum drm_mode_subconnector get_subconnector_type(struct dc_link *link)
183 {
184 	switch (link->dpcd_caps.dongle_type) {
185 	case DISPLAY_DONGLE_NONE:
186 		return DRM_MODE_SUBCONNECTOR_Native;
187 	case DISPLAY_DONGLE_DP_VGA_CONVERTER:
188 		return DRM_MODE_SUBCONNECTOR_VGA;
189 	case DISPLAY_DONGLE_DP_DVI_CONVERTER:
190 	case DISPLAY_DONGLE_DP_DVI_DONGLE:
191 		return DRM_MODE_SUBCONNECTOR_DVID;
192 	case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
193 	case DISPLAY_DONGLE_DP_HDMI_DONGLE:
194 		return DRM_MODE_SUBCONNECTOR_HDMIA;
195 	case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
196 	default:
197 		return DRM_MODE_SUBCONNECTOR_Unknown;
198 	}
199 }
200 
201 static void update_subconnector_property(struct amdgpu_dm_connector *aconnector)
202 {
203 	struct dc_link *link = aconnector->dc_link;
204 	struct drm_connector *connector = &aconnector->base;
205 	enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
206 
207 	if (connector->connector_type != DRM_MODE_CONNECTOR_DisplayPort)
208 		return;
209 
210 	if (aconnector->dc_sink)
211 		subconnector = get_subconnector_type(link);
212 
213 	drm_object_property_set_value(&connector->base,
214 			connector->dev->mode_config.dp_subconnector_property,
215 			subconnector);
216 }
217 
218 /*
219  * initializes drm_device display related structures, based on the information
220  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
221  * drm_encoder, drm_mode_config
222  *
223  * Returns 0 on success
224  */
225 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
226 /* removes and deallocates the drm structures, created by the above function */
227 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
228 
229 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
230 				    struct amdgpu_dm_connector *amdgpu_dm_connector,
231 				    u32 link_index,
232 				    struct amdgpu_encoder *amdgpu_encoder);
233 static int amdgpu_dm_encoder_init(struct drm_device *dev,
234 				  struct amdgpu_encoder *aencoder,
235 				  uint32_t link_index);
236 
237 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
238 
239 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state);
240 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state);
241 
242 static int amdgpu_dm_atomic_check(struct drm_device *dev,
243 				  struct drm_atomic_commit *state);
244 
245 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector);
246 static void handle_hpd_rx_irq(void *param);
247 
248 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
249 					 int bl_idx,
250 					 u32 user_brightness);
251 
252 static bool
253 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
254 				 struct drm_crtc_state *new_crtc_state);
255 /*
256  * dm_vblank_get_counter
257  *
258  * @brief
259  * Get counter for number of vertical blanks
260  *
261  * @param
262  * struct amdgpu_device *adev - [in] desired amdgpu device
263  * int disp_idx - [in] which CRTC to get the counter from
264  *
265  * @return
266  * Counter for vertical blanks
267  */
268 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
269 {
270 	struct amdgpu_crtc *acrtc = NULL;
271 
272 	if (crtc >= adev->mode_info.num_crtc)
273 		return 0;
274 
275 	acrtc = adev->mode_info.crtcs[crtc];
276 
277 	if (!acrtc->dm_irq_params.stream) {
278 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
279 			  crtc);
280 		return 0;
281 	}
282 
283 	return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
284 }
285 
286 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
287 				  u32 *vbl, u32 *position)
288 {
289 	u32 v_blank_start = 0, v_blank_end = 0, h_position = 0, v_position = 0;
290 	struct amdgpu_crtc *acrtc = NULL;
291 	struct dc *dc = adev->dm.dc;
292 
293 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
294 		return -EINVAL;
295 
296 	acrtc = adev->mode_info.crtcs[crtc];
297 
298 	if (!acrtc->dm_irq_params.stream) {
299 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
300 			  crtc);
301 		return 0;
302 	}
303 
304 	if (dc && dc->caps.ips_support && dc->idle_optimizations_allowed)
305 		dc_allow_idle_optimizations(dc, false);
306 
307 	/*
308 	 * TODO rework base driver to use values directly.
309 	 * for now parse it back into reg-format
310 	 */
311 	dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
312 				 &v_blank_start,
313 				 &v_blank_end,
314 				 &h_position,
315 				 &v_position);
316 
317 	*position = v_position | (h_position << 16);
318 	*vbl = v_blank_start | (v_blank_end << 16);
319 
320 	return 0;
321 }
322 
323 static bool dm_is_idle(struct amdgpu_ip_block *ip_block)
324 {
325 	/* XXX todo */
326 	return true;
327 }
328 
329 static int dm_wait_for_idle(struct amdgpu_ip_block *ip_block)
330 {
331 	/* XXX todo */
332 	return 0;
333 }
334 
335 static bool dm_check_soft_reset(struct amdgpu_ip_block *ip_block)
336 {
337 	return false;
338 }
339 
340 static int dm_soft_reset(struct amdgpu_ip_block *ip_block)
341 {
342 	/* XXX todo */
343 	return 0;
344 }
345 
346 static struct amdgpu_crtc *
347 get_crtc_by_otg_inst(struct amdgpu_device *adev,
348 		     int otg_inst)
349 {
350 	struct drm_device *dev = adev_to_drm(adev);
351 	struct drm_crtc *crtc;
352 	struct amdgpu_crtc *amdgpu_crtc;
353 
354 	if (WARN_ON(otg_inst == -1))
355 		return adev->mode_info.crtcs[0];
356 
357 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
358 		amdgpu_crtc = to_amdgpu_crtc(crtc);
359 
360 		if (amdgpu_crtc->otg_inst == otg_inst)
361 			return amdgpu_crtc;
362 	}
363 
364 	return NULL;
365 }
366 
367 static inline bool is_dc_timing_adjust_needed(struct dm_crtc_state *old_state,
368 					      struct dm_crtc_state *new_state)
369 {
370 	if (new_state->stream->adjust.timing_adjust_pending)
371 		return true;
372 	if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
373 		return true;
374 	else if (amdgpu_dm_crtc_vrr_active(old_state) != amdgpu_dm_crtc_vrr_active(new_state))
375 		return true;
376 	else
377 		return false;
378 }
379 
380 /*
381  * DC will program planes with their z-order determined by their ordering
382  * in the dc_surface_updates array. This comparator is used to sort them
383  * by descending zpos.
384  */
385 static int dm_plane_layer_index_cmp(const void *a, const void *b)
386 {
387 	const struct dc_surface_update *sa = (struct dc_surface_update *)a;
388 	const struct dc_surface_update *sb = (struct dc_surface_update *)b;
389 
390 	/* Sort by descending dc_plane layer_index (i.e. normalized_zpos) */
391 	return sb->surface->layer_index - sa->surface->layer_index;
392 }
393 
394 /**
395  * update_planes_and_stream_adapter() - Send planes to be updated in DC
396  *
397  * DC has a generic way to update planes and stream via
398  * dc_update_planes_and_stream function; however, DM might need some
399  * adjustments and preparation before calling it. This function is a wrapper
400  * for the dc_update_planes_and_stream that does any required configuration
401  * before passing control to DC.
402  *
403  * @dc: Display Core control structure
404  * @update_type: specify whether it is FULL/MEDIUM/FAST update
405  * @planes_count: planes count to update
406  * @stream: stream state
407  * @stream_update: stream update
408  * @array_of_surface_update: dc surface update pointer
409  *
410  */
411 static inline bool update_planes_and_stream_adapter(struct dc *dc,
412 						    int update_type,
413 						    int planes_count,
414 						    struct dc_stream_state *stream,
415 						    struct dc_stream_update *stream_update,
416 						    struct dc_surface_update *array_of_surface_update)
417 {
418 	sort(array_of_surface_update, planes_count,
419 	     sizeof(*array_of_surface_update), dm_plane_layer_index_cmp, NULL);
420 
421 	/*
422 	 * Previous frame finished and HW is ready for optimization.
423 	 */
424 	dc_post_update_surfaces_to_stream(dc);
425 
426 	return dc_update_planes_and_stream(dc,
427 					   array_of_surface_update,
428 					   planes_count,
429 					   stream,
430 					   stream_update);
431 }
432 
433 /**
434  * dm_pflip_high_irq() - Handle pageflip interrupt
435  * @interrupt_params: ignored
436  *
437  * Handles the pageflip interrupt by notifying all interested parties
438  * that the pageflip has been completed.
439  */
440 static void dm_pflip_high_irq(void *interrupt_params)
441 {
442 	struct amdgpu_crtc *amdgpu_crtc;
443 	struct common_irq_params *irq_params = interrupt_params;
444 	struct amdgpu_device *adev = irq_params->adev;
445 	struct drm_device *dev = adev_to_drm(adev);
446 	unsigned long flags;
447 	struct drm_pending_vblank_event *e;
448 	u32 vpos, hpos, v_blank_start, v_blank_end;
449 	bool vrr_active;
450 
451 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
452 
453 	/* IRQ could occur when in initial stage */
454 	/* TODO work and BO cleanup */
455 	if (amdgpu_crtc == NULL) {
456 		drm_dbg_state(dev, "CRTC is null, returning.\n");
457 		return;
458 	}
459 
460 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
461 
462 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED) {
463 		drm_dbg_state(dev,
464 			      "amdgpu_crtc->pflip_status = %d != AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p]\n",
465 			      amdgpu_crtc->pflip_status, AMDGPU_FLIP_SUBMITTED,
466 			      amdgpu_crtc->crtc_id, amdgpu_crtc);
467 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
468 		return;
469 	}
470 
471 	/* page flip completed. */
472 	e = amdgpu_crtc->event;
473 	amdgpu_crtc->event = NULL;
474 
475 	WARN_ON(!e);
476 
477 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(amdgpu_crtc);
478 
479 	/* Fixed refresh rate, or VRR scanout position outside front-porch? */
480 	if (!vrr_active ||
481 	    !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
482 				      &v_blank_end, &hpos, &vpos) ||
483 	    (vpos < v_blank_start)) {
484 		/* Update to correct count and vblank timestamp if racing with
485 		 * vblank irq. This also updates to the correct vblank timestamp
486 		 * even in VRR mode, as scanout is past the front-porch atm.
487 		 */
488 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
489 
490 		/* Wake up userspace by sending the pageflip event with proper
491 		 * count and timestamp of vblank of flip completion.
492 		 */
493 		if (e) {
494 			drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
495 
496 			/* Event sent, so done with vblank for this flip */
497 			drm_crtc_vblank_put(&amdgpu_crtc->base);
498 		}
499 	} else if (e) {
500 		/* VRR active and inside front-porch: vblank count and
501 		 * timestamp for pageflip event will only be up to date after
502 		 * drm_crtc_handle_vblank() has been executed from late vblank
503 		 * irq handler after start of back-porch (vline 0). We queue the
504 		 * pageflip event for send-out by drm_crtc_handle_vblank() with
505 		 * updated timestamp and count, once it runs after us.
506 		 *
507 		 * We need to open-code this instead of using the helper
508 		 * drm_crtc_arm_vblank_event(), as that helper would
509 		 * call drm_crtc_accurate_vblank_count(), which we must
510 		 * not call in VRR mode while we are in front-porch!
511 		 */
512 
513 		/* sequence will be replaced by real count during send-out. */
514 		e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
515 		e->pipe = amdgpu_crtc->crtc_id;
516 
517 		list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
518 		e = NULL;
519 	}
520 
521 	/* Keep track of vblank of this flip for flip throttling. We use the
522 	 * cooked hw counter, as that one incremented at start of this vblank
523 	 * of pageflip completion, so last_flip_vblank is the forbidden count
524 	 * for queueing new pageflips if vsync + VRR is enabled.
525 	 */
526 	amdgpu_crtc->dm_irq_params.last_flip_vblank =
527 		amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
528 
529 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
530 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
531 
532 	drm_dbg_state(dev,
533 		      "crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
534 		      amdgpu_crtc->crtc_id, amdgpu_crtc, vrr_active, (int)!e);
535 }
536 
537 static void dm_handle_vmin_vmax_update(struct work_struct *offload_work)
538 {
539 	struct vupdate_offload_work *work = container_of(offload_work, struct vupdate_offload_work, work);
540 	struct amdgpu_device *adev = work->adev;
541 	struct dc_stream_state *stream = work->stream;
542 	struct dc_crtc_timing_adjust *adjust = work->adjust;
543 
544 	mutex_lock(&adev->dm.dc_lock);
545 	dc_stream_adjust_vmin_vmax(adev->dm.dc, stream, adjust);
546 	mutex_unlock(&adev->dm.dc_lock);
547 
548 	dc_stream_release(stream);
549 	kfree(work->adjust);
550 	kfree(work);
551 }
552 
553 static void schedule_dc_vmin_vmax(struct amdgpu_device *adev,
554 	struct dc_stream_state *stream,
555 	struct dc_crtc_timing_adjust *adjust)
556 {
557 	struct vupdate_offload_work *offload_work = kzalloc_obj(*offload_work,
558 								GFP_NOWAIT);
559 	if (!offload_work) {
560 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate vupdate_offload_work\n");
561 		return;
562 	}
563 
564 	struct dc_crtc_timing_adjust *adjust_copy = kzalloc_obj(*adjust_copy,
565 								GFP_NOWAIT);
566 	if (!adjust_copy) {
567 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate adjust_copy\n");
568 		kfree(offload_work);
569 		return;
570 	}
571 
572 	dc_stream_retain(stream);
573 	memcpy(adjust_copy, adjust, sizeof(*adjust_copy));
574 
575 	INIT_WORK(&offload_work->work, dm_handle_vmin_vmax_update);
576 	offload_work->adev = adev;
577 	offload_work->stream = stream;
578 	offload_work->adjust = adjust_copy;
579 
580 	queue_work(system_percpu_wq, &offload_work->work);
581 }
582 
583 static void dm_vupdate_high_irq(void *interrupt_params)
584 {
585 	struct common_irq_params *irq_params = interrupt_params;
586 	struct amdgpu_device *adev = irq_params->adev;
587 	struct amdgpu_crtc *acrtc;
588 	struct drm_device *drm_dev;
589 	struct drm_vblank_crtc *vblank;
590 	ktime_t frame_duration_ns, previous_timestamp;
591 	unsigned long flags;
592 	int vrr_active;
593 
594 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
595 
596 	if (acrtc) {
597 		vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
598 		drm_dev = acrtc->base.dev;
599 		vblank = drm_crtc_vblank_crtc(&acrtc->base);
600 		previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
601 		frame_duration_ns = vblank->time - previous_timestamp;
602 
603 		if (frame_duration_ns > 0) {
604 			trace_amdgpu_refresh_rate_track(acrtc->base.index,
605 						frame_duration_ns,
606 						ktime_divns(NSEC_PER_SEC, frame_duration_ns));
607 			atomic64_set(&irq_params->previous_timestamp, vblank->time);
608 		}
609 
610 		drm_dbg_vbl(drm_dev,
611 			    "crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
612 			    vrr_active);
613 
614 		/* Core vblank handling is done here after end of front-porch in
615 		 * vrr mode, as vblank timestamping will give valid results
616 		 * while now done after front-porch. This will also deliver
617 		 * page-flip completion events that have been queued to us
618 		 * if a pageflip happened inside front-porch.
619 		 */
620 		if (vrr_active && acrtc->dm_irq_params.stream) {
621 			bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
622 			bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
623 			bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state
624 				== VRR_STATE_ACTIVE_VARIABLE;
625 
626 			amdgpu_dm_crtc_handle_vblank(acrtc);
627 
628 			/* BTR processing for pre-DCE12 ASICs */
629 			if (adev->family < AMDGPU_FAMILY_AI) {
630 				spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
631 				mod_freesync_handle_v_update(
632 				    adev->dm.freesync_module,
633 				    acrtc->dm_irq_params.stream,
634 				    &acrtc->dm_irq_params.vrr_params);
635 
636 				if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
637 					schedule_dc_vmin_vmax(adev,
638 						acrtc->dm_irq_params.stream,
639 						&acrtc->dm_irq_params.vrr_params.adjust);
640 				}
641 				spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
642 			}
643 		}
644 	}
645 }
646 
647 /**
648  * dm_crtc_high_irq() - Handles CRTC interrupt
649  * @interrupt_params: used for determining the CRTC instance
650  *
651  * Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
652  * event handler.
653  */
654 static void dm_crtc_high_irq(void *interrupt_params)
655 {
656 	struct common_irq_params *irq_params = interrupt_params;
657 	struct amdgpu_device *adev = irq_params->adev;
658 	struct drm_writeback_job *job;
659 	struct amdgpu_crtc *acrtc;
660 	unsigned long flags;
661 	int vrr_active;
662 
663 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
664 	if (!acrtc)
665 		return;
666 
667 	if (acrtc->wb_conn) {
668 		spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
669 
670 		if (acrtc->wb_pending) {
671 			job = list_first_entry_or_null(&acrtc->wb_conn->job_queue,
672 						       struct drm_writeback_job,
673 						       list_entry);
674 			acrtc->wb_pending = false;
675 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
676 
677 			if (job) {
678 				unsigned int v_total, refresh_hz;
679 				struct dc_stream_state *stream = acrtc->dm_irq_params.stream;
680 
681 				v_total = stream->adjust.v_total_max ?
682 					  stream->adjust.v_total_max : stream->timing.v_total;
683 				refresh_hz = div_u64((uint64_t) stream->timing.pix_clk_100hz *
684 					     100LL, (v_total * stream->timing.h_total));
685 				mdelay(1000 / refresh_hz);
686 
687 				drm_writeback_signal_completion(acrtc->wb_conn, 0);
688 				dc_stream_fc_disable_writeback(adev->dm.dc,
689 							       acrtc->dm_irq_params.stream, 0);
690 			}
691 		} else
692 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
693 	}
694 
695 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
696 
697 	drm_dbg_vbl(adev_to_drm(adev),
698 		    "crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
699 		    vrr_active, acrtc->dm_irq_params.active_planes);
700 
701 	/**
702 	 * Core vblank handling at start of front-porch is only possible
703 	 * in non-vrr mode, as only there vblank timestamping will give
704 	 * valid results while done in front-porch. Otherwise defer it
705 	 * to dm_vupdate_high_irq after end of front-porch.
706 	 */
707 	if (!vrr_active)
708 		amdgpu_dm_crtc_handle_vblank(acrtc);
709 
710 	/**
711 	 * Following stuff must happen at start of vblank, for crc
712 	 * computation and below-the-range btr support in vrr mode.
713 	 */
714 	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
715 
716 	/* BTR updates need to happen before VUPDATE on Vega and above. */
717 	if (adev->family < AMDGPU_FAMILY_AI)
718 		return;
719 
720 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
721 
722 	if (acrtc->dm_irq_params.stream &&
723 		acrtc->dm_irq_params.vrr_params.supported) {
724 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
725 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
726 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state == VRR_STATE_ACTIVE_VARIABLE;
727 
728 		mod_freesync_handle_v_update(adev->dm.freesync_module,
729 					     acrtc->dm_irq_params.stream,
730 					     &acrtc->dm_irq_params.vrr_params);
731 
732 		/* update vmin_vmax only if freesync is enabled, or only if PSR and REPLAY are disabled */
733 		if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
734 			schedule_dc_vmin_vmax(adev, acrtc->dm_irq_params.stream,
735 					&acrtc->dm_irq_params.vrr_params.adjust);
736 		}
737 	}
738 
739 	/*
740 	 * If there aren't any active_planes then DCH HUBP may be clock-gated.
741 	 * In that case, pageflip completion interrupts won't fire and pageflip
742 	 * completion events won't get delivered. Prevent this by sending
743 	 * pending pageflip events from here if a flip is still pending.
744 	 *
745 	 * If any planes are enabled, use dm_pflip_high_irq() instead, to
746 	 * avoid race conditions between flip programming and completion,
747 	 * which could cause too early flip completion events.
748 	 */
749 	if (adev->family >= AMDGPU_FAMILY_RV &&
750 	    acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
751 	    acrtc->dm_irq_params.active_planes == 0) {
752 		if (acrtc->event) {
753 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
754 			acrtc->event = NULL;
755 			drm_crtc_vblank_put(&acrtc->base);
756 		}
757 		acrtc->pflip_status = AMDGPU_FLIP_NONE;
758 	}
759 
760 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
761 }
762 
763 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
764 /**
765  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
766  * DCN generation ASICs
767  * @interrupt_params: interrupt parameters
768  *
769  * Used to set crc window/read out crc value at vertical line 0 position
770  */
771 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
772 {
773 	struct common_irq_params *irq_params = interrupt_params;
774 	struct amdgpu_device *adev = irq_params->adev;
775 	struct amdgpu_crtc *acrtc;
776 
777 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
778 
779 	if (!acrtc)
780 		return;
781 
782 	amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
783 }
784 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
785 
786 /**
787  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
788  * @adev: amdgpu_device pointer
789  * @notify: dmub notification structure
790  *
791  * Dmub AUX or SET_CONFIG command completion processing callback
792  * Copies dmub notification to DM which is to be read by AUX command.
793  * issuing thread and also signals the event to wake up the thread.
794  */
795 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
796 					struct dmub_notification *notify)
797 {
798 	if (adev->dm.dmub_notify)
799 		memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
800 	if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
801 		complete(&adev->dm.dmub_aux_transfer_done);
802 }
803 
804 static void dmub_aux_fused_io_callback(struct amdgpu_device *adev,
805 					struct dmub_notification *notify)
806 {
807 	if (!adev || !notify) {
808 		ASSERT(false);
809 		return;
810 	}
811 
812 	const struct dmub_cmd_fused_request *req = &notify->fused_request;
813 	const uint8_t ddc_line = req->u.aux.ddc_line;
814 
815 	if (ddc_line >= ARRAY_SIZE(adev->dm.fused_io)) {
816 		ASSERT(false);
817 		return;
818 	}
819 
820 	struct fused_io_sync *sync = &adev->dm.fused_io[ddc_line];
821 
822 	static_assert(sizeof(*req) <= sizeof(sync->reply_data), "Size mismatch");
823 	memcpy(sync->reply_data, req, sizeof(*req));
824 	complete(&sync->replied);
825 }
826 
827 /**
828  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
829  * @adev: amdgpu_device pointer
830  * @notify: dmub notification structure
831  *
832  * Dmub Hpd interrupt processing callback. Gets displayindex through the
833  * ink index and calls helper to do the processing.
834  */
835 static void dmub_hpd_callback(struct amdgpu_device *adev,
836 			      struct dmub_notification *notify)
837 {
838 	struct amdgpu_dm_connector *aconnector;
839 	struct amdgpu_dm_connector *hpd_aconnector = NULL;
840 	struct drm_connector *connector;
841 	struct drm_connector_list_iter iter;
842 	struct dc_link *link;
843 	u8 link_index = 0;
844 	struct drm_device *dev;
845 
846 	if (adev == NULL)
847 		return;
848 
849 	if (notify == NULL) {
850 		drm_err(adev_to_drm(adev), "DMUB HPD callback notification was NULL");
851 		return;
852 	}
853 
854 	if (notify->link_index > adev->dm.dc->link_count) {
855 		drm_err(adev_to_drm(adev), "DMUB HPD index (%u)is abnormal", notify->link_index);
856 		return;
857 	}
858 
859 	/* Skip DMUB HPD IRQ in suspend/resume. We will probe them later. */
860 	if (notify->type == DMUB_NOTIFICATION_HPD && adev->in_suspend) {
861 		drm_info(adev_to_drm(adev), "Skip DMUB HPD IRQ callback in suspend/resume\n");
862 		return;
863 	}
864 
865 	link_index = notify->link_index;
866 	link = adev->dm.dc->links[link_index];
867 	dev = adev->dm.ddev;
868 
869 	drm_connector_list_iter_begin(dev, &iter);
870 	drm_for_each_connector_iter(connector, &iter) {
871 
872 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
873 			continue;
874 
875 		aconnector = to_amdgpu_dm_connector(connector);
876 		if (link && aconnector->dc_link == link) {
877 			if (notify->type == DMUB_NOTIFICATION_HPD)
878 				drm_info(adev_to_drm(adev), "DMUB HPD IRQ callback: link_index=%u\n", link_index);
879 			else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
880 				drm_info(adev_to_drm(adev), "DMUB HPD RX IRQ callback: link_index=%u\n", link_index);
881 			else
882 				drm_warn(adev_to_drm(adev), "DMUB Unknown HPD callback type %d, link_index=%u\n",
883 						notify->type, link_index);
884 
885 			hpd_aconnector = aconnector;
886 			break;
887 		}
888 	}
889 	drm_connector_list_iter_end(&iter);
890 
891 	if (hpd_aconnector) {
892 		if (notify->type == DMUB_NOTIFICATION_HPD) {
893 			if (hpd_aconnector->dc_link->hpd_status == (notify->hpd_status == DP_HPD_PLUG))
894 				drm_warn(adev_to_drm(adev), "DMUB reported hpd status unchanged. link_index=%u\n", link_index);
895 			handle_hpd_irq_helper(hpd_aconnector);
896 		} else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ) {
897 			handle_hpd_rx_irq(hpd_aconnector);
898 		}
899 	}
900 }
901 
902 /**
903  * dmub_hpd_sense_callback - DMUB HPD sense processing callback.
904  * @adev: amdgpu_device pointer
905  * @notify: dmub notification structure
906  *
907  * HPD sense changes can occur during low power states and need to be
908  * notified from firmware to driver.
909  */
910 static void dmub_hpd_sense_callback(struct amdgpu_device *adev,
911 			      struct dmub_notification *notify)
912 {
913 	drm_dbg_driver(adev_to_drm(adev), "DMUB HPD SENSE callback.\n");
914 }
915 
916 /**
917  * register_dmub_notify_callback - Sets callback for DMUB notify
918  * @adev: amdgpu_device pointer
919  * @type: Type of dmub notification
920  * @callback: Dmub interrupt callback function
921  * @dmub_int_thread_offload: offload indicator
922  *
923  * API to register a dmub callback handler for a dmub notification
924  * Also sets indicator whether callback processing to be offloaded.
925  * to dmub interrupt handling thread
926  * Return: true if successfully registered, false if there is existing registration
927  */
928 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
929 					  enum dmub_notification_type type,
930 					  dmub_notify_interrupt_callback_t callback,
931 					  bool dmub_int_thread_offload)
932 {
933 	if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
934 		adev->dm.dmub_callback[type] = callback;
935 		adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
936 	} else
937 		return false;
938 
939 	return true;
940 }
941 
942 static void dm_handle_hpd_work(struct work_struct *work)
943 {
944 	struct dmub_hpd_work *dmub_hpd_wrk;
945 
946 	dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
947 
948 	if (!dmub_hpd_wrk->dmub_notify) {
949 		drm_err(adev_to_drm(dmub_hpd_wrk->adev), "dmub_hpd_wrk dmub_notify is NULL");
950 		return;
951 	}
952 
953 	if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
954 		dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
955 		dmub_hpd_wrk->dmub_notify);
956 	}
957 
958 	kfree(dmub_hpd_wrk->dmub_notify);
959 	kfree(dmub_hpd_wrk);
960 
961 }
962 
963 static const char *dmub_notification_type_str(enum dmub_notification_type e)
964 {
965 	switch (e) {
966 	case DMUB_NOTIFICATION_NO_DATA:
967 		return "NO_DATA";
968 	case DMUB_NOTIFICATION_AUX_REPLY:
969 		return "AUX_REPLY";
970 	case DMUB_NOTIFICATION_HPD:
971 		return "HPD";
972 	case DMUB_NOTIFICATION_HPD_IRQ:
973 		return "HPD_IRQ";
974 	case DMUB_NOTIFICATION_SET_CONFIG_REPLY:
975 		return "SET_CONFIG_REPLY";
976 	case DMUB_NOTIFICATION_DPIA_NOTIFICATION:
977 		return "DPIA_NOTIFICATION";
978 	case DMUB_NOTIFICATION_HPD_SENSE_NOTIFY:
979 		return "HPD_SENSE_NOTIFY";
980 	case DMUB_NOTIFICATION_FUSED_IO:
981 		return "FUSED_IO";
982 	default:
983 		return "<unknown>";
984 	}
985 }
986 
987 #define DMUB_TRACE_MAX_READ 64
988 /**
989  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
990  * @interrupt_params: used for determining the Outbox instance
991  *
992  * Handles the Outbox Interrupt
993  * event handler.
994  */
995 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
996 {
997 	struct dmub_notification notify = {0};
998 	struct common_irq_params *irq_params = interrupt_params;
999 	struct amdgpu_device *adev = irq_params->adev;
1000 	struct amdgpu_display_manager *dm = &adev->dm;
1001 	struct dmcub_trace_buf_entry entry = { 0 };
1002 	u32 count = 0;
1003 	struct dmub_hpd_work *dmub_hpd_wrk;
1004 
1005 	do {
1006 		if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
1007 			trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
1008 							entry.param0, entry.param1);
1009 
1010 			drm_dbg_driver(adev_to_drm(adev), "trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
1011 				 entry.trace_code, entry.tick_count, entry.param0, entry.param1);
1012 		} else
1013 			break;
1014 
1015 		count++;
1016 
1017 	} while (count <= DMUB_TRACE_MAX_READ);
1018 
1019 	if (count > DMUB_TRACE_MAX_READ)
1020 		drm_dbg_driver(adev_to_drm(adev), "Warning : count > DMUB_TRACE_MAX_READ");
1021 
1022 	if (dc_enable_dmub_notifications(adev->dm.dc) &&
1023 		irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
1024 
1025 		do {
1026 			dc_stat_get_dmub_notification(adev->dm.dc, &notify);
1027 			if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
1028 				drm_err(adev_to_drm(adev), "DM: notify type %d invalid!", notify.type);
1029 				continue;
1030 			}
1031 			if (!dm->dmub_callback[notify.type]) {
1032 				drm_warn(adev_to_drm(adev), "DMUB notification skipped due to no handler: type=%s\n",
1033 					dmub_notification_type_str(notify.type));
1034 				continue;
1035 			}
1036 			if (dm->dmub_thread_offload[notify.type] == true) {
1037 				dmub_hpd_wrk = kzalloc_obj(*dmub_hpd_wrk,
1038 							   GFP_ATOMIC);
1039 				if (!dmub_hpd_wrk) {
1040 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk");
1041 					return;
1042 				}
1043 				dmub_hpd_wrk->dmub_notify = kmemdup(&notify, sizeof(struct dmub_notification),
1044 								    GFP_ATOMIC);
1045 				if (!dmub_hpd_wrk->dmub_notify) {
1046 					kfree(dmub_hpd_wrk);
1047 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk->dmub_notify");
1048 					return;
1049 				}
1050 				INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
1051 				dmub_hpd_wrk->adev = adev;
1052 				queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
1053 			} else {
1054 				dm->dmub_callback[notify.type](adev, &notify);
1055 			}
1056 		} while (notify.pending_notification);
1057 	}
1058 }
1059 
1060 static int dm_set_clockgating_state(struct amdgpu_ip_block *ip_block,
1061 		  enum amd_clockgating_state state)
1062 {
1063 	return 0;
1064 }
1065 
1066 static int dm_set_powergating_state(struct amdgpu_ip_block *ip_block,
1067 		  enum amd_powergating_state state)
1068 {
1069 	return 0;
1070 }
1071 
1072 /* Prototypes of private functions */
1073 static int dm_early_init(struct amdgpu_ip_block *ip_block);
1074 
1075 /* Allocate memory for FBC compressed data  */
1076 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
1077 {
1078 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
1079 	struct dm_compressor_info *compressor = &adev->dm.compressor;
1080 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
1081 	struct drm_display_mode *mode;
1082 	unsigned long max_size = 0;
1083 
1084 	if (adev->dm.dc->fbc_compressor == NULL)
1085 		return;
1086 
1087 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
1088 		return;
1089 
1090 	if (compressor->bo_ptr)
1091 		return;
1092 
1093 
1094 	list_for_each_entry(mode, &connector->modes, head) {
1095 		if (max_size < (unsigned long) mode->htotal * mode->vtotal)
1096 			max_size = (unsigned long) mode->htotal * mode->vtotal;
1097 	}
1098 
1099 	if (max_size) {
1100 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
1101 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
1102 			    &compressor->gpu_addr, &compressor->cpu_addr);
1103 
1104 		if (r)
1105 			drm_err(adev_to_drm(adev), "DM: Failed to initialize FBC\n");
1106 		else {
1107 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
1108 			drm_info(adev_to_drm(adev), "DM: FBC alloc %lu\n", max_size*4);
1109 		}
1110 
1111 	}
1112 
1113 }
1114 
1115 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
1116 					  int pipe, bool *enabled,
1117 					  unsigned char *buf, int max_bytes)
1118 {
1119 	struct drm_device *dev = dev_get_drvdata(kdev);
1120 	struct amdgpu_device *adev = drm_to_adev(dev);
1121 	struct drm_connector *connector;
1122 	struct drm_connector_list_iter conn_iter;
1123 	struct amdgpu_dm_connector *aconnector;
1124 	int ret = 0;
1125 
1126 	*enabled = false;
1127 
1128 	mutex_lock(&adev->dm.audio_lock);
1129 
1130 	drm_connector_list_iter_begin(dev, &conn_iter);
1131 	drm_for_each_connector_iter(connector, &conn_iter) {
1132 
1133 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1134 			continue;
1135 
1136 		aconnector = to_amdgpu_dm_connector(connector);
1137 		if (aconnector->audio_inst != port)
1138 			continue;
1139 
1140 		*enabled = true;
1141 		mutex_lock(&connector->eld_mutex);
1142 		ret = drm_eld_size(connector->eld);
1143 		memcpy(buf, connector->eld, min(max_bytes, ret));
1144 		mutex_unlock(&connector->eld_mutex);
1145 
1146 		break;
1147 	}
1148 	drm_connector_list_iter_end(&conn_iter);
1149 
1150 	mutex_unlock(&adev->dm.audio_lock);
1151 
1152 	drm_dbg_kms(adev_to_drm(adev), "Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
1153 
1154 	return ret;
1155 }
1156 
1157 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
1158 	.get_eld = amdgpu_dm_audio_component_get_eld,
1159 };
1160 
1161 static int amdgpu_dm_audio_component_bind(struct device *kdev,
1162 				       struct device *hda_kdev, void *data)
1163 {
1164 	struct drm_device *dev = dev_get_drvdata(kdev);
1165 	struct amdgpu_device *adev = drm_to_adev(dev);
1166 	struct drm_audio_component *acomp = data;
1167 
1168 	acomp->ops = &amdgpu_dm_audio_component_ops;
1169 	acomp->dev = kdev;
1170 	adev->dm.audio_component = acomp;
1171 
1172 	return 0;
1173 }
1174 
1175 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
1176 					  struct device *hda_kdev, void *data)
1177 {
1178 	struct amdgpu_device *adev = drm_to_adev(dev_get_drvdata(kdev));
1179 	struct drm_audio_component *acomp = data;
1180 
1181 	acomp->ops = NULL;
1182 	acomp->dev = NULL;
1183 	adev->dm.audio_component = NULL;
1184 }
1185 
1186 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
1187 	.bind	= amdgpu_dm_audio_component_bind,
1188 	.unbind	= amdgpu_dm_audio_component_unbind,
1189 };
1190 
1191 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
1192 {
1193 	int i, ret;
1194 
1195 	if (!amdgpu_audio)
1196 		return 0;
1197 
1198 	adev->mode_info.audio.enabled = true;
1199 
1200 	adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
1201 
1202 	for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
1203 		adev->mode_info.audio.pin[i].channels = -1;
1204 		adev->mode_info.audio.pin[i].rate = -1;
1205 		adev->mode_info.audio.pin[i].bits_per_sample = -1;
1206 		adev->mode_info.audio.pin[i].status_bits = 0;
1207 		adev->mode_info.audio.pin[i].category_code = 0;
1208 		adev->mode_info.audio.pin[i].connected = false;
1209 		adev->mode_info.audio.pin[i].id =
1210 			adev->dm.dc->res_pool->audios[i]->inst;
1211 		adev->mode_info.audio.pin[i].offset = 0;
1212 	}
1213 
1214 	ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1215 	if (ret < 0)
1216 		return ret;
1217 
1218 	adev->dm.audio_registered = true;
1219 
1220 	return 0;
1221 }
1222 
1223 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
1224 {
1225 	if (!amdgpu_audio)
1226 		return;
1227 
1228 	if (!adev->mode_info.audio.enabled)
1229 		return;
1230 
1231 	if (adev->dm.audio_registered) {
1232 		component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1233 		adev->dm.audio_registered = false;
1234 	}
1235 
1236 	/* TODO: Disable audio? */
1237 
1238 	adev->mode_info.audio.enabled = false;
1239 }
1240 
1241 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
1242 {
1243 	struct drm_audio_component *acomp = adev->dm.audio_component;
1244 
1245 	if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
1246 		drm_dbg_kms(adev_to_drm(adev), "Notify ELD: %d\n", pin);
1247 
1248 		acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1249 						 pin, -1);
1250 	}
1251 }
1252 
1253 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1254 {
1255 	const struct dmcub_firmware_header_v1_0 *hdr;
1256 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1257 	struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1258 	const struct firmware *dmub_fw = adev->dm.dmub_fw;
1259 	struct dc *dc = adev->dm.dc;
1260 	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1261 	struct abm *abm = adev->dm.dc->res_pool->abm;
1262 	struct dc_context *ctx = adev->dm.dc->ctx;
1263 	struct dmub_srv_hw_params hw_params;
1264 	enum dmub_status status;
1265 	const unsigned char *fw_inst_const, *fw_bss_data;
1266 	u32 i, fw_inst_const_size, fw_bss_data_size;
1267 	bool has_hw_support;
1268 
1269 	if (!dmub_srv)
1270 		/* DMUB isn't supported on the ASIC. */
1271 		return 0;
1272 
1273 	if (!fb_info) {
1274 		drm_err(adev_to_drm(adev), "No framebuffer info for DMUB service.\n");
1275 		return -EINVAL;
1276 	}
1277 
1278 	if (!dmub_fw) {
1279 		/* Firmware required for DMUB support. */
1280 		drm_err(adev_to_drm(adev), "No firmware provided for DMUB.\n");
1281 		return -EINVAL;
1282 	}
1283 
1284 	/* initialize register offsets for ASICs with runtime initialization available */
1285 	if (dmub_srv->hw_funcs.init_reg_offsets)
1286 		dmub_srv->hw_funcs.init_reg_offsets(dmub_srv, ctx);
1287 
1288 	status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1289 	if (status != DMUB_STATUS_OK) {
1290 		drm_err(adev_to_drm(adev), "Error checking HW support for DMUB: %d\n", status);
1291 		return -EINVAL;
1292 	}
1293 
1294 	if (!has_hw_support) {
1295 		drm_info(adev_to_drm(adev), "DMUB unsupported on ASIC\n");
1296 		return 0;
1297 	}
1298 
1299 	/* Reset DMCUB if it was previously running - before we overwrite its memory. */
1300 	status = dmub_srv_hw_reset(dmub_srv);
1301 	if (status != DMUB_STATUS_OK)
1302 		drm_warn(adev_to_drm(adev), "Error resetting DMUB HW: %d\n", status);
1303 
1304 	hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1305 
1306 	fw_inst_const = dmub_fw->data +
1307 			le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1308 			PSP_HEADER_BYTES_256;
1309 
1310 	fw_bss_data = dmub_fw->data +
1311 		      le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1312 		      le32_to_cpu(hdr->inst_const_bytes);
1313 
1314 	/* Copy firmware and bios info into FB memory. */
1315 	fw_inst_const_size = adev->dm.fw_inst_size;
1316 
1317 	fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1318 
1319 	/* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1320 	 * amdgpu_ucode_init_single_fw will load dmub firmware
1321 	 * fw_inst_const part to cw0; otherwise, the firmware back door load
1322 	 * will be done by dm_dmub_hw_init
1323 	 */
1324 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1325 		memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1326 				fw_inst_const_size);
1327 	}
1328 
1329 	if (fw_bss_data_size)
1330 		memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1331 		       fw_bss_data, fw_bss_data_size);
1332 
1333 	/* Copy firmware bios info into FB memory. */
1334 	memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1335 	       adev->bios_size);
1336 
1337 	/* Reset regions that need to be reset. */
1338 	memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1339 	fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1340 
1341 	memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1342 	       fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1343 
1344 	memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1345 	       fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1346 
1347 	memset(fb_info->fb[DMUB_WINDOW_SHARED_STATE].cpu_addr, 0,
1348 	       fb_info->fb[DMUB_WINDOW_SHARED_STATE].size);
1349 
1350 	/* Initialize hardware. */
1351 	memset(&hw_params, 0, sizeof(hw_params));
1352 	hw_params.soc_fb_info.fb_base = adev->gmc.fb_start;
1353 	hw_params.soc_fb_info.fb_offset = adev->vm_manager.vram_base_offset;
1354 
1355 	/* backdoor load firmware and trigger dmub running */
1356 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1357 		hw_params.load_inst_const = true;
1358 
1359 	if (dmcu)
1360 		hw_params.psp_version = dmcu->psp_version;
1361 
1362 	for (i = 0; i < fb_info->num_fb; ++i)
1363 		hw_params.fb[i] = &fb_info->fb[i];
1364 
1365 	/* Enable usb4 dpia in the FW APU */
1366 	if (dc->caps.is_apu &&
1367 		dc->res_pool->usb4_dpia_count != 0 &&
1368 		!dc->debug.dpia_debug.bits.disable_dpia) {
1369 		hw_params.dpia_supported = true;
1370 		hw_params.disable_dpia = dc->debug.dpia_debug.bits.disable_dpia;
1371 		hw_params.dpia_hpd_int_enable_supported = false;
1372 		hw_params.enable_non_transparent_setconfig = dc->config.consolidated_dpia_dp_lt;
1373 		hw_params.disable_dpia_bw_allocation = !dc->config.usb4_bw_alloc_support;
1374 	}
1375 
1376 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1377 	case IP_VERSION(3, 5, 0):
1378 	case IP_VERSION(3, 5, 1):
1379 	case IP_VERSION(3, 6, 0):
1380 	case IP_VERSION(4, 2, 0):
1381 	case IP_VERSION(4, 2, 1):
1382 		hw_params.ips_sequential_ono = adev->external_rev_id > 0x10;
1383 		hw_params.lower_hbr3_phy_ssc = true;
1384 		break;
1385 	default:
1386 		break;
1387 	}
1388 
1389 	status = dmub_srv_hw_init(dmub_srv, &hw_params);
1390 	if (status != DMUB_STATUS_OK) {
1391 		drm_err(adev_to_drm(adev), "Error initializing DMUB HW: %d\n", status);
1392 		return -EINVAL;
1393 	}
1394 
1395 	/* Wait for firmware load to finish. */
1396 	status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1397 	if (status != DMUB_STATUS_OK)
1398 		drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1399 
1400 	/* Init DMCU and ABM if available. */
1401 	if (dmcu && abm) {
1402 		dmcu->funcs->dmcu_init(dmcu);
1403 		abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1404 	}
1405 
1406 	if (!adev->dm.dc->ctx->dmub_srv)
1407 		adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1408 	if (!adev->dm.dc->ctx->dmub_srv) {
1409 		drm_err(adev_to_drm(adev), "Couldn't allocate DC DMUB server!\n");
1410 		return -ENOMEM;
1411 	}
1412 
1413 	drm_info(adev_to_drm(adev), "DMUB hardware initialized: version=0x%08X\n",
1414 		 adev->dm.dmcub_fw_version);
1415 
1416 	/* Keeping sanity checks off if
1417 	 * DCN31 >= 4.0.59.0
1418 	 * DCN314 >= 8.0.16.0
1419 	 * Otherwise, turn on sanity checks
1420 	 */
1421 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1422 	case IP_VERSION(3, 1, 2):
1423 	case IP_VERSION(3, 1, 3):
1424 		if (adev->dm.dmcub_fw_version &&
1425 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1426 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(4, 0, 59))
1427 				adev->dm.dc->debug.sanity_checks = true;
1428 		break;
1429 	case IP_VERSION(3, 1, 4):
1430 		if (adev->dm.dmcub_fw_version &&
1431 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1432 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(8, 0, 16))
1433 				adev->dm.dc->debug.sanity_checks = true;
1434 		break;
1435 	default:
1436 		break;
1437 	}
1438 
1439 	return 0;
1440 }
1441 
1442 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1443 {
1444 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1445 	enum dmub_status status;
1446 	bool init;
1447 	int r;
1448 
1449 	if (!dmub_srv) {
1450 		/* DMUB isn't supported on the ASIC. */
1451 		return;
1452 	}
1453 
1454 	status = dmub_srv_is_hw_init(dmub_srv, &init);
1455 	if (status != DMUB_STATUS_OK)
1456 		drm_warn(adev_to_drm(adev), "DMUB hardware init check failed: %d\n", status);
1457 
1458 	if (status == DMUB_STATUS_OK && init) {
1459 		/* Wait for firmware load to finish. */
1460 		status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1461 		if (status != DMUB_STATUS_OK)
1462 			drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1463 	} else {
1464 		/* Perform the full hardware initialization. */
1465 		r = dm_dmub_hw_init(adev);
1466 		if (r)
1467 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
1468 	}
1469 }
1470 
1471 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1472 {
1473 	u64 pt_base;
1474 	u32 logical_addr_low;
1475 	u32 logical_addr_high;
1476 	u32 agp_base, agp_bot, agp_top;
1477 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1478 
1479 	memset(pa_config, 0, sizeof(*pa_config));
1480 
1481 	agp_base = 0;
1482 	agp_bot = adev->gmc.agp_start >> 24;
1483 	agp_top = adev->gmc.agp_end >> 24;
1484 
1485 	/* AGP aperture is disabled */
1486 	if (agp_bot > agp_top) {
1487 		logical_addr_low = adev->gmc.fb_start >> 18;
1488 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1489 				       AMD_APU_IS_RENOIR |
1490 				       AMD_APU_IS_GREEN_SARDINE))
1491 			/*
1492 			 * Raven2 has a HW issue that it is unable to use the vram which
1493 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1494 			 * workaround that increase system aperture high address (add 1)
1495 			 * to get rid of the VM fault and hardware hang.
1496 			 */
1497 			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
1498 		else
1499 			logical_addr_high = adev->gmc.fb_end >> 18;
1500 	} else {
1501 		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1502 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1503 				       AMD_APU_IS_RENOIR |
1504 				       AMD_APU_IS_GREEN_SARDINE))
1505 			/*
1506 			 * Raven2 has a HW issue that it is unable to use the vram which
1507 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1508 			 * workaround that increase system aperture high address (add 1)
1509 			 * to get rid of the VM fault and hardware hang.
1510 			 */
1511 			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1512 		else
1513 			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1514 	}
1515 
1516 	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1517 
1518 	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
1519 						   AMDGPU_GPU_PAGE_SHIFT);
1520 	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
1521 						  AMDGPU_GPU_PAGE_SHIFT);
1522 	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
1523 						 AMDGPU_GPU_PAGE_SHIFT);
1524 	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
1525 						AMDGPU_GPU_PAGE_SHIFT);
1526 	page_table_base.high_part = upper_32_bits(pt_base);
1527 	page_table_base.low_part = lower_32_bits(pt_base);
1528 
1529 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1530 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1531 
1532 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
1533 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1534 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1535 
1536 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1537 	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
1538 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1539 
1540 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1541 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1542 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1543 
1544 	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
1545 
1546 }
1547 
1548 static void force_connector_state(
1549 	struct amdgpu_dm_connector *aconnector,
1550 	enum drm_connector_force force_state)
1551 {
1552 	struct drm_connector *connector = &aconnector->base;
1553 
1554 	mutex_lock(&connector->dev->mode_config.mutex);
1555 	aconnector->base.force = force_state;
1556 	mutex_unlock(&connector->dev->mode_config.mutex);
1557 
1558 	mutex_lock(&aconnector->hpd_lock);
1559 	drm_kms_helper_connector_hotplug_event(connector);
1560 	mutex_unlock(&aconnector->hpd_lock);
1561 }
1562 
1563 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1564 {
1565 	struct hpd_rx_irq_offload_work *offload_work;
1566 	struct amdgpu_dm_connector *aconnector;
1567 	struct dc_link *dc_link;
1568 	struct amdgpu_device *adev;
1569 	enum dc_connection_type new_connection_type = dc_connection_none;
1570 	unsigned long flags;
1571 	union test_response test_response;
1572 
1573 	memset(&test_response, 0, sizeof(test_response));
1574 
1575 	offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1576 	aconnector = offload_work->offload_wq->aconnector;
1577 	adev = offload_work->adev;
1578 
1579 	if (!aconnector) {
1580 		drm_err(adev_to_drm(adev), "Can't retrieve aconnector in hpd_rx_irq_offload_work");
1581 		goto skip;
1582 	}
1583 
1584 	dc_link = aconnector->dc_link;
1585 
1586 	mutex_lock(&aconnector->hpd_lock);
1587 	if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
1588 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
1589 	mutex_unlock(&aconnector->hpd_lock);
1590 
1591 	if (new_connection_type == dc_connection_none)
1592 		goto skip;
1593 
1594 	if (amdgpu_in_reset(adev))
1595 		goto skip;
1596 
1597 	if (offload_work->data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
1598 		offload_work->data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
1599 		dm_handle_mst_sideband_msg_ready_event(&aconnector->mst_mgr, DOWN_OR_UP_MSG_RDY_EVENT);
1600 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1601 		offload_work->offload_wq->is_handling_mst_msg_rdy_event = false;
1602 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1603 		goto skip;
1604 	}
1605 
1606 	mutex_lock(&adev->dm.dc_lock);
1607 	if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
1608 		dc_link_dp_handle_automated_test(dc_link);
1609 
1610 		if (aconnector->timing_changed) {
1611 			/* force connector disconnect and reconnect */
1612 			force_connector_state(aconnector, DRM_FORCE_OFF);
1613 			msleep(100);
1614 			force_connector_state(aconnector, DRM_FORCE_UNSPECIFIED);
1615 		}
1616 
1617 		test_response.bits.ACK = 1;
1618 
1619 		core_link_write_dpcd(
1620 		dc_link,
1621 		DP_TEST_RESPONSE,
1622 		&test_response.raw,
1623 		sizeof(test_response));
1624 	} else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1625 			dc_link_check_link_loss_status(dc_link, &offload_work->data) &&
1626 			dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1627 		/* offload_work->data is from handle_hpd_rx_irq->
1628 		 * schedule_hpd_rx_offload_work.this is defer handle
1629 		 * for hpd short pulse. upon here, link status may be
1630 		 * changed, need get latest link status from dpcd
1631 		 * registers. if link status is good, skip run link
1632 		 * training again.
1633 		 */
1634 		union hpd_irq_data irq_data;
1635 
1636 		memset(&irq_data, 0, sizeof(irq_data));
1637 
1638 		/* before dc_link_dp_handle_link_loss, allow new link lost handle
1639 		 * request be added to work queue if link lost at end of dc_link_
1640 		 * dp_handle_link_loss
1641 		 */
1642 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1643 		offload_work->offload_wq->is_handling_link_loss = false;
1644 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1645 
1646 		if ((dc_link_dp_read_hpd_rx_irq_data(dc_link, &irq_data) == DC_OK) &&
1647 			dc_link_check_link_loss_status(dc_link, &irq_data))
1648 			dc_link_dp_handle_link_loss(dc_link);
1649 	}
1650 	mutex_unlock(&adev->dm.dc_lock);
1651 
1652 skip:
1653 	kfree(offload_work);
1654 
1655 }
1656 
1657 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct amdgpu_device *adev)
1658 {
1659 	struct dc *dc = adev->dm.dc;
1660 	int max_caps = dc->caps.max_links;
1661 	int i = 0;
1662 	struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1663 
1664 	hpd_rx_offload_wq = kzalloc_objs(*hpd_rx_offload_wq, max_caps);
1665 
1666 	if (!hpd_rx_offload_wq)
1667 		return NULL;
1668 
1669 
1670 	for (i = 0; i < max_caps; i++) {
1671 		hpd_rx_offload_wq[i].wq =
1672 				    create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1673 
1674 		if (hpd_rx_offload_wq[i].wq == NULL) {
1675 			drm_err(adev_to_drm(adev), "create amdgpu_dm_hpd_rx_offload_wq fail!");
1676 			goto out_err;
1677 		}
1678 
1679 		spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
1680 	}
1681 
1682 	return hpd_rx_offload_wq;
1683 
1684 out_err:
1685 	for (i = 0; i < max_caps; i++) {
1686 		if (hpd_rx_offload_wq[i].wq)
1687 			destroy_workqueue(hpd_rx_offload_wq[i].wq);
1688 	}
1689 	kfree(hpd_rx_offload_wq);
1690 	return NULL;
1691 }
1692 
1693 struct amdgpu_stutter_quirk {
1694 	u16 chip_vendor;
1695 	u16 chip_device;
1696 	u16 subsys_vendor;
1697 	u16 subsys_device;
1698 	u8 revision;
1699 };
1700 
1701 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1702 	/* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1703 	{ 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1704 	{ 0, 0, 0, 0, 0 },
1705 };
1706 
1707 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1708 {
1709 	const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1710 
1711 	while (p && p->chip_device != 0) {
1712 		if (pdev->vendor == p->chip_vendor &&
1713 		    pdev->device == p->chip_device &&
1714 		    pdev->subsystem_vendor == p->subsys_vendor &&
1715 		    pdev->subsystem_device == p->subsys_device &&
1716 		    pdev->revision == p->revision) {
1717 			return true;
1718 		}
1719 		++p;
1720 	}
1721 	return false;
1722 }
1723 
1724 
1725 void*
1726 dm_allocate_gpu_mem(
1727 		struct amdgpu_device *adev,
1728 		enum dc_gpu_mem_alloc_type type,
1729 		size_t size,
1730 		long long *addr)
1731 {
1732 	struct dal_allocation *da;
1733 	u32 domain = (type == DC_MEM_ALLOC_TYPE_GART) ?
1734 		AMDGPU_GEM_DOMAIN_GTT : AMDGPU_GEM_DOMAIN_VRAM;
1735 	int ret;
1736 
1737 	da = kzalloc_obj(struct dal_allocation);
1738 	if (!da)
1739 		return NULL;
1740 
1741 	ret = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
1742 				      domain, &da->bo,
1743 				      &da->gpu_addr, &da->cpu_ptr);
1744 
1745 	*addr = da->gpu_addr;
1746 
1747 	if (ret) {
1748 		kfree(da);
1749 		return NULL;
1750 	}
1751 
1752 	/* add da to list in dm */
1753 	list_add(&da->list, &adev->dm.da_list);
1754 
1755 	return da->cpu_ptr;
1756 }
1757 
1758 void
1759 dm_free_gpu_mem(
1760 		struct amdgpu_device *adev,
1761 		enum dc_gpu_mem_alloc_type type,
1762 		void *pvMem)
1763 {
1764 	struct dal_allocation *da;
1765 
1766 	/* walk the da list in DM */
1767 	list_for_each_entry(da, &adev->dm.da_list, list) {
1768 		if (pvMem == da->cpu_ptr) {
1769 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
1770 			list_del(&da->list);
1771 			kfree(da);
1772 			break;
1773 		}
1774 	}
1775 
1776 }
1777 
1778 static enum dmub_status
1779 dm_dmub_send_vbios_gpint_command(struct amdgpu_device *adev,
1780 				 enum dmub_gpint_command command_code,
1781 				 uint16_t param,
1782 				 uint32_t timeout_us)
1783 {
1784 	union dmub_gpint_data_register reg, test;
1785 	uint32_t i;
1786 
1787 	/* Assume that VBIOS DMUB is ready to take commands */
1788 
1789 	reg.bits.status = 1;
1790 	reg.bits.command_code = command_code;
1791 	reg.bits.param = param;
1792 
1793 	cgs_write_register(adev->dm.cgs_device, 0x34c0 + 0x01f8, reg.all);
1794 
1795 	for (i = 0; i < timeout_us; ++i) {
1796 		udelay(1);
1797 
1798 		/* Check if our GPINT got acked */
1799 		reg.bits.status = 0;
1800 		test = (union dmub_gpint_data_register)
1801 			cgs_read_register(adev->dm.cgs_device, 0x34c0 + 0x01f8);
1802 
1803 		if (test.all == reg.all)
1804 			return DMUB_STATUS_OK;
1805 	}
1806 
1807 	return DMUB_STATUS_TIMEOUT;
1808 }
1809 
1810 static void *dm_dmub_get_vbios_bounding_box(struct amdgpu_device *adev)
1811 {
1812 	void *bb;
1813 	long long addr;
1814 	unsigned int bb_size;
1815 	int i = 0;
1816 	uint16_t chunk;
1817 	enum dmub_gpint_command send_addrs[] = {
1818 		DMUB_GPINT__SET_BB_ADDR_WORD0,
1819 		DMUB_GPINT__SET_BB_ADDR_WORD1,
1820 		DMUB_GPINT__SET_BB_ADDR_WORD2,
1821 		DMUB_GPINT__SET_BB_ADDR_WORD3,
1822 	};
1823 	enum dmub_status ret;
1824 
1825 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1826 	case IP_VERSION(4, 0, 1):
1827 		bb_size = sizeof(struct dml2_soc_bb);
1828 		break;
1829 	case IP_VERSION(4, 2, 0):
1830 	case IP_VERSION(4, 2, 1):
1831 		bb_size = sizeof(struct dml2_soc_bb);
1832 		break;
1833 	default:
1834 		return NULL;
1835 	}
1836 
1837 	bb =  dm_allocate_gpu_mem(adev,
1838 				  DC_MEM_ALLOC_TYPE_GART,
1839 				  bb_size,
1840 				  &addr);
1841 	if (!bb)
1842 		return NULL;
1843 
1844 	for (i = 0; i < 4; i++) {
1845 		/* Extract 16-bit chunk */
1846 		chunk = ((uint64_t) addr >> (i * 16)) & 0xFFFF;
1847 		/* Send the chunk */
1848 		ret = dm_dmub_send_vbios_gpint_command(adev, send_addrs[i], chunk, 30000);
1849 		if (ret != DMUB_STATUS_OK)
1850 			goto free_bb;
1851 	}
1852 
1853 	/* Now ask DMUB to copy the bb */
1854 	ret = dm_dmub_send_vbios_gpint_command(adev, DMUB_GPINT__BB_COPY, 1, 200000);
1855 	if (ret != DMUB_STATUS_OK)
1856 		goto free_bb;
1857 
1858 	return bb;
1859 
1860 free_bb:
1861 	dm_free_gpu_mem(adev, DC_MEM_ALLOC_TYPE_GART, (void *) bb);
1862 	return NULL;
1863 
1864 }
1865 
1866 static enum dmub_ips_disable_type dm_get_default_ips_mode(
1867 	struct amdgpu_device *adev)
1868 {
1869 	enum dmub_ips_disable_type ret = DMUB_IPS_ENABLE;
1870 
1871 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1872 	case IP_VERSION(3, 5, 0):
1873 	case IP_VERSION(3, 6, 0):
1874 	case IP_VERSION(3, 5, 1):
1875 		ret =  DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
1876 		break;
1877 	case IP_VERSION(4, 2, 0):
1878 	case IP_VERSION(4, 2, 1):
1879 		ret =  DMUB_IPS_ENABLE;
1880 		break;
1881 	default:
1882 		/* ASICs older than DCN35 do not have IPSs */
1883 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 5, 0))
1884 			ret = DMUB_IPS_DISABLE_ALL;
1885 		break;
1886 	}
1887 
1888 	return ret;
1889 }
1890 
1891 static int amdgpu_dm_init_power_module(struct amdgpu_display_manager *dm)
1892 {
1893 	struct mod_power_init_params init_data[MAX_NUM_EDP];
1894 
1895 	if (dm->num_of_edps == 0) {
1896 		drm_dbg_driver(
1897 			dm->ddev,
1898 			"amdgpu: No eDP detected, skip initializing power module\n");
1899 		return 0;
1900 	}
1901 
1902 	/* Initialize all the power module parameters */
1903 	for (int i = 0; i < dm->num_of_edps; i++) {
1904 		init_data[i].allow_psr_smu_optimizations =
1905 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_SMU_OPT);
1906 		init_data[i].allow_psr_multi_disp_optimizations =
1907 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_MULTI_DISP_OPT);
1908 		/* See dm_late_init */
1909 		init_data[i].backlight_ramping_override = false;
1910 		init_data[i].backlight_ramping_start = 0xCCCC;
1911 		init_data[i].backlight_ramping_reduction = 0xCCCCCCCC;
1912 		init_data[i].def_varibright_level = 0;
1913 		init_data[i].abm_config_setting = 0;
1914 		init_data[i].num_backlight_levels = 101;
1915 		init_data[i].use_nits_based_brightness = false;
1916 		init_data[i].panel_max_millinits = 0;
1917 		init_data[i].panel_min_millinits = 0;
1918 		init_data[i].disable_fractional_pwm =
1919 			!(amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK);
1920 		init_data[i].use_custom_backlight_caps = false;
1921 		init_data[i].custom_backlight_caps_config_no = 0;
1922 		init_data[i].use_linear_backlight_curve = false;
1923 		init_data[i].def_varibright_enable = 0;
1924 		init_data[i].varibright_level = 0;
1925 		/*
1926 		 * Power module uses 16-bit backlight levels (0xFFFF max) rather
1927 		 * than 8-bit(0XFF max)
1928 		 */
1929 		init_data[i].min_backlight_pwm =
1930 			dm->backlight_caps[i].min_input_signal * 0x101;
1931 		init_data[i].max_backlight_pwm =
1932 			dm->backlight_caps[i].max_input_signal * 0x101;
1933 		init_data[i].min_abm_backlight =
1934 			dm->backlight_caps[i].min_input_signal * 0x101;
1935 
1936 		/* Min backlight level after ABM reduction,  Don't allow below 1%
1937 		 * 0xFFFF x 0.01 = 0x28F
1938 		 */
1939 		init_data[i].min_abm_backlight = (init_data[i].min_abm_backlight < 0x28F) ?
1940 			0x28F : init_data[i].min_abm_backlight;
1941 	}
1942 
1943 	dm->power_module = mod_power_create(dm->dc, init_data, dm->num_of_edps);
1944 	if (!dm->power_module) {
1945 		drm_err(dm->ddev, "amdgpu: Error allocating memory for power module\n");
1946 		return -ENOMEM;
1947 	}
1948 
1949 	mod_power_hw_init(dm->power_module);
1950 	drm_dbg_driver(dm->ddev, "amdgpu: Power module init done\n");
1951 
1952 	return 0;
1953 }
1954 
1955 static void hdmi_frl_status_polling_work(struct work_struct *work)
1956 {
1957 	struct amdgpu_display_manager *dm =
1958 		container_of(to_delayed_work(work), struct amdgpu_display_manager,
1959 				hdmi_frl_status_polling_work);
1960 	struct dc *dc = dm->dc;
1961 	struct dc_link *dc_link;
1962 	bool link_update = false;
1963 
1964 	for (int i = 0; i < MAX_LINKS; i++) {
1965 		dc_link = dc->links[i];
1966 
1967 		if (!dc_link || !dc_link->local_sink)
1968 			continue;
1969 
1970 		if (!dc_is_hdmi_signal(dc_link->connector_signal))
1971 			continue;
1972 
1973 		if (dc_link->connector_signal != SIGNAL_TYPE_HDMI_FRL)
1974 			continue;
1975 
1976 		link_update = dc_link_frl_poll_status_flag(dc_link);
1977 		if (link_update) {
1978 			mutex_lock(&dm->dc_lock);
1979 			dc_link_detect(dc_link, DETECT_REASON_RETRAIN);
1980 			mutex_unlock(&dm->dc_lock);
1981 		}
1982 	}
1983 
1984 	queue_delayed_work(dm->hdmi_frl_status_polling_wq,
1985 			   &dm->hdmi_frl_status_polling_work,
1986 			   msecs_to_jiffies(dm->hdmi_frl_status_polling_delay_ms));
1987 }
1988 
1989 static int amdgpu_dm_init(struct amdgpu_device *adev)
1990 {
1991 	struct dc_init_data init_data;
1992 	struct dc_callback_init init_params;
1993 	int r;
1994 
1995 	adev->dm.ddev = adev_to_drm(adev);
1996 	adev->dm.adev = adev;
1997 
1998 	/* Zero all the fields */
1999 	memset(&init_data, 0, sizeof(init_data));
2000 	memset(&init_params, 0, sizeof(init_params));
2001 
2002 	mutex_init(&adev->dm.dpia_aux_lock);
2003 	mutex_init(&adev->dm.dc_lock);
2004 	mutex_init(&adev->dm.audio_lock);
2005 
2006 	spin_lock_init(&adev->dm.dmub_lock);
2007 
2008 	if (amdgpu_dm_irq_init(adev)) {
2009 		drm_err(adev_to_drm(adev), "failed to initialize DM IRQ support.\n");
2010 		goto error;
2011 	}
2012 
2013 	/* special handling for early revisions of GC 11.5.4 */
2014 	if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(11, 5, 4))
2015 		init_data.asic_id.chip_family = AMDGPU_FAMILY_GC_11_5_4;
2016 	else
2017 		init_data.asic_id.chip_family = adev->family;
2018 
2019 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
2020 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
2021 	init_data.asic_id.chip_id = adev->pdev->device;
2022 
2023 	init_data.asic_id.vram_width = adev->gmc.vram_width;
2024 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
2025 	init_data.asic_id.atombios_base_address =
2026 		adev->mode_info.atom_context->bios;
2027 
2028 	init_data.driver = adev;
2029 
2030 	/* cgs_device was created in dm_sw_init() */
2031 	init_data.cgs_device = adev->dm.cgs_device;
2032 
2033 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
2034 
2035 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2036 	case IP_VERSION(2, 1, 0):
2037 		switch (adev->dm.dmcub_fw_version) {
2038 		case 0: /* development */
2039 		case 0x1: /* linux-firmware.git hash 6d9f399 */
2040 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
2041 			init_data.flags.disable_dmcu = false;
2042 			break;
2043 		default:
2044 			init_data.flags.disable_dmcu = true;
2045 		}
2046 		break;
2047 	case IP_VERSION(2, 0, 3):
2048 		init_data.flags.disable_dmcu = true;
2049 		break;
2050 	default:
2051 		break;
2052 	}
2053 
2054 	/* APU support S/G display by default except:
2055 	 * ASICs before Carrizo,
2056 	 * RAVEN1 (Users reported stability issue)
2057 	 */
2058 
2059 	if (adev->asic_type < CHIP_CARRIZO) {
2060 		init_data.flags.gpu_vm_support = false;
2061 	} else if (adev->asic_type == CHIP_RAVEN) {
2062 		if (adev->apu_flags & AMD_APU_IS_RAVEN)
2063 			init_data.flags.gpu_vm_support = false;
2064 		else
2065 			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
2066 	} else {
2067 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(2, 0, 3))
2068 			init_data.flags.gpu_vm_support = (amdgpu_sg_display == 1);
2069 		else
2070 			init_data.flags.gpu_vm_support =
2071 				(amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
2072 	}
2073 
2074 	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
2075 
2076 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
2077 		init_data.flags.fbc_support = true;
2078 
2079 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
2080 		init_data.flags.multi_mon_pp_mclk_switch = true;
2081 
2082 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
2083 		init_data.flags.disable_fractional_pwm = true;
2084 
2085 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
2086 		init_data.flags.edp_no_power_sequencing = true;
2087 
2088 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
2089 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
2090 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
2091 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
2092 
2093 	init_data.flags.seamless_boot_edp_requested = false;
2094 
2095 	if (amdgpu_device_seamless_boot_supported(adev)) {
2096 		init_data.flags.seamless_boot_edp_requested = true;
2097 		init_data.flags.allow_seamless_boot_optimization = true;
2098 		drm_dbg(adev->dm.ddev, "Seamless boot requested\n");
2099 	}
2100 
2101 	init_data.flags.enable_mipi_converter_optimization = true;
2102 
2103 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
2104 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
2105 	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
2106 
2107 	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
2108 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
2109 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS_DYNAMIC)
2110 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_DYNAMIC;
2111 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS2_DYNAMIC)
2112 		init_data.flags.disable_ips = DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
2113 	else if (amdgpu_dc_debug_mask & DC_FORCE_IPS_ENABLE)
2114 		init_data.flags.disable_ips = DMUB_IPS_ENABLE;
2115 	else
2116 		init_data.flags.disable_ips = dm_get_default_ips_mode(adev);
2117 
2118 	init_data.flags.disable_ips_in_vpb = 0;
2119 
2120 	/* DCN35 and above supports dynamic DTBCLK switch */
2121 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 5, 0))
2122 		init_data.flags.allow_0_dtb_clk = true;
2123 
2124 	/* Enable DWB for tested platforms only */
2125 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
2126 		init_data.num_virtual_links = 1;
2127 
2128 	/* DCN42 and above dpia switch to unified link training path */
2129 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 2, 0)) {
2130 		init_data.flags.consolidated_dpia_dp_lt = true;
2131 		init_data.flags.enable_dpia_pre_training = true;
2132 		init_data.flags.unify_link_enc_assignment = true;
2133 		init_data.flags.usb4_bw_alloc_support = true;
2134 	}
2135 	retrieve_dmi_info(&adev->dm);
2136 	if (adev->dm.edp0_on_dp1_quirk)
2137 		init_data.flags.support_edp0_on_dp1 = true;
2138 
2139 	if (adev->dm.bb_from_dmub)
2140 		init_data.bb_from_dmub = adev->dm.bb_from_dmub;
2141 	else
2142 		init_data.bb_from_dmub = NULL;
2143 
2144 	/* Display Core create. */
2145 	adev->dm.dc = dc_create(&init_data);
2146 
2147 	if (adev->dm.dc) {
2148 		drm_info(adev_to_drm(adev), "Display Core v%s initialized on %s\n", DC_VER,
2149 			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
2150 	} else {
2151 		drm_info(adev_to_drm(adev), "Display Core failed to initialize with v%s!\n", DC_VER);
2152 		goto error;
2153 	}
2154 
2155 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
2156 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
2157 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
2158 	}
2159 
2160 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2161 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2162 	if (dm_should_disable_stutter(adev->pdev))
2163 		adev->dm.dc->debug.disable_stutter = true;
2164 
2165 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
2166 		adev->dm.dc->debug.disable_stutter = true;
2167 
2168 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
2169 		adev->dm.dc->debug.disable_dsc = true;
2170 
2171 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
2172 		adev->dm.dc->debug.disable_clock_gate = true;
2173 
2174 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
2175 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
2176 
2177 	if (amdgpu_dc_debug_mask & DC_DISABLE_SUBVP_FAMS) {
2178 		adev->dm.dc->debug.force_disable_subvp = true;
2179 		adev->dm.dc->debug.fams2_config.bits.enable = false;
2180 	}
2181 
2182 	if (amdgpu_dc_debug_mask & DC_ENABLE_DML2) {
2183 		adev->dm.dc->debug.using_dml2 = true;
2184 		adev->dm.dc->debug.using_dml21 = true;
2185 	}
2186 
2187 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_FORCE_FW_ENABLE)
2188 		adev->dm.dc->debug.hdcp_lc_force_fw_enable = true;
2189 
2190 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_ENABLE_SW_FALLBACK)
2191 		adev->dm.dc->debug.hdcp_lc_enable_sw_fallback = true;
2192 
2193 	if (amdgpu_dc_debug_mask & DC_SKIP_DETECTION_LT)
2194 		adev->dm.dc->debug.skip_detection_link_training = true;
2195 
2196 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
2197 
2198 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
2199 	adev->dm.dc->debug.ignore_cable_id = true;
2200 
2201 	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
2202 		drm_info(adev_to_drm(adev), "DP-HDMI FRL PCON supported\n");
2203 
2204 	r = dm_dmub_hw_init(adev);
2205 	if (r) {
2206 		drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
2207 		goto error;
2208 	}
2209 
2210 	dc_hardware_init(adev->dm.dc);
2211 
2212 	adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev);
2213 	if (!adev->dm.hpd_rx_offload_wq) {
2214 		drm_err(adev_to_drm(adev), "failed to create hpd rx offload workqueue.\n");
2215 		goto error;
2216 	}
2217 
2218 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
2219 		struct dc_phy_addr_space_config pa_config;
2220 
2221 		mmhub_read_system_context(adev, &pa_config);
2222 
2223 		// Call the DC init_memory func
2224 		dc_setup_system_context(adev->dm.dc, &pa_config);
2225 	}
2226 
2227 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
2228 	if (!adev->dm.freesync_module) {
2229 		drm_err(adev_to_drm(adev),
2230 		"failed to initialize freesync_module.\n");
2231 	} else
2232 		drm_dbg_driver(adev_to_drm(adev), "freesync_module init done %p.\n",
2233 				adev->dm.freesync_module);
2234 
2235 	amdgpu_dm_init_color_mod();
2236 
2237 	if (adev->dm.dc->caps.max_links > 0) {
2238 		adev->dm.vblank_control_workqueue =
2239 			create_singlethread_workqueue("dm_vblank_control_workqueue");
2240 		if (!adev->dm.vblank_control_workqueue)
2241 			drm_err(adev_to_drm(adev), "failed to initialize vblank_workqueue.\n");
2242 	}
2243 
2244 	if (adev->dm.dc->caps.ips_support &&
2245 	    adev->dm.dc->config.disable_ips != DMUB_IPS_DISABLE_ALL)
2246 		adev->dm.idle_workqueue = idle_create_workqueue(adev);
2247 
2248 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
2249 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
2250 
2251 		if (!adev->dm.hdcp_workqueue)
2252 			drm_err(adev_to_drm(adev), "failed to initialize hdcp_workqueue.\n");
2253 		else
2254 			drm_dbg_driver(adev_to_drm(adev),
2255 				       "hdcp_workqueue init done %p.\n",
2256 				       adev->dm.hdcp_workqueue);
2257 
2258 		dc_init_callbacks(adev->dm.dc, &init_params);
2259 	}
2260 	if (adev->dm.dc->caps.max_links > 0) {
2261 		adev->dm.hdmi_frl_status_polling_wq =
2262 			create_singlethread_workqueue("hdmi_frl_status_polling_workqueue");
2263 		if (!adev->dm.hdmi_frl_status_polling_wq)
2264 			drm_err(adev_to_drm(adev), "failed to initialize hdmi_frl_status_polling_workqueue\n");
2265 		adev->dm.hdmi_frl_status_polling_delay_ms = 200;
2266 		INIT_DELAYED_WORK(&adev->dm.hdmi_frl_status_polling_work, hdmi_frl_status_polling_work);
2267 	}
2268 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2269 		init_completion(&adev->dm.dmub_aux_transfer_done);
2270 		adev->dm.dmub_notify = kzalloc_obj(struct dmub_notification);
2271 		if (!adev->dm.dmub_notify) {
2272 			drm_info(adev_to_drm(adev), "fail to allocate adev->dm.dmub_notify");
2273 			goto error;
2274 		}
2275 
2276 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
2277 		if (!adev->dm.delayed_hpd_wq) {
2278 			drm_err(adev_to_drm(adev), "failed to create hpd offload workqueue.\n");
2279 			goto error;
2280 		}
2281 
2282 		amdgpu_dm_outbox_init(adev);
2283 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
2284 			dmub_aux_setconfig_callback, false)) {
2285 			drm_err(adev_to_drm(adev), "fail to register dmub aux callback");
2286 			goto error;
2287 		}
2288 
2289 		for (size_t i = 0; i < ARRAY_SIZE(adev->dm.fused_io); i++)
2290 			init_completion(&adev->dm.fused_io[i].replied);
2291 
2292 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_FUSED_IO,
2293 			dmub_aux_fused_io_callback, false)) {
2294 			drm_err(adev_to_drm(adev), "fail to register dmub fused io callback");
2295 			goto error;
2296 		}
2297 		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
2298 		 * It is expected that DMUB will resend any pending notifications at this point. Note
2299 		 * that hpd and hpd_irq handler registration are deferred to register_hpd_handlers() to
2300 		 * align legacy interface initialization sequence. Connection status will be proactivly
2301 		 * detected once in the amdgpu_dm_initialize_drm_device.
2302 		 */
2303 		dc_enable_dmub_outbox(adev->dm.dc);
2304 
2305 		/* DPIA trace goes to dmesg logs only if outbox is enabled */
2306 		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
2307 			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
2308 	}
2309 
2310 	if (amdgpu_dm_initialize_drm_device(adev)) {
2311 		drm_err(adev_to_drm(adev),
2312 		"failed to initialize sw for display support.\n");
2313 		goto error;
2314 	}
2315 
2316 	if (amdgpu_dm_init_power_module(&adev->dm))
2317 		goto error;
2318 
2319 	/* create fake encoders for MST */
2320 	dm_dp_create_fake_mst_encoders(adev);
2321 
2322 	/* TODO: Add_display_info? */
2323 
2324 	/* TODO use dynamic cursor width */
2325 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
2326 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
2327 
2328 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
2329 		drm_err(adev_to_drm(adev),
2330 		"failed to initialize vblank for display support.\n");
2331 		goto error;
2332 	}
2333 
2334 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2335 	amdgpu_dm_crtc_secure_display_create_contexts(adev);
2336 	if (!adev->dm.secure_display_ctx.crtc_ctx)
2337 		drm_err(adev_to_drm(adev), "failed to initialize secure display contexts.\n");
2338 
2339 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))
2340 		adev->dm.secure_display_ctx.support_mul_roi = true;
2341 
2342 #endif
2343 
2344 	drm_dbg_driver(adev_to_drm(adev), "KMS initialized.\n");
2345 
2346 	return 0;
2347 error:
2348 	amdgpu_dm_fini(adev);
2349 
2350 	return -EINVAL;
2351 }
2352 
2353 static int amdgpu_dm_early_fini(struct amdgpu_ip_block *ip_block)
2354 {
2355 	struct amdgpu_device *adev = ip_block->adev;
2356 
2357 	amdgpu_dm_audio_fini(adev);
2358 
2359 	return 0;
2360 }
2361 
2362 static void amdgpu_dm_fini(struct amdgpu_device *adev)
2363 {
2364 	int i;
2365 
2366 	if (adev->dm.vblank_control_workqueue) {
2367 		destroy_workqueue(adev->dm.vblank_control_workqueue);
2368 		adev->dm.vblank_control_workqueue = NULL;
2369 	}
2370 
2371 	if (adev->dm.idle_workqueue) {
2372 		if (adev->dm.idle_workqueue->running) {
2373 			adev->dm.idle_workqueue->enable = false;
2374 			flush_work(&adev->dm.idle_workqueue->work);
2375 		}
2376 
2377 		kfree(adev->dm.idle_workqueue);
2378 		adev->dm.idle_workqueue = NULL;
2379 	}
2380 
2381 	/*
2382 	 * Disable ISM before dc_destroy() invalidates dm->dc.
2383 	 *
2384 	 * Quiesce workers first without dc_lock (they take dc_lock
2385 	 * themselves, so syncing under it would deadlock), then drive the
2386 	 * FSM back to FULL_POWER_RUNNING under dc_lock.
2387 	 */
2388 	amdgpu_dm_ism_disable(&adev->dm);
2389 	scoped_guard(mutex, &adev->dm.dc_lock)
2390 		amdgpu_dm_ism_force_full_power(&adev->dm);
2391 
2392 	amdgpu_dm_destroy_drm_device(&adev->dm);
2393 
2394 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2395 	if (adev->dm.secure_display_ctx.crtc_ctx) {
2396 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
2397 			if (adev->dm.secure_display_ctx.crtc_ctx[i].crtc) {
2398 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].notify_ta_work);
2399 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].forward_roi_work);
2400 			}
2401 		}
2402 		kfree(adev->dm.secure_display_ctx.crtc_ctx);
2403 		adev->dm.secure_display_ctx.crtc_ctx = NULL;
2404 	}
2405 #endif
2406 	if (adev->dm.hdcp_workqueue) {
2407 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
2408 		adev->dm.hdcp_workqueue = NULL;
2409 	}
2410 
2411 	if (adev->dm.dc) {
2412 		dc_deinit_callbacks(adev->dm.dc);
2413 		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
2414 		if (dc_enable_dmub_notifications(adev->dm.dc)) {
2415 			kfree(adev->dm.dmub_notify);
2416 			adev->dm.dmub_notify = NULL;
2417 			destroy_workqueue(adev->dm.delayed_hpd_wq);
2418 			adev->dm.delayed_hpd_wq = NULL;
2419 		}
2420 	}
2421 
2422 	if (adev->dm.dmub_bo)
2423 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
2424 				      &adev->dm.dmub_bo_gpu_addr,
2425 				      &adev->dm.dmub_bo_cpu_addr);
2426 
2427 	if (adev->dm.boot_time_crc_info.bo_ptr)
2428 		amdgpu_bo_free_kernel(&adev->dm.boot_time_crc_info.bo_ptr,
2429 					&adev->dm.boot_time_crc_info.gpu_addr,
2430 					&adev->dm.boot_time_crc_info.cpu_addr);
2431 
2432 	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
2433 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
2434 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
2435 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
2436 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
2437 			}
2438 		}
2439 
2440 		kfree(adev->dm.hpd_rx_offload_wq);
2441 		adev->dm.hpd_rx_offload_wq = NULL;
2442 	}
2443 
2444 	/* DC Destroy TODO: Replace destroy DAL */
2445 	if (adev->dm.dc)
2446 		dc_destroy(&adev->dm.dc);
2447 	/*
2448 	 * TODO: pageflip, vlank interrupt
2449 	 *
2450 	 * amdgpu_dm_irq_fini(adev);
2451 	 */
2452 
2453 	if (adev->dm.cgs_device) {
2454 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
2455 		adev->dm.cgs_device = NULL;
2456 	}
2457 	if (adev->dm.freesync_module) {
2458 		mod_freesync_destroy(adev->dm.freesync_module);
2459 		adev->dm.freesync_module = NULL;
2460 	}
2461 
2462 	if (adev->dm.power_module) {
2463 		mod_power_destroy(adev->dm.power_module);
2464 		adev->dm.power_module = NULL;
2465 	}
2466 	mutex_destroy(&adev->dm.audio_lock);
2467 	mutex_destroy(&adev->dm.dc_lock);
2468 	mutex_destroy(&adev->dm.dpia_aux_lock);
2469 }
2470 
2471 static int load_dmcu_fw(struct amdgpu_device *adev)
2472 {
2473 	const char *fw_name_dmcu = NULL;
2474 	int r;
2475 	const struct dmcu_firmware_header_v1_0 *hdr;
2476 
2477 	switch (adev->asic_type) {
2478 #if defined(CONFIG_DRM_AMD_DC_SI)
2479 	case CHIP_TAHITI:
2480 	case CHIP_PITCAIRN:
2481 	case CHIP_VERDE:
2482 	case CHIP_OLAND:
2483 #endif
2484 	case CHIP_BONAIRE:
2485 	case CHIP_HAWAII:
2486 	case CHIP_KAVERI:
2487 	case CHIP_KABINI:
2488 	case CHIP_MULLINS:
2489 	case CHIP_TONGA:
2490 	case CHIP_FIJI:
2491 	case CHIP_CARRIZO:
2492 	case CHIP_STONEY:
2493 	case CHIP_POLARIS11:
2494 	case CHIP_POLARIS10:
2495 	case CHIP_POLARIS12:
2496 	case CHIP_VEGAM:
2497 	case CHIP_VEGA10:
2498 	case CHIP_VEGA12:
2499 	case CHIP_VEGA20:
2500 		return 0;
2501 	case CHIP_NAVI12:
2502 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
2503 		break;
2504 	case CHIP_RAVEN:
2505 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
2506 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2507 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
2508 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2509 		else
2510 			return 0;
2511 		break;
2512 	default:
2513 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2514 		case IP_VERSION(2, 0, 2):
2515 		case IP_VERSION(2, 0, 3):
2516 		case IP_VERSION(2, 0, 0):
2517 		case IP_VERSION(2, 1, 0):
2518 		case IP_VERSION(3, 0, 0):
2519 		case IP_VERSION(3, 0, 2):
2520 		case IP_VERSION(3, 0, 3):
2521 		case IP_VERSION(3, 0, 1):
2522 		case IP_VERSION(3, 1, 2):
2523 		case IP_VERSION(3, 1, 3):
2524 		case IP_VERSION(3, 1, 4):
2525 		case IP_VERSION(3, 1, 5):
2526 		case IP_VERSION(3, 1, 6):
2527 		case IP_VERSION(3, 2, 0):
2528 		case IP_VERSION(3, 2, 1):
2529 		case IP_VERSION(3, 5, 0):
2530 		case IP_VERSION(3, 5, 1):
2531 		case IP_VERSION(3, 6, 0):
2532 		case IP_VERSION(4, 0, 1):
2533 		case IP_VERSION(4, 2, 0):
2534 		case IP_VERSION(4, 2, 1):
2535 			return 0;
2536 		default:
2537 			break;
2538 		}
2539 		drm_err(adev_to_drm(adev), "Unsupported ASIC type: 0x%X\n", adev->asic_type);
2540 		return -EINVAL;
2541 	}
2542 
2543 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
2544 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not supported on direct or SMU loading\n");
2545 		return 0;
2546 	}
2547 
2548 	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, AMDGPU_UCODE_REQUIRED,
2549 				 "%s", fw_name_dmcu);
2550 	if (r == -ENODEV) {
2551 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
2552 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not found\n");
2553 		adev->dm.fw_dmcu = NULL;
2554 		return 0;
2555 	}
2556 	if (r) {
2557 		drm_err(adev_to_drm(adev), "amdgpu_dm: Can't validate firmware \"%s\"\n",
2558 			fw_name_dmcu);
2559 		amdgpu_ucode_release(&adev->dm.fw_dmcu);
2560 		return r;
2561 	}
2562 
2563 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
2564 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
2565 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
2566 	adev->firmware.fw_size +=
2567 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2568 
2569 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
2570 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
2571 	adev->firmware.fw_size +=
2572 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2573 
2574 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
2575 
2576 	drm_dbg_kms(adev_to_drm(adev), "PSP loading DMCU firmware\n");
2577 
2578 	return 0;
2579 }
2580 
2581 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
2582 {
2583 	struct amdgpu_device *adev = ctx;
2584 
2585 	return dm_read_reg(adev->dm.dc->ctx, address);
2586 }
2587 
2588 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
2589 				     uint32_t value)
2590 {
2591 	struct amdgpu_device *adev = ctx;
2592 
2593 	return dm_write_reg(adev->dm.dc->ctx, address, value);
2594 }
2595 
2596 static int dm_dmub_sw_init(struct amdgpu_device *adev)
2597 {
2598 	struct dmub_srv_create_params create_params;
2599 	struct dmub_srv_fw_meta_info_params fw_meta_info_params;
2600 	struct dmub_srv_region_params region_params;
2601 	struct dmub_srv_region_info region_info;
2602 	struct dmub_srv_memory_params memory_params;
2603 	struct dmub_fw_meta_info fw_info;
2604 	struct dmub_srv_fb_info *fb_info;
2605 	struct dmub_srv *dmub_srv;
2606 	const struct dmcub_firmware_header_v1_0 *hdr;
2607 	enum dmub_asic dmub_asic;
2608 	enum dmub_status status;
2609 	static enum dmub_window_memory_type window_memory_type[DMUB_WINDOW_TOTAL] = {
2610 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_0_INST_CONST
2611 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_1_STACK
2612 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_2_BSS_DATA
2613 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_3_VBIOS
2614 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_4_MAILBOX
2615 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_5_TRACEBUFF
2616 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_6_FW_STATE
2617 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_7_SCRATCH_MEM
2618 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_IB_MEM
2619 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_SHARED_STATE
2620 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_LSDMA_BUFFER
2621 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_CURSOR_OFFLOAD
2622 	};
2623 	int r;
2624 
2625 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2626 	case IP_VERSION(2, 1, 0):
2627 		dmub_asic = DMUB_ASIC_DCN21;
2628 		break;
2629 	case IP_VERSION(3, 0, 0):
2630 		dmub_asic = DMUB_ASIC_DCN30;
2631 		break;
2632 	case IP_VERSION(3, 0, 1):
2633 		dmub_asic = DMUB_ASIC_DCN301;
2634 		break;
2635 	case IP_VERSION(3, 0, 2):
2636 		dmub_asic = DMUB_ASIC_DCN302;
2637 		break;
2638 	case IP_VERSION(3, 0, 3):
2639 		dmub_asic = DMUB_ASIC_DCN303;
2640 		break;
2641 	case IP_VERSION(3, 1, 2):
2642 	case IP_VERSION(3, 1, 3):
2643 		dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
2644 		break;
2645 	case IP_VERSION(3, 1, 4):
2646 		dmub_asic = DMUB_ASIC_DCN314;
2647 		break;
2648 	case IP_VERSION(3, 1, 5):
2649 		dmub_asic = DMUB_ASIC_DCN315;
2650 		break;
2651 	case IP_VERSION(3, 1, 6):
2652 		dmub_asic = DMUB_ASIC_DCN316;
2653 		break;
2654 	case IP_VERSION(3, 2, 0):
2655 		dmub_asic = DMUB_ASIC_DCN32;
2656 		break;
2657 	case IP_VERSION(3, 2, 1):
2658 		dmub_asic = DMUB_ASIC_DCN321;
2659 		break;
2660 	case IP_VERSION(3, 5, 0):
2661 	case IP_VERSION(3, 5, 1):
2662 		dmub_asic = DMUB_ASIC_DCN35;
2663 		break;
2664 	case IP_VERSION(3, 6, 0):
2665 		dmub_asic = DMUB_ASIC_DCN36;
2666 		break;
2667 	case IP_VERSION(4, 0, 1):
2668 		dmub_asic = DMUB_ASIC_DCN401;
2669 		break;
2670 	case IP_VERSION(4, 2, 0):
2671 		dmub_asic = DMUB_ASIC_DCN42;
2672 		break;
2673 	case IP_VERSION(4, 2, 1):
2674 		dmub_asic = DMUB_ASIC_DCN42B;
2675 		break;
2676 	default:
2677 		/* ASIC doesn't support DMUB. */
2678 		return 0;
2679 	}
2680 
2681 	hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
2682 	adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
2683 
2684 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
2685 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
2686 			AMDGPU_UCODE_ID_DMCUB;
2687 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
2688 			adev->dm.dmub_fw;
2689 		adev->firmware.fw_size +=
2690 			ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
2691 
2692 		drm_info(adev_to_drm(adev), "Loading DMUB firmware via PSP: version=0x%08X\n",
2693 			 adev->dm.dmcub_fw_version);
2694 	}
2695 
2696 
2697 	adev->dm.dmub_srv = kzalloc_obj(*adev->dm.dmub_srv);
2698 	dmub_srv = adev->dm.dmub_srv;
2699 
2700 	if (!dmub_srv) {
2701 		drm_err(adev_to_drm(adev), "Failed to allocate DMUB service!\n");
2702 		return -ENOMEM;
2703 	}
2704 
2705 	memset(&create_params, 0, sizeof(create_params));
2706 	create_params.user_ctx = adev;
2707 	create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2708 	create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2709 	create_params.asic = dmub_asic;
2710 
2711 	/* Create the DMUB service. */
2712 	status = dmub_srv_create(dmub_srv, &create_params);
2713 	if (status != DMUB_STATUS_OK) {
2714 		drm_err(adev_to_drm(adev), "Error creating DMUB service: %d\n", status);
2715 		return -EINVAL;
2716 	}
2717 
2718 	/* Extract the FW meta info. */
2719 	memset(&fw_meta_info_params, 0, sizeof(fw_meta_info_params));
2720 
2721 	fw_meta_info_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2722 					      PSP_HEADER_BYTES_256;
2723 	fw_meta_info_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2724 	fw_meta_info_params.fw_inst_const = adev->dm.dmub_fw->data +
2725 					    le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2726 					    PSP_HEADER_BYTES_256;
2727 	fw_meta_info_params.fw_bss_data = fw_meta_info_params.bss_data_size ? adev->dm.dmub_fw->data +
2728 					  le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2729 					  le32_to_cpu(hdr->inst_const_bytes) : NULL;
2730 	fw_meta_info_params.custom_psp_footer_size = 0;
2731 
2732 	status = dmub_srv_get_fw_meta_info_from_raw_fw(&fw_meta_info_params, &fw_info);
2733 	if (status != DMUB_STATUS_OK) {
2734 		/* Skip returning early, just log the error. */
2735 		drm_err(adev_to_drm(adev), "Error getting DMUB FW meta info: %d\n", status);
2736 		// return -EINVAL;
2737 	}
2738 
2739 	/* Calculate the size of all the regions for the DMUB service. */
2740 	memset(&region_params, 0, sizeof(region_params));
2741 
2742 	region_params.inst_const_size = fw_meta_info_params.inst_const_size;
2743 	region_params.bss_data_size = fw_meta_info_params.bss_data_size;
2744 	region_params.vbios_size = adev->bios_size;
2745 	region_params.fw_bss_data = fw_meta_info_params.fw_bss_data;
2746 	region_params.fw_inst_const = fw_meta_info_params.fw_inst_const;
2747 	region_params.window_memory_type = window_memory_type;
2748 	region_params.fw_info = (status == DMUB_STATUS_OK) ? &fw_info : NULL;
2749 
2750 	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2751 					   &region_info);
2752 
2753 	if (status != DMUB_STATUS_OK) {
2754 		drm_err(adev_to_drm(adev), "Error calculating DMUB region info: %d\n", status);
2755 		return -EINVAL;
2756 	}
2757 
2758 	/*
2759 	 * Allocate a framebuffer based on the total size of all the regions.
2760 	 * TODO: Move this into GART.
2761 	 */
2762 	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2763 				    AMDGPU_GEM_DOMAIN_VRAM |
2764 				    AMDGPU_GEM_DOMAIN_GTT,
2765 				    &adev->dm.dmub_bo,
2766 				    &adev->dm.dmub_bo_gpu_addr,
2767 				    &adev->dm.dmub_bo_cpu_addr);
2768 	if (r)
2769 		return r;
2770 
2771 	/* Rebase the regions on the framebuffer address. */
2772 	memset(&memory_params, 0, sizeof(memory_params));
2773 	memory_params.cpu_fb_addr = adev->dm.dmub_bo_cpu_addr;
2774 	memory_params.gpu_fb_addr = adev->dm.dmub_bo_gpu_addr;
2775 	memory_params.region_info = &region_info;
2776 	memory_params.window_memory_type = window_memory_type;
2777 
2778 	adev->dm.dmub_fb_info = kzalloc_obj(*adev->dm.dmub_fb_info);
2779 	fb_info = adev->dm.dmub_fb_info;
2780 
2781 	if (!fb_info) {
2782 		drm_err(adev_to_drm(adev),
2783 			"Failed to allocate framebuffer info for DMUB service!\n");
2784 		return -ENOMEM;
2785 	}
2786 
2787 	status = dmub_srv_calc_mem_info(dmub_srv, &memory_params, fb_info);
2788 	if (status != DMUB_STATUS_OK) {
2789 		drm_err(adev_to_drm(adev), "Error calculating DMUB FB info: %d\n", status);
2790 		return -EINVAL;
2791 	}
2792 
2793 	adev->dm.bb_from_dmub = dm_dmub_get_vbios_bounding_box(adev);
2794 	adev->dm.fw_inst_size = fw_meta_info_params.inst_const_size;
2795 
2796 	return 0;
2797 }
2798 
2799 static int dm_sw_init(struct amdgpu_ip_block *ip_block)
2800 {
2801 	struct amdgpu_device *adev = ip_block->adev;
2802 	int r;
2803 
2804 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
2805 
2806 	if (!adev->dm.cgs_device) {
2807 		drm_err(adev_to_drm(adev), "failed to create cgs device.\n");
2808 		return -EINVAL;
2809 	}
2810 
2811 	/* Moved from dm init since we need to use allocations for storing bounding box data */
2812 	INIT_LIST_HEAD(&adev->dm.da_list);
2813 
2814 	r = dm_dmub_sw_init(adev);
2815 	if (r)
2816 		return r;
2817 
2818 	return load_dmcu_fw(adev);
2819 }
2820 
2821 static int dm_sw_fini(struct amdgpu_ip_block *ip_block)
2822 {
2823 	struct amdgpu_device *adev = ip_block->adev;
2824 	struct dal_allocation *da;
2825 
2826 	list_for_each_entry(da, &adev->dm.da_list, list) {
2827 		if (adev->dm.bb_from_dmub == (void *) da->cpu_ptr) {
2828 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
2829 			list_del(&da->list);
2830 			kfree(da);
2831 			adev->dm.bb_from_dmub = NULL;
2832 			break;
2833 		}
2834 	}
2835 
2836 
2837 	kfree(adev->dm.dmub_fb_info);
2838 	adev->dm.dmub_fb_info = NULL;
2839 
2840 	if (adev->dm.dmub_srv) {
2841 		dmub_srv_destroy(adev->dm.dmub_srv);
2842 		kfree(adev->dm.dmub_srv);
2843 		adev->dm.dmub_srv = NULL;
2844 	}
2845 
2846 	amdgpu_ucode_release(&adev->dm.dmub_fw);
2847 	amdgpu_ucode_release(&adev->dm.fw_dmcu);
2848 
2849 	return 0;
2850 }
2851 
2852 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2853 {
2854 	struct amdgpu_dm_connector *aconnector;
2855 	struct drm_connector *connector;
2856 	struct drm_connector_list_iter iter;
2857 	int ret = 0;
2858 
2859 	drm_connector_list_iter_begin(dev, &iter);
2860 	drm_for_each_connector_iter(connector, &iter) {
2861 
2862 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2863 			continue;
2864 
2865 		aconnector = to_amdgpu_dm_connector(connector);
2866 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
2867 		    aconnector->mst_mgr.aux) {
2868 			drm_dbg_kms(dev, "DM_MST: starting TM on aconnector: %p [id: %d]\n",
2869 					 aconnector,
2870 					 aconnector->base.base.id);
2871 
2872 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2873 			if (ret < 0) {
2874 				drm_err(dev, "DM_MST: Failed to start MST\n");
2875 				aconnector->dc_link->type =
2876 					dc_connection_single;
2877 				ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2878 								     aconnector->dc_link);
2879 				break;
2880 			}
2881 		}
2882 	}
2883 	drm_connector_list_iter_end(&iter);
2884 
2885 	return ret;
2886 }
2887 
2888 static void amdgpu_dm_boot_time_crc_init(struct amdgpu_device *adev)
2889 {
2890 	struct dm_boot_time_crc_info *bootcrc_info = NULL;
2891 	struct dmub_srv *dmub = NULL;
2892 	union dmub_fw_boot_options option = {0};
2893 	int ret = 0;
2894 	const uint32_t fb_size = 3 * 1024 * 1024;	/* 3MB for DCC pattern */
2895 
2896 	if (!adev || !adev->dm.dc || !adev->dm.dc->ctx ||
2897 		!adev->dm.dc->ctx->dmub_srv) {
2898 		return;
2899 	}
2900 
2901 	dmub = adev->dm.dc->ctx->dmub_srv->dmub;
2902 	bootcrc_info = &adev->dm.boot_time_crc_info;
2903 
2904 	if (!dmub || !dmub->hw_funcs.get_fw_boot_option) {
2905 		drm_dbg(adev_to_drm(adev), "failed to init boot time crc buffer\n");
2906 		return;
2907 	}
2908 
2909 	option = dmub->hw_funcs.get_fw_boot_option(dmub);
2910 
2911 	/* Return if boot time CRC is not enabled */
2912 	if (option.bits.bootcrc_en_at_S0i3 == 0)
2913 		return;
2914 
2915 	/* Create a buffer for boot time CRC */
2916 	ret = amdgpu_bo_create_kernel(adev, fb_size, PAGE_SIZE,
2917 		AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT,
2918 		&bootcrc_info->bo_ptr,
2919 		&bootcrc_info->gpu_addr,
2920 		&bootcrc_info->cpu_addr);
2921 
2922 	if (ret) {
2923 		drm_dbg(adev_to_drm(adev), "failed to create boot time crc buffer\n");
2924 	} else {
2925 		bootcrc_info->size = fb_size;
2926 
2927 		drm_dbg(adev_to_drm(adev), "boot time crc buffer created addr 0x%llx, size %u\n",
2928 			bootcrc_info->gpu_addr, bootcrc_info->size);
2929 
2930 		/* Send the buffer info to DMUB */
2931 		dc_dmub_srv_boot_time_crc_init(adev->dm.dc,
2932 			bootcrc_info->gpu_addr, bootcrc_info->size);
2933 	}
2934 }
2935 
2936 static int dm_late_init(struct amdgpu_ip_block *ip_block)
2937 {
2938 	struct amdgpu_device *adev = ip_block->adev;
2939 
2940 	struct dmcu_iram_parameters params;
2941 	unsigned int linear_lut[16];
2942 	int i;
2943 	struct dmcu *dmcu = NULL;
2944 
2945 	dmcu = adev->dm.dc->res_pool->dmcu;
2946 
2947 	/* Init the boot time CRC (skip in resume) */
2948 	if ((adev->in_suspend == 0) &&
2949 		(amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(3, 6, 0)))
2950 		amdgpu_dm_boot_time_crc_init(adev);
2951 
2952 	for (i = 0; i < 16; i++)
2953 		linear_lut[i] = 0xFFFF * i / 15;
2954 
2955 	params.set = 0;
2956 	params.backlight_ramping_override = false;
2957 	params.backlight_ramping_start = 0xCCCC;
2958 	params.backlight_ramping_reduction = 0xCCCCCCCC;
2959 	params.backlight_lut_array_size = 16;
2960 	params.backlight_lut_array = linear_lut;
2961 
2962 	/* Min backlight level after ABM reduction,  Don't allow below 1%
2963 	 * 0xFFFF x 0.01 = 0x28F
2964 	 */
2965 	params.min_abm_backlight = 0x28F;
2966 	/* In the case where abm is implemented on dmcub,
2967 	 * dmcu object will be null.
2968 	 * ABM 2.4 and up are implemented on dmcub.
2969 	 */
2970 	if (dmcu) {
2971 		if (!dmcu_load_iram(dmcu, params))
2972 			return -EINVAL;
2973 	} else if (adev->dm.dc->ctx->dmub_srv) {
2974 		struct dc_link *edp_links[MAX_NUM_EDP];
2975 		int edp_num;
2976 
2977 		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
2978 		for (i = 0; i < edp_num; i++) {
2979 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
2980 				return -EINVAL;
2981 		}
2982 	}
2983 
2984 	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
2985 }
2986 
2987 static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
2988 {
2989 	u8 buf[UUID_SIZE];
2990 	guid_t guid;
2991 	int ret;
2992 
2993 	mutex_lock(&mgr->lock);
2994 	if (!mgr->mst_primary)
2995 		goto out_fail;
2996 
2997 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
2998 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2999 		goto out_fail;
3000 	}
3001 
3002 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
3003 				 DP_MST_EN |
3004 				 DP_UP_REQ_EN |
3005 				 DP_UPSTREAM_IS_SRC);
3006 	if (ret < 0) {
3007 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
3008 		goto out_fail;
3009 	}
3010 
3011 	/* Some hubs forget their guids after they resume */
3012 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, buf, sizeof(buf));
3013 	if (ret != sizeof(buf)) {
3014 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
3015 		goto out_fail;
3016 	}
3017 
3018 	import_guid(&guid, buf);
3019 
3020 	if (guid_is_null(&guid)) {
3021 		guid_gen(&guid);
3022 		export_guid(buf, &guid);
3023 
3024 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, buf, sizeof(buf));
3025 
3026 		if (ret != sizeof(buf)) {
3027 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
3028 			goto out_fail;
3029 		}
3030 	}
3031 
3032 	guid_copy(&mgr->mst_primary->guid, &guid);
3033 
3034 out_fail:
3035 	mutex_unlock(&mgr->lock);
3036 }
3037 
3038 void hdmi_cec_unset_edid(struct amdgpu_dm_connector *aconnector)
3039 {
3040 	struct cec_notifier *n = aconnector->notifier;
3041 
3042 	if (!n)
3043 		return;
3044 
3045 	cec_notifier_phys_addr_invalidate(n);
3046 }
3047 
3048 void hdmi_cec_set_edid(struct amdgpu_dm_connector *aconnector)
3049 {
3050 	struct drm_connector *connector = &aconnector->base;
3051 	struct cec_notifier *n = aconnector->notifier;
3052 
3053 	if (!n)
3054 		return;
3055 
3056 	cec_notifier_set_phys_addr(n,
3057 				   connector->display_info.source_physical_address);
3058 }
3059 
3060 static void s3_handle_hdmi_cec(struct drm_device *ddev, bool suspend)
3061 {
3062 	struct amdgpu_dm_connector *aconnector;
3063 	struct drm_connector *connector;
3064 	struct drm_connector_list_iter conn_iter;
3065 
3066 	drm_connector_list_iter_begin(ddev, &conn_iter);
3067 	drm_for_each_connector_iter(connector, &conn_iter) {
3068 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3069 			continue;
3070 
3071 		aconnector = to_amdgpu_dm_connector(connector);
3072 		if (suspend)
3073 			hdmi_cec_unset_edid(aconnector);
3074 		else
3075 			hdmi_cec_set_edid(aconnector);
3076 	}
3077 	drm_connector_list_iter_end(&conn_iter);
3078 }
3079 
3080 static void s3_handle_mst(struct drm_device *dev, bool suspend)
3081 {
3082 	struct amdgpu_dm_connector *aconnector;
3083 	struct drm_connector *connector;
3084 	struct drm_connector_list_iter iter;
3085 	struct drm_dp_mst_topology_mgr *mgr;
3086 
3087 	drm_connector_list_iter_begin(dev, &iter);
3088 	drm_for_each_connector_iter(connector, &iter) {
3089 
3090 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3091 			continue;
3092 
3093 		aconnector = to_amdgpu_dm_connector(connector);
3094 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3095 		    aconnector->mst_root)
3096 			continue;
3097 
3098 		mgr = &aconnector->mst_mgr;
3099 
3100 		if (suspend) {
3101 			drm_dp_mst_topology_mgr_suspend(mgr);
3102 		} else {
3103 			/* if extended timeout is supported in hardware,
3104 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
3105 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
3106 			 */
3107 			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
3108 			if (!dp_is_lttpr_present(aconnector->dc_link))
3109 				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
3110 
3111 			/* TODO: move resume_mst_branch_status() into drm mst resume again
3112 			 * once topology probing work is pulled out from mst resume into mst
3113 			 * resume 2nd step. mst resume 2nd step should be called after old
3114 			 * state getting restored (i.e. drm_atomic_helper_resume()).
3115 			 */
3116 			resume_mst_branch_status(mgr);
3117 		}
3118 	}
3119 	drm_connector_list_iter_end(&iter);
3120 }
3121 
3122 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
3123 {
3124 	int ret = 0;
3125 
3126 	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
3127 	 * on window driver dc implementation.
3128 	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
3129 	 * should be passed to smu during boot up and resume from s3.
3130 	 * boot up: dc calculate dcn watermark clock settings within dc_create,
3131 	 * dcn20_resource_construct
3132 	 * then call pplib functions below to pass the settings to smu:
3133 	 * smu_set_watermarks_for_clock_ranges
3134 	 * smu_set_watermarks_table
3135 	 * navi10_set_watermarks_table
3136 	 * smu_write_watermarks_table
3137 	 *
3138 	 * For Renoir, clock settings of dcn watermark are also fixed values.
3139 	 * dc has implemented different flow for window driver:
3140 	 * dc_hardware_init / dc_set_power_state
3141 	 * dcn10_init_hw
3142 	 * notify_wm_ranges
3143 	 * set_wm_ranges
3144 	 * -- Linux
3145 	 * smu_set_watermarks_for_clock_ranges
3146 	 * renoir_set_watermarks_table
3147 	 * smu_write_watermarks_table
3148 	 *
3149 	 * For Linux,
3150 	 * dc_hardware_init -> amdgpu_dm_init
3151 	 * dc_set_power_state --> dm_resume
3152 	 *
3153 	 * therefore, this function apply to navi10/12/14 but not Renoir
3154 	 * *
3155 	 */
3156 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
3157 	case IP_VERSION(2, 0, 2):
3158 	case IP_VERSION(2, 0, 0):
3159 		break;
3160 	default:
3161 		return 0;
3162 	}
3163 
3164 	ret = amdgpu_dpm_write_watermarks_table(adev);
3165 	if (ret) {
3166 		drm_err(adev_to_drm(adev), "Failed to update WMTABLE!\n");
3167 		return ret;
3168 	}
3169 
3170 	return 0;
3171 }
3172 
3173 static int dm_oem_i2c_hw_init(struct amdgpu_device *adev)
3174 {
3175 	struct amdgpu_display_manager *dm = &adev->dm;
3176 	struct amdgpu_i2c_adapter *oem_i2c;
3177 	struct ddc_service *oem_ddc_service;
3178 	int r;
3179 
3180 	oem_ddc_service = dc_get_oem_i2c_device(adev->dm.dc);
3181 	if (oem_ddc_service) {
3182 		oem_i2c = create_i2c(oem_ddc_service, true);
3183 		if (!oem_i2c) {
3184 			drm_info(adev_to_drm(adev), "Failed to create oem i2c adapter data\n");
3185 			return -ENOMEM;
3186 		}
3187 
3188 		r = devm_i2c_add_adapter(adev->dev, &oem_i2c->base);
3189 		if (r) {
3190 			drm_info(adev_to_drm(adev), "Failed to register oem i2c\n");
3191 			kfree(oem_i2c);
3192 			return r;
3193 		}
3194 		dm->oem_i2c = oem_i2c;
3195 	}
3196 
3197 	return 0;
3198 }
3199 
3200 /**
3201  * dm_hw_init() - Initialize DC device
3202  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3203  *
3204  * Initialize the &struct amdgpu_display_manager device. This involves calling
3205  * the initializers of each DM component, then populating the struct with them.
3206  *
3207  * Although the function implies hardware initialization, both hardware and
3208  * software are initialized here. Splitting them out to their relevant init
3209  * hooks is a future TODO item.
3210  *
3211  * Some notable things that are initialized here:
3212  *
3213  * - Display Core, both software and hardware
3214  * - DC modules that we need (freesync and color management)
3215  * - DRM software states
3216  * - Interrupt sources and handlers
3217  * - Vblank support
3218  * - Debug FS entries, if enabled
3219  */
3220 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
3221 {
3222 	struct amdgpu_device *adev = ip_block->adev;
3223 	int r;
3224 
3225 	/* Create DAL display manager */
3226 	r = amdgpu_dm_init(adev);
3227 	if (r)
3228 		return r;
3229 	amdgpu_dm_hpd_init(adev);
3230 
3231 	r = dm_oem_i2c_hw_init(adev);
3232 	if (r)
3233 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
3234 
3235 	return 0;
3236 }
3237 
3238 /**
3239  * dm_hw_fini() - Teardown DC device
3240  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3241  *
3242  * Teardown components within &struct amdgpu_display_manager that require
3243  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
3244  * were loaded. Also flush IRQ workqueues and disable them.
3245  */
3246 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
3247 {
3248 	struct amdgpu_device *adev = ip_block->adev;
3249 
3250 	amdgpu_dm_hpd_fini(adev);
3251 
3252 	amdgpu_dm_irq_fini(adev);
3253 	amdgpu_dm_fini(adev);
3254 	return 0;
3255 }
3256 
3257 
3258 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
3259 				 struct dc_state *state, bool enable)
3260 {
3261 	enum dc_irq_source irq_source;
3262 	struct amdgpu_crtc *acrtc;
3263 	int rc = -EBUSY;
3264 	int i = 0;
3265 
3266 	for (i = 0; i < state->stream_count; i++) {
3267 		acrtc = get_crtc_by_otg_inst(
3268 				adev, state->stream_status[i].primary_otg_inst);
3269 
3270 		if (acrtc && state->stream_status[i].plane_count != 0) {
3271 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
3272 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3273 			if (rc)
3274 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
3275 					 enable ? "enable" : "disable");
3276 
3277 			if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
3278 				if (enable) {
3279 					if (amdgpu_dm_crtc_vrr_active(
3280 							to_dm_crtc_state(acrtc->base.state)))
3281 						rc = amdgpu_dm_crtc_set_vupdate_irq(
3282 							&acrtc->base, true);
3283 				} else
3284 					rc = amdgpu_dm_crtc_set_vupdate_irq(
3285 							&acrtc->base, false);
3286 
3287 				if (rc)
3288 					drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
3289 						enable ? "en" : "dis");
3290 			}
3291 
3292 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3293 			/* During gpu-reset we disable and then enable vblank irq, so
3294 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
3295 			 */
3296 			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
3297 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
3298 		}
3299 	}
3300 
3301 }
3302 
3303 DEFINE_FREE(state_release, struct dc_state *, if (_T) dc_state_release(_T))
3304 
3305 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
3306 {
3307 	struct dc_state *context __free(state_release) = NULL;
3308 	int i;
3309 	struct dc_stream_state *del_streams[MAX_PIPES];
3310 	int del_streams_count = 0;
3311 	struct dc_commit_streams_params params = {};
3312 
3313 	memset(del_streams, 0, sizeof(del_streams));
3314 
3315 	context = dc_state_create_current_copy(dc);
3316 	if (context == NULL)
3317 		return DC_ERROR_UNEXPECTED;
3318 
3319 	/* First remove from context all streams */
3320 	for (i = 0; i < context->stream_count; i++) {
3321 		struct dc_stream_state *stream = context->streams[i];
3322 
3323 		del_streams[del_streams_count++] = stream;
3324 	}
3325 
3326 	/* Remove all planes for removed streams and then remove the streams */
3327 	for (i = 0; i < del_streams_count; i++) {
3328 		enum dc_status res;
3329 
3330 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
3331 			return DC_FAIL_DETACH_SURFACES;
3332 
3333 		res = dc_state_remove_stream(dc, context, del_streams[i]);
3334 		if (res != DC_OK)
3335 			return res;
3336 	}
3337 
3338 	params.streams = context->streams;
3339 	params.stream_count = context->stream_count;
3340 
3341 	return dc_commit_streams(dc, &params);
3342 }
3343 
3344 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
3345 {
3346 	int i;
3347 
3348 	if (dm->hpd_rx_offload_wq) {
3349 		for (i = 0; i < dm->dc->caps.max_links; i++)
3350 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
3351 	}
3352 }
3353 
3354 static int dm_cache_state(struct amdgpu_device *adev)
3355 {
3356 	int r;
3357 
3358 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
3359 	if (IS_ERR(adev->dm.cached_state)) {
3360 		r = PTR_ERR(adev->dm.cached_state);
3361 		adev->dm.cached_state = NULL;
3362 	}
3363 
3364 	return adev->dm.cached_state ? 0 : r;
3365 }
3366 
3367 static void dm_destroy_cached_state(struct amdgpu_device *adev)
3368 {
3369 	struct amdgpu_display_manager *dm = &adev->dm;
3370 	struct drm_device *ddev = adev_to_drm(adev);
3371 	struct dm_plane_state *dm_new_plane_state;
3372 	struct drm_plane_state *new_plane_state;
3373 	struct dm_crtc_state *dm_new_crtc_state;
3374 	struct drm_crtc_state *new_crtc_state;
3375 	struct drm_plane *plane;
3376 	struct drm_crtc *crtc;
3377 	int i;
3378 
3379 	if (!dm->cached_state)
3380 		return;
3381 
3382 	/* Force mode set in atomic commit */
3383 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3384 		new_crtc_state->active_changed = true;
3385 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3386 		reset_freesync_config_for_crtc(dm_new_crtc_state);
3387 	}
3388 
3389 	/*
3390 	 * atomic_check is expected to create the dc states. We need to release
3391 	 * them here, since they were duplicated as part of the suspend
3392 	 * procedure.
3393 	 */
3394 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3395 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3396 		if (dm_new_crtc_state->stream) {
3397 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
3398 			dc_stream_release(dm_new_crtc_state->stream);
3399 			dm_new_crtc_state->stream = NULL;
3400 		}
3401 		dm_new_crtc_state->base.color_mgmt_changed = true;
3402 	}
3403 
3404 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
3405 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
3406 		if (dm_new_plane_state->dc_state) {
3407 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
3408 			dc_plane_state_release(dm_new_plane_state->dc_state);
3409 			dm_new_plane_state->dc_state = NULL;
3410 		}
3411 	}
3412 
3413 	drm_atomic_helper_resume(ddev, dm->cached_state);
3414 
3415 	dm->cached_state = NULL;
3416 }
3417 
3418 static int dm_suspend(struct amdgpu_ip_block *ip_block)
3419 {
3420 	struct amdgpu_device *adev = ip_block->adev;
3421 	struct amdgpu_display_manager *dm = &adev->dm;
3422 
3423 	if (amdgpu_in_reset(adev)) {
3424 		enum dc_status res;
3425 
3426 		/* Quiesce ISM workers before taking dc_lock (workers take
3427 		 * dc_lock themselves; syncing under it would deadlock).
3428 		 */
3429 		amdgpu_dm_ism_disable(dm);
3430 
3431 		mutex_lock(&dm->dc_lock);
3432 
3433 		amdgpu_dm_ism_force_full_power(dm);
3434 		dc_allow_idle_optimizations(adev->dm.dc, false);
3435 
3436 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
3437 
3438 		if (dm->cached_dc_state)
3439 			dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
3440 
3441 		res = amdgpu_dm_commit_zero_streams(dm->dc);
3442 		if (res != DC_OK) {
3443 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
3444 			return -EINVAL;
3445 		}
3446 
3447 		amdgpu_dm_irq_suspend(adev);
3448 
3449 		hpd_rx_irq_work_suspend(dm);
3450 
3451 		return 0;
3452 	}
3453 
3454 	if (!adev->dm.cached_state) {
3455 		int r = dm_cache_state(adev);
3456 
3457 		if (r)
3458 			return r;
3459 	}
3460 
3461 	s3_handle_hdmi_cec(adev_to_drm(adev), true);
3462 
3463 	s3_handle_mst(adev_to_drm(adev), true);
3464 
3465 	amdgpu_dm_irq_suspend(adev);
3466 
3467 	/*
3468 	 * Quiesce ISM workers before taking dc_lock (workers take dc_lock
3469 	 * themselves; syncing under it would deadlock).
3470 	 */
3471 	amdgpu_dm_ism_disable(dm);
3472 	scoped_guard(mutex, &dm->dc_lock)
3473 		amdgpu_dm_ism_force_full_power(dm);
3474 
3475 	hpd_rx_irq_work_suspend(dm);
3476 
3477 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
3478 
3479 	if (dm->dc->caps.ips_support && adev->in_s0ix)
3480 		dc_allow_idle_optimizations(dm->dc, true);
3481 
3482 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
3483 
3484 	return 0;
3485 }
3486 
3487 struct drm_connector *
3488 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_commit *state,
3489 					     struct drm_crtc *crtc)
3490 {
3491 	u32 i;
3492 	struct drm_connector_state *new_con_state;
3493 	struct drm_connector *connector;
3494 	struct drm_crtc *crtc_from_state;
3495 
3496 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3497 		crtc_from_state = new_con_state->crtc;
3498 
3499 		if (crtc_from_state == crtc)
3500 			return connector;
3501 	}
3502 
3503 	return NULL;
3504 }
3505 
3506 static void emulated_link_detect(struct dc_link *link)
3507 {
3508 	struct dc_sink_init_data sink_init_data = { 0 };
3509 	struct display_sink_capability sink_caps = { 0 };
3510 	enum dc_edid_status edid_status;
3511 	struct dc_context *dc_ctx = link->ctx;
3512 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
3513 	struct dc_sink *sink = NULL;
3514 	struct dc_sink *prev_sink = NULL;
3515 
3516 	link->type = dc_connection_none;
3517 	prev_sink = link->local_sink;
3518 
3519 	if (prev_sink)
3520 		dc_sink_release(prev_sink);
3521 
3522 	switch (link->connector_signal) {
3523 	case SIGNAL_TYPE_HDMI_TYPE_A: {
3524 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3525 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
3526 		break;
3527 	}
3528 
3529 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
3530 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3531 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
3532 		break;
3533 	}
3534 
3535 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
3536 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3537 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
3538 		break;
3539 	}
3540 
3541 	case SIGNAL_TYPE_LVDS: {
3542 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3543 		sink_caps.signal = SIGNAL_TYPE_LVDS;
3544 		break;
3545 	}
3546 
3547 	case SIGNAL_TYPE_EDP: {
3548 		sink_caps.transaction_type =
3549 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3550 		sink_caps.signal = SIGNAL_TYPE_EDP;
3551 		break;
3552 	}
3553 
3554 	case SIGNAL_TYPE_DISPLAY_PORT: {
3555 		sink_caps.transaction_type =
3556 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3557 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
3558 		break;
3559 	}
3560 
3561 	default:
3562 		drm_err(dev, "Invalid connector type! signal:%d\n",
3563 			link->connector_signal);
3564 		return;
3565 	}
3566 
3567 	sink_init_data.link = link;
3568 	sink_init_data.sink_signal = sink_caps.signal;
3569 
3570 	sink = dc_sink_create(&sink_init_data);
3571 	if (!sink) {
3572 		drm_err(dev, "Failed to create sink!\n");
3573 		return;
3574 	}
3575 
3576 	/* dc_sink_create returns a new reference */
3577 	link->local_sink = sink;
3578 
3579 	edid_status = dm_helpers_read_local_edid(
3580 			link->ctx,
3581 			link,
3582 			sink);
3583 
3584 	if (edid_status != EDID_OK)
3585 		drm_err(dev, "Failed to read EDID\n");
3586 
3587 }
3588 
3589 static void dm_gpureset_commit_state(struct dc_state *dc_state,
3590 				     struct amdgpu_display_manager *dm)
3591 {
3592 	struct {
3593 		struct dc_surface_update surface_updates[MAX_SURFACES];
3594 		struct dc_plane_info plane_infos[MAX_SURFACES];
3595 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3596 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3597 		struct dc_stream_update stream_update;
3598 	} *bundle __free(kfree);
3599 	int k, m;
3600 
3601 	bundle = kzalloc_obj(*bundle);
3602 
3603 	if (!bundle) {
3604 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
3605 		return;
3606 	}
3607 
3608 	for (k = 0; k < dc_state->stream_count; k++) {
3609 		bundle->stream_update.stream = dc_state->streams[k];
3610 
3611 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
3612 			bundle->surface_updates[m].surface =
3613 				dc_state->stream_status[k].plane_states[m];
3614 			bundle->surface_updates[m].surface->force_full_update =
3615 				true;
3616 		}
3617 
3618 		update_planes_and_stream_adapter(dm->dc,
3619 					 UPDATE_TYPE_FULL,
3620 					 dc_state->stream_status[k].plane_count,
3621 					 dc_state->streams[k],
3622 					 &bundle->stream_update,
3623 					 bundle->surface_updates);
3624 	}
3625 }
3626 
3627 static void apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
3628 					    struct dc_sink *sink)
3629 {
3630 	struct dc_panel_patch *ppatch = NULL;
3631 
3632 	if (!sink)
3633 		return;
3634 
3635 	ppatch = &sink->edid_caps.panel_patch;
3636 	if (ppatch->wait_after_dpcd_poweroff_ms) {
3637 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
3638 		drm_dbg_driver(adev_to_drm(adev),
3639 			       "%s: adding a %ds delay as w/a for panel\n",
3640 			       __func__,
3641 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
3642 	}
3643 }
3644 
3645 /**
3646  * amdgpu_dm_dump_links_and_sinks - Debug dump of all DC links and their sinks
3647  * @adev: amdgpu device pointer
3648  *
3649  * Iterates through all DC links and dumps information about local and remote
3650  * (MST) sinks. Should be called after connector detection is complete to see
3651  * the final state of all links.
3652  */
3653 static void amdgpu_dm_dump_links_and_sinks(struct amdgpu_device *adev)
3654 {
3655 	struct dc *dc = adev->dm.dc;
3656 	struct drm_device *dev = adev_to_drm(adev);
3657 	int li;
3658 
3659 	if (!dc)
3660 		return;
3661 
3662 	for (li = 0; li < dc->link_count; li++) {
3663 		struct dc_link *l = dc->links[li];
3664 		const char *name = NULL;
3665 		int rs;
3666 
3667 		if (!l)
3668 			continue;
3669 		if (l->local_sink && l->local_sink->edid_caps.display_name[0])
3670 			name = l->local_sink->edid_caps.display_name;
3671 		else
3672 			name = "n/a";
3673 
3674 		drm_dbg_kms(dev,
3675 			"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",
3676 			li,
3677 			l->local_sink,
3678 			l->type,
3679 			l->local_sink ? l->local_sink->sink_signal : SIGNAL_TYPE_NONE,
3680 			l->sink_count,
3681 			name,
3682 			l->dpcd_caps.is_mst_capable,
3683 			l->mst_stream_alloc_table.stream_count);
3684 
3685 		/* Dump remote (MST) sinks if any */
3686 		for (rs = 0; rs < l->sink_count; rs++) {
3687 			struct dc_sink *rsink = l->remote_sinks[rs];
3688 			const char *rname = NULL;
3689 
3690 			if (!rsink)
3691 				continue;
3692 			if (rsink->edid_caps.display_name[0])
3693 				rname = rsink->edid_caps.display_name;
3694 			else
3695 				rname = "n/a";
3696 			drm_dbg_kms(dev,
3697 				"  REMOTE_SINK[%d:%d]: sink=%p signal=%d edid_name=%s\n",
3698 				li, rs,
3699 				rsink,
3700 				rsink->sink_signal,
3701 				rname);
3702 		}
3703 	}
3704 }
3705 
3706 static int dm_resume(struct amdgpu_ip_block *ip_block)
3707 {
3708 	struct amdgpu_device *adev = ip_block->adev;
3709 	struct drm_device *ddev = adev_to_drm(adev);
3710 	struct amdgpu_display_manager *dm = &adev->dm;
3711 	struct amdgpu_dm_connector *aconnector;
3712 	struct drm_connector *connector;
3713 	struct drm_connector_list_iter iter;
3714 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
3715 	enum dc_connection_type new_connection_type = dc_connection_none;
3716 	struct dc_state *dc_state;
3717 	int i, r, j;
3718 	struct dc_commit_streams_params commit_params = {};
3719 
3720 	if (dm->dc->caps.ips_support) {
3721 		if (!amdgpu_in_reset(adev))
3722 			mutex_lock(&dm->dc_lock);
3723 
3724 		/* Need to set POWER_STATE_D0 first or it will not execute
3725 		 * idle_power_optimizations command to DMUB.
3726 		 */
3727 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3728 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
3729 
3730 		if (!amdgpu_in_reset(adev))
3731 			mutex_unlock(&dm->dc_lock);
3732 	}
3733 
3734 	if (amdgpu_in_reset(adev)) {
3735 		dc_state = dm->cached_dc_state;
3736 
3737 		/*
3738 		 * The dc->current_state is backed up into dm->cached_dc_state
3739 		 * before we commit 0 streams.
3740 		 *
3741 		 * DC will clear link encoder assignments on the real state
3742 		 * but the changes won't propagate over to the copy we made
3743 		 * before the 0 streams commit.
3744 		 *
3745 		 * DC expects that link encoder assignments are *not* valid
3746 		 * when committing a state, so as a workaround we can copy
3747 		 * off of the current state.
3748 		 *
3749 		 * We lose the previous assignments, but we had already
3750 		 * commit 0 streams anyway.
3751 		 */
3752 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
3753 
3754 		r = dm_dmub_hw_init(adev);
3755 		if (r) {
3756 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
3757 			return r;
3758 		}
3759 
3760 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3761 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3762 
3763 		dc_resume(dm->dc);
3764 
3765 		amdgpu_dm_ism_enable(dm);
3766 		amdgpu_dm_irq_resume_early(adev);
3767 
3768 		for (i = 0; i < dc_state->stream_count; i++) {
3769 			dc_state->streams[i]->mode_changed = true;
3770 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
3771 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
3772 					= 0xffffffff;
3773 			}
3774 		}
3775 
3776 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3777 			amdgpu_dm_outbox_init(adev);
3778 			dc_enable_dmub_outbox(adev->dm.dc);
3779 		}
3780 
3781 		commit_params.streams = dc_state->streams;
3782 		commit_params.stream_count = dc_state->stream_count;
3783 		dc_exit_ips_for_hw_access(dm->dc);
3784 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
3785 
3786 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
3787 
3788 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
3789 
3790 		dc_state_release(dm->cached_dc_state);
3791 		dm->cached_dc_state = NULL;
3792 
3793 		amdgpu_dm_irq_resume_late(adev);
3794 
3795 		mutex_unlock(&dm->dc_lock);
3796 
3797 		/* set the backlight after a reset */
3798 		for (i = 0; i < dm->num_of_edps; i++) {
3799 			if (dm->backlight_dev[i])
3800 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
3801 		}
3802 
3803 		return 0;
3804 	}
3805 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
3806 	dc_state_release(dm_state->context);
3807 	dm_state->context = dc_state_create(dm->dc, NULL);
3808 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
3809 
3810 	/* Before powering on DC we need to re-initialize DMUB. */
3811 	dm_dmub_hw_resume(adev);
3812 
3813 	/* Re-enable outbox interrupts for DPIA. */
3814 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3815 		amdgpu_dm_outbox_init(adev);
3816 		dc_enable_dmub_outbox(adev->dm.dc);
3817 	}
3818 
3819 	/* power on hardware */
3820 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3821 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3822 
3823 	/* program HPD filter */
3824 	dc_resume(dm->dc);
3825 
3826 	scoped_guard(mutex, &dm->dc_lock)
3827 		amdgpu_dm_ism_enable(dm);
3828 
3829 	/*
3830 	 * early enable HPD Rx IRQ, should be done before set mode as short
3831 	 * pulse interrupts are used for MST
3832 	 */
3833 	amdgpu_dm_irq_resume_early(adev);
3834 
3835 	s3_handle_hdmi_cec(ddev, false);
3836 
3837 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
3838 	s3_handle_mst(ddev, false);
3839 
3840 	/* Do detection*/
3841 	drm_connector_list_iter_begin(ddev, &iter);
3842 	drm_for_each_connector_iter(connector, &iter) {
3843 		bool ret;
3844 
3845 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3846 			continue;
3847 
3848 		aconnector = to_amdgpu_dm_connector(connector);
3849 
3850 		if (!aconnector->dc_link)
3851 			continue;
3852 
3853 		/*
3854 		 * this is the case when traversing through already created end sink
3855 		 * MST connectors, should be skipped
3856 		 */
3857 		if (aconnector->mst_root)
3858 			continue;
3859 
3860 		/* Skip eDP detection, when there is no sink present */
3861 		if (aconnector->dc_link->connector_signal == SIGNAL_TYPE_EDP &&
3862 		    !aconnector->dc_link->edp_sink_present)
3863 			continue;
3864 
3865 		guard(mutex)(&aconnector->hpd_lock);
3866 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3867 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3868 
3869 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3870 			emulated_link_detect(aconnector->dc_link);
3871 		} else {
3872 			guard(mutex)(&dm->dc_lock);
3873 			dc_exit_ips_for_hw_access(dm->dc);
3874 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
3875 			if (ret) {
3876 				/* w/a delay for certain panels */
3877 				apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3878 			}
3879 		}
3880 
3881 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
3882 			aconnector->fake_enable = false;
3883 
3884 		if (aconnector->dc_sink)
3885 			dc_sink_release(aconnector->dc_sink);
3886 		aconnector->dc_sink = NULL;
3887 		amdgpu_dm_update_connector_after_detect(aconnector);
3888 	}
3889 	drm_connector_list_iter_end(&iter);
3890 
3891 	dm_destroy_cached_state(adev);
3892 
3893 	/* Do mst topology probing after resuming cached state*/
3894 	drm_connector_list_iter_begin(ddev, &iter);
3895 	drm_for_each_connector_iter(connector, &iter) {
3896 		bool init = false;
3897 
3898 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3899 			continue;
3900 
3901 		aconnector = to_amdgpu_dm_connector(connector);
3902 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3903 		    aconnector->mst_root)
3904 			continue;
3905 
3906 		scoped_guard(mutex, &aconnector->mst_mgr.lock) {
3907 			init = !aconnector->mst_mgr.mst_primary;
3908 		}
3909 		if (init)
3910 			dm_helpers_dp_mst_start_top_mgr(aconnector->dc_link->ctx,
3911 				aconnector->dc_link, false);
3912 		else
3913 			drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
3914 	}
3915 	drm_connector_list_iter_end(&iter);
3916 
3917 	/* Debug dump: list all DC links and their associated sinks after detection
3918 	 * is complete for all connectors. This provides a comprehensive view of the
3919 	 * final state without repeating the dump for each connector.
3920 	 */
3921 	amdgpu_dm_dump_links_and_sinks(adev);
3922 
3923 	amdgpu_dm_irq_resume_late(adev);
3924 
3925 	amdgpu_dm_smu_write_watermarks_table(adev);
3926 
3927 	drm_kms_helper_hotplug_event(ddev);
3928 
3929 	return 0;
3930 }
3931 
3932 /**
3933  * DOC: DM Lifecycle
3934  *
3935  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
3936  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
3937  * the base driver's device list to be initialized and torn down accordingly.
3938  *
3939  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
3940  */
3941 
3942 static const struct amd_ip_funcs amdgpu_dm_funcs = {
3943 	.name = "dm",
3944 	.early_init = dm_early_init,
3945 	.late_init = dm_late_init,
3946 	.sw_init = dm_sw_init,
3947 	.sw_fini = dm_sw_fini,
3948 	.early_fini = amdgpu_dm_early_fini,
3949 	.hw_init = dm_hw_init,
3950 	.hw_fini = dm_hw_fini,
3951 	.suspend = dm_suspend,
3952 	.resume = dm_resume,
3953 	.is_idle = dm_is_idle,
3954 	.wait_for_idle = dm_wait_for_idle,
3955 	.check_soft_reset = dm_check_soft_reset,
3956 	.soft_reset = dm_soft_reset,
3957 	.set_clockgating_state = dm_set_clockgating_state,
3958 	.set_powergating_state = dm_set_powergating_state,
3959 };
3960 
3961 const struct amdgpu_ip_block_version dm_ip_block = {
3962 	.type = AMD_IP_BLOCK_TYPE_DCE,
3963 	.major = 1,
3964 	.minor = 0,
3965 	.rev = 0,
3966 	.funcs = &amdgpu_dm_funcs,
3967 };
3968 
3969 
3970 /**
3971  * DOC: atomic
3972  *
3973  * *WIP*
3974  */
3975 
3976 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
3977 	.fb_create = amdgpu_display_user_framebuffer_create,
3978 	.get_format_info = amdgpu_dm_plane_get_format_info,
3979 	.atomic_check = amdgpu_dm_atomic_check,
3980 	.atomic_commit = drm_atomic_helper_commit,
3981 };
3982 
3983 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
3984 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
3985 	.atomic_commit_setup = amdgpu_dm_atomic_setup_commit,
3986 };
3987 
3988 #define DDC_MANUFACTURERNAME_SAMSUNG 0x2D4C
3989 
3990 static void dm_set_panel_type(struct amdgpu_dm_connector *aconnector)
3991 {
3992 	struct drm_connector *connector = &aconnector->base;
3993 	struct drm_display_info *display_info = &connector->display_info;
3994 	struct dc_link *link = aconnector->dc_link;
3995 	struct amdgpu_device *adev;
3996 
3997 	adev = drm_to_adev(connector->dev);
3998 
3999 	link->panel_type = PANEL_TYPE_NONE;
4000 
4001 	switch (display_info->amd_vsdb.panel_type) {
4002 	case AMD_VSDB_PANEL_TYPE_OLED:
4003 		link->panel_type = PANEL_TYPE_OLED;
4004 		break;
4005 	case AMD_VSDB_PANEL_TYPE_MINILED:
4006 		link->panel_type = PANEL_TYPE_MINILED;
4007 		break;
4008 	}
4009 
4010 	/* If VSDB didn't determine panel type, check DPCD ext caps */
4011 	if (link->panel_type == PANEL_TYPE_NONE) {
4012 		if (link->dpcd_sink_ext_caps.bits.miniled == 1)
4013 			link->panel_type = PANEL_TYPE_MINILED;
4014 		if (link->dpcd_sink_ext_caps.bits.oled == 1)
4015 			link->panel_type = PANEL_TYPE_OLED;
4016 	}
4017 
4018 	/*
4019 	 * TODO: get panel type from DID2 that has device technology field
4020 	 * to specify if it's OLED or not. But we need to wait for DID2
4021 	 * support in DC and EDID parser to be able to use it here.
4022 	 */
4023 
4024 	if (link->panel_type == PANEL_TYPE_NONE) {
4025 		struct drm_amd_vsdb_info *vsdb = &display_info->amd_vsdb;
4026 		u32 lum1_max = vsdb->luminance_range1.max_luminance;
4027 		u32 lum2_max = vsdb->luminance_range2.max_luminance;
4028 
4029 		if (vsdb->version && link->local_sink &&
4030 		    link->local_sink->edid_caps.manufacturer_id ==
4031 		    DDC_MANUFACTURERNAME_SAMSUNG &&
4032 		    lum1_max >= ((lum2_max * 3) / 2))
4033 			link->panel_type = PANEL_TYPE_MINILED;
4034 	}
4035 
4036 	if (link->panel_type == PANEL_TYPE_OLED)
4037 		drm_object_property_set_value(&connector->base,
4038 		    adev_to_drm(adev)->mode_config.panel_type_property,
4039 		    DRM_MODE_PANEL_TYPE_OLED);
4040 	else
4041 		drm_object_property_set_value(&connector->base,
4042 		    adev_to_drm(adev)->mode_config.panel_type_property,
4043 		    DRM_MODE_PANEL_TYPE_UNKNOWN);
4044 
4045 	drm_dbg_kms(aconnector->base.dev, "Panel type: %d\n", link->panel_type);
4046 }
4047 
4048 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
4049 {
4050 	const struct drm_panel_backlight_quirk *panel_backlight_quirk;
4051 	struct amdgpu_dm_backlight_caps *caps;
4052 	struct drm_connector *conn_base;
4053 	struct amdgpu_device *adev;
4054 	struct drm_luminance_range_info *luminance_range;
4055 	struct drm_device *drm;
4056 
4057 	if (aconnector->bl_idx == -1 ||
4058 	    aconnector->dc_link->connector_signal != SIGNAL_TYPE_EDP)
4059 		return;
4060 
4061 	conn_base = &aconnector->base;
4062 	drm = conn_base->dev;
4063 	adev = drm_to_adev(drm);
4064 
4065 	caps = &adev->dm.backlight_caps[aconnector->bl_idx];
4066 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
4067 	caps->aux_support = false;
4068 
4069 	if (caps->ext_caps->bits.oled == 1
4070 	    /*
4071 	     * ||
4072 	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
4073 	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
4074 	     */)
4075 		caps->aux_support = true;
4076 
4077 	if (amdgpu_backlight == 0)
4078 		caps->aux_support = false;
4079 	else if (amdgpu_backlight == 1)
4080 		caps->aux_support = true;
4081 	if (caps->aux_support)
4082 		aconnector->dc_link->backlight_control_type = BACKLIGHT_CONTROL_AMD_AUX;
4083 
4084 	luminance_range = &conn_base->display_info.luminance_range;
4085 
4086 	if (luminance_range->max_luminance)
4087 		caps->aux_max_input_signal = luminance_range->max_luminance;
4088 	else
4089 		caps->aux_max_input_signal = 512;
4090 
4091 	if (luminance_range->min_luminance)
4092 		caps->aux_min_input_signal = luminance_range->min_luminance;
4093 	else
4094 		caps->aux_min_input_signal = 1;
4095 
4096 	panel_backlight_quirk =
4097 		drm_get_panel_backlight_quirk(aconnector->drm_edid);
4098 	if (!IS_ERR_OR_NULL(panel_backlight_quirk)) {
4099 		if (panel_backlight_quirk->min_brightness) {
4100 			caps->min_input_signal =
4101 				panel_backlight_quirk->min_brightness - 1;
4102 			drm_info(drm,
4103 				 "Applying panel backlight quirk, min_brightness: %d\n",
4104 				 caps->min_input_signal);
4105 		}
4106 		if (panel_backlight_quirk->brightness_mask) {
4107 			drm_info(drm,
4108 				 "Applying panel backlight quirk, brightness_mask: 0x%X\n",
4109 				 panel_backlight_quirk->brightness_mask);
4110 			caps->brightness_mask =
4111 				panel_backlight_quirk->brightness_mask;
4112 		}
4113 	}
4114 }
4115 
4116 DEFINE_FREE(sink_release, struct dc_sink *, if (_T) dc_sink_release(_T))
4117 
4118 void amdgpu_dm_update_connector_after_detect(
4119 		struct amdgpu_dm_connector *aconnector)
4120 {
4121 	struct drm_connector *connector = &aconnector->base;
4122 	struct dc_sink *sink __free(sink_release) = NULL;
4123 	struct drm_device *dev = connector->dev;
4124 
4125 	/* MST handled by drm_mst framework */
4126 	if (aconnector->mst_mgr.mst_state == true)
4127 		return;
4128 
4129 	sink = aconnector->dc_link->local_sink;
4130 	if (sink)
4131 		dc_sink_retain(sink);
4132 
4133 	/*
4134 	 * Edid mgmt connector gets first update only in mode_valid hook and then
4135 	 * the connector sink is set to either fake or physical sink depends on link status.
4136 	 * Skip if already done during boot.
4137 	 */
4138 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
4139 			&& aconnector->dc_em_sink) {
4140 
4141 		/*
4142 		 * For S3 resume with headless use eml_sink to fake stream
4143 		 * because on resume connector->sink is set to NULL
4144 		 */
4145 		guard(mutex)(&dev->mode_config.mutex);
4146 
4147 		if (sink) {
4148 			if (aconnector->dc_sink) {
4149 				amdgpu_dm_update_freesync_caps(connector, NULL, true);
4150 				/*
4151 				 * retain and release below are used to
4152 				 * bump up refcount for sink because the link doesn't point
4153 				 * to it anymore after disconnect, so on next crtc to connector
4154 				 * reshuffle by UMD we will get into unwanted dc_sink release
4155 				 */
4156 				dc_sink_release(aconnector->dc_sink);
4157 			}
4158 			aconnector->dc_sink = sink;
4159 			dc_sink_retain(aconnector->dc_sink);
4160 			amdgpu_dm_update_freesync_caps(connector,
4161 					aconnector->drm_edid, true);
4162 		} else {
4163 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4164 			if (!aconnector->dc_sink) {
4165 				aconnector->dc_sink = aconnector->dc_em_sink;
4166 				dc_sink_retain(aconnector->dc_sink);
4167 			}
4168 		}
4169 
4170 		return;
4171 	}
4172 
4173 	/*
4174 	 * TODO: temporary guard to look for proper fix
4175 	 * if this sink is MST sink, we should not do anything
4176 	 */
4177 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
4178 		return;
4179 
4180 	if (aconnector->dc_sink == sink) {
4181 		/*
4182 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
4183 		 * Do nothing!!
4184 		 */
4185 		drm_dbg_kms(dev, "DCHPD: connector_id=%d: dc_sink didn't change.\n",
4186 				 aconnector->connector_id);
4187 		return;
4188 	}
4189 
4190 	drm_dbg_kms(dev, "DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
4191 		    aconnector->connector_id, aconnector->dc_sink, sink);
4192 
4193 	/* When polling, DRM has already locked the mutex for us. */
4194 	if (!drm_kms_helper_is_poll_worker())
4195 		mutex_lock(&dev->mode_config.mutex);
4196 
4197 	/*
4198 	 * 1. Update status of the drm connector
4199 	 * 2. Send an event and let userspace tell us what to do
4200 	 */
4201 	if (sink) {
4202 		/*
4203 		 * TODO: check if we still need the S3 mode update workaround.
4204 		 * If yes, put it here.
4205 		 */
4206 		if (aconnector->dc_sink) {
4207 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4208 			dc_sink_release(aconnector->dc_sink);
4209 		}
4210 
4211 		aconnector->dc_sink = sink;
4212 		dc_sink_retain(aconnector->dc_sink);
4213 		drm_edid_free(aconnector->drm_edid);
4214 		aconnector->drm_edid = NULL;
4215 		if (sink->dc_edid.length == 0) {
4216 			hdmi_cec_unset_edid(aconnector);
4217 			if (aconnector->dc_link->aux_mode) {
4218 				drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4219 			}
4220 		} else {
4221 			const struct edid *edid = (const struct edid *)sink->dc_edid.raw_edid;
4222 
4223 			aconnector->drm_edid = drm_edid_alloc(edid, sink->dc_edid.length);
4224 			drm_edid_connector_update(connector, aconnector->drm_edid);
4225 
4226 			hdmi_cec_set_edid(aconnector);
4227 			if (aconnector->dc_link->aux_mode)
4228 				drm_dp_cec_attach(&aconnector->dm_dp_aux.aux,
4229 						  connector->display_info.source_physical_address);
4230 		}
4231 
4232 		if (!aconnector->timing_requested) {
4233 			aconnector->timing_requested =
4234 				kzalloc_obj(struct dc_crtc_timing);
4235 			if (!aconnector->timing_requested)
4236 				drm_err(dev,
4237 					"failed to create aconnector->requested_timing\n");
4238 		}
4239 
4240 		amdgpu_dm_update_freesync_caps(connector, aconnector->drm_edid, true);
4241 		update_connector_ext_caps(aconnector);
4242 		dm_set_panel_type(aconnector);
4243 	} else {
4244 		hdmi_cec_unset_edid(aconnector);
4245 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4246 		amdgpu_dm_update_freesync_caps(connector, NULL, true);
4247 		aconnector->num_modes = 0;
4248 		dc_sink_release(aconnector->dc_sink);
4249 		aconnector->dc_sink = NULL;
4250 		drm_edid_free(aconnector->drm_edid);
4251 		aconnector->drm_edid = NULL;
4252 		kfree(aconnector->timing_requested);
4253 		aconnector->timing_requested = NULL;
4254 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
4255 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
4256 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
4257 	}
4258 
4259 	update_subconnector_property(aconnector);
4260 
4261 	/* When polling, the mutex will be unlocked for us by DRM. */
4262 	if (!drm_kms_helper_is_poll_worker())
4263 		mutex_unlock(&dev->mode_config.mutex);
4264 }
4265 
4266 static bool are_sinks_equal(const struct dc_sink *sink1, const struct dc_sink *sink2)
4267 {
4268 	if (!sink1 || !sink2)
4269 		return false;
4270 	if (sink1->sink_signal != sink2->sink_signal)
4271 		return false;
4272 
4273 	if (sink1->dc_edid.length != sink2->dc_edid.length)
4274 		return false;
4275 
4276 	if (memcmp(sink1->dc_edid.raw_edid, sink2->dc_edid.raw_edid,
4277 		   sink1->dc_edid.length) != 0)
4278 		return false;
4279 	return true;
4280 }
4281 
4282 
4283 /**
4284  * DOC: hdmi_hpd_debounce_work
4285  *
4286  * HDMI HPD debounce delay in milliseconds. When an HDMI display toggles HPD
4287  * (such as during power save transitions), this delay determines how long to
4288  * wait before processing the HPD event. This allows distinguishing between a
4289  * physical unplug (>hdmi_hpd_debounce_delay)
4290  * and a spontaneous RX HPD toggle (<hdmi_hpd_debounce_delay).
4291  *
4292  * If the toggle is less than this delay, the driver compares sink capabilities
4293  * and permits a hotplug event if they changed.
4294  *
4295  * The default value of 1500ms was chosen based on experimental testing with
4296  * various monitors that exhibit spontaneous HPD toggling behavior.
4297  */
4298 static void hdmi_hpd_debounce_work(struct work_struct *work)
4299 {
4300 	struct amdgpu_dm_connector *aconnector =
4301 		container_of(to_delayed_work(work), struct amdgpu_dm_connector,
4302 			     hdmi_hpd_debounce_work);
4303 	struct drm_connector *connector = &aconnector->base;
4304 	struct drm_device *dev = connector->dev;
4305 	struct amdgpu_device *adev = drm_to_adev(dev);
4306 	struct dc *dc = aconnector->dc_link->ctx->dc;
4307 	bool fake_reconnect = false;
4308 	bool reallow_idle = false;
4309 	bool ret = false;
4310 	guard(mutex)(&aconnector->hpd_lock);
4311 
4312 	/* Re-detect the display */
4313 	scoped_guard(mutex, &adev->dm.dc_lock) {
4314 		if (dc->caps.ips_support && dc->ctx->dmub_srv->idle_allowed) {
4315 			dc_allow_idle_optimizations(dc, false);
4316 			reallow_idle = true;
4317 		}
4318 		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4319 	}
4320 
4321 	if (ret) {
4322 		/* Apply workaround delay for certain panels */
4323 		apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4324 		/* Compare sinks to determine if this was a spontaneous HPD toggle */
4325 		if (are_sinks_equal(aconnector->dc_link->local_sink, aconnector->hdmi_prev_sink)) {
4326 			/*
4327 			* Sinks match - this was a spontaneous HDMI HPD toggle.
4328 			*/
4329 			drm_dbg_kms(dev, "HDMI HPD: Sink unchanged after debounce, internal re-enable\n");
4330 			fake_reconnect = true;
4331 		}
4332 
4333 		/* Update connector state */
4334 		amdgpu_dm_update_connector_after_detect(aconnector);
4335 
4336 		drm_modeset_lock_all(dev);
4337 		dm_restore_drm_connector_state(dev, connector);
4338 		drm_modeset_unlock_all(dev);
4339 
4340 		/* Only notify OS if sink actually changed */
4341 		if (!fake_reconnect && aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4342 			drm_kms_helper_hotplug_event(dev);
4343 	}
4344 
4345 	/* Release the cached sink reference */
4346 	if (aconnector->hdmi_prev_sink) {
4347 		dc_sink_release(aconnector->hdmi_prev_sink);
4348 		aconnector->hdmi_prev_sink = NULL;
4349 	}
4350 
4351 	scoped_guard(mutex, &adev->dm.dc_lock) {
4352 		if (reallow_idle && dc->caps.ips_support)
4353 			dc_allow_idle_optimizations(dc, true);
4354 	}
4355 }
4356 
4357 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
4358 {
4359 	struct drm_connector *connector = &aconnector->base;
4360 	struct drm_device *dev = connector->dev;
4361 	enum dc_connection_type new_connection_type = dc_connection_none;
4362 	struct amdgpu_device *adev = drm_to_adev(dev);
4363 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
4364 	struct dc *dc = aconnector->dc_link->ctx->dc;
4365 	bool ret = false;
4366 	bool debounce_required = false;
4367 
4368 	if (adev->dm.disable_hpd_irq)
4369 		return;
4370 
4371 	/*
4372 	 * In case of failure or MST no need to update connector status or notify the OS
4373 	 * since (for MST case) MST does this in its own context.
4374 	 */
4375 	guard(mutex)(&aconnector->hpd_lock);
4376 
4377 	if (adev->dm.hdcp_workqueue) {
4378 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
4379 		dm_con_state->update_hdcp = true;
4380 	}
4381 	if (aconnector->fake_enable)
4382 		aconnector->fake_enable = false;
4383 
4384 	aconnector->timing_changed = false;
4385 
4386 	if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
4387 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4388 
4389 	/*
4390 	 * Check for HDMI disconnect with debounce enabled.
4391 	 */
4392 	debounce_required = (aconnector->hdmi_hpd_debounce_delay_ms > 0 &&
4393 			      dc_is_hdmi_signal(aconnector->dc_link->connector_signal) &&
4394 			      new_connection_type == dc_connection_none &&
4395 			      aconnector->dc_link->local_sink != NULL);
4396 
4397 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
4398 		emulated_link_detect(aconnector->dc_link);
4399 
4400 		drm_modeset_lock_all(dev);
4401 		dm_restore_drm_connector_state(dev, connector);
4402 		drm_modeset_unlock_all(dev);
4403 
4404 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4405 			drm_kms_helper_connector_hotplug_event(connector);
4406 	} else if (debounce_required) {
4407 		/*
4408 		 * HDMI disconnect detected - schedule delayed work instead of
4409 		 * processing immediately. This allows us to coalesce spurious
4410 		 * HDMI signals from physical unplugs.
4411 		 */
4412 		drm_dbg_kms(dev, "HDMI HPD: Disconnect detected, scheduling debounce work (%u ms)\n",
4413 			    aconnector->hdmi_hpd_debounce_delay_ms);
4414 
4415 		/* Cache the current sink for later comparison */
4416 		if (aconnector->hdmi_prev_sink)
4417 			dc_sink_release(aconnector->hdmi_prev_sink);
4418 		aconnector->hdmi_prev_sink = aconnector->dc_link->local_sink;
4419 		if (aconnector->hdmi_prev_sink)
4420 			dc_sink_retain(aconnector->hdmi_prev_sink);
4421 
4422 		/* Schedule delayed detection. */
4423 		if (mod_delayed_work(system_percpu_wq,
4424 				 &aconnector->hdmi_hpd_debounce_work,
4425 				 msecs_to_jiffies(aconnector->hdmi_hpd_debounce_delay_ms)))
4426 			drm_dbg_kms(dev, "HDMI HPD: Re-scheduled debounce work\n");
4427 
4428 	} else {
4429 
4430 		/* If the aconnector->hdmi_hpd_debounce_work is scheduled, exit early */
4431 		if (delayed_work_pending(&aconnector->hdmi_hpd_debounce_work))
4432 			return;
4433 
4434 		scoped_guard(mutex, &adev->dm.dc_lock) {
4435 			dc_exit_ips_for_hw_access(dc);
4436 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4437 		}
4438 		if (ret) {
4439 			/* w/a delay for certain panels */
4440 			apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4441 			amdgpu_dm_update_connector_after_detect(aconnector);
4442 
4443 			drm_modeset_lock_all(dev);
4444 			dm_restore_drm_connector_state(dev, connector);
4445 			drm_modeset_unlock_all(dev);
4446 
4447 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4448 				drm_kms_helper_connector_hotplug_event(connector);
4449 		}
4450 	}
4451 }
4452 
4453 static void handle_hpd_irq(void *param)
4454 {
4455 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4456 
4457 	handle_hpd_irq_helper(aconnector);
4458 
4459 }
4460 
4461 static void schedule_hpd_rx_offload_work(struct amdgpu_device *adev, struct hpd_rx_irq_offload_work_queue *offload_wq,
4462 							union hpd_irq_data hpd_irq_data)
4463 {
4464 	struct hpd_rx_irq_offload_work *offload_work = kzalloc_obj(*offload_work);
4465 
4466 	if (!offload_work) {
4467 		drm_err(adev_to_drm(adev), "Failed to allocate hpd_rx_irq_offload_work.\n");
4468 		return;
4469 	}
4470 
4471 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
4472 	offload_work->data = hpd_irq_data;
4473 	offload_work->offload_wq = offload_wq;
4474 	offload_work->adev = adev;
4475 
4476 	queue_work(offload_wq->wq, &offload_work->work);
4477 	drm_dbg_kms(adev_to_drm(adev), "queue work to handle hpd_rx offload work");
4478 }
4479 
4480 static void handle_hpd_rx_irq(void *param)
4481 {
4482 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4483 	struct drm_connector *connector = &aconnector->base;
4484 	struct drm_device *dev = connector->dev;
4485 	struct dc_link *dc_link = aconnector->dc_link;
4486 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
4487 	bool result = false;
4488 	enum dc_connection_type new_connection_type = dc_connection_none;
4489 	struct amdgpu_device *adev = drm_to_adev(dev);
4490 	union hpd_irq_data hpd_irq_data;
4491 	bool link_loss = false;
4492 	bool has_left_work = false;
4493 	int idx = dc_link->link_index;
4494 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
4495 	struct dc *dc = aconnector->dc_link->ctx->dc;
4496 
4497 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
4498 
4499 	if (adev->dm.disable_hpd_irq)
4500 		return;
4501 
4502 	/*
4503 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
4504 	 * conflict, after implement i2c helper, this mutex should be
4505 	 * retired.
4506 	 */
4507 	mutex_lock(&aconnector->hpd_lock);
4508 
4509 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
4510 						&link_loss, true, &has_left_work);
4511 
4512 	if (!has_left_work)
4513 		goto out;
4514 
4515 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
4516 		schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4517 		goto out;
4518 	}
4519 
4520 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
4521 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
4522 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
4523 			bool skip = false;
4524 
4525 			/*
4526 			 * DOWN_REP_MSG_RDY is also handled by polling method
4527 			 * mgr->cbs->poll_hpd_irq()
4528 			 */
4529 			spin_lock(&offload_wq->offload_lock);
4530 			skip = offload_wq->is_handling_mst_msg_rdy_event;
4531 
4532 			if (!skip)
4533 				offload_wq->is_handling_mst_msg_rdy_event = true;
4534 
4535 			spin_unlock(&offload_wq->offload_lock);
4536 
4537 			if (!skip)
4538 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4539 
4540 			goto out;
4541 		}
4542 
4543 		if (link_loss) {
4544 			bool skip = false;
4545 
4546 			spin_lock(&offload_wq->offload_lock);
4547 			skip = offload_wq->is_handling_link_loss;
4548 
4549 			if (!skip)
4550 				offload_wq->is_handling_link_loss = true;
4551 
4552 			spin_unlock(&offload_wq->offload_lock);
4553 
4554 			if (!skip)
4555 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4556 
4557 			goto out;
4558 		}
4559 	}
4560 
4561 out:
4562 	if (result && !is_mst_root_connector) {
4563 		/* Downstream Port status changed. */
4564 		if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
4565 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4566 
4567 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4568 			emulated_link_detect(dc_link);
4569 
4570 			if (aconnector->fake_enable)
4571 				aconnector->fake_enable = false;
4572 
4573 			amdgpu_dm_update_connector_after_detect(aconnector);
4574 
4575 
4576 			drm_modeset_lock_all(dev);
4577 			dm_restore_drm_connector_state(dev, connector);
4578 			drm_modeset_unlock_all(dev);
4579 
4580 			drm_kms_helper_connector_hotplug_event(connector);
4581 		} else {
4582 			bool ret = false;
4583 
4584 			mutex_lock(&adev->dm.dc_lock);
4585 			dc_exit_ips_for_hw_access(dc);
4586 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
4587 			mutex_unlock(&adev->dm.dc_lock);
4588 
4589 			if (ret) {
4590 				if (aconnector->fake_enable)
4591 					aconnector->fake_enable = false;
4592 
4593 				amdgpu_dm_update_connector_after_detect(aconnector);
4594 
4595 				drm_modeset_lock_all(dev);
4596 				dm_restore_drm_connector_state(dev, connector);
4597 				drm_modeset_unlock_all(dev);
4598 
4599 				drm_kms_helper_connector_hotplug_event(connector);
4600 			}
4601 		}
4602 	}
4603 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
4604 		if (adev->dm.hdcp_workqueue)
4605 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
4606 	}
4607 
4608 	if (dc_link->type != dc_connection_mst_branch)
4609 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
4610 
4611 	mutex_unlock(&aconnector->hpd_lock);
4612 }
4613 
4614 static int register_hpd_handlers(struct amdgpu_device *adev)
4615 {
4616 	struct drm_device *dev = adev_to_drm(adev);
4617 	struct drm_connector *connector;
4618 	struct amdgpu_dm_connector *aconnector;
4619 	const struct dc_link *dc_link;
4620 	struct dc_interrupt_params int_params = {0};
4621 
4622 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4623 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4624 
4625 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
4626 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD,
4627 			dmub_hpd_callback, true)) {
4628 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4629 			return -EINVAL;
4630 		}
4631 
4632 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ,
4633 			dmub_hpd_callback, true)) {
4634 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4635 			return -EINVAL;
4636 		}
4637 
4638 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_SENSE_NOTIFY,
4639 			dmub_hpd_sense_callback, true)) {
4640 			drm_err(adev_to_drm(adev), "fail to register dmub hpd sense callback");
4641 			return -EINVAL;
4642 		}
4643 	}
4644 
4645 	list_for_each_entry(connector,
4646 			&dev->mode_config.connector_list, head)	{
4647 
4648 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
4649 			continue;
4650 
4651 		aconnector = to_amdgpu_dm_connector(connector);
4652 		dc_link = aconnector->dc_link;
4653 
4654 		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
4655 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4656 			int_params.irq_source = dc_link->irq_source_hpd;
4657 
4658 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4659 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1 ||
4660 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6) {
4661 				drm_err(adev_to_drm(adev), "Failed to register hpd irq!\n");
4662 				return -EINVAL;
4663 			}
4664 
4665 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4666 				handle_hpd_irq, (void *) aconnector))
4667 				return -ENOMEM;
4668 		}
4669 
4670 		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
4671 
4672 			/* Also register for DP short pulse (hpd_rx). */
4673 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4674 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
4675 
4676 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4677 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1RX ||
4678 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6RX) {
4679 				drm_err(adev_to_drm(adev), "Failed to register hpd rx irq!\n");
4680 				return -EINVAL;
4681 			}
4682 
4683 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4684 				handle_hpd_rx_irq, (void *) aconnector))
4685 				return -ENOMEM;
4686 		}
4687 	}
4688 	return 0;
4689 }
4690 
4691 /* Register IRQ sources and initialize IRQ callbacks */
4692 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
4693 {
4694 	struct dc *dc = adev->dm.dc;
4695 	struct common_irq_params *c_irq_params;
4696 	struct dc_interrupt_params int_params = {0};
4697 	int r;
4698 	int i;
4699 	unsigned int src_id;
4700 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4701 	/* Use different interrupts for VBLANK on DCE 6 vs. newer. */
4702 	const unsigned int vblank_d1 =
4703 		adev->dm.dc->ctx->dce_version >= DCE_VERSION_8_0
4704 		? VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0 : 1;
4705 
4706 	if (adev->family >= AMDGPU_FAMILY_AI)
4707 		client_id = SOC15_IH_CLIENTID_DCE;
4708 
4709 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4710 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4711 
4712 	/*
4713 	 * Actions of amdgpu_irq_add_id():
4714 	 * 1. Register a set() function with base driver.
4715 	 *    Base driver will call set() function to enable/disable an
4716 	 *    interrupt in DC hardware.
4717 	 * 2. Register amdgpu_dm_irq_handler().
4718 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4719 	 *    coming from DC hardware.
4720 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4721 	 *    for acknowledging and handling.
4722 	 */
4723 
4724 	/* Use VBLANK interrupt */
4725 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
4726 		src_id = vblank_d1 + i;
4727 		r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->crtc_irq);
4728 		if (r) {
4729 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4730 			return r;
4731 		}
4732 
4733 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4734 		int_params.irq_source =
4735 			dc_interrupt_to_irq_source(dc, src_id, 0);
4736 
4737 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4738 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4739 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4740 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4741 			return -EINVAL;
4742 		}
4743 
4744 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4745 
4746 		c_irq_params->adev = adev;
4747 		c_irq_params->irq_src = int_params.irq_source;
4748 
4749 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4750 			dm_crtc_high_irq, c_irq_params))
4751 			return -ENOMEM;
4752 	}
4753 
4754 	if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
4755 		/* Use VUPDATE interrupt */
4756 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
4757 			src_id = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT + i * 2;
4758 			r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->vupdate_irq);
4759 			if (r) {
4760 				drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4761 				return r;
4762 			}
4763 
4764 			int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4765 			int_params.irq_source =
4766 				dc_interrupt_to_irq_source(dc, src_id, 0);
4767 
4768 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4769 				int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4770 				int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4771 				drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4772 				return -EINVAL;
4773 			}
4774 
4775 			c_irq_params = &adev->dm.vupdate_params[
4776 				int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4777 			c_irq_params->adev = adev;
4778 			c_irq_params->irq_src = int_params.irq_source;
4779 
4780 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4781 				dm_vupdate_high_irq, c_irq_params))
4782 				return -ENOMEM;
4783 		}
4784 	}
4785 
4786 	/* Use GRPH_PFLIP interrupt */
4787 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4788 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4789 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4790 		if (r) {
4791 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4792 			return r;
4793 		}
4794 
4795 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4796 		int_params.irq_source =
4797 			dc_interrupt_to_irq_source(dc, i, 0);
4798 
4799 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4800 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4801 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4802 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4803 			return -EINVAL;
4804 		}
4805 
4806 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4807 
4808 		c_irq_params->adev = adev;
4809 		c_irq_params->irq_src = int_params.irq_source;
4810 
4811 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4812 			dm_pflip_high_irq, c_irq_params))
4813 			return -ENOMEM;
4814 	}
4815 
4816 	/* HPD */
4817 	r = amdgpu_irq_add_id(adev, client_id,
4818 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4819 	if (r) {
4820 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4821 		return r;
4822 	}
4823 
4824 	r = register_hpd_handlers(adev);
4825 
4826 	return r;
4827 }
4828 
4829 /* Register IRQ sources and initialize IRQ callbacks */
4830 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
4831 {
4832 	struct dc *dc = adev->dm.dc;
4833 	struct common_irq_params *c_irq_params;
4834 	struct dc_interrupt_params int_params = {0};
4835 	int r;
4836 	int i;
4837 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4838 	static const unsigned int vrtl_int_srcid[] = {
4839 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
4840 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
4841 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
4842 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
4843 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
4844 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
4845 	};
4846 #endif
4847 
4848 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4849 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4850 
4851 	/*
4852 	 * Actions of amdgpu_irq_add_id():
4853 	 * 1. Register a set() function with base driver.
4854 	 *    Base driver will call set() function to enable/disable an
4855 	 *    interrupt in DC hardware.
4856 	 * 2. Register amdgpu_dm_irq_handler().
4857 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4858 	 *    coming from DC hardware.
4859 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4860 	 *    for acknowledging and handling.
4861 	 */
4862 
4863 	/* Use VSTARTUP interrupt */
4864 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
4865 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
4866 			i++) {
4867 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
4868 
4869 		if (r) {
4870 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4871 			return r;
4872 		}
4873 
4874 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4875 		int_params.irq_source =
4876 			dc_interrupt_to_irq_source(dc, i, 0);
4877 
4878 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4879 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4880 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4881 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4882 			return -EINVAL;
4883 		}
4884 
4885 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4886 
4887 		c_irq_params->adev = adev;
4888 		c_irq_params->irq_src = int_params.irq_source;
4889 
4890 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4891 			dm_crtc_high_irq, c_irq_params))
4892 			return -ENOMEM;
4893 	}
4894 
4895 	/* Use otg vertical line interrupt */
4896 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4897 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
4898 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
4899 				vrtl_int_srcid[i], &adev->vline0_irq);
4900 
4901 		if (r) {
4902 			drm_err(adev_to_drm(adev), "Failed to add vline0 irq id!\n");
4903 			return r;
4904 		}
4905 
4906 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4907 		int_params.irq_source =
4908 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
4909 
4910 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4911 			int_params.irq_source < DC_IRQ_SOURCE_DC1_VLINE0 ||
4912 			int_params.irq_source > DC_IRQ_SOURCE_DC6_VLINE0) {
4913 			drm_err(adev_to_drm(adev), "Failed to register vline0 irq!\n");
4914 			return -EINVAL;
4915 		}
4916 
4917 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
4918 					- DC_IRQ_SOURCE_DC1_VLINE0];
4919 
4920 		c_irq_params->adev = adev;
4921 		c_irq_params->irq_src = int_params.irq_source;
4922 
4923 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4924 			dm_dcn_vertical_interrupt0_high_irq,
4925 			c_irq_params))
4926 			return -ENOMEM;
4927 	}
4928 #endif
4929 
4930 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
4931 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
4932 	 * to trigger at end of each vblank, regardless of state of the lock,
4933 	 * matching DCE behaviour.
4934 	 */
4935 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
4936 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
4937 	     i++) {
4938 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
4939 
4940 		if (r) {
4941 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4942 			return r;
4943 		}
4944 
4945 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4946 		int_params.irq_source =
4947 			dc_interrupt_to_irq_source(dc, i, 0);
4948 
4949 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4950 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4951 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4952 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4953 			return -EINVAL;
4954 		}
4955 
4956 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4957 
4958 		c_irq_params->adev = adev;
4959 		c_irq_params->irq_src = int_params.irq_source;
4960 
4961 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4962 			dm_vupdate_high_irq, c_irq_params))
4963 			return -ENOMEM;
4964 	}
4965 
4966 	/* Use GRPH_PFLIP interrupt */
4967 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
4968 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
4969 			i++) {
4970 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
4971 		if (r) {
4972 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4973 			return r;
4974 		}
4975 
4976 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4977 		int_params.irq_source =
4978 			dc_interrupt_to_irq_source(dc, i, 0);
4979 
4980 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4981 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4982 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4983 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4984 			return -EINVAL;
4985 		}
4986 
4987 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4988 
4989 		c_irq_params->adev = adev;
4990 		c_irq_params->irq_src = int_params.irq_source;
4991 
4992 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4993 			dm_pflip_high_irq, c_irq_params))
4994 			return -ENOMEM;
4995 	}
4996 
4997 	/* HPD */
4998 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
4999 			&adev->hpd_irq);
5000 	if (r) {
5001 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
5002 		return r;
5003 	}
5004 
5005 	r = register_hpd_handlers(adev);
5006 
5007 	return r;
5008 }
5009 /* Register Outbox IRQ sources and initialize IRQ callbacks */
5010 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
5011 {
5012 	struct dc *dc = adev->dm.dc;
5013 	struct common_irq_params *c_irq_params;
5014 	struct dc_interrupt_params int_params = {0};
5015 	int r, i;
5016 
5017 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
5018 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
5019 
5020 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
5021 			&adev->dmub_outbox_irq);
5022 	if (r) {
5023 		drm_err(adev_to_drm(adev), "Failed to add outbox irq id!\n");
5024 		return r;
5025 	}
5026 
5027 	if (dc->ctx->dmub_srv) {
5028 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
5029 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
5030 		int_params.irq_source =
5031 		dc_interrupt_to_irq_source(dc, i, 0);
5032 
5033 		c_irq_params = &adev->dm.dmub_outbox_params[0];
5034 
5035 		c_irq_params->adev = adev;
5036 		c_irq_params->irq_src = int_params.irq_source;
5037 
5038 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
5039 			dm_dmub_outbox1_low_irq, c_irq_params))
5040 			return -ENOMEM;
5041 	}
5042 
5043 	return 0;
5044 }
5045 
5046 /*
5047  * Acquires the lock for the atomic state object and returns
5048  * the new atomic state.
5049  *
5050  * This should only be called during atomic check.
5051  */
5052 int dm_atomic_get_state(struct drm_atomic_commit *state,
5053 			struct dm_atomic_state **dm_state)
5054 {
5055 	struct drm_device *dev = state->dev;
5056 	struct amdgpu_device *adev = drm_to_adev(dev);
5057 	struct amdgpu_display_manager *dm = &adev->dm;
5058 	struct drm_private_state *priv_state;
5059 
5060 	if (*dm_state)
5061 		return 0;
5062 
5063 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
5064 	if (IS_ERR(priv_state))
5065 		return PTR_ERR(priv_state);
5066 
5067 	*dm_state = to_dm_atomic_state(priv_state);
5068 
5069 	return 0;
5070 }
5071 
5072 static struct dm_atomic_state *
5073 dm_atomic_get_new_state(struct drm_atomic_commit *state)
5074 {
5075 	struct drm_device *dev = state->dev;
5076 	struct amdgpu_device *adev = drm_to_adev(dev);
5077 	struct amdgpu_display_manager *dm = &adev->dm;
5078 	struct drm_private_obj *obj;
5079 	struct drm_private_state *new_obj_state;
5080 	int i;
5081 
5082 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
5083 		if (obj->funcs == dm->atomic_obj.funcs)
5084 			return to_dm_atomic_state(new_obj_state);
5085 	}
5086 
5087 	return NULL;
5088 }
5089 
5090 static struct drm_private_state *
5091 dm_atomic_duplicate_state(struct drm_private_obj *obj)
5092 {
5093 	struct dm_atomic_state *old_state, *new_state;
5094 
5095 	new_state = kzalloc_obj(*new_state);
5096 	if (!new_state)
5097 		return NULL;
5098 
5099 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
5100 
5101 	old_state = to_dm_atomic_state(obj->state);
5102 
5103 	if (old_state && old_state->context)
5104 		new_state->context = dc_state_create_copy(old_state->context);
5105 
5106 	if (!new_state->context) {
5107 		kfree(new_state);
5108 		return NULL;
5109 	}
5110 
5111 	return &new_state->base;
5112 }
5113 
5114 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
5115 				    struct drm_private_state *state)
5116 {
5117 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
5118 
5119 	if (dm_state && dm_state->context)
5120 		dc_state_release(dm_state->context);
5121 
5122 	kfree(dm_state);
5123 }
5124 
5125 static struct drm_private_state *
5126 dm_atomic_create_state(struct drm_private_obj *obj)
5127 {
5128 	struct amdgpu_device *adev = drm_to_adev(obj->dev);
5129 	struct dm_atomic_state *dm_state;
5130 	struct dc_state *context;
5131 
5132 	dm_state = kzalloc_obj(*dm_state);
5133 	if (!dm_state)
5134 		return ERR_PTR(-ENOMEM);
5135 
5136 	context = dc_state_create_current_copy(adev->dm.dc);
5137 	if (!context) {
5138 		kfree(dm_state);
5139 		return ERR_PTR(-ENOMEM);
5140 	}
5141 
5142 	__drm_atomic_helper_private_obj_create_state(obj, &dm_state->base);
5143 	dm_state->context = context;
5144 
5145 	return &dm_state->base;
5146 }
5147 
5148 static struct drm_private_state_funcs dm_atomic_state_funcs = {
5149 	.atomic_create_state = dm_atomic_create_state,
5150 	.atomic_duplicate_state = dm_atomic_duplicate_state,
5151 	.atomic_destroy_state = dm_atomic_destroy_state,
5152 };
5153 
5154 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
5155 {
5156 	int r;
5157 
5158 	adev->mode_info.mode_config_initialized = true;
5159 
5160 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
5161 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
5162 
5163 	adev_to_drm(adev)->mode_config.max_width = 16384;
5164 	adev_to_drm(adev)->mode_config.max_height = 16384;
5165 
5166 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
5167 	if (adev->asic_type == CHIP_HAWAII)
5168 		/* disable prefer shadow for now due to hibernation issues */
5169 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
5170 	else
5171 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
5172 	/* indicates support for immediate flip */
5173 	adev_to_drm(adev)->mode_config.async_page_flip = true;
5174 
5175 	drm_atomic_private_obj_init(adev_to_drm(adev),
5176 				    &adev->dm.atomic_obj,
5177 				    &dm_atomic_state_funcs);
5178 
5179 	r = amdgpu_display_modeset_create_props(adev);
5180 	if (r)
5181 		return r;
5182 
5183 #ifdef AMD_PRIVATE_COLOR
5184 	if (amdgpu_dm_create_color_properties(adev))
5185 		return -ENOMEM;
5186 #endif
5187 
5188 	r = amdgpu_dm_audio_init(adev);
5189 	if (r)
5190 		return r;
5191 
5192 	return 0;
5193 }
5194 
5195 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
5196 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
5197 #define AMDGPU_DM_MIN_SPREAD ((AMDGPU_DM_DEFAULT_MAX_BACKLIGHT - AMDGPU_DM_DEFAULT_MIN_BACKLIGHT) / 2)
5198 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
5199 
5200 void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
5201 				     int bl_idx)
5202 {
5203 	struct amdgpu_dm_backlight_caps *caps = &dm->backlight_caps[bl_idx];
5204 
5205 	if (caps->caps_valid)
5206 		return;
5207 
5208 #if defined(CONFIG_ACPI)
5209 	amdgpu_acpi_get_backlight_caps(caps);
5210 
5211 	/* validate the firmware value is sane */
5212 	if (caps->caps_valid) {
5213 		int spread = caps->max_input_signal - caps->min_input_signal;
5214 
5215 		if (caps->max_input_signal > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5216 		    caps->min_input_signal < 0 ||
5217 		    spread > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5218 		    spread < AMDGPU_DM_MIN_SPREAD) {
5219 			drm_dbg_kms(adev_to_drm(dm->adev), "DM: Invalid backlight caps: min=%d, max=%d\n",
5220 				      caps->min_input_signal, caps->max_input_signal);
5221 			caps->caps_valid = false;
5222 		}
5223 	}
5224 
5225 	if (!caps->caps_valid) {
5226 		caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5227 		caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5228 		caps->caps_valid = true;
5229 	}
5230 #else
5231 	if (caps->aux_support)
5232 		return;
5233 
5234 	caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5235 	caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5236 	caps->caps_valid = true;
5237 #endif
5238 }
5239 
5240 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
5241 				unsigned int *min, unsigned int *max)
5242 {
5243 	if (!caps)
5244 		return 0;
5245 
5246 	if (caps->aux_support) {
5247 		// Firmware limits are in nits, DC API wants millinits.
5248 		*max = 1000 * caps->aux_max_input_signal;
5249 		*min = 1000 * caps->aux_min_input_signal;
5250 	} else {
5251 		// Firmware limits are 8-bit, PWM control is 16-bit.
5252 		*max = 0x101 * caps->max_input_signal;
5253 		*min = 0x101 * caps->min_input_signal;
5254 	}
5255 	return 1;
5256 }
5257 
5258 /* Rescale from [min..max] to [0..AMDGPU_MAX_BL_LEVEL] */
5259 static inline u32 scale_input_to_fw(int min, int max, u64 input)
5260 {
5261 	return DIV_ROUND_CLOSEST_ULL(input * AMDGPU_MAX_BL_LEVEL, max - min);
5262 }
5263 
5264 /* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [min..max] */
5265 static inline u32 scale_fw_to_input(int min, int max, u64 input)
5266 {
5267 	return min + DIV_ROUND_CLOSEST_ULL(input * (max - min), AMDGPU_MAX_BL_LEVEL);
5268 }
5269 
5270 static void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps,
5271 				      unsigned int min, unsigned int max,
5272 				      uint32_t *user_brightness)
5273 {
5274 	u32 brightness = scale_input_to_fw(min, max, *user_brightness);
5275 	u8 lower_signal, upper_signal, upper_lum, lower_lum, lum;
5276 	int left, right;
5277 
5278 	if (amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)
5279 		return;
5280 
5281 	if (!caps->data_points)
5282 		return;
5283 
5284 	/*
5285 	 * Handle the case where brightness is below the first data point
5286 	 * Interpolate between (0,0) and (first_signal, first_lum)
5287 	 */
5288 	if (brightness < caps->luminance_data[0].input_signal) {
5289 		lum = DIV_ROUND_CLOSEST(caps->luminance_data[0].luminance * brightness,
5290 					caps->luminance_data[0].input_signal);
5291 		goto scale;
5292 	}
5293 
5294 	left = 0;
5295 	right = caps->data_points - 1;
5296 	while (left <= right) {
5297 		int mid = left + (right - left) / 2;
5298 		u8 signal = caps->luminance_data[mid].input_signal;
5299 
5300 		/* Exact match found */
5301 		if (signal == brightness) {
5302 			lum = caps->luminance_data[mid].luminance;
5303 			goto scale;
5304 		}
5305 
5306 		if (signal < brightness)
5307 			left = mid + 1;
5308 		else
5309 			right = mid - 1;
5310 	}
5311 
5312 	/* verify bound */
5313 	if (left >= caps->data_points)
5314 		left = caps->data_points - 1;
5315 
5316 	/* At this point, left > right */
5317 	lower_signal = caps->luminance_data[right].input_signal;
5318 	upper_signal = caps->luminance_data[left].input_signal;
5319 	lower_lum = caps->luminance_data[right].luminance;
5320 	upper_lum = caps->luminance_data[left].luminance;
5321 
5322 	/* interpolate */
5323 	if (right == left || !lower_lum)
5324 		lum = upper_lum;
5325 	else
5326 		lum = lower_lum + DIV_ROUND_CLOSEST((upper_lum - lower_lum) *
5327 						    (brightness - lower_signal),
5328 						    upper_signal - lower_signal);
5329 scale:
5330 	*user_brightness = scale_fw_to_input(min, max,
5331 					     DIV_ROUND_CLOSEST(lum * brightness, 101));
5332 }
5333 
5334 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
5335 					uint32_t brightness)
5336 {
5337 	unsigned int min, max;
5338 
5339 	if (!get_brightness_range(caps, &min, &max))
5340 		return brightness;
5341 
5342 	convert_custom_brightness(caps, min, max, &brightness);
5343 
5344 	// Rescale 0..max to min..max
5345 	return min + DIV_ROUND_CLOSEST_ULL((u64)(max - min) * brightness, max);
5346 }
5347 
5348 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
5349 				      uint32_t brightness)
5350 {
5351 	unsigned int min, max;
5352 
5353 	if (!get_brightness_range(caps, &min, &max))
5354 		return brightness;
5355 
5356 	if (brightness < min)
5357 		return 0;
5358 	// Rescale min..max to 0..max
5359 	return DIV_ROUND_CLOSEST_ULL((u64)max * (brightness - min),
5360 				 max - min);
5361 }
5362 
5363 static struct dc_stream_state *dm_find_stream_with_link(
5364 	struct amdgpu_display_manager *dm,
5365 	struct dc_link *link)
5366 {
5367 	struct dc_state *cur_dc_state = dm->dc->current_state;
5368 	struct dc_stream_state *stream = NULL;
5369 	int i;
5370 
5371 	for (i = 0; i < cur_dc_state->stream_count; i++) {
5372 		stream = cur_dc_state->streams[i];
5373 		if (stream->link == link)
5374 			return stream;
5375 	}
5376 
5377 	return NULL;
5378 }
5379 
5380 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
5381 					 int bl_idx,
5382 					 u32 user_brightness)
5383 {
5384 	struct amdgpu_dm_backlight_caps *caps;
5385 	struct dc_link *link;
5386 	u32 brightness = 0;
5387 	bool rc = false, reallow_idle = false;
5388 	struct drm_connector *connector;
5389 	struct dc_stream_state *stream;
5390 	unsigned int min, max;
5391 
5392 	list_for_each_entry(connector, &dm->ddev->mode_config.connector_list, head) {
5393 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5394 
5395 		if (aconnector->bl_idx != bl_idx)
5396 			continue;
5397 
5398 		/* if connector is off, save the brightness for next time it's on */
5399 		if (!aconnector->base.encoder) {
5400 			dm->brightness[bl_idx] = user_brightness;
5401 			dm->actual_brightness[bl_idx] = 0;
5402 			return;
5403 		}
5404 	}
5405 
5406 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5407 	caps = &dm->backlight_caps[bl_idx];
5408 
5409 	dm->brightness[bl_idx] = user_brightness;
5410 	/* update scratch register */
5411 	if (bl_idx == 0)
5412 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
5413 	brightness = convert_brightness_from_user(caps, dm->brightness[bl_idx]);
5414 	link = (struct dc_link *)dm->backlight_link[bl_idx];
5415 
5416 	/* Apply brightness quirk */
5417 	if (caps->brightness_mask)
5418 		brightness |= caps->brightness_mask;
5419 
5420 	if (trace_amdgpu_dm_brightness_enabled()) {
5421 		trace_amdgpu_dm_brightness(__builtin_return_address(0),
5422 					   user_brightness,
5423 					   brightness,
5424 					   caps->aux_support,
5425 					   power_supply_is_system_supplied() > 0);
5426 	}
5427 
5428 	stream = dm_find_stream_with_link(dm, link);
5429 	if (!stream)
5430 		return;
5431 
5432 	mutex_lock(&dm->dc_lock);
5433 	if (dm->dc->caps.ips_support && dm->dc->ctx->dmub_srv->idle_allowed) {
5434 		dc_allow_idle_optimizations(dm->dc, false);
5435 		reallow_idle = true;
5436 	}
5437 
5438 	if (caps->aux_support) {
5439 		rc = mod_power_set_backlight_nits(dm->power_module, stream, brightness,
5440 			AUX_BL_DEFAULT_TRANSITION_TIME_MS, false, true);
5441 	} else {
5442 		/* power module uses millipercent */
5443 		get_brightness_range(caps, &min, &max);
5444 		brightness = DIV_ROUND_CLOSEST(brightness * 100, (max - min)) * 1000;
5445 		rc = mod_power_set_backlight_percent(dm->power_module, stream,
5446 						     brightness, 0, false);
5447 	}
5448 
5449 	/*
5450 	 * Some kms clients create a ramped backlight transition effect
5451 	 * by rapidly changing the backlight. Yet we must wait on dmcub
5452 	 * fw to exit psr/replay before programming backlight. To
5453 	 * prevent lag, keep disable psr/replay and let the next atomic
5454 	 * flip clear the event.
5455 	 *
5456 	 * ToDo: use ISM to handle rapidly backlight change
5457 	 *
5458 	 * Rapidly backlight change is similar to rapidly cursor events,
5459 	 * which is now handled by ISM. ISM can delay the event until system
5460 	 * is really idle, so we may use ISM to handle backlight change as well.
5461 	 */
5462 	amdgpu_dm_psr_set_event(dm, stream, true,
5463 		psr_event_hw_programming, true);
5464 	amdgpu_dm_replay_set_event(dm, stream, true,
5465 		replay_event_hw_programming, true);
5466 
5467 	if (dm->dc->caps.ips_support && reallow_idle)
5468 		dc_allow_idle_optimizations(dm->dc, true);
5469 
5470 	mutex_unlock(&dm->dc_lock);
5471 
5472 	if (rc)
5473 		dm->actual_brightness[bl_idx] = user_brightness;
5474 }
5475 
5476 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
5477 {
5478 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5479 	int i;
5480 
5481 	for (i = 0; i < dm->num_of_edps; i++) {
5482 		if (bd == dm->backlight_dev[i])
5483 			break;
5484 	}
5485 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5486 		i = 0;
5487 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
5488 
5489 	return 0;
5490 }
5491 
5492 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
5493 					 int bl_idx)
5494 {
5495 	int ret;
5496 	struct amdgpu_dm_backlight_caps caps;
5497 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
5498 
5499 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5500 	caps = dm->backlight_caps[bl_idx];
5501 
5502 	if (caps.aux_support) {
5503 		u32 avg, peak;
5504 
5505 		if (!dc_link_get_backlight_level_nits(link, &avg, &peak))
5506 			return dm->brightness[bl_idx];
5507 		return convert_brightness_to_user(&caps, avg);
5508 	}
5509 
5510 	ret = dc_link_get_backlight_level(link);
5511 
5512 	if (ret == DC_ERROR_UNEXPECTED)
5513 		return dm->brightness[bl_idx];
5514 
5515 	return convert_brightness_to_user(&caps, ret);
5516 }
5517 
5518 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
5519 {
5520 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5521 	int i;
5522 
5523 	for (i = 0; i < dm->num_of_edps; i++) {
5524 		if (bd == dm->backlight_dev[i])
5525 			break;
5526 	}
5527 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5528 		i = 0;
5529 	return amdgpu_dm_backlight_get_level(dm, i);
5530 }
5531 
5532 static const struct backlight_ops amdgpu_dm_backlight_ops = {
5533 	.options = BL_CORE_SUSPENDRESUME,
5534 	.get_brightness = amdgpu_dm_backlight_get_brightness,
5535 	.update_status	= amdgpu_dm_backlight_update_status,
5536 };
5537 
5538 static void
5539 amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector *aconnector)
5540 {
5541 	struct drm_device *drm = aconnector->base.dev;
5542 	struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
5543 	struct backlight_properties props = { 0 };
5544 	struct amdgpu_dm_backlight_caps *caps;
5545 	char bl_name[16];
5546 	int min, max;
5547 	int real_brightness;
5548 	int init_brightness;
5549 
5550 	if (aconnector->bl_idx == -1)
5551 		return;
5552 
5553 	if (!acpi_video_backlight_use_native()) {
5554 		drm_info(drm, "Skipping amdgpu DM backlight registration\n");
5555 		/* Try registering an ACPI video backlight device instead. */
5556 		acpi_video_register_backlight();
5557 		return;
5558 	}
5559 
5560 	caps = &dm->backlight_caps[aconnector->bl_idx];
5561 	if (get_brightness_range(caps, &min, &max)) {
5562 		if (power_supply_is_system_supplied() > 0)
5563 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->ac_level, 100);
5564 		else
5565 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->dc_level, 100);
5566 		/* min is zero, so max needs to be adjusted */
5567 		props.max_brightness = max - min;
5568 		drm_dbg(drm, "Backlight caps: min: %d, max: %d, ac %d, dc %d\n", min, max,
5569 			caps->ac_level, caps->dc_level);
5570 	} else
5571 		props.brightness = props.max_brightness = MAX_BACKLIGHT_LEVEL;
5572 
5573 	init_brightness = props.brightness;
5574 
5575 	if (caps->data_points && !(amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)) {
5576 		drm_info(drm, "Using custom brightness curve\n");
5577 		props.scale = BACKLIGHT_SCALE_NON_LINEAR;
5578 	} else
5579 		props.scale = BACKLIGHT_SCALE_LINEAR;
5580 	props.type = BACKLIGHT_RAW;
5581 
5582 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
5583 		 drm->primary->index + aconnector->bl_idx);
5584 
5585 	dm->backlight_dev[aconnector->bl_idx] =
5586 		backlight_device_register(bl_name, aconnector->base.kdev, dm,
5587 					  &amdgpu_dm_backlight_ops, &props);
5588 	dm->brightness[aconnector->bl_idx] = props.brightness;
5589 
5590 	if (IS_ERR(dm->backlight_dev[aconnector->bl_idx])) {
5591 		drm_err(drm, "DM: Backlight registration failed!\n");
5592 		dm->backlight_dev[aconnector->bl_idx] = NULL;
5593 	} else {
5594 		/*
5595 		 * dm->brightness[x] can be inconsistent just after startup until
5596 		 * ops.get_brightness is called.
5597 		 */
5598 		real_brightness =
5599 			amdgpu_dm_backlight_ops.get_brightness(dm->backlight_dev[aconnector->bl_idx]);
5600 
5601 		if (real_brightness != init_brightness) {
5602 			dm->actual_brightness[aconnector->bl_idx] = real_brightness;
5603 			dm->brightness[aconnector->bl_idx] = real_brightness;
5604 		}
5605 		drm_dbg_driver(drm, "DM: Registered Backlight device: %s\n", bl_name);
5606 	}
5607 }
5608 
5609 static int initialize_plane(struct amdgpu_display_manager *dm,
5610 			    struct amdgpu_mode_info *mode_info, int plane_id,
5611 			    enum drm_plane_type plane_type,
5612 			    const struct dc_plane_cap *plane_cap)
5613 {
5614 	struct drm_plane *plane;
5615 	unsigned long possible_crtcs;
5616 	int ret = 0;
5617 
5618 	plane = kzalloc_obj(struct drm_plane);
5619 	if (!plane) {
5620 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
5621 		return -ENOMEM;
5622 	}
5623 	plane->type = plane_type;
5624 
5625 	/*
5626 	 * HACK: IGT tests expect that the primary plane for a CRTC
5627 	 * can only have one possible CRTC. Only expose support for
5628 	 * any CRTC if they're not going to be used as a primary plane
5629 	 * for a CRTC - like overlay or underlay planes.
5630 	 */
5631 	possible_crtcs = 1 << plane_id;
5632 	if (plane_id >= dm->dc->caps.max_streams)
5633 		possible_crtcs = 0xff;
5634 
5635 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
5636 
5637 	if (ret) {
5638 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
5639 		kfree(plane);
5640 		return ret;
5641 	}
5642 
5643 	if (mode_info)
5644 		mode_info->planes[plane_id] = plane;
5645 
5646 	return ret;
5647 }
5648 
5649 
5650 static void setup_backlight_device(struct amdgpu_display_manager *dm,
5651 				   struct amdgpu_dm_connector *aconnector)
5652 {
5653 	struct amdgpu_dm_backlight_caps *caps;
5654 	struct dc_link *link = aconnector->dc_link;
5655 	int bl_idx = dm->num_of_edps;
5656 
5657 	if (!(link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) ||
5658 	    link->type == dc_connection_none)
5659 		return;
5660 
5661 	if (dm->num_of_edps >= AMDGPU_DM_MAX_NUM_EDP) {
5662 		drm_warn(adev_to_drm(dm->adev), "Too much eDP connections, skipping backlight setup for additional eDPs\n");
5663 		return;
5664 	}
5665 
5666 	aconnector->bl_idx = bl_idx;
5667 
5668 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5669 	dm->backlight_link[bl_idx] = link;
5670 	dm->num_of_edps++;
5671 
5672 	update_connector_ext_caps(aconnector);
5673 	caps = &dm->backlight_caps[aconnector->bl_idx];
5674 
5675 	/* Only offer ABM property when non-OLED and user didn't turn off by module parameter */
5676 	if (caps->ext_caps && !caps->ext_caps->bits.oled && amdgpu_dm_abm_level < 0)
5677 		drm_object_attach_property(&aconnector->base.base,
5678 					   dm->adev->mode_info.abm_level_property,
5679 					   ABM_SYSFS_CONTROL);
5680 }
5681 
5682 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
5683 
5684 
5685 
5686 /*
5687  * In this architecture, the association
5688  * connector -> encoder -> crtc
5689  * id not really requried. The crtc and connector will hold the
5690  * display_index as an abstraction to use with DAL component
5691  *
5692  * Returns 0 on success
5693  */
5694 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
5695 {
5696 	struct amdgpu_display_manager *dm = &adev->dm;
5697 	s32 i;
5698 	struct amdgpu_dm_connector *aconnector = NULL;
5699 	struct amdgpu_encoder *aencoder = NULL;
5700 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5701 	u32 link_cnt;
5702 	s32 primary_planes;
5703 	enum dc_connection_type new_connection_type = dc_connection_none;
5704 	const struct dc_plane_cap *plane;
5705 	bool psr_feature_enabled = false;
5706 	bool replay_feature_enabled = false;
5707 	int max_overlay = dm->dc->caps.max_slave_planes;
5708 
5709 	dm->display_indexes_num = dm->dc->caps.max_streams;
5710 	/* Update the actual used number of crtc */
5711 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
5712 
5713 	amdgpu_dm_set_irq_funcs(adev);
5714 
5715 	link_cnt = dm->dc->caps.max_links;
5716 	if (amdgpu_dm_mode_config_init(dm->adev)) {
5717 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
5718 		return -EINVAL;
5719 	}
5720 
5721 	/* There is one primary plane per CRTC */
5722 	primary_planes = dm->dc->caps.max_streams;
5723 	if (primary_planes > AMDGPU_MAX_PLANES) {
5724 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
5725 		return -EINVAL;
5726 	}
5727 
5728 	/*
5729 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
5730 	 * Order is reversed to match iteration order in atomic check.
5731 	 */
5732 	for (i = (primary_planes - 1); i >= 0; i--) {
5733 		plane = &dm->dc->caps.planes[i];
5734 
5735 		if (initialize_plane(dm, mode_info, i,
5736 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
5737 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
5738 			goto fail;
5739 		}
5740 	}
5741 
5742 	/*
5743 	 * Initialize overlay planes, index starting after primary planes.
5744 	 * These planes have a higher DRM index than the primary planes since
5745 	 * they should be considered as having a higher z-order.
5746 	 * Order is reversed to match iteration order in atomic check.
5747 	 *
5748 	 * Only support DCN for now, and only expose one so we don't encourage
5749 	 * userspace to use up all the pipes.
5750 	 */
5751 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
5752 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
5753 
5754 		/* Do not create overlay if MPO disabled */
5755 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
5756 			break;
5757 
5758 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
5759 			continue;
5760 
5761 		if (!plane->pixel_format_support.argb8888)
5762 			continue;
5763 
5764 		if (max_overlay-- == 0)
5765 			break;
5766 
5767 		if (initialize_plane(dm, NULL, primary_planes + i,
5768 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
5769 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
5770 			goto fail;
5771 		}
5772 	}
5773 
5774 	for (i = 0; i < dm->dc->caps.max_streams; i++)
5775 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
5776 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
5777 			goto fail;
5778 		}
5779 
5780 	/* Use Outbox interrupt */
5781 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5782 	case IP_VERSION(3, 0, 0):
5783 	case IP_VERSION(3, 1, 2):
5784 	case IP_VERSION(3, 1, 3):
5785 	case IP_VERSION(3, 1, 4):
5786 	case IP_VERSION(3, 1, 5):
5787 	case IP_VERSION(3, 1, 6):
5788 	case IP_VERSION(3, 2, 0):
5789 	case IP_VERSION(3, 2, 1):
5790 	case IP_VERSION(2, 1, 0):
5791 	case IP_VERSION(3, 5, 0):
5792 	case IP_VERSION(3, 5, 1):
5793 	case IP_VERSION(3, 6, 0):
5794 	case IP_VERSION(4, 0, 1):
5795 	case IP_VERSION(4, 2, 0):
5796 	case IP_VERSION(4, 2, 1):
5797 		if (register_outbox_irq_handlers(dm->adev)) {
5798 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5799 			goto fail;
5800 		}
5801 		break;
5802 	default:
5803 		drm_dbg_kms(adev_to_drm(adev), "Unsupported DCN IP version for outbox: 0x%X\n",
5804 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
5805 	}
5806 
5807 	/* Determine whether to enable PSR support by default. */
5808 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
5809 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5810 		case IP_VERSION(3, 1, 2):
5811 		case IP_VERSION(3, 1, 3):
5812 		case IP_VERSION(3, 1, 4):
5813 		case IP_VERSION(3, 1, 5):
5814 		case IP_VERSION(3, 1, 6):
5815 		case IP_VERSION(3, 2, 0):
5816 		case IP_VERSION(3, 2, 1):
5817 		case IP_VERSION(3, 5, 0):
5818 		case IP_VERSION(3, 5, 1):
5819 		case IP_VERSION(3, 6, 0):
5820 		case IP_VERSION(4, 0, 1):
5821 		case IP_VERSION(4, 2, 0):
5822 		case IP_VERSION(4, 2, 1):
5823 			psr_feature_enabled = true;
5824 			break;
5825 		default:
5826 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
5827 			break;
5828 		}
5829 	}
5830 
5831 	/* Determine whether to enable Replay support by default. */
5832 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
5833 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5834 		case IP_VERSION(3, 1, 4):
5835 		case IP_VERSION(3, 2, 0):
5836 		case IP_VERSION(3, 2, 1):
5837 		case IP_VERSION(3, 5, 0):
5838 		case IP_VERSION(3, 5, 1):
5839 		case IP_VERSION(3, 6, 0):
5840 		case IP_VERSION(4, 2, 0):
5841 		case IP_VERSION(4, 2, 1):
5842 			replay_feature_enabled = true;
5843 			break;
5844 
5845 		default:
5846 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
5847 			break;
5848 		}
5849 	}
5850 
5851 	if (link_cnt > MAX_LINKS) {
5852 		drm_err(adev_to_drm(adev),
5853 			"KMS: Cannot support more than %d display indexes\n",
5854 				MAX_LINKS);
5855 		goto fail;
5856 	}
5857 
5858 	/* loops over all connectors on the board */
5859 	for (i = 0; i < link_cnt; i++) {
5860 		struct dc_link *link = NULL;
5861 
5862 		link = dc_get_link_at_index(dm->dc, i);
5863 
5864 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
5865 			struct amdgpu_dm_wb_connector *wbcon = kzalloc_obj(*wbcon);
5866 
5867 			if (!wbcon) {
5868 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
5869 				continue;
5870 			}
5871 
5872 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
5873 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
5874 				kfree(wbcon);
5875 				continue;
5876 			}
5877 
5878 			link->psr_settings.psr_feature_enabled = false;
5879 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
5880 
5881 			continue;
5882 		}
5883 
5884 		aconnector = kzalloc_obj(*aconnector);
5885 		if (!aconnector)
5886 			goto fail;
5887 
5888 		aencoder = kzalloc_obj(*aencoder);
5889 		if (!aencoder)
5890 			goto fail;
5891 
5892 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
5893 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
5894 			goto fail;
5895 		}
5896 
5897 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
5898 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
5899 			goto fail;
5900 		}
5901 
5902 		if (dm->hpd_rx_offload_wq)
5903 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
5904 				aconnector;
5905 
5906 		if (!dc_link_detect_connection_type(link, &new_connection_type))
5907 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
5908 
5909 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
5910 			emulated_link_detect(link);
5911 			amdgpu_dm_update_connector_after_detect(aconnector);
5912 		} else {
5913 			bool ret = false;
5914 
5915 			mutex_lock(&dm->dc_lock);
5916 			dc_exit_ips_for_hw_access(dm->dc);
5917 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
5918 			mutex_unlock(&dm->dc_lock);
5919 
5920 			if (ret) {
5921 				amdgpu_dm_update_connector_after_detect(aconnector);
5922 				setup_backlight_device(dm, aconnector);
5923 
5924 				/* Disable PSR if Replay can be enabled */
5925 				if (replay_feature_enabled)
5926 					if (amdgpu_dm_set_replay_caps(link, aconnector))
5927 						psr_feature_enabled = false;
5928 
5929 				if (psr_feature_enabled) {
5930 					amdgpu_dm_set_psr_caps(link, aconnector);
5931 					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",
5932 						 aconnector->base.name,
5933 						 link->psr_settings.psr_feature_enabled,
5934 						 link->psr_settings.psr_version,
5935 						 link->dpcd_caps.psr_info.psr_version,
5936 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
5937 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
5938 				}
5939 			}
5940 		}
5941 		amdgpu_set_panel_orientation(&aconnector->base);
5942 	}
5943 
5944 	/* Debug dump: list all DC links and their associated sinks after detection
5945 	 * is complete for all connectors. This provides a comprehensive view of the
5946 	 * final state without repeating the dump for each connector.
5947 	 */
5948 	amdgpu_dm_dump_links_and_sinks(adev);
5949 
5950 	/* Software is initialized. Now we can register interrupt handlers. */
5951 	switch (adev->asic_type) {
5952 #if defined(CONFIG_DRM_AMD_DC_SI)
5953 	case CHIP_TAHITI:
5954 	case CHIP_PITCAIRN:
5955 	case CHIP_VERDE:
5956 	case CHIP_OLAND:
5957 #endif
5958 	case CHIP_BONAIRE:
5959 	case CHIP_HAWAII:
5960 	case CHIP_KAVERI:
5961 	case CHIP_KABINI:
5962 	case CHIP_MULLINS:
5963 	case CHIP_TONGA:
5964 	case CHIP_FIJI:
5965 	case CHIP_CARRIZO:
5966 	case CHIP_STONEY:
5967 	case CHIP_POLARIS11:
5968 	case CHIP_POLARIS10:
5969 	case CHIP_POLARIS12:
5970 	case CHIP_VEGAM:
5971 	case CHIP_VEGA10:
5972 	case CHIP_VEGA12:
5973 	case CHIP_VEGA20:
5974 		if (dce110_register_irq_handlers(dm->adev)) {
5975 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5976 			goto fail;
5977 		}
5978 		break;
5979 	default:
5980 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5981 		case IP_VERSION(1, 0, 0):
5982 		case IP_VERSION(1, 0, 1):
5983 		case IP_VERSION(2, 0, 2):
5984 		case IP_VERSION(2, 0, 3):
5985 		case IP_VERSION(2, 0, 0):
5986 		case IP_VERSION(2, 1, 0):
5987 		case IP_VERSION(3, 0, 0):
5988 		case IP_VERSION(3, 0, 2):
5989 		case IP_VERSION(3, 0, 3):
5990 		case IP_VERSION(3, 0, 1):
5991 		case IP_VERSION(3, 1, 2):
5992 		case IP_VERSION(3, 1, 3):
5993 		case IP_VERSION(3, 1, 4):
5994 		case IP_VERSION(3, 1, 5):
5995 		case IP_VERSION(3, 1, 6):
5996 		case IP_VERSION(3, 2, 0):
5997 		case IP_VERSION(3, 2, 1):
5998 		case IP_VERSION(3, 5, 0):
5999 		case IP_VERSION(3, 5, 1):
6000 		case IP_VERSION(3, 6, 0):
6001 		case IP_VERSION(4, 0, 1):
6002 		case IP_VERSION(4, 2, 0):
6003 		case IP_VERSION(4, 2, 1):
6004 			if (dcn10_register_irq_handlers(dm->adev)) {
6005 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
6006 				goto fail;
6007 			}
6008 			break;
6009 		default:
6010 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
6011 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6012 			goto fail;
6013 		}
6014 		break;
6015 	}
6016 
6017 	return 0;
6018 fail:
6019 	kfree(aencoder);
6020 	kfree(aconnector);
6021 
6022 	return -EINVAL;
6023 }
6024 
6025 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
6026 {
6027 	if (dm->atomic_obj.state)
6028 		drm_atomic_private_obj_fini(&dm->atomic_obj);
6029 }
6030 
6031 /******************************************************************************
6032  * amdgpu_display_funcs functions
6033  *****************************************************************************/
6034 
6035 /*
6036  * dm_bandwidth_update - program display watermarks
6037  *
6038  * @adev: amdgpu_device pointer
6039  *
6040  * Calculate and program the display watermarks and line buffer allocation.
6041  */
6042 static void dm_bandwidth_update(struct amdgpu_device *adev)
6043 {
6044 	/* TODO: implement later */
6045 }
6046 
6047 static const struct amdgpu_display_funcs dm_display_funcs = {
6048 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
6049 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
6050 	.backlight_set_level = NULL, /* never called for DC */
6051 	.backlight_get_level = NULL, /* never called for DC */
6052 	.hpd_sense = NULL,/* called unconditionally */
6053 	.hpd_set_polarity = NULL, /* called unconditionally */
6054 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
6055 	.page_flip_get_scanoutpos =
6056 		dm_crtc_get_scanoutpos,/* called unconditionally */
6057 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
6058 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
6059 };
6060 
6061 #if defined(CONFIG_DEBUG_KERNEL_DC)
6062 
6063 static ssize_t s3_debug_store(struct device *device,
6064 			      struct device_attribute *attr,
6065 			      const char *buf,
6066 			      size_t count)
6067 {
6068 	int ret;
6069 	int s3_state;
6070 	struct drm_device *drm_dev = dev_get_drvdata(device);
6071 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
6072 	struct amdgpu_ip_block *ip_block;
6073 
6074 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
6075 	if (!ip_block)
6076 		return -EINVAL;
6077 
6078 	ret = kstrtoint(buf, 0, &s3_state);
6079 
6080 	if (ret == 0) {
6081 		if (s3_state) {
6082 			dm_resume(ip_block);
6083 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
6084 		} else
6085 			dm_suspend(ip_block);
6086 	}
6087 
6088 	return ret == 0 ? count : 0;
6089 }
6090 
6091 DEVICE_ATTR_WO(s3_debug);
6092 
6093 #endif
6094 
6095 static int dm_init_microcode(struct amdgpu_device *adev)
6096 {
6097 	char *fw_name_dmub;
6098 	int r;
6099 
6100 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6101 	case IP_VERSION(2, 1, 0):
6102 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
6103 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
6104 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
6105 		break;
6106 	case IP_VERSION(3, 0, 0):
6107 		if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(10, 3, 0))
6108 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
6109 		else
6110 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
6111 		break;
6112 	case IP_VERSION(3, 0, 1):
6113 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
6114 		break;
6115 	case IP_VERSION(3, 0, 2):
6116 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
6117 		break;
6118 	case IP_VERSION(3, 0, 3):
6119 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
6120 		break;
6121 	case IP_VERSION(3, 1, 2):
6122 	case IP_VERSION(3, 1, 3):
6123 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
6124 		break;
6125 	case IP_VERSION(3, 1, 4):
6126 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
6127 		break;
6128 	case IP_VERSION(3, 1, 5):
6129 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
6130 		break;
6131 	case IP_VERSION(3, 1, 6):
6132 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
6133 		break;
6134 	case IP_VERSION(3, 2, 0):
6135 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
6136 		break;
6137 	case IP_VERSION(3, 2, 1):
6138 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
6139 		break;
6140 	case IP_VERSION(3, 5, 0):
6141 		fw_name_dmub = FIRMWARE_DCN_35_DMUB;
6142 		break;
6143 	case IP_VERSION(3, 5, 1):
6144 		fw_name_dmub = FIRMWARE_DCN_351_DMUB;
6145 		break;
6146 	case IP_VERSION(3, 6, 0):
6147 		fw_name_dmub = FIRMWARE_DCN_36_DMUB;
6148 		break;
6149 	case IP_VERSION(4, 0, 1):
6150 		fw_name_dmub = FIRMWARE_DCN_401_DMUB;
6151 		break;
6152 	case IP_VERSION(4, 2, 0):
6153 		fw_name_dmub = FIRMWARE_DCN_42_DMUB;
6154 		break;
6155 	case IP_VERSION(4, 2, 1):
6156 		fw_name_dmub = FIRMWARE_DCN_42B_DMUB;
6157 		break;
6158 	default:
6159 		/* ASIC doesn't support DMUB. */
6160 		return 0;
6161 	}
6162 	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, AMDGPU_UCODE_REQUIRED,
6163 				 "%s", fw_name_dmub);
6164 	return r;
6165 }
6166 
6167 static int dm_early_init(struct amdgpu_ip_block *ip_block)
6168 {
6169 	struct amdgpu_device *adev = ip_block->adev;
6170 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
6171 	struct atom_context *ctx = mode_info->atom_context;
6172 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
6173 	u16 data_offset;
6174 
6175 	/* if there is no object header, skip DM */
6176 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
6177 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
6178 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
6179 		return -ENOENT;
6180 	}
6181 
6182 	switch (adev->asic_type) {
6183 #if defined(CONFIG_DRM_AMD_DC_SI)
6184 	case CHIP_TAHITI:
6185 	case CHIP_PITCAIRN:
6186 	case CHIP_VERDE:
6187 		adev->mode_info.num_crtc = 6;
6188 		adev->mode_info.num_hpd = 6;
6189 		adev->mode_info.num_dig = 6;
6190 		break;
6191 	case CHIP_OLAND:
6192 		adev->mode_info.num_crtc = 2;
6193 		adev->mode_info.num_hpd = 2;
6194 		adev->mode_info.num_dig = 2;
6195 		break;
6196 #endif
6197 	case CHIP_BONAIRE:
6198 	case CHIP_HAWAII:
6199 		adev->mode_info.num_crtc = 6;
6200 		adev->mode_info.num_hpd = 6;
6201 		adev->mode_info.num_dig = 6;
6202 		break;
6203 	case CHIP_KAVERI:
6204 		adev->mode_info.num_crtc = 4;
6205 		adev->mode_info.num_hpd = 6;
6206 		adev->mode_info.num_dig = 7;
6207 		break;
6208 	case CHIP_KABINI:
6209 	case CHIP_MULLINS:
6210 		adev->mode_info.num_crtc = 2;
6211 		adev->mode_info.num_hpd = 6;
6212 		adev->mode_info.num_dig = 6;
6213 		break;
6214 	case CHIP_FIJI:
6215 	case CHIP_TONGA:
6216 		adev->mode_info.num_crtc = 6;
6217 		adev->mode_info.num_hpd = 6;
6218 		adev->mode_info.num_dig = 7;
6219 		break;
6220 	case CHIP_CARRIZO:
6221 		adev->mode_info.num_crtc = 3;
6222 		adev->mode_info.num_hpd = 6;
6223 		adev->mode_info.num_dig = 9;
6224 		break;
6225 	case CHIP_STONEY:
6226 		adev->mode_info.num_crtc = 2;
6227 		adev->mode_info.num_hpd = 6;
6228 		adev->mode_info.num_dig = 9;
6229 		break;
6230 	case CHIP_POLARIS11:
6231 	case CHIP_POLARIS12:
6232 		adev->mode_info.num_crtc = 5;
6233 		adev->mode_info.num_hpd = 5;
6234 		adev->mode_info.num_dig = 5;
6235 		break;
6236 	case CHIP_POLARIS10:
6237 	case CHIP_VEGAM:
6238 		adev->mode_info.num_crtc = 6;
6239 		adev->mode_info.num_hpd = 6;
6240 		adev->mode_info.num_dig = 6;
6241 		break;
6242 	case CHIP_VEGA10:
6243 	case CHIP_VEGA12:
6244 	case CHIP_VEGA20:
6245 		adev->mode_info.num_crtc = 6;
6246 		adev->mode_info.num_hpd = 6;
6247 		adev->mode_info.num_dig = 6;
6248 		break;
6249 	default:
6250 
6251 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6252 		case IP_VERSION(2, 0, 2):
6253 		case IP_VERSION(3, 0, 0):
6254 			adev->mode_info.num_crtc = 6;
6255 			adev->mode_info.num_hpd = 6;
6256 			adev->mode_info.num_dig = 6;
6257 			break;
6258 		case IP_VERSION(2, 0, 0):
6259 		case IP_VERSION(3, 0, 2):
6260 			adev->mode_info.num_crtc = 5;
6261 			adev->mode_info.num_hpd = 5;
6262 			adev->mode_info.num_dig = 5;
6263 			break;
6264 		case IP_VERSION(2, 0, 3):
6265 		case IP_VERSION(3, 0, 3):
6266 			adev->mode_info.num_crtc = 2;
6267 			adev->mode_info.num_hpd = 2;
6268 			adev->mode_info.num_dig = 2;
6269 			break;
6270 		case IP_VERSION(1, 0, 0):
6271 		case IP_VERSION(1, 0, 1):
6272 		case IP_VERSION(3, 0, 1):
6273 		case IP_VERSION(2, 1, 0):
6274 		case IP_VERSION(3, 1, 2):
6275 		case IP_VERSION(3, 1, 3):
6276 		case IP_VERSION(3, 1, 4):
6277 		case IP_VERSION(3, 1, 5):
6278 		case IP_VERSION(3, 1, 6):
6279 		case IP_VERSION(3, 2, 0):
6280 		case IP_VERSION(3, 2, 1):
6281 		case IP_VERSION(3, 5, 0):
6282 		case IP_VERSION(3, 5, 1):
6283 		case IP_VERSION(3, 6, 0):
6284 		case IP_VERSION(4, 0, 1):
6285 		case IP_VERSION(4, 2, 0):
6286 		case IP_VERSION(4, 2, 1):
6287 			adev->mode_info.num_crtc = 4;
6288 			adev->mode_info.num_hpd = 4;
6289 			adev->mode_info.num_dig = 4;
6290 			break;
6291 		default:
6292 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
6293 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6294 			return -EINVAL;
6295 		}
6296 		break;
6297 	}
6298 
6299 	if (adev->mode_info.funcs == NULL)
6300 		adev->mode_info.funcs = &dm_display_funcs;
6301 
6302 	/*
6303 	 * Note: Do NOT change adev->reg.audio_endpt.rreg and
6304 	 * adev->reg.audio_endpt.wreg because they are initialised in
6305 	 * amdgpu_device_init()
6306 	 */
6307 #if defined(CONFIG_DEBUG_KERNEL_DC)
6308 	device_create_file(
6309 		adev_to_drm(adev)->dev,
6310 		&dev_attr_s3_debug);
6311 #endif
6312 	adev->dc_enabled = true;
6313 
6314 	return dm_init_microcode(adev);
6315 }
6316 
6317 static bool modereset_required(struct drm_crtc_state *crtc_state)
6318 {
6319 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
6320 }
6321 
6322 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
6323 {
6324 	drm_encoder_cleanup(encoder);
6325 	kfree(encoder);
6326 }
6327 
6328 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
6329 	.destroy = amdgpu_dm_encoder_destroy,
6330 };
6331 
6332 static int
6333 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
6334 			    const enum surface_pixel_format format,
6335 			    enum dc_color_space *color_space)
6336 {
6337 	bool full_range;
6338 
6339 	*color_space = COLOR_SPACE_SRGB;
6340 
6341 	/* Ignore properties when DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE is set */
6342 	if (plane_state->state && plane_state->state->plane_color_pipeline)
6343 		return 0;
6344 
6345 	/* DRM color properties only affect non-RGB formats. */
6346 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
6347 		return 0;
6348 
6349 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
6350 
6351 	switch (plane_state->color_encoding) {
6352 	case DRM_COLOR_YCBCR_BT601:
6353 		if (full_range)
6354 			*color_space = COLOR_SPACE_YCBCR601;
6355 		else
6356 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
6357 		break;
6358 
6359 	case DRM_COLOR_YCBCR_BT709:
6360 		if (full_range)
6361 			*color_space = COLOR_SPACE_YCBCR709;
6362 		else
6363 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
6364 		break;
6365 
6366 	case DRM_COLOR_YCBCR_BT2020:
6367 		if (full_range)
6368 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
6369 		else
6370 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6371 		break;
6372 
6373 	default:
6374 		return -EINVAL;
6375 	}
6376 
6377 	return 0;
6378 }
6379 
6380 static int
6381 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
6382 			    const struct drm_plane_state *plane_state,
6383 			    const u64 tiling_flags,
6384 			    struct dc_plane_info *plane_info,
6385 			    struct dc_plane_address *address,
6386 			    bool tmz_surface)
6387 {
6388 	const struct drm_framebuffer *fb = plane_state->fb;
6389 	const struct amdgpu_framebuffer *afb =
6390 		to_amdgpu_framebuffer(plane_state->fb);
6391 	int ret;
6392 
6393 	memset(plane_info, 0, sizeof(*plane_info));
6394 
6395 	switch (fb->format->format) {
6396 	case DRM_FORMAT_C8:
6397 		plane_info->format =
6398 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
6399 		break;
6400 	case DRM_FORMAT_RGB565:
6401 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
6402 		break;
6403 	case DRM_FORMAT_XRGB8888:
6404 	case DRM_FORMAT_ARGB8888:
6405 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6406 		break;
6407 	case DRM_FORMAT_XRGB2101010:
6408 	case DRM_FORMAT_ARGB2101010:
6409 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
6410 		break;
6411 	case DRM_FORMAT_XBGR2101010:
6412 	case DRM_FORMAT_ABGR2101010:
6413 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
6414 		break;
6415 	case DRM_FORMAT_XBGR8888:
6416 	case DRM_FORMAT_ABGR8888:
6417 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
6418 		break;
6419 	case DRM_FORMAT_NV21:
6420 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
6421 		break;
6422 	case DRM_FORMAT_NV12:
6423 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
6424 		break;
6425 	case DRM_FORMAT_P010:
6426 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
6427 		break;
6428 	case DRM_FORMAT_XRGB16161616F:
6429 	case DRM_FORMAT_ARGB16161616F:
6430 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
6431 		break;
6432 	case DRM_FORMAT_XBGR16161616F:
6433 	case DRM_FORMAT_ABGR16161616F:
6434 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
6435 		break;
6436 	case DRM_FORMAT_XRGB16161616:
6437 	case DRM_FORMAT_ARGB16161616:
6438 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
6439 		break;
6440 	case DRM_FORMAT_XBGR16161616:
6441 	case DRM_FORMAT_ABGR16161616:
6442 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
6443 		break;
6444 	default:
6445 		drm_err(adev_to_drm(adev),
6446 			"Unsupported screen format %p4cc\n",
6447 			&fb->format->format);
6448 		return -EINVAL;
6449 	}
6450 
6451 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
6452 	case DRM_MODE_ROTATE_0:
6453 		plane_info->rotation = ROTATION_ANGLE_0;
6454 		break;
6455 	case DRM_MODE_ROTATE_90:
6456 		plane_info->rotation = ROTATION_ANGLE_90;
6457 		break;
6458 	case DRM_MODE_ROTATE_180:
6459 		plane_info->rotation = ROTATION_ANGLE_180;
6460 		break;
6461 	case DRM_MODE_ROTATE_270:
6462 		plane_info->rotation = ROTATION_ANGLE_270;
6463 		break;
6464 	default:
6465 		plane_info->rotation = ROTATION_ANGLE_0;
6466 		break;
6467 	}
6468 
6469 
6470 	plane_info->visible = true;
6471 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
6472 
6473 	plane_info->layer_index = plane_state->normalized_zpos;
6474 
6475 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
6476 					  &plane_info->color_space);
6477 	if (ret)
6478 		return ret;
6479 
6480 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
6481 					   plane_info->rotation, tiling_flags,
6482 					   &plane_info->tiling_info,
6483 					   &plane_info->plane_size,
6484 					   &plane_info->dcc, address,
6485 					   tmz_surface);
6486 	if (ret)
6487 		return ret;
6488 
6489 	amdgpu_dm_plane_fill_blending_from_plane_state(
6490 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
6491 		&plane_info->global_alpha, &plane_info->global_alpha_value);
6492 
6493 	return 0;
6494 }
6495 
6496 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
6497 				    struct dc_plane_state *dc_plane_state,
6498 				    struct drm_plane_state *plane_state,
6499 				    struct drm_crtc_state *crtc_state)
6500 {
6501 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6502 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
6503 	struct dc_scaling_info scaling_info;
6504 	struct dc_plane_info plane_info;
6505 	int ret;
6506 
6507 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
6508 	if (ret)
6509 		return ret;
6510 
6511 	dc_plane_state->src_rect = scaling_info.src_rect;
6512 	dc_plane_state->dst_rect = scaling_info.dst_rect;
6513 	dc_plane_state->clip_rect = scaling_info.clip_rect;
6514 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
6515 
6516 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
6517 					  afb->tiling_flags,
6518 					  &plane_info,
6519 					  &dc_plane_state->address,
6520 					  afb->tmz_surface);
6521 	if (ret)
6522 		return ret;
6523 
6524 	dc_plane_state->format = plane_info.format;
6525 	dc_plane_state->color_space = plane_info.color_space;
6526 	dc_plane_state->format = plane_info.format;
6527 	dc_plane_state->plane_size = plane_info.plane_size;
6528 	dc_plane_state->rotation = plane_info.rotation;
6529 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
6530 	dc_plane_state->stereo_format = plane_info.stereo_format;
6531 	dc_plane_state->tiling_info = plane_info.tiling_info;
6532 	dc_plane_state->visible = plane_info.visible;
6533 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
6534 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
6535 	dc_plane_state->global_alpha = plane_info.global_alpha;
6536 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
6537 	dc_plane_state->dcc = plane_info.dcc;
6538 	dc_plane_state->layer_index = plane_info.layer_index;
6539 	dc_plane_state->flip_int_enabled = true;
6540 
6541 	/*
6542 	 * Always set input transfer function, since plane state is refreshed
6543 	 * every time.
6544 	 */
6545 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
6546 						plane_state,
6547 						dc_plane_state);
6548 	if (ret)
6549 		return ret;
6550 
6551 	return 0;
6552 }
6553 
6554 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
6555 				      struct rect *dirty_rect, int32_t x,
6556 				      s32 y, s32 width, s32 height,
6557 				      int *i, bool ffu)
6558 {
6559 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
6560 
6561 	dirty_rect->x = x;
6562 	dirty_rect->y = y;
6563 	dirty_rect->width = width;
6564 	dirty_rect->height = height;
6565 
6566 	if (ffu)
6567 		drm_dbg(plane->dev,
6568 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
6569 			plane->base.id, width, height);
6570 	else
6571 		drm_dbg(plane->dev,
6572 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
6573 			plane->base.id, x, y, width, height);
6574 
6575 	(*i)++;
6576 }
6577 
6578 /**
6579  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
6580  *
6581  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
6582  *         remote fb
6583  * @old_plane_state: Old state of @plane
6584  * @new_plane_state: New state of @plane
6585  * @crtc_state: New state of CRTC connected to the @plane
6586  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
6587  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
6588  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
6589  *             that have changed will be updated. If PSR SU is not enabled,
6590  *             or if damage clips are not available, the entire screen will be updated.
6591  * @dirty_regions_changed: dirty regions changed
6592  *
6593  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
6594  * (referred to as "damage clips" in DRM nomenclature) that require updating on
6595  * the eDP remote buffer. The responsibility of specifying the dirty regions is
6596  * amdgpu_dm's.
6597  *
6598  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
6599  * plane with regions that require flushing to the eDP remote buffer. In
6600  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
6601  * implicitly provide damage clips without any client support via the plane
6602  * bounds.
6603  */
6604 static void fill_dc_dirty_rects(struct drm_plane *plane,
6605 				struct drm_plane_state *old_plane_state,
6606 				struct drm_plane_state *new_plane_state,
6607 				struct drm_crtc_state *crtc_state,
6608 				struct dc_flip_addrs *flip_addrs,
6609 				bool is_psr_su,
6610 				bool *dirty_regions_changed)
6611 {
6612 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6613 	struct rect *dirty_rects = flip_addrs->dirty_rects;
6614 	u32 num_clips;
6615 	struct drm_mode_rect *clips;
6616 	bool bb_changed;
6617 	bool fb_changed;
6618 	u32 i = 0;
6619 	*dirty_regions_changed = false;
6620 
6621 	/*
6622 	 * Cursor plane has it's own dirty rect update interface. See
6623 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
6624 	 */
6625 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
6626 		return;
6627 
6628 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
6629 		goto ffu;
6630 
6631 	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
6632 	clips = drm_plane_get_damage_clips(new_plane_state);
6633 
6634 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
6635 						   is_psr_su)))
6636 		goto ffu;
6637 
6638 	if (!dm_crtc_state->mpo_requested) {
6639 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
6640 			goto ffu;
6641 
6642 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
6643 			fill_dc_dirty_rect(new_plane_state->plane,
6644 					   &dirty_rects[flip_addrs->dirty_rect_count],
6645 					   clips->x1, clips->y1,
6646 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
6647 					   &flip_addrs->dirty_rect_count,
6648 					   false);
6649 		return;
6650 	}
6651 
6652 	/*
6653 	 * MPO is requested. Add entire plane bounding box to dirty rects if
6654 	 * flipped to or damaged.
6655 	 *
6656 	 * If plane is moved or resized, also add old bounding box to dirty
6657 	 * rects.
6658 	 */
6659 	fb_changed = old_plane_state->fb->base.id !=
6660 		     new_plane_state->fb->base.id;
6661 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
6662 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
6663 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
6664 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
6665 
6666 	drm_dbg(plane->dev,
6667 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
6668 		new_plane_state->plane->base.id,
6669 		bb_changed, fb_changed, num_clips);
6670 
6671 	*dirty_regions_changed = bb_changed;
6672 
6673 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
6674 		goto ffu;
6675 
6676 	if (bb_changed) {
6677 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6678 				   new_plane_state->crtc_x,
6679 				   new_plane_state->crtc_y,
6680 				   new_plane_state->crtc_w,
6681 				   new_plane_state->crtc_h, &i, false);
6682 
6683 		/* Add old plane bounding-box if plane is moved or resized */
6684 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6685 				   old_plane_state->crtc_x,
6686 				   old_plane_state->crtc_y,
6687 				   old_plane_state->crtc_w,
6688 				   old_plane_state->crtc_h, &i, false);
6689 	}
6690 
6691 	if (num_clips) {
6692 		for (; i < num_clips; clips++)
6693 			fill_dc_dirty_rect(new_plane_state->plane,
6694 					   &dirty_rects[i], clips->x1,
6695 					   clips->y1, clips->x2 - clips->x1,
6696 					   clips->y2 - clips->y1, &i, false);
6697 	} else if (fb_changed && !bb_changed) {
6698 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6699 				   new_plane_state->crtc_x,
6700 				   new_plane_state->crtc_y,
6701 				   new_plane_state->crtc_w,
6702 				   new_plane_state->crtc_h, &i, false);
6703 	}
6704 
6705 	flip_addrs->dirty_rect_count = i;
6706 	return;
6707 
6708 ffu:
6709 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
6710 			   dm_crtc_state->base.mode.crtc_hdisplay,
6711 			   dm_crtc_state->base.mode.crtc_vdisplay,
6712 			   &flip_addrs->dirty_rect_count, true);
6713 }
6714 
6715 static void update_stream_scaling_settings(struct drm_device *dev,
6716 					   const struct drm_display_mode *mode,
6717 					   const struct dm_connector_state *dm_state,
6718 					   struct dc_stream_state *stream)
6719 {
6720 	enum amdgpu_rmx_type rmx_type;
6721 
6722 	struct rect src = { 0 }; /* viewport in composition space*/
6723 	struct rect dst = { 0 }; /* stream addressable area */
6724 
6725 	/* no mode. nothing to be done */
6726 	if (!mode)
6727 		return;
6728 
6729 	/* Full screen scaling by default */
6730 	src.width = mode->hdisplay;
6731 	src.height = mode->vdisplay;
6732 	dst.width = stream->timing.h_addressable;
6733 	dst.height = stream->timing.v_addressable;
6734 
6735 	if (dm_state) {
6736 		rmx_type = dm_state->scaling;
6737 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
6738 			if (src.width * dst.height <
6739 					src.height * dst.width) {
6740 				/* height needs less upscaling/more downscaling */
6741 				dst.width = src.width *
6742 						dst.height / src.height;
6743 			} else {
6744 				/* width needs less upscaling/more downscaling */
6745 				dst.height = src.height *
6746 						dst.width / src.width;
6747 			}
6748 		} else if (rmx_type == RMX_CENTER) {
6749 			dst = src;
6750 		}
6751 
6752 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
6753 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
6754 
6755 		if (dm_state->underscan_enable) {
6756 			dst.x += dm_state->underscan_hborder / 2;
6757 			dst.y += dm_state->underscan_vborder / 2;
6758 			dst.width -= dm_state->underscan_hborder;
6759 			dst.height -= dm_state->underscan_vborder;
6760 		}
6761 	}
6762 
6763 	stream->src = src;
6764 	stream->dst = dst;
6765 
6766 	drm_dbg_kms(dev, "Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
6767 		    dst.x, dst.y, dst.width, dst.height);
6768 
6769 }
6770 
6771 static enum dc_color_depth
6772 convert_color_depth_from_display_info(const struct drm_connector *connector,
6773 				      bool is_y420, int requested_bpc)
6774 {
6775 	u8 bpc;
6776 
6777 	if (is_y420) {
6778 		bpc = 8;
6779 
6780 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
6781 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
6782 			bpc = 16;
6783 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
6784 			bpc = 12;
6785 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
6786 			bpc = 10;
6787 	} else {
6788 		bpc = (uint8_t)connector->display_info.bpc;
6789 		/* Assume 8 bpc by default if no bpc is specified. */
6790 		bpc = bpc ? bpc : 8;
6791 	}
6792 
6793 	if (requested_bpc > 0) {
6794 		/*
6795 		 * Cap display bpc based on the user requested value.
6796 		 *
6797 		 * The value for state->max_bpc may not correctly updated
6798 		 * depending on when the connector gets added to the state
6799 		 * or if this was called outside of atomic check, so it
6800 		 * can't be used directly.
6801 		 */
6802 		bpc = min_t(u8, bpc, requested_bpc);
6803 
6804 		/* Round down to the nearest even number. */
6805 		bpc = bpc - (bpc & 1);
6806 	}
6807 
6808 	switch (bpc) {
6809 	case 0:
6810 		/*
6811 		 * Temporary Work around, DRM doesn't parse color depth for
6812 		 * EDID revision before 1.4
6813 		 * TODO: Fix edid parsing
6814 		 */
6815 		return COLOR_DEPTH_888;
6816 	case 6:
6817 		return COLOR_DEPTH_666;
6818 	case 8:
6819 		return COLOR_DEPTH_888;
6820 	case 10:
6821 		return COLOR_DEPTH_101010;
6822 	case 12:
6823 		return COLOR_DEPTH_121212;
6824 	case 14:
6825 		return COLOR_DEPTH_141414;
6826 	case 16:
6827 		return COLOR_DEPTH_161616;
6828 	default:
6829 		return COLOR_DEPTH_UNDEFINED;
6830 	}
6831 }
6832 
6833 static enum dc_aspect_ratio
6834 get_aspect_ratio(const struct drm_display_mode *mode_in)
6835 {
6836 	/* 1-1 mapping, since both enums follow the HDMI spec. */
6837 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
6838 }
6839 
6840 static enum dc_color_space
6841 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
6842 		       const struct drm_connector_state *connector_state)
6843 {
6844 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
6845 
6846 	switch (connector_state->colorspace) {
6847 	case DRM_MODE_COLORIMETRY_BT601_YCC:
6848 		if (dc_crtc_timing->flags.Y_ONLY)
6849 			color_space = COLOR_SPACE_YCBCR601_LIMITED;
6850 		else
6851 			color_space = COLOR_SPACE_YCBCR601;
6852 		break;
6853 	case DRM_MODE_COLORIMETRY_BT709_YCC:
6854 		if (dc_crtc_timing->flags.Y_ONLY)
6855 			color_space = COLOR_SPACE_YCBCR709_LIMITED;
6856 		else
6857 			color_space = COLOR_SPACE_YCBCR709;
6858 		break;
6859 	case DRM_MODE_COLORIMETRY_OPRGB:
6860 		color_space = COLOR_SPACE_ADOBERGB;
6861 		break;
6862 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
6863 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
6864 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
6865 			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
6866 		else
6867 			color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6868 		break;
6869 	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
6870 	default:
6871 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
6872 			color_space = COLOR_SPACE_SRGB;
6873 			if (connector_state->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_LIMITED)
6874 				color_space = COLOR_SPACE_SRGB_LIMITED;
6875 		/*
6876 		 * 27030khz is the separation point between HDTV and SDTV
6877 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
6878 		 * respectively
6879 		 */
6880 		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
6881 			if (dc_crtc_timing->flags.Y_ONLY)
6882 				color_space =
6883 					COLOR_SPACE_YCBCR709_LIMITED;
6884 			else
6885 				color_space = COLOR_SPACE_YCBCR709;
6886 		} else {
6887 			if (dc_crtc_timing->flags.Y_ONLY)
6888 				color_space =
6889 					COLOR_SPACE_YCBCR601_LIMITED;
6890 			else
6891 				color_space = COLOR_SPACE_YCBCR601;
6892 		}
6893 		break;
6894 	}
6895 
6896 	return color_space;
6897 }
6898 
6899 static enum display_content_type
6900 get_output_content_type(const struct drm_connector_state *connector_state)
6901 {
6902 	switch (connector_state->content_type) {
6903 	default:
6904 	case DRM_MODE_CONTENT_TYPE_NO_DATA:
6905 		return DISPLAY_CONTENT_TYPE_NO_DATA;
6906 	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
6907 		return DISPLAY_CONTENT_TYPE_GRAPHICS;
6908 	case DRM_MODE_CONTENT_TYPE_PHOTO:
6909 		return DISPLAY_CONTENT_TYPE_PHOTO;
6910 	case DRM_MODE_CONTENT_TYPE_CINEMA:
6911 		return DISPLAY_CONTENT_TYPE_CINEMA;
6912 	case DRM_MODE_CONTENT_TYPE_GAME:
6913 		return DISPLAY_CONTENT_TYPE_GAME;
6914 	}
6915 }
6916 
6917 static bool adjust_colour_depth_from_display_info(
6918 	struct dc_crtc_timing *timing_out,
6919 	const struct drm_display_info *info)
6920 {
6921 	enum dc_color_depth depth = timing_out->display_color_depth;
6922 	int normalized_clk;
6923 
6924 	do {
6925 		normalized_clk = timing_out->pix_clk_100hz / 10;
6926 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
6927 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
6928 			normalized_clk /= 2;
6929 		/* Adjusting pix clock following on HDMI spec based on colour depth */
6930 		switch (depth) {
6931 		case COLOR_DEPTH_888:
6932 			break;
6933 		case COLOR_DEPTH_101010:
6934 			normalized_clk = (normalized_clk * 30) / 24;
6935 			break;
6936 		case COLOR_DEPTH_121212:
6937 			normalized_clk = (normalized_clk * 36) / 24;
6938 			break;
6939 		case COLOR_DEPTH_161616:
6940 			normalized_clk = (normalized_clk * 48) / 24;
6941 			break;
6942 		default:
6943 			/* The above depths are the only ones valid for HDMI. */
6944 			return false;
6945 		}
6946 		if (normalized_clk <= info->max_tmds_clock) {
6947 			timing_out->display_color_depth = depth;
6948 			return true;
6949 		}
6950 	} while (--depth > COLOR_DEPTH_666);
6951 	return false;
6952 }
6953 
6954 static void fill_stream_properties_from_drm_display_mode(
6955 	struct dc_stream_state *stream,
6956 	const struct drm_display_mode *mode_in,
6957 	const struct drm_connector *connector,
6958 	const struct drm_connector_state *connector_state,
6959 	const struct dc_stream_state *old_stream,
6960 	int requested_bpc)
6961 {
6962 	struct dc_crtc_timing *timing_out = &stream->timing;
6963 	const struct drm_display_info *info = &connector->display_info;
6964 	struct amdgpu_dm_connector *aconnector = NULL;
6965 	struct hdmi_vendor_infoframe hv_frame;
6966 	struct hdmi_avi_infoframe avi_frame;
6967 	ssize_t err;
6968 
6969 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
6970 		aconnector = to_amdgpu_dm_connector(connector);
6971 
6972 	memset(&hv_frame, 0, sizeof(hv_frame));
6973 	memset(&avi_frame, 0, sizeof(avi_frame));
6974 
6975 	timing_out->h_border_left = 0;
6976 	timing_out->h_border_right = 0;
6977 	timing_out->v_border_top = 0;
6978 	timing_out->v_border_bottom = 0;
6979 	/* TODO: un-hardcode */
6980 	if (drm_mode_is_420_only(info, mode_in)
6981 			&& (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
6982 			    stream->signal == SIGNAL_TYPE_HDMI_FRL)
6983 			&& aconnector
6984 			&& aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR420)
6985 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6986 	else if (drm_mode_is_420_also(info, mode_in)
6987 			&& aconnector
6988 			&& (aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR420
6989 			|| aconnector->force_yuv420_output))
6990 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6991 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR422))
6992 			&& aconnector
6993 			&& (aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR422
6994 			|| aconnector->force_yuv422_output))
6995 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR422;
6996 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR444))
6997 			&& (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
6998 			    stream->signal == SIGNAL_TYPE_HDMI_FRL)
6999 			&& aconnector
7000 			&& aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR444)
7001 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
7002 	else
7003 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
7004 
7005 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
7006 	timing_out->display_color_depth = convert_color_depth_from_display_info(
7007 		connector,
7008 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
7009 		requested_bpc);
7010 	timing_out->scan_type = SCANNING_TYPE_NODATA;
7011 	timing_out->hdmi_vic = 0;
7012 
7013 	if (old_stream) {
7014 		timing_out->vic = old_stream->timing.vic;
7015 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
7016 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
7017 	} else {
7018 		timing_out->vic = drm_match_cea_mode(mode_in);
7019 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
7020 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
7021 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
7022 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
7023 	}
7024 
7025 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7026 		stream->signal == SIGNAL_TYPE_HDMI_FRL) {
7027 		err = drm_hdmi_avi_infoframe_from_display_mode(&avi_frame,
7028 							       (struct drm_connector *)connector,
7029 							       mode_in);
7030 		if (err < 0)
7031 			drm_warn_once(connector->dev, "Failed to setup avi infoframe on connector %s: %zd\n",
7032 				      connector->name, err);
7033 		timing_out->vic = avi_frame.video_code;
7034 		err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame,
7035 								  (struct drm_connector *)connector,
7036 								  mode_in);
7037 		if (err < 0)
7038 			drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n",
7039 				      connector->name, err);
7040 		timing_out->hdmi_vic = hv_frame.vic;
7041 	}
7042 
7043 	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
7044 		timing_out->h_addressable = mode_in->hdisplay;
7045 		timing_out->h_total = mode_in->htotal;
7046 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
7047 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
7048 		timing_out->v_total = mode_in->vtotal;
7049 		timing_out->v_addressable = mode_in->vdisplay;
7050 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
7051 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
7052 		timing_out->pix_clk_100hz = mode_in->clock * 10;
7053 	} else {
7054 		timing_out->h_addressable = mode_in->crtc_hdisplay;
7055 		timing_out->h_total = mode_in->crtc_htotal;
7056 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
7057 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
7058 		timing_out->v_total = mode_in->crtc_vtotal;
7059 		timing_out->v_addressable = mode_in->crtc_vdisplay;
7060 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
7061 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
7062 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
7063 	}
7064 
7065 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
7066 
7067 	stream->out_transfer_func.type = TF_TYPE_PREDEFINED;
7068 	stream->out_transfer_func.tf = TRANSFER_FUNCTION_SRGB;
7069 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
7070 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
7071 		    drm_mode_is_420_also(info, mode_in) &&
7072 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
7073 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
7074 			adjust_colour_depth_from_display_info(timing_out, info);
7075 		}
7076 	}
7077 
7078 	stream->output_color_space = get_output_color_space(timing_out, connector_state);
7079 	stream->content_type = get_output_content_type(connector_state);
7080 }
7081 
7082 static void fill_audio_info(struct audio_info *audio_info,
7083 			    const struct drm_connector *drm_connector,
7084 			    const struct dc_sink *dc_sink)
7085 {
7086 	int i = 0;
7087 	int cea_revision = 0;
7088 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
7089 
7090 	audio_info->manufacture_id = edid_caps->manufacturer_id;
7091 	audio_info->product_id = edid_caps->product_id;
7092 
7093 	cea_revision = drm_connector->display_info.cea_rev;
7094 
7095 	strscpy(audio_info->display_name,
7096 		edid_caps->display_name,
7097 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
7098 
7099 	if (cea_revision >= 3) {
7100 		audio_info->mode_count = edid_caps->audio_mode_count;
7101 
7102 		for (i = 0; i < audio_info->mode_count; ++i) {
7103 			audio_info->modes[i].format_code =
7104 					(enum audio_format_code)
7105 					(edid_caps->audio_modes[i].format_code);
7106 			audio_info->modes[i].channel_count =
7107 					edid_caps->audio_modes[i].channel_count;
7108 			audio_info->modes[i].sample_rates.all =
7109 					edid_caps->audio_modes[i].sample_rate;
7110 			audio_info->modes[i].sample_size =
7111 					edid_caps->audio_modes[i].sample_size;
7112 		}
7113 	}
7114 
7115 	audio_info->flags.all = edid_caps->speaker_flags;
7116 
7117 	/* TODO: We only check for the progressive mode, check for interlace mode too */
7118 	if (drm_connector->latency_present[0]) {
7119 		audio_info->video_latency = drm_connector->video_latency[0];
7120 		audio_info->audio_latency = drm_connector->audio_latency[0];
7121 	}
7122 
7123 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
7124 
7125 }
7126 
7127 static void
7128 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
7129 				      struct drm_display_mode *dst_mode)
7130 {
7131 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
7132 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
7133 	dst_mode->crtc_clock = src_mode->crtc_clock;
7134 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
7135 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
7136 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
7137 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
7138 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
7139 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
7140 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
7141 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
7142 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
7143 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
7144 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
7145 }
7146 
7147 static void
7148 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
7149 					const struct drm_display_mode *native_mode,
7150 					bool scale_enabled)
7151 {
7152 	if (scale_enabled || (
7153 	    native_mode->clock == drm_mode->clock &&
7154 	    native_mode->htotal == drm_mode->htotal &&
7155 	    native_mode->vtotal == drm_mode->vtotal)) {
7156 		if (native_mode->crtc_clock)
7157 			copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
7158 	} else {
7159 		/* no scaling nor amdgpu inserted, no need to patch */
7160 	}
7161 }
7162 
7163 static struct dc_sink *
7164 create_fake_sink(struct drm_device *dev, struct dc_link *link)
7165 {
7166 	struct dc_sink_init_data sink_init_data = { 0 };
7167 	struct dc_sink *sink = NULL;
7168 
7169 	sink_init_data.link = link;
7170 	sink_init_data.sink_signal = link->connector_signal;
7171 
7172 	sink = dc_sink_create(&sink_init_data);
7173 	if (!sink) {
7174 		drm_err(dev, "Failed to create sink!\n");
7175 		return NULL;
7176 	}
7177 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
7178 
7179 	return sink;
7180 }
7181 
7182 static void set_multisync_trigger_params(
7183 		struct dc_stream_state *stream)
7184 {
7185 	struct dc_stream_state *master = NULL;
7186 
7187 	if (stream->triggered_crtc_reset.enabled) {
7188 		master = stream->triggered_crtc_reset.event_source;
7189 		stream->triggered_crtc_reset.event =
7190 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
7191 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
7192 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
7193 	}
7194 }
7195 
7196 static void set_master_stream(struct dc_stream_state *stream_set[],
7197 			      int stream_count)
7198 {
7199 	int j, highest_rfr = 0, master_stream = 0;
7200 
7201 	for (j = 0;  j < stream_count; j++) {
7202 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
7203 			int refresh_rate = 0;
7204 
7205 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
7206 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
7207 			if (refresh_rate > highest_rfr) {
7208 				highest_rfr = refresh_rate;
7209 				master_stream = j;
7210 			}
7211 		}
7212 	}
7213 	for (j = 0;  j < stream_count; j++) {
7214 		if (stream_set[j])
7215 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
7216 	}
7217 }
7218 
7219 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
7220 {
7221 	int i = 0;
7222 	struct dc_stream_state *stream;
7223 
7224 	if (context->stream_count < 2)
7225 		return;
7226 	for (i = 0; i < context->stream_count ; i++) {
7227 		if (!context->streams[i])
7228 			continue;
7229 		/*
7230 		 * TODO: add a function to read AMD VSDB bits and set
7231 		 * crtc_sync_master.multi_sync_enabled flag
7232 		 * For now it's set to false
7233 		 */
7234 	}
7235 
7236 	set_master_stream(context->streams, context->stream_count);
7237 
7238 	for (i = 0; i < context->stream_count ; i++) {
7239 		stream = context->streams[i];
7240 
7241 		if (!stream)
7242 			continue;
7243 
7244 		set_multisync_trigger_params(stream);
7245 	}
7246 }
7247 
7248 /**
7249  * DOC: FreeSync Video
7250  *
7251  * When a userspace application wants to play a video, the content follows a
7252  * standard format definition that usually specifies the FPS for that format.
7253  * The below list illustrates some video format and the expected FPS,
7254  * respectively:
7255  *
7256  * - TV/NTSC (23.976 FPS)
7257  * - Cinema (24 FPS)
7258  * - TV/PAL (25 FPS)
7259  * - TV/NTSC (29.97 FPS)
7260  * - TV/NTSC (30 FPS)
7261  * - Cinema HFR (48 FPS)
7262  * - TV/PAL (50 FPS)
7263  * - Commonly used (60 FPS)
7264  * - Multiples of 24 (48,72,96 FPS)
7265  *
7266  * The list of standards video format is not huge and can be added to the
7267  * connector modeset list beforehand. With that, userspace can leverage
7268  * FreeSync to extends the front porch in order to attain the target refresh
7269  * rate. Such a switch will happen seamlessly, without screen blanking or
7270  * reprogramming of the output in any other way. If the userspace requests a
7271  * modesetting change compatible with FreeSync modes that only differ in the
7272  * refresh rate, DC will skip the full update and avoid blink during the
7273  * transition. For example, the video player can change the modesetting from
7274  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
7275  * causing any display blink. This same concept can be applied to a mode
7276  * setting change.
7277  */
7278 static struct drm_display_mode *
7279 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
7280 		bool use_probed_modes)
7281 {
7282 	struct drm_display_mode *m, *m_pref = NULL;
7283 	u16 current_refresh, highest_refresh;
7284 	struct list_head *list_head = use_probed_modes ?
7285 		&aconnector->base.probed_modes :
7286 		&aconnector->base.modes;
7287 
7288 	if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
7289 		return NULL;
7290 
7291 	if (aconnector->freesync_vid_base.clock != 0)
7292 		return &aconnector->freesync_vid_base;
7293 
7294 	/* Find the preferred mode */
7295 	list_for_each_entry(m, list_head, head) {
7296 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
7297 			m_pref = m;
7298 			break;
7299 		}
7300 	}
7301 
7302 	if (!m_pref) {
7303 		/* Probably an EDID with no preferred mode. Fallback to first entry */
7304 		m_pref = list_first_entry_or_null(
7305 				&aconnector->base.modes, struct drm_display_mode, head);
7306 		if (!m_pref) {
7307 			drm_dbg_driver(aconnector->base.dev, "No preferred mode found in EDID\n");
7308 			return NULL;
7309 		}
7310 	}
7311 
7312 	highest_refresh = drm_mode_vrefresh(m_pref);
7313 
7314 	/*
7315 	 * Find the mode with highest refresh rate with same resolution.
7316 	 * For some monitors, preferred mode is not the mode with highest
7317 	 * supported refresh rate.
7318 	 */
7319 	list_for_each_entry(m, list_head, head) {
7320 		current_refresh  = drm_mode_vrefresh(m);
7321 
7322 		if (m->hdisplay == m_pref->hdisplay &&
7323 		    m->vdisplay == m_pref->vdisplay &&
7324 		    highest_refresh < current_refresh) {
7325 			highest_refresh = current_refresh;
7326 			m_pref = m;
7327 		}
7328 	}
7329 
7330 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
7331 	return m_pref;
7332 }
7333 
7334 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
7335 		struct amdgpu_dm_connector *aconnector)
7336 {
7337 	struct drm_display_mode *high_mode;
7338 	int timing_diff;
7339 
7340 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
7341 	if (!high_mode || !mode)
7342 		return false;
7343 
7344 	timing_diff = high_mode->vtotal - mode->vtotal;
7345 
7346 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
7347 	    high_mode->hdisplay != mode->hdisplay ||
7348 	    high_mode->vdisplay != mode->vdisplay ||
7349 	    high_mode->hsync_start != mode->hsync_start ||
7350 	    high_mode->hsync_end != mode->hsync_end ||
7351 	    high_mode->htotal != mode->htotal ||
7352 	    high_mode->hskew != mode->hskew ||
7353 	    high_mode->vscan != mode->vscan ||
7354 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
7355 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
7356 		return false;
7357 	else
7358 		return true;
7359 }
7360 
7361 #if defined(CONFIG_DRM_AMD_DC_FP)
7362 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
7363 			    struct dc_sink *sink, struct dc_stream_state *stream,
7364 			    struct dsc_dec_dpcd_caps *dsc_caps)
7365 {
7366 	stream->timing.flags.DSC = 0;
7367 	dsc_caps->is_dsc_supported = false;
7368 
7369 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
7370 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
7371 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE)
7372 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7373 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7374 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7375 				dsc_caps);
7376 		else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7377 			if (aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.fields.dsc_support.DSC_PASSTHROUGH_SUPPORT &&
7378 					!aconnector->dsc_settings.dsc_force_disable_passthrough &&
7379 					aconnector->dc_link->dpcd_caps.dongle_caps.dp_hdmi_frl_max_link_bw_in_kbps > 0 &&
7380 					sink->edid_caps.frl_dsc_support &&
7381 					sink->edid_caps.max_frl_rate > 0 &&
7382 					sink->edid_caps.frl_dsc_max_frl_rate > 0)
7383 				dc_dsc_parse_dsc_edid(aconnector->dc_link->ctx->dc, &sink->edid_caps, dsc_caps);
7384 			else
7385 				dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7386 				      aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7387 				      aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7388 				      dsc_caps);
7389 		}
7390 	} else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_HDMI_FRL) {
7391 		if (sink->edid_caps.frl_dsc_support &&
7392 				sink->edid_caps.max_frl_rate > 0 &&
7393 				sink->edid_caps.frl_dsc_max_frl_rate > 0)
7394 			dc_dsc_parse_dsc_edid(aconnector->dc_link->ctx->dc, &sink->edid_caps, dsc_caps);
7395 	}
7396 }
7397 
7398 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
7399 				    struct dc_sink *sink, struct dc_stream_state *stream,
7400 				    struct dsc_dec_dpcd_caps *dsc_caps,
7401 				    uint32_t max_dsc_target_bpp_limit_override)
7402 {
7403 	const struct dc_link_settings *verified_link_cap = NULL;
7404 	u32 link_bw_in_kbps;
7405 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
7406 	struct dc *dc = sink->ctx->dc;
7407 	struct dc_dsc_bw_range bw_range = {0};
7408 	struct dc_dsc_config dsc_cfg = {0};
7409 	struct dc_dsc_config_options dsc_options = {0};
7410 
7411 	dc_dsc_get_default_config_option(dc, &dsc_options);
7412 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7413 
7414 	verified_link_cap = dc_link_get_link_cap(stream->link);
7415 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
7416 	edp_min_bpp_x16 = 8 * 16;
7417 	edp_max_bpp_x16 = 8 * 16;
7418 
7419 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
7420 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
7421 
7422 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
7423 		edp_min_bpp_x16 = edp_max_bpp_x16;
7424 
7425 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
7426 				dc->debug.dsc_min_slice_height_override,
7427 				edp_min_bpp_x16, edp_max_bpp_x16,
7428 				dsc_caps,
7429 				&stream->timing,
7430 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7431 				&bw_range)) {
7432 
7433 		if (bw_range.max_kbps < link_bw_in_kbps) {
7434 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7435 					dsc_caps,
7436 					&dsc_options,
7437 					0,
7438 					&stream->timing,
7439 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7440 					&dsc_cfg)) {
7441 				stream->timing.dsc_cfg = dsc_cfg;
7442 				stream->timing.flags.DSC = 1;
7443 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
7444 			}
7445 			return;
7446 		}
7447 	}
7448 
7449 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7450 				dsc_caps,
7451 				&dsc_options,
7452 				link_bw_in_kbps,
7453 				&stream->timing,
7454 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7455 				&dsc_cfg)) {
7456 		stream->timing.dsc_cfg = dsc_cfg;
7457 		stream->timing.flags.DSC = 1;
7458 	}
7459 }
7460 
7461 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
7462 					struct dc_sink *sink, struct dc_stream_state *stream,
7463 					struct dsc_dec_dpcd_caps *dsc_caps)
7464 {
7465 	struct drm_connector *drm_connector = &aconnector->base;
7466 	u32 link_bandwidth_kbps;
7467 	struct dc *dc = sink->ctx->dc;
7468 	const struct dc_hdmi_frl_link_settings *frl_verified_link_cap = NULL;
7469 	u32 converter_bw_in_kbps;
7470 	u32 sink_bw_in_kbps;
7471 	u32 dsc_sink_bw_in_kbps;
7472 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
7473 	u32 dsc_max_supported_bw_in_kbps;
7474 	u32 max_dsc_target_bpp_limit_override =
7475 		drm_connector->display_info.max_dsc_bpp;
7476 	struct dc_dsc_config_options dsc_options = {0};
7477 
7478 	dc_dsc_get_default_config_option(dc, &dsc_options);
7479 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7480 
7481 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
7482 							dc_link_get_link_cap(aconnector->dc_link));
7483 
7484 	/* Set DSC policy according to dsc_clock_en */
7485 	dc_dsc_policy_set_enable_dsc_when_not_needed(
7486 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
7487 
7488 	if (sink->sink_signal == SIGNAL_TYPE_EDP &&
7489 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
7490 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
7491 
7492 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
7493 
7494 	} else if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
7495 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
7496 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7497 						dsc_caps,
7498 						&dsc_options,
7499 						link_bandwidth_kbps,
7500 						&stream->timing,
7501 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7502 						&stream->timing.dsc_cfg)) {
7503 				stream->timing.flags.DSC = 1;
7504 				drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from SST RX\n",
7505 							__func__, drm_connector->name);
7506 			}
7507 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7508 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
7509 					dc_link_get_highest_encoding_format(aconnector->dc_link));
7510 			converter_bw_in_kbps = aconnector->dc_link->dpcd_caps.dongle_caps.dp_hdmi_frl_max_link_bw_in_kbps;
7511 			sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.max_frl_rate);
7512 			dsc_sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.frl_dsc_max_frl_rate);
7513 
7514 			if (dsc_caps->is_frl) {
7515 				max_supported_bw_in_kbps = min(link_bandwidth_kbps, converter_bw_in_kbps);
7516 				max_supported_bw_in_kbps = min(max_supported_bw_in_kbps, sink_bw_in_kbps);
7517 				dsc_max_supported_bw_in_kbps = min(max_supported_bw_in_kbps, dsc_sink_bw_in_kbps);
7518 			} else {
7519 				max_supported_bw_in_kbps = link_bandwidth_kbps;
7520 				dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
7521 			}
7522 
7523 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
7524 					max_supported_bw_in_kbps > 0 &&
7525 					dsc_max_supported_bw_in_kbps > 0)
7526 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7527 						dsc_caps,
7528 						&dsc_options,
7529 						dsc_max_supported_bw_in_kbps,
7530 						&stream->timing,
7531 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7532 						&stream->timing.dsc_cfg)) {
7533 					stream->timing.flags.DSC = 1;
7534 					drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from %s\n",
7535 							__func__, drm_connector->name,
7536 							(dsc_caps->is_frl == 1) ? "HDMI FRL RX" : "DP-HDMI PCON");
7537 				}
7538 		}
7539 	}
7540 	else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_HDMI_FRL) {
7541 		struct dc_dsc_policy dsc_policy = {0};
7542 
7543 		frl_verified_link_cap = dc_link_get_frl_link_cap(stream->link);
7544 		if (frl_verified_link_cap->frl_link_rate != HDMI_FRL_LINK_RATE_DISABLE &&
7545 			aconnector->dc_link->frl_flags.force_frl_dsc) {
7546 			dc_dsc_policy_set_enable_dsc_when_not_needed(true);
7547 			dc_dsc_get_policy_for_timing(&stream->timing, 0, &dsc_policy, dc_link_get_highest_encoding_format(stream->link));
7548 		}
7549 
7550 		timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing, DC_LINK_ENCODING_HDMI_FRL);
7551 		link_bandwidth_kbps = dc_link_frl_bandwidth_kbps(stream->link, frl_verified_link_cap->frl_link_rate);
7552 		dsc_sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.frl_dsc_max_frl_rate);
7553 
7554 		if ((timing_bw_in_kbps > link_bandwidth_kbps && dsc_sink_bw_in_kbps > 0) ||
7555 		    (dsc_policy.enable_dsc_when_not_needed || dsc_options.force_dsc_when_not_needed)) {
7556 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7557 					dsc_caps,
7558 					&dsc_options,
7559 					dsc_sink_bw_in_kbps,
7560 					&stream->timing,
7561 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7562 					&stream->timing.dsc_cfg)) {
7563 				stream->timing.flags.DSC = 1;
7564 				drm_dbg_driver(drm_connector->dev, "%s: HDMI_FRL_DSC [%s] DSC is selected from HDMI FRL RX\n",
7565 						__func__, drm_connector->name);
7566 			}
7567 		}
7568 	}
7569 
7570 	/* Overwrite the stream flag if DSC is enabled through debugfs */
7571 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
7572 		stream->timing.flags.DSC = 1;
7573 
7574 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
7575 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
7576 
7577 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
7578 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
7579 
7580 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
7581 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
7582 }
7583 #endif
7584 
7585 static struct dc_stream_state *
7586 create_stream_for_sink(struct drm_connector *connector,
7587 		       const struct drm_display_mode *drm_mode,
7588 		       const struct dm_connector_state *dm_state,
7589 		       const struct dc_stream_state *old_stream,
7590 		       int requested_bpc)
7591 {
7592 	struct drm_device *dev = connector->dev;
7593 	struct amdgpu_dm_connector *aconnector = NULL;
7594 	struct drm_display_mode *preferred_mode = NULL;
7595 	const struct drm_connector_state *con_state = &dm_state->base;
7596 	struct dc_stream_state *stream = NULL;
7597 	struct drm_display_mode mode;
7598 	struct drm_display_mode saved_mode;
7599 	struct drm_display_mode *freesync_mode = NULL;
7600 	bool native_mode_found = false;
7601 	bool recalculate_timing = false;
7602 	bool scale = dm_state->scaling != RMX_OFF;
7603 	int mode_refresh;
7604 	int preferred_refresh = 0;
7605 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
7606 #if defined(CONFIG_DRM_AMD_DC_FP)
7607 	struct dsc_dec_dpcd_caps dsc_caps = {0};
7608 #endif
7609 	struct dc_link *link = NULL;
7610 	struct dc_sink *sink = NULL;
7611 
7612 	drm_mode_init(&mode, drm_mode);
7613 	memset(&saved_mode, 0, sizeof(saved_mode));
7614 
7615 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK) {
7616 		aconnector = NULL;
7617 		aconnector = to_amdgpu_dm_connector(connector);
7618 		link = aconnector->dc_link;
7619 	} else {
7620 		struct drm_writeback_connector *wbcon = NULL;
7621 		struct amdgpu_dm_wb_connector *dm_wbcon = NULL;
7622 
7623 		wbcon = drm_connector_to_writeback(connector);
7624 		dm_wbcon = to_amdgpu_dm_wb_connector(wbcon);
7625 		link = dm_wbcon->link;
7626 	}
7627 
7628 	if (!aconnector || !aconnector->dc_sink) {
7629 		sink = create_fake_sink(dev, link);
7630 		if (!sink)
7631 			return stream;
7632 
7633 	} else {
7634 		sink = aconnector->dc_sink;
7635 		dc_sink_retain(sink);
7636 	}
7637 
7638 	stream = dc_create_stream_for_sink(sink);
7639 
7640 	if (stream == NULL) {
7641 		drm_err(dev, "Failed to create stream for sink!\n");
7642 		goto finish;
7643 	}
7644 
7645 	/* We leave this NULL for writeback connectors */
7646 	stream->dm_stream_context = aconnector;
7647 
7648 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
7649 		connector->display_info.hdmi.scdc.scrambling.low_rates;
7650 
7651 	list_for_each_entry(preferred_mode, &connector->modes, head) {
7652 		/* Search for preferred mode */
7653 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
7654 			native_mode_found = true;
7655 			break;
7656 		}
7657 	}
7658 	if (!native_mode_found)
7659 		preferred_mode = list_first_entry_or_null(
7660 				&connector->modes,
7661 				struct drm_display_mode,
7662 				head);
7663 
7664 	mode_refresh = drm_mode_vrefresh(&mode);
7665 
7666 	if (preferred_mode == NULL) {
7667 		/*
7668 		 * This may not be an error, the use case is when we have no
7669 		 * usermode calls to reset and set mode upon hotplug. In this
7670 		 * case, we call set mode ourselves to restore the previous mode
7671 		 * and the modelist may not be filled in time.
7672 		 */
7673 		drm_dbg_driver(dev, "No preferred mode found\n");
7674 	} else if (aconnector) {
7675 		recalculate_timing = amdgpu_freesync_vid_mode &&
7676 				 is_freesync_video_mode(&mode, aconnector);
7677 		if (recalculate_timing) {
7678 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
7679 			drm_mode_copy(&saved_mode, &mode);
7680 			saved_mode.picture_aspect_ratio = mode.picture_aspect_ratio;
7681 			drm_mode_copy(&mode, freesync_mode);
7682 			mode.picture_aspect_ratio = saved_mode.picture_aspect_ratio;
7683 		} else {
7684 			decide_crtc_timing_for_drm_display_mode(
7685 					&mode, preferred_mode, scale);
7686 
7687 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
7688 		}
7689 	}
7690 
7691 	if (recalculate_timing)
7692 		drm_mode_set_crtcinfo(&saved_mode, 0);
7693 
7694 	/*
7695 	 * If scaling is enabled and refresh rate didn't change
7696 	 * we copy the vic and polarities of the old timings
7697 	 */
7698 	if (!scale || mode_refresh != preferred_refresh)
7699 		fill_stream_properties_from_drm_display_mode(
7700 			stream, &mode, connector, con_state, NULL,
7701 			requested_bpc);
7702 	else
7703 		fill_stream_properties_from_drm_display_mode(
7704 			stream, &mode, connector, con_state, old_stream,
7705 			requested_bpc);
7706 
7707 	/* The rest isn't needed for writeback connectors */
7708 	if (!aconnector)
7709 		goto finish;
7710 
7711 	if (aconnector->timing_changed) {
7712 		drm_dbg(aconnector->base.dev,
7713 			"overriding timing for automated test, bpc %d, changing to %d\n",
7714 			stream->timing.display_color_depth,
7715 			aconnector->timing_requested->display_color_depth);
7716 		stream->timing = *aconnector->timing_requested;
7717 	}
7718 
7719 #if defined(CONFIG_DRM_AMD_DC_FP)
7720 	/* SST DSC determination policy */
7721 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
7722 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
7723 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
7724 #endif
7725 
7726 	update_stream_scaling_settings(dev, &mode, dm_state, stream);
7727 
7728 	fill_audio_info(
7729 		&stream->audio_info,
7730 		connector,
7731 		sink);
7732 
7733 	update_stream_signal(stream, sink);
7734 
7735 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7736 	    stream->signal == SIGNAL_TYPE_HDMI_FRL)
7737 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket, false, false);
7738 
7739 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT ||
7740 	    stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
7741 	    stream->signal == SIGNAL_TYPE_EDP) {
7742 		const struct dc_edid_caps *edid_caps;
7743 		unsigned int disable_colorimetry = 0;
7744 
7745 		if (aconnector->dc_sink) {
7746 			edid_caps = &aconnector->dc_sink->edid_caps;
7747 			disable_colorimetry = edid_caps->panel_patch.disable_colorimetry;
7748 		}
7749 
7750 		//
7751 		// should decide stream support vsc sdp colorimetry capability
7752 		// before building vsc info packet
7753 		//
7754 		stream->use_vsc_sdp_for_colorimetry = stream->link->dpcd_caps.dpcd_rev.raw >= 0x14 &&
7755 						      stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED &&
7756 						      !disable_colorimetry;
7757 
7758 		if (stream->out_transfer_func.tf == TRANSFER_FUNCTION_GAMMA22)
7759 			tf = TRANSFER_FUNC_GAMMA_22;
7760 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
7761 		aconnector->sr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
7762 
7763 	}
7764 finish:
7765 	dc_sink_release(sink);
7766 
7767 	return stream;
7768 }
7769 
7770 /**
7771  * amdgpu_dm_connector_poll - Poll a connector to see if it's connected to a display
7772  * @aconnector: DM connector to poll (owns @base drm_connector and @dc_link)
7773  * @force: if true, force polling even when DAC load detection was used
7774  *
7775  * Used for connectors that don't support HPD (hotplug detection) to
7776  * periodically check whether the connector is connected to a display.
7777  *
7778  * When connection was determined via DAC load detection, we avoid
7779  * re-running it on normal polls to prevent visible glitches, unless
7780  * @force is set.
7781  *
7782  * Return: The probed connector status (connected/disconnected/unknown).
7783  */
7784 static enum drm_connector_status
7785 amdgpu_dm_connector_poll(struct amdgpu_dm_connector *aconnector, bool force)
7786 {
7787 	struct drm_connector *connector = &aconnector->base;
7788 	struct drm_device *dev = connector->dev;
7789 	struct amdgpu_device *adev = drm_to_adev(dev);
7790 	struct dc_link *link = aconnector->dc_link;
7791 	enum dc_connection_type conn_type = dc_connection_none;
7792 	enum drm_connector_status status = connector_status_disconnected;
7793 
7794 	/* When we determined the connection using DAC load detection,
7795 	 * do NOT poll the connector do detect disconnect because
7796 	 * that would run DAC load detection again which can cause
7797 	 * visible visual glitches.
7798 	 *
7799 	 * Only allow to poll such a connector again when forcing.
7800 	 */
7801 	if (!force && link->local_sink && link->type == dc_connection_analog_load)
7802 		return connector->status;
7803 
7804 	mutex_lock(&aconnector->hpd_lock);
7805 
7806 	if (dc_link_detect_connection_type(aconnector->dc_link, &conn_type) &&
7807 	    conn_type != dc_connection_none) {
7808 		mutex_lock(&adev->dm.dc_lock);
7809 
7810 		/* Only call full link detection when a sink isn't created yet,
7811 		 * ie. just when the display is plugged in, otherwise we risk flickering.
7812 		 */
7813 		if (link->local_sink ||
7814 			dc_link_detect(link, DETECT_REASON_HPD))
7815 			status = connector_status_connected;
7816 
7817 		mutex_unlock(&adev->dm.dc_lock);
7818 	}
7819 
7820 	if (connector->status != status) {
7821 		if (status == connector_status_disconnected) {
7822 			if (link->local_sink)
7823 				dc_sink_release(link->local_sink);
7824 
7825 			link->local_sink = NULL;
7826 			link->dpcd_sink_count = 0;
7827 			link->type = dc_connection_none;
7828 		}
7829 
7830 		amdgpu_dm_update_connector_after_detect(aconnector);
7831 	}
7832 
7833 	mutex_unlock(&aconnector->hpd_lock);
7834 	return status;
7835 }
7836 
7837 /**
7838  * amdgpu_dm_connector_detect() - Detect whether a DRM connector is connected to a display
7839  *
7840  * A connector is considered connected when it has a sink that is not NULL.
7841  * For connectors that support HPD (hotplug detection), the connection is
7842  * handled in the HPD interrupt.
7843  * For connectors that may not support HPD, such as analog connectors,
7844  * DRM will call this function repeatedly to poll them.
7845  *
7846  * Notes:
7847  * 1. This interface is NOT called in context of HPD irq.
7848  * 2. This interface *is called* in context of user-mode ioctl. Which
7849  *    makes it a bad place for *any* MST-related activity.
7850  *
7851  * @connector: The DRM connector we are checking. We convert it to
7852  *             amdgpu_dm_connector so we can read the DC link and state.
7853  * @force:     If true, do a full detect again. This is used even when
7854  *             a lighter check would normally be used to avoid flicker.
7855  *
7856  * Return: The connector status (connected, disconnected, or unknown).
7857  *
7858  */
7859 static enum drm_connector_status
7860 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
7861 {
7862 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7863 
7864 	update_subconnector_property(aconnector);
7865 
7866 	if (aconnector->base.force == DRM_FORCE_ON ||
7867 		aconnector->base.force == DRM_FORCE_ON_DIGITAL)
7868 		return connector_status_connected;
7869 	else if (aconnector->base.force == DRM_FORCE_OFF)
7870 		return connector_status_disconnected;
7871 
7872 	/* Poll analog connectors and only when either
7873 	 * disconnected or connected to an analog display.
7874 	 */
7875 	if (drm_kms_helper_is_poll_worker() &&
7876 		dc_connector_supports_analog(aconnector->dc_link->link_id.id) &&
7877 		(!aconnector->dc_sink || aconnector->dc_sink->edid_caps.analog))
7878 		return amdgpu_dm_connector_poll(aconnector, force);
7879 
7880 	return (aconnector->dc_sink ? connector_status_connected :
7881 			connector_status_disconnected);
7882 }
7883 
7884 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
7885 					    struct drm_connector_state *connector_state,
7886 					    struct drm_property *property,
7887 					    uint64_t val)
7888 {
7889 	struct drm_device *dev = connector->dev;
7890 	struct amdgpu_device *adev = drm_to_adev(dev);
7891 	struct dm_connector_state *dm_old_state =
7892 		to_dm_connector_state(connector->state);
7893 	struct dm_connector_state *dm_new_state =
7894 		to_dm_connector_state(connector_state);
7895 
7896 	int ret = -EINVAL;
7897 
7898 	if (property == dev->mode_config.scaling_mode_property) {
7899 		enum amdgpu_rmx_type rmx_type;
7900 
7901 		switch (val) {
7902 		case DRM_MODE_SCALE_CENTER:
7903 			rmx_type = RMX_CENTER;
7904 			break;
7905 		case DRM_MODE_SCALE_ASPECT:
7906 			rmx_type = RMX_ASPECT;
7907 			break;
7908 		case DRM_MODE_SCALE_FULLSCREEN:
7909 			rmx_type = RMX_FULL;
7910 			break;
7911 		case DRM_MODE_SCALE_NONE:
7912 		default:
7913 			rmx_type = RMX_OFF;
7914 			break;
7915 		}
7916 
7917 		if (dm_old_state->scaling == rmx_type)
7918 			return 0;
7919 
7920 		dm_new_state->scaling = rmx_type;
7921 		ret = 0;
7922 	} else if (property == adev->mode_info.underscan_hborder_property) {
7923 		dm_new_state->underscan_hborder = val;
7924 		ret = 0;
7925 	} else if (property == adev->mode_info.underscan_vborder_property) {
7926 		dm_new_state->underscan_vborder = val;
7927 		ret = 0;
7928 	} else if (property == adev->mode_info.underscan_property) {
7929 		dm_new_state->underscan_enable = val;
7930 		ret = 0;
7931 	} else if (property == adev->mode_info.abm_level_property) {
7932 		switch (val) {
7933 		case ABM_SYSFS_CONTROL:
7934 			dm_new_state->abm_sysfs_forbidden = false;
7935 			break;
7936 		case ABM_LEVEL_OFF:
7937 			dm_new_state->abm_sysfs_forbidden = true;
7938 			dm_new_state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7939 			break;
7940 		default:
7941 			dm_new_state->abm_sysfs_forbidden = true;
7942 			dm_new_state->abm_level = val;
7943 		}
7944 		ret = 0;
7945 	}
7946 
7947 	return ret;
7948 }
7949 
7950 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
7951 					    const struct drm_connector_state *state,
7952 					    struct drm_property *property,
7953 					    uint64_t *val)
7954 {
7955 	struct drm_device *dev = connector->dev;
7956 	struct amdgpu_device *adev = drm_to_adev(dev);
7957 	struct dm_connector_state *dm_state =
7958 		to_dm_connector_state(state);
7959 	int ret = -EINVAL;
7960 
7961 	if (property == dev->mode_config.scaling_mode_property) {
7962 		switch (dm_state->scaling) {
7963 		case RMX_CENTER:
7964 			*val = DRM_MODE_SCALE_CENTER;
7965 			break;
7966 		case RMX_ASPECT:
7967 			*val = DRM_MODE_SCALE_ASPECT;
7968 			break;
7969 		case RMX_FULL:
7970 			*val = DRM_MODE_SCALE_FULLSCREEN;
7971 			break;
7972 		case RMX_OFF:
7973 		default:
7974 			*val = DRM_MODE_SCALE_NONE;
7975 			break;
7976 		}
7977 		ret = 0;
7978 	} else if (property == adev->mode_info.underscan_hborder_property) {
7979 		*val = dm_state->underscan_hborder;
7980 		ret = 0;
7981 	} else if (property == adev->mode_info.underscan_vborder_property) {
7982 		*val = dm_state->underscan_vborder;
7983 		ret = 0;
7984 	} else if (property == adev->mode_info.underscan_property) {
7985 		*val = dm_state->underscan_enable;
7986 		ret = 0;
7987 	} else if (property == adev->mode_info.abm_level_property) {
7988 		if (!dm_state->abm_sysfs_forbidden)
7989 			*val = ABM_SYSFS_CONTROL;
7990 		else
7991 			*val = (dm_state->abm_level != ABM_LEVEL_IMMEDIATE_DISABLE) ?
7992 				dm_state->abm_level : 0;
7993 		ret = 0;
7994 	}
7995 
7996 	return ret;
7997 }
7998 
7999 /**
8000  * DOC: panel power savings
8001  *
8002  * The display manager allows you to set your desired **panel power savings**
8003  * level (between 0-4, with 0 representing off), e.g. using the following::
8004  *
8005  *   # echo 3 > /sys/class/drm/card0-eDP-1/amdgpu/panel_power_savings
8006  *
8007  * Modifying this value can have implications on color accuracy, so tread
8008  * carefully.
8009  */
8010 
8011 static ssize_t panel_power_savings_show(struct device *device,
8012 					struct device_attribute *attr,
8013 					char *buf)
8014 {
8015 	struct drm_connector *connector = dev_get_drvdata(device);
8016 	struct drm_device *dev = connector->dev;
8017 	u8 val;
8018 
8019 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
8020 	val = to_dm_connector_state(connector->state)->abm_level ==
8021 		ABM_LEVEL_IMMEDIATE_DISABLE ? 0 :
8022 		to_dm_connector_state(connector->state)->abm_level;
8023 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
8024 
8025 	return sysfs_emit(buf, "%u\n", val);
8026 }
8027 
8028 static ssize_t panel_power_savings_store(struct device *device,
8029 					 struct device_attribute *attr,
8030 					 const char *buf, size_t count)
8031 {
8032 	struct drm_connector *connector = dev_get_drvdata(device);
8033 	struct drm_device *dev = connector->dev;
8034 	long val;
8035 	int ret;
8036 
8037 	ret = kstrtol(buf, 0, &val);
8038 
8039 	if (ret)
8040 		return ret;
8041 
8042 	if (val < 0 || val > 4)
8043 		return -EINVAL;
8044 
8045 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
8046 	if (to_dm_connector_state(connector->state)->abm_sysfs_forbidden)
8047 		ret = -EBUSY;
8048 	else
8049 		to_dm_connector_state(connector->state)->abm_level = val ?:
8050 			ABM_LEVEL_IMMEDIATE_DISABLE;
8051 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
8052 
8053 	if (ret)
8054 		return ret;
8055 
8056 	drm_kms_helper_hotplug_event(dev);
8057 
8058 	return count;
8059 }
8060 
8061 static DEVICE_ATTR_RW(panel_power_savings);
8062 
8063 static struct attribute *amdgpu_attrs[] = {
8064 	&dev_attr_panel_power_savings.attr,
8065 	NULL
8066 };
8067 
8068 static const struct attribute_group amdgpu_group = {
8069 	.name = "amdgpu",
8070 	.attrs = amdgpu_attrs
8071 };
8072 
8073 static bool
8074 amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector *amdgpu_dm_connector)
8075 {
8076 	if (amdgpu_dm_abm_level >= 0)
8077 		return false;
8078 
8079 	if (amdgpu_dm_connector->base.connector_type != DRM_MODE_CONNECTOR_eDP)
8080 		return false;
8081 
8082 	/* check for OLED panels */
8083 	if (amdgpu_dm_connector->bl_idx >= 0) {
8084 		struct drm_device *drm = amdgpu_dm_connector->base.dev;
8085 		struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
8086 		struct amdgpu_dm_backlight_caps *caps;
8087 
8088 		caps = &dm->backlight_caps[amdgpu_dm_connector->bl_idx];
8089 		if (caps->aux_support)
8090 			return false;
8091 	}
8092 
8093 	return true;
8094 }
8095 
8096 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
8097 {
8098 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
8099 
8100 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector))
8101 		sysfs_remove_group(&connector->kdev->kobj, &amdgpu_group);
8102 
8103 	cec_notifier_conn_unregister(amdgpu_dm_connector->notifier);
8104 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
8105 }
8106 
8107 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
8108 {
8109 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8110 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8111 	struct amdgpu_display_manager *dm = &adev->dm;
8112 
8113 	/*
8114 	 * Call only if mst_mgr was initialized before since it's not done
8115 	 * for all connector types.
8116 	 */
8117 	if (aconnector->mst_mgr.dev)
8118 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
8119 
8120 	/* Cancel and flush any pending HDMI HPD debounce work */
8121 	if (aconnector->hdmi_hpd_debounce_delay_ms) {
8122 		cancel_delayed_work_sync(&aconnector->hdmi_hpd_debounce_work);
8123 		if (aconnector->hdmi_prev_sink) {
8124 			dc_sink_release(aconnector->hdmi_prev_sink);
8125 			aconnector->hdmi_prev_sink = NULL;
8126 		}
8127 	}
8128 
8129 	if (aconnector->bl_idx != -1) {
8130 		backlight_device_unregister(dm->backlight_dev[aconnector->bl_idx]);
8131 		dm->backlight_dev[aconnector->bl_idx] = NULL;
8132 	}
8133 
8134 	if (aconnector->dc_em_sink)
8135 		dc_sink_release(aconnector->dc_em_sink);
8136 	aconnector->dc_em_sink = NULL;
8137 	if (aconnector->dc_sink)
8138 		dc_sink_release(aconnector->dc_sink);
8139 	aconnector->dc_sink = NULL;
8140 
8141 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
8142 	drm_connector_unregister(connector);
8143 	drm_connector_cleanup(connector);
8144 	kfree(aconnector->dm_dp_aux.aux.name);
8145 
8146 	kfree(connector);
8147 }
8148 
8149 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
8150 {
8151 	struct dm_connector_state *state =
8152 		to_dm_connector_state(connector->state);
8153 
8154 	if (connector->state)
8155 		__drm_atomic_helper_connector_destroy_state(connector->state);
8156 
8157 	kfree(state);
8158 
8159 	state = kzalloc_obj(*state);
8160 
8161 	if (state) {
8162 		state->scaling = RMX_OFF;
8163 		state->underscan_enable = false;
8164 		state->underscan_hborder = 0;
8165 		state->underscan_vborder = 0;
8166 		state->base.max_requested_bpc = 8;
8167 		state->vcpi_slots = 0;
8168 		state->pbn = 0;
8169 
8170 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) {
8171 			if (amdgpu_dm_abm_level <= 0)
8172 				state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
8173 			else
8174 				state->abm_level = amdgpu_dm_abm_level;
8175 		}
8176 
8177 		__drm_atomic_helper_connector_reset(connector, &state->base);
8178 	}
8179 }
8180 
8181 struct drm_connector_state *
8182 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
8183 {
8184 	struct dm_connector_state *state =
8185 		to_dm_connector_state(connector->state);
8186 
8187 	struct dm_connector_state *new_state =
8188 			kmemdup(state, sizeof(*state), GFP_KERNEL);
8189 
8190 	if (!new_state)
8191 		return NULL;
8192 
8193 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
8194 
8195 	new_state->freesync_capable = state->freesync_capable;
8196 	new_state->abm_level = state->abm_level;
8197 	new_state->scaling = state->scaling;
8198 	new_state->underscan_enable = state->underscan_enable;
8199 	new_state->underscan_hborder = state->underscan_hborder;
8200 	new_state->underscan_vborder = state->underscan_vborder;
8201 	new_state->vcpi_slots = state->vcpi_slots;
8202 	new_state->pbn = state->pbn;
8203 	return &new_state->base;
8204 }
8205 
8206 static int
8207 amdgpu_dm_connector_late_register(struct drm_connector *connector)
8208 {
8209 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8210 		to_amdgpu_dm_connector(connector);
8211 	int r;
8212 
8213 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector)) {
8214 		r = sysfs_create_group(&connector->kdev->kobj,
8215 				       &amdgpu_group);
8216 		if (r)
8217 			return r;
8218 	}
8219 
8220 	amdgpu_dm_register_backlight_device(amdgpu_dm_connector);
8221 
8222 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
8223 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
8224 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
8225 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
8226 		if (r)
8227 			return r;
8228 	}
8229 
8230 #if defined(CONFIG_DEBUG_FS)
8231 	connector_debugfs_init(amdgpu_dm_connector);
8232 #endif
8233 
8234 	return 0;
8235 }
8236 
8237 static void amdgpu_dm_connector_funcs_force(struct drm_connector *connector)
8238 {
8239 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8240 	struct dc_link *dc_link = aconnector->dc_link;
8241 	struct dc_sink *dc_em_sink = aconnector->dc_em_sink;
8242 	const struct drm_edid *drm_edid;
8243 	struct i2c_adapter *ddc;
8244 	struct drm_device *dev = connector->dev;
8245 
8246 	if (dc_link && dc_link->aux_mode)
8247 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8248 	else
8249 		ddc = &aconnector->i2c->base;
8250 
8251 	drm_edid = drm_edid_read_ddc(connector, ddc);
8252 	drm_edid_connector_update(connector, drm_edid);
8253 	if (!drm_edid) {
8254 		drm_err(dev, "No EDID found on connector: %s.\n", connector->name);
8255 		return;
8256 	}
8257 
8258 	aconnector->drm_edid = drm_edid;
8259 	/* Update emulated (virtual) sink's EDID */
8260 	if (dc_em_sink && dc_link) {
8261 		// FIXME: Get rid of drm_edid_raw()
8262 		const struct edid *edid = drm_edid_raw(drm_edid);
8263 
8264 		memset(&dc_em_sink->edid_caps, 0, sizeof(struct dc_edid_caps));
8265 		memmove(dc_em_sink->dc_edid.raw_edid, edid,
8266 			(edid->extensions + 1) * EDID_LENGTH);
8267 		dm_helpers_parse_edid_caps(
8268 			dc_link,
8269 			&dc_em_sink->dc_edid,
8270 			&dc_em_sink->edid_caps);
8271 	}
8272 }
8273 
8274 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
8275 	.reset = amdgpu_dm_connector_funcs_reset,
8276 	.detect = amdgpu_dm_connector_detect,
8277 	.fill_modes = drm_helper_probe_single_connector_modes,
8278 	.destroy = amdgpu_dm_connector_destroy,
8279 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
8280 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
8281 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
8282 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
8283 	.late_register = amdgpu_dm_connector_late_register,
8284 	.early_unregister = amdgpu_dm_connector_unregister,
8285 	.force = amdgpu_dm_connector_funcs_force
8286 };
8287 
8288 static int get_modes(struct drm_connector *connector)
8289 {
8290 	return amdgpu_dm_connector_get_modes(connector);
8291 }
8292 
8293 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
8294 {
8295 	struct drm_connector *connector = &aconnector->base;
8296 	struct dc_link *dc_link = aconnector->dc_link;
8297 	struct dc_sink_init_data init_params = {
8298 			.link = aconnector->dc_link,
8299 			.sink_signal = SIGNAL_TYPE_VIRTUAL
8300 	};
8301 	const struct drm_edid *drm_edid;
8302 	const struct edid *edid;
8303 	struct i2c_adapter *ddc;
8304 
8305 	if (dc_link && dc_link->aux_mode)
8306 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8307 	else
8308 		ddc = &aconnector->i2c->base;
8309 
8310 	drm_edid = drm_edid_read_ddc(connector, ddc);
8311 	drm_edid_connector_update(connector, drm_edid);
8312 	if (!drm_edid) {
8313 		drm_err(connector->dev, "No EDID found on connector: %s.\n", connector->name);
8314 		return;
8315 	}
8316 
8317 	if (connector->display_info.is_hdmi)
8318 		init_params.sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
8319 
8320 	aconnector->drm_edid = drm_edid;
8321 
8322 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
8323 	aconnector->dc_em_sink = dc_link_add_remote_sink(
8324 		aconnector->dc_link,
8325 		(uint8_t *)edid,
8326 		(edid->extensions + 1) * EDID_LENGTH,
8327 		&init_params);
8328 
8329 	if (aconnector->base.force == DRM_FORCE_ON) {
8330 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
8331 		aconnector->dc_link->local_sink :
8332 		aconnector->dc_em_sink;
8333 		if (aconnector->dc_sink)
8334 			dc_sink_retain(aconnector->dc_sink);
8335 	}
8336 }
8337 
8338 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
8339 {
8340 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
8341 
8342 	/*
8343 	 * In case of headless boot with force on for DP managed connector
8344 	 * Those settings have to be != 0 to get initial modeset
8345 	 */
8346 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
8347 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
8348 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
8349 	}
8350 
8351 	create_eml_sink(aconnector);
8352 }
8353 
8354 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
8355 						struct dc_stream_state *stream)
8356 {
8357 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
8358 	struct dc_plane_state *dc_plane_state = NULL;
8359 	struct dc_state *dc_state = NULL;
8360 
8361 	if (!stream)
8362 		goto cleanup;
8363 
8364 	dc_plane_state = dc_create_plane_state(dc);
8365 	if (!dc_plane_state)
8366 		goto cleanup;
8367 
8368 	dc_state = dc_state_create(dc, NULL);
8369 	if (!dc_state)
8370 		goto cleanup;
8371 
8372 	/* populate stream to plane */
8373 	dc_plane_state->src_rect.height  = stream->src.height;
8374 	dc_plane_state->src_rect.width   = stream->src.width;
8375 	dc_plane_state->dst_rect.height  = stream->src.height;
8376 	dc_plane_state->dst_rect.width   = stream->src.width;
8377 	dc_plane_state->clip_rect.height = stream->src.height;
8378 	dc_plane_state->clip_rect.width  = stream->src.width;
8379 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
8380 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
8381 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
8382 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
8383 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
8384 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
8385 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
8386 	dc_plane_state->rotation = ROTATION_ANGLE_0;
8387 	dc_plane_state->is_tiling_rotated = false;
8388 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
8389 
8390 	dc_result = dc_validate_stream(dc, stream);
8391 	if (dc_result == DC_OK)
8392 		dc_result = dc_validate_plane(dc, dc_plane_state);
8393 
8394 	if (dc_result == DC_OK)
8395 		dc_result = dc_state_add_stream(dc, dc_state, stream);
8396 
8397 	if (dc_result == DC_OK && !dc_state_add_plane(
8398 						dc,
8399 						stream,
8400 						dc_plane_state,
8401 						dc_state))
8402 		dc_result = DC_FAIL_ATTACH_SURFACES;
8403 
8404 	if (dc_result == DC_OK)
8405 		dc_result = dc_validate_global_state(dc, dc_state, DC_VALIDATE_MODE_ONLY);
8406 
8407 cleanup:
8408 	if (dc_state)
8409 		dc_state_release(dc_state);
8410 
8411 	if (dc_plane_state)
8412 		dc_plane_state_release(dc_plane_state);
8413 
8414 	return dc_result;
8415 }
8416 
8417 struct dc_stream_state *
8418 create_validate_stream_for_sink(struct drm_connector *connector,
8419 				const struct drm_display_mode *drm_mode,
8420 				const struct dm_connector_state *dm_state,
8421 				const struct dc_stream_state *old_stream)
8422 {
8423 	struct amdgpu_dm_connector *aconnector = NULL;
8424 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8425 	struct dc_stream_state *stream;
8426 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
8427 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
8428 	enum dc_status dc_result = DC_OK;
8429 	uint8_t bpc_limit = 6;
8430 
8431 	if (!dm_state)
8432 		return NULL;
8433 
8434 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
8435 		aconnector = to_amdgpu_dm_connector(connector);
8436 
8437 	if (aconnector &&
8438 	    (aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
8439 	     aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_FRL ||
8440 	     aconnector->dc_link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER))
8441 		bpc_limit = 8;
8442 
8443 	do {
8444 		drm_dbg_kms(connector->dev, "Trying with %d bpc\n", requested_bpc);
8445 		stream = create_stream_for_sink(connector, drm_mode,
8446 						dm_state, old_stream,
8447 						requested_bpc);
8448 		if (stream == NULL) {
8449 			drm_err(adev_to_drm(adev), "Failed to create stream for sink!\n");
8450 			break;
8451 		}
8452 
8453 		dc_result = dc_validate_stream(adev->dm.dc, stream);
8454 
8455 		if (!aconnector) /* writeback connector */
8456 			return stream;
8457 
8458 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
8459 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
8460 
8461 		if (dc_result == DC_OK)
8462 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
8463 
8464 		if (dc_result != DC_OK) {
8465 			drm_dbg_kms(connector->dev, "Pruned mode %d x %d (clk %d) %s %s -- %s\n",
8466 				      drm_mode->hdisplay,
8467 				      drm_mode->vdisplay,
8468 				      drm_mode->clock,
8469 				      dc_pixel_encoding_to_str(stream->timing.pixel_encoding),
8470 				      dc_color_depth_to_str(stream->timing.display_color_depth),
8471 				      dc_status_to_str(dc_result));
8472 
8473 			dc_stream_release(stream);
8474 			stream = NULL;
8475 			requested_bpc -= 2; /* lower bpc to retry validation */
8476 		}
8477 
8478 	} while (stream == NULL && requested_bpc >= bpc_limit);
8479 
8480 	switch (dc_result) {
8481 	/*
8482 	 * If we failed to validate DP bandwidth stream with the requested RGB color depth,
8483 	 * we try to fallback and configure in order:
8484 	 * YUV422 (8bpc, 6bpc)
8485 	 * YUV420 (8bpc, 6bpc)
8486 	 */
8487 	case DC_FAIL_ENC_VALIDATE:
8488 	case DC_EXCEED_DONGLE_CAP:
8489 	case DC_NO_DP_LINK_BANDWIDTH:
8490 		/* recursively entered twice and already tried both YUV422 and YUV420 */
8491 		if (aconnector->force_yuv422_output && aconnector->force_yuv420_output)
8492 			break;
8493 		/* first failure; try YUV422 */
8494 		if (!aconnector->force_yuv422_output) {
8495 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV422\n",
8496 				    __func__, __LINE__, dc_result);
8497 			aconnector->force_yuv422_output = true;
8498 		/* recursively entered and YUV422 failed, try YUV420 */
8499 		} else if (!aconnector->force_yuv420_output) {
8500 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV420\n",
8501 				    __func__, __LINE__, dc_result);
8502 			aconnector->force_yuv420_output = true;
8503 		}
8504 		stream = create_validate_stream_for_sink(connector, drm_mode,
8505 							 dm_state, old_stream);
8506 		aconnector->force_yuv422_output = false;
8507 		aconnector->force_yuv420_output = false;
8508 		break;
8509 	case DC_OK:
8510 		break;
8511 	default:
8512 		drm_dbg_kms(connector->dev, "%s:%d Unhandled validation failure %d\n",
8513 			    __func__, __LINE__, dc_result);
8514 		break;
8515 	}
8516 
8517 	return stream;
8518 }
8519 
8520 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
8521 				   const struct drm_display_mode *mode)
8522 {
8523 	int result = MODE_ERROR;
8524 	struct dc_sink *dc_sink;
8525 	struct drm_display_mode *test_mode;
8526 	/* TODO: Unhardcode stream count */
8527 	struct dc_stream_state *stream;
8528 	/* we always have an amdgpu_dm_connector here since we got
8529 	 * here via the amdgpu_dm_connector_helper_funcs
8530 	 */
8531 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8532 
8533 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
8534 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
8535 		return result;
8536 
8537 	/*
8538 	 * Only run this the first time mode_valid is called to initilialize
8539 	 * EDID mgmt
8540 	 */
8541 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
8542 		!aconnector->dc_em_sink)
8543 		handle_edid_mgmt(aconnector);
8544 
8545 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
8546 
8547 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
8548 				aconnector->base.force != DRM_FORCE_ON) {
8549 		drm_err(connector->dev, "dc_sink is NULL!\n");
8550 		goto fail;
8551 	}
8552 
8553 	test_mode = drm_mode_duplicate(connector->dev, mode);
8554 	if (!test_mode)
8555 		goto fail;
8556 
8557 	drm_mode_set_crtcinfo(test_mode, 0);
8558 
8559 	stream = create_validate_stream_for_sink(connector, test_mode,
8560 						 to_dm_connector_state(connector->state),
8561 						 NULL);
8562 	drm_mode_destroy(connector->dev, test_mode);
8563 	if (stream) {
8564 		dc_stream_release(stream);
8565 		result = MODE_OK;
8566 	}
8567 
8568 fail:
8569 	/* TODO: error handling*/
8570 	return result;
8571 }
8572 
8573 static int fill_hdr_info_packet(const struct drm_connector_state *state,
8574 				struct dc_info_packet *out)
8575 {
8576 	struct hdmi_drm_infoframe frame;
8577 	unsigned char buf[30]; /* 26 + 4 */
8578 	ssize_t len;
8579 	int ret, i;
8580 
8581 	memset(out, 0, sizeof(*out));
8582 
8583 	if (!state->hdr_output_metadata)
8584 		return 0;
8585 
8586 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
8587 	if (ret)
8588 		return ret;
8589 
8590 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
8591 	if (len < 0)
8592 		return (int)len;
8593 
8594 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
8595 	if (len != 30)
8596 		return -EINVAL;
8597 
8598 	/* Prepare the infopacket for DC. */
8599 	switch (state->connector->connector_type) {
8600 	case DRM_MODE_CONNECTOR_HDMIA:
8601 		out->hb0 = 0x87; /* type */
8602 		out->hb1 = 0x01; /* version */
8603 		out->hb2 = 0x1A; /* length */
8604 		out->sb[0] = buf[3]; /* checksum */
8605 		i = 1;
8606 		break;
8607 
8608 	case DRM_MODE_CONNECTOR_DisplayPort:
8609 	case DRM_MODE_CONNECTOR_eDP:
8610 		out->hb0 = 0x00; /* sdp id, zero */
8611 		out->hb1 = 0x87; /* type */
8612 		out->hb2 = 0x1D; /* payload len - 1 */
8613 		out->hb3 = (0x13 << 2); /* sdp version */
8614 		out->sb[0] = 0x01; /* version */
8615 		out->sb[1] = 0x1A; /* length */
8616 		i = 2;
8617 		break;
8618 
8619 	default:
8620 		return -EINVAL;
8621 	}
8622 
8623 	memcpy(&out->sb[i], &buf[4], 26);
8624 	out->valid = true;
8625 
8626 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
8627 		       sizeof(out->sb), false);
8628 
8629 	return 0;
8630 }
8631 
8632 static int
8633 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
8634 				 struct drm_atomic_commit *state)
8635 {
8636 	struct drm_connector_state *new_con_state =
8637 		drm_atomic_get_new_connector_state(state, conn);
8638 	struct drm_connector_state *old_con_state =
8639 		drm_atomic_get_old_connector_state(state, conn);
8640 	struct drm_crtc *crtc = new_con_state->crtc;
8641 	struct drm_crtc_state *new_crtc_state;
8642 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
8643 	int ret;
8644 
8645 	if (WARN_ON(unlikely(!old_con_state || !new_con_state)))
8646 		return -EINVAL;
8647 
8648 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
8649 
8650 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
8651 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
8652 		if (ret < 0)
8653 			return ret;
8654 	}
8655 
8656 	if (!crtc)
8657 		return 0;
8658 
8659 	if (new_con_state->privacy_screen_sw_state != old_con_state->privacy_screen_sw_state) {
8660 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8661 		if (IS_ERR(new_crtc_state))
8662 			return PTR_ERR(new_crtc_state);
8663 
8664 		new_crtc_state->mode_changed = true;
8665 	}
8666 
8667 	if (new_con_state->colorspace != old_con_state->colorspace) {
8668 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8669 		if (IS_ERR(new_crtc_state))
8670 			return PTR_ERR(new_crtc_state);
8671 
8672 		new_crtc_state->mode_changed = true;
8673 	}
8674 
8675 	if (new_con_state->content_type != old_con_state->content_type) {
8676 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8677 		if (IS_ERR(new_crtc_state))
8678 			return PTR_ERR(new_crtc_state);
8679 
8680 		new_crtc_state->mode_changed = true;
8681 	}
8682 
8683 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
8684 		struct dc_info_packet hdr_infopacket;
8685 
8686 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
8687 		if (ret)
8688 			return ret;
8689 
8690 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8691 		if (IS_ERR(new_crtc_state))
8692 			return PTR_ERR(new_crtc_state);
8693 
8694 		/*
8695 		 * DC considers the stream backends changed if the
8696 		 * static metadata changes. Forcing the modeset also
8697 		 * gives a simple way for userspace to switch from
8698 		 * 8bpc to 10bpc when setting the metadata to enter
8699 		 * or exit HDR.
8700 		 *
8701 		 * Changing the static metadata after it's been
8702 		 * set is permissible, however. So only force a
8703 		 * modeset if we're entering or exiting HDR.
8704 		 */
8705 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
8706 			!old_con_state->hdr_output_metadata ||
8707 			!new_con_state->hdr_output_metadata;
8708 	}
8709 
8710 	return 0;
8711 }
8712 
8713 static const struct drm_connector_helper_funcs
8714 amdgpu_dm_connector_helper_funcs = {
8715 	/*
8716 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
8717 	 * modes will be filtered by drm_mode_validate_size(), and those modes
8718 	 * are missing after user start lightdm. So we need to renew modes list.
8719 	 * in get_modes call back, not just return the modes count
8720 	 */
8721 	.get_modes = get_modes,
8722 	.mode_valid = amdgpu_dm_connector_mode_valid,
8723 	.atomic_check = amdgpu_dm_connector_atomic_check,
8724 };
8725 
8726 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
8727 {
8728 
8729 }
8730 
8731 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
8732 {
8733 	switch (display_color_depth) {
8734 	case COLOR_DEPTH_666:
8735 		return 6;
8736 	case COLOR_DEPTH_888:
8737 		return 8;
8738 	case COLOR_DEPTH_101010:
8739 		return 10;
8740 	case COLOR_DEPTH_121212:
8741 		return 12;
8742 	case COLOR_DEPTH_141414:
8743 		return 14;
8744 	case COLOR_DEPTH_161616:
8745 		return 16;
8746 	default:
8747 		break;
8748 	}
8749 	return 0;
8750 }
8751 
8752 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
8753 					  struct drm_crtc_state *crtc_state,
8754 					  struct drm_connector_state *conn_state)
8755 {
8756 	struct drm_atomic_commit *state = crtc_state->state;
8757 	struct drm_connector *connector = conn_state->connector;
8758 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8759 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
8760 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
8761 	struct drm_dp_mst_topology_mgr *mst_mgr;
8762 	struct drm_dp_mst_port *mst_port;
8763 	struct drm_dp_mst_topology_state *mst_state;
8764 	enum dc_color_depth color_depth;
8765 	int clock, bpp = 0;
8766 	bool is_y420 = false;
8767 
8768 	if ((connector->connector_type == DRM_MODE_CONNECTOR_eDP) ||
8769 	    (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)) {
8770 		struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8771 		struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8772 		enum drm_mode_status result;
8773 
8774 		result = drm_crtc_helper_mode_valid_fixed(encoder->crtc, adjusted_mode, native_mode);
8775 		if (result != MODE_OK && dm_new_connector_state->scaling == RMX_OFF) {
8776 			drm_dbg_driver(encoder->dev,
8777 				       "mode %dx%d@%dHz is not native, enabling scaling\n",
8778 				       adjusted_mode->hdisplay, adjusted_mode->vdisplay,
8779 				       drm_mode_vrefresh(adjusted_mode));
8780 			dm_new_connector_state->scaling = RMX_ASPECT;
8781 		}
8782 		return 0;
8783 	}
8784 
8785 	if (!aconnector->mst_output_port)
8786 		return 0;
8787 
8788 	mst_port = aconnector->mst_output_port;
8789 	mst_mgr = &aconnector->mst_root->mst_mgr;
8790 
8791 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
8792 		return 0;
8793 
8794 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
8795 	if (IS_ERR(mst_state))
8796 		return PTR_ERR(mst_state);
8797 
8798 	mst_state->pbn_div.full = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
8799 
8800 	if (!state->duplicated) {
8801 		int max_bpc = conn_state->max_requested_bpc;
8802 
8803 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
8804 			  aconnector->force_yuv420_output;
8805 		color_depth = convert_color_depth_from_display_info(connector,
8806 								    is_y420,
8807 								    max_bpc);
8808 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
8809 		clock = adjusted_mode->clock;
8810 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
8811 	}
8812 
8813 	dm_new_connector_state->vcpi_slots =
8814 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
8815 					      dm_new_connector_state->pbn);
8816 	if (dm_new_connector_state->vcpi_slots < 0) {
8817 		drm_dbg_atomic(connector->dev, "failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
8818 		return dm_new_connector_state->vcpi_slots;
8819 	}
8820 	return 0;
8821 }
8822 
8823 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
8824 	.disable = dm_encoder_helper_disable,
8825 	.atomic_check = dm_encoder_helper_atomic_check
8826 };
8827 
8828 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_commit *state,
8829 					    struct dc_state *dc_state,
8830 					    struct dsc_mst_fairness_vars *vars)
8831 {
8832 	struct dc_stream_state *stream = NULL;
8833 	struct drm_connector *connector;
8834 	struct drm_connector_state *new_con_state;
8835 	struct amdgpu_dm_connector *aconnector;
8836 	struct dm_connector_state *dm_conn_state;
8837 	int i, j, ret;
8838 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
8839 
8840 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8841 
8842 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
8843 			continue;
8844 
8845 		aconnector = to_amdgpu_dm_connector(connector);
8846 
8847 		if (!aconnector->mst_output_port)
8848 			continue;
8849 
8850 		if (!new_con_state || !new_con_state->crtc)
8851 			continue;
8852 
8853 		dm_conn_state = to_dm_connector_state(new_con_state);
8854 
8855 		for (j = 0; j < dc_state->stream_count; j++) {
8856 			stream = dc_state->streams[j];
8857 			if (!stream)
8858 				continue;
8859 
8860 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
8861 				break;
8862 
8863 			stream = NULL;
8864 		}
8865 
8866 		if (!stream)
8867 			continue;
8868 
8869 		pbn_div = dm_mst_get_pbn_divider(stream->link);
8870 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
8871 		for (j = 0; j < dc_state->stream_count; j++) {
8872 			if (vars[j].aconnector == aconnector) {
8873 				pbn = vars[j].pbn;
8874 				break;
8875 			}
8876 		}
8877 
8878 		if (j == dc_state->stream_count || pbn_div == 0)
8879 			continue;
8880 
8881 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
8882 
8883 		if (stream->timing.flags.DSC != 1) {
8884 			dm_conn_state->pbn = pbn;
8885 			dm_conn_state->vcpi_slots = slot_num;
8886 
8887 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
8888 							   dm_conn_state->pbn, false);
8889 			if (ret < 0)
8890 				return ret;
8891 
8892 			continue;
8893 		}
8894 
8895 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
8896 		if (vcpi < 0)
8897 			return vcpi;
8898 
8899 		dm_conn_state->pbn = pbn;
8900 		dm_conn_state->vcpi_slots = vcpi;
8901 	}
8902 	return 0;
8903 }
8904 
8905 static int to_drm_connector_type(enum signal_type st, uint32_t connector_id)
8906 {
8907 	switch (st) {
8908 	case SIGNAL_TYPE_HDMI_TYPE_A:
8909 		return DRM_MODE_CONNECTOR_HDMIA;
8910 	case SIGNAL_TYPE_EDP:
8911 		return DRM_MODE_CONNECTOR_eDP;
8912 	case SIGNAL_TYPE_LVDS:
8913 		return DRM_MODE_CONNECTOR_LVDS;
8914 	case SIGNAL_TYPE_RGB:
8915 		return DRM_MODE_CONNECTOR_VGA;
8916 	case SIGNAL_TYPE_DISPLAY_PORT:
8917 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
8918 		/* External DP bridges have a different connector type. */
8919 		if (connector_id == CONNECTOR_ID_VGA)
8920 			return DRM_MODE_CONNECTOR_VGA;
8921 		else if (connector_id == CONNECTOR_ID_LVDS)
8922 			return DRM_MODE_CONNECTOR_LVDS;
8923 
8924 		return DRM_MODE_CONNECTOR_DisplayPort;
8925 	case SIGNAL_TYPE_DVI_DUAL_LINK:
8926 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
8927 		if (connector_id == CONNECTOR_ID_SINGLE_LINK_DVII ||
8928 			connector_id == CONNECTOR_ID_DUAL_LINK_DVII)
8929 			return DRM_MODE_CONNECTOR_DVII;
8930 
8931 		return DRM_MODE_CONNECTOR_DVID;
8932 	case SIGNAL_TYPE_VIRTUAL:
8933 		return DRM_MODE_CONNECTOR_VIRTUAL;
8934 
8935 	default:
8936 		return DRM_MODE_CONNECTOR_Unknown;
8937 	}
8938 }
8939 
8940 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
8941 {
8942 	struct drm_encoder *encoder;
8943 
8944 	/* There is only one encoder per connector */
8945 	drm_connector_for_each_possible_encoder(connector, encoder)
8946 		return encoder;
8947 
8948 	return NULL;
8949 }
8950 
8951 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
8952 {
8953 	struct drm_encoder *encoder;
8954 	struct amdgpu_encoder *amdgpu_encoder;
8955 
8956 	encoder = amdgpu_dm_connector_to_encoder(connector);
8957 
8958 	if (encoder == NULL)
8959 		return;
8960 
8961 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8962 
8963 	amdgpu_encoder->native_mode.clock = 0;
8964 
8965 	if (!list_empty(&connector->probed_modes)) {
8966 		struct drm_display_mode *preferred_mode = NULL;
8967 
8968 		list_for_each_entry(preferred_mode,
8969 				    &connector->probed_modes,
8970 				    head) {
8971 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
8972 				amdgpu_encoder->native_mode = *preferred_mode;
8973 
8974 			break;
8975 		}
8976 
8977 	}
8978 }
8979 
8980 static struct drm_display_mode *
8981 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
8982 			     const char *name,
8983 			     int hdisplay, int vdisplay)
8984 {
8985 	struct drm_device *dev = encoder->dev;
8986 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8987 	struct drm_display_mode *mode = NULL;
8988 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8989 
8990 	mode = drm_mode_duplicate(dev, native_mode);
8991 
8992 	if (mode == NULL)
8993 		return NULL;
8994 
8995 	mode->hdisplay = hdisplay;
8996 	mode->vdisplay = vdisplay;
8997 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8998 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
8999 
9000 	return mode;
9001 
9002 }
9003 
9004 static const struct amdgpu_dm_mode_size {
9005 	char name[DRM_DISPLAY_MODE_LEN];
9006 	int w;
9007 	int h;
9008 } common_modes[] = {
9009 	{  "640x480",  640,  480},
9010 	{  "800x600",  800,  600},
9011 	{ "1024x768", 1024,  768},
9012 	{ "1280x720", 1280,  720},
9013 	{ "1280x800", 1280,  800},
9014 	{"1280x1024", 1280, 1024},
9015 	{ "1440x900", 1440,  900},
9016 	{"1680x1050", 1680, 1050},
9017 	{"1600x1200", 1600, 1200},
9018 	{"1920x1080", 1920, 1080},
9019 	{"1920x1200", 1920, 1200}
9020 };
9021 
9022 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
9023 						 struct drm_connector *connector)
9024 {
9025 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
9026 	struct drm_display_mode *mode = NULL;
9027 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
9028 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9029 				to_amdgpu_dm_connector(connector);
9030 	int i;
9031 	int n;
9032 
9033 	if ((connector->connector_type != DRM_MODE_CONNECTOR_eDP) &&
9034 	    (connector->connector_type != DRM_MODE_CONNECTOR_LVDS))
9035 		return;
9036 
9037 	n = ARRAY_SIZE(common_modes);
9038 
9039 	for (i = 0; i < n; i++) {
9040 		struct drm_display_mode *curmode = NULL;
9041 		bool mode_existed = false;
9042 
9043 		if (common_modes[i].w > native_mode->hdisplay ||
9044 		    common_modes[i].h > native_mode->vdisplay ||
9045 		   (common_modes[i].w == native_mode->hdisplay &&
9046 		    common_modes[i].h == native_mode->vdisplay))
9047 			continue;
9048 
9049 		list_for_each_entry(curmode, &connector->probed_modes, head) {
9050 			if (common_modes[i].w == curmode->hdisplay &&
9051 			    common_modes[i].h == curmode->vdisplay) {
9052 				mode_existed = true;
9053 				break;
9054 			}
9055 		}
9056 
9057 		if (mode_existed)
9058 			continue;
9059 
9060 		mode = amdgpu_dm_create_common_mode(encoder,
9061 				common_modes[i].name, common_modes[i].w,
9062 				common_modes[i].h);
9063 		if (!mode)
9064 			continue;
9065 
9066 		drm_mode_probed_add(connector, mode);
9067 		amdgpu_dm_connector->num_modes++;
9068 	}
9069 }
9070 
9071 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
9072 {
9073 	struct drm_encoder *encoder;
9074 	struct amdgpu_encoder *amdgpu_encoder;
9075 	const struct drm_display_mode *native_mode;
9076 
9077 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
9078 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
9079 		return;
9080 
9081 	mutex_lock(&connector->dev->mode_config.mutex);
9082 	amdgpu_dm_connector_get_modes(connector);
9083 	mutex_unlock(&connector->dev->mode_config.mutex);
9084 
9085 	encoder = amdgpu_dm_connector_to_encoder(connector);
9086 	if (!encoder)
9087 		return;
9088 
9089 	amdgpu_encoder = to_amdgpu_encoder(encoder);
9090 
9091 	native_mode = &amdgpu_encoder->native_mode;
9092 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
9093 		return;
9094 
9095 	drm_connector_set_panel_orientation_with_quirk(connector,
9096 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
9097 						       native_mode->hdisplay,
9098 						       native_mode->vdisplay);
9099 }
9100 
9101 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
9102 					      const struct drm_edid *drm_edid)
9103 {
9104 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9105 			to_amdgpu_dm_connector(connector);
9106 
9107 	if (drm_edid) {
9108 		/* empty probed_modes */
9109 		INIT_LIST_HEAD(&connector->probed_modes);
9110 		amdgpu_dm_connector->num_modes =
9111 				drm_edid_connector_add_modes(connector);
9112 
9113 		/* sorting the probed modes before calling function
9114 		 * amdgpu_dm_get_native_mode() since EDID can have
9115 		 * more than one preferred mode. The modes that are
9116 		 * later in the probed mode list could be of higher
9117 		 * and preferred resolution. For example, 3840x2160
9118 		 * resolution in base EDID preferred timing and 4096x2160
9119 		 * preferred resolution in DID extension block later.
9120 		 */
9121 		drm_mode_sort(&connector->probed_modes);
9122 		amdgpu_dm_get_native_mode(connector);
9123 
9124 		/* Freesync capabilities are reset by calling
9125 		 * drm_edid_connector_add_modes() and need to be
9126 		 * restored here.
9127 		 */
9128 		amdgpu_dm_update_freesync_caps(connector, drm_edid, false);
9129 	} else {
9130 		amdgpu_dm_connector->num_modes = 0;
9131 	}
9132 }
9133 
9134 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
9135 			      struct drm_display_mode *mode)
9136 {
9137 	struct drm_display_mode *m;
9138 
9139 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
9140 		if (drm_mode_equal(m, mode))
9141 			return true;
9142 	}
9143 
9144 	return false;
9145 }
9146 
9147 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
9148 {
9149 	const struct drm_display_mode *m;
9150 	struct drm_display_mode *new_mode;
9151 	uint i;
9152 	u32 new_modes_count = 0;
9153 
9154 	/* Standard FPS values
9155 	 *
9156 	 * 23.976       - TV/NTSC
9157 	 * 24           - Cinema
9158 	 * 25           - TV/PAL
9159 	 * 29.97        - TV/NTSC
9160 	 * 30           - TV/NTSC
9161 	 * 48           - Cinema HFR
9162 	 * 50           - TV/PAL
9163 	 * 60           - Commonly used
9164 	 * 48,72,96,120 - Multiples of 24
9165 	 */
9166 	static const u32 common_rates[] = {
9167 		23976, 24000, 25000, 29970, 30000,
9168 		48000, 50000, 60000, 72000, 96000, 120000
9169 	};
9170 
9171 	/*
9172 	 * Find mode with highest refresh rate with the same resolution
9173 	 * as the preferred mode. Some monitors report a preferred mode
9174 	 * with lower resolution than the highest refresh rate supported.
9175 	 */
9176 
9177 	m = get_highest_refresh_rate_mode(aconnector, true);
9178 	if (!m)
9179 		return 0;
9180 
9181 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
9182 		u64 target_vtotal, target_vtotal_diff;
9183 		u64 num, den;
9184 
9185 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
9186 			continue;
9187 
9188 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
9189 		    common_rates[i] > aconnector->max_vfreq * 1000)
9190 			continue;
9191 
9192 		num = (unsigned long long)m->clock * 1000 * 1000;
9193 		den = common_rates[i] * (unsigned long long)m->htotal;
9194 		target_vtotal = div_u64(num, den);
9195 		target_vtotal_diff = target_vtotal - m->vtotal;
9196 
9197 		/* Check for illegal modes */
9198 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
9199 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
9200 		    m->vtotal + target_vtotal_diff < m->vsync_end)
9201 			continue;
9202 
9203 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
9204 		if (!new_mode)
9205 			goto out;
9206 
9207 		new_mode->vtotal += (u16)target_vtotal_diff;
9208 		new_mode->vsync_start += (u16)target_vtotal_diff;
9209 		new_mode->vsync_end += (u16)target_vtotal_diff;
9210 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
9211 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
9212 
9213 		if (!is_duplicate_mode(aconnector, new_mode)) {
9214 			drm_mode_probed_add(&aconnector->base, new_mode);
9215 			new_modes_count += 1;
9216 		} else
9217 			drm_mode_destroy(aconnector->base.dev, new_mode);
9218 	}
9219  out:
9220 	return new_modes_count;
9221 }
9222 
9223 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
9224 						   const struct drm_edid *drm_edid)
9225 {
9226 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9227 		to_amdgpu_dm_connector(connector);
9228 
9229 	if (!(amdgpu_freesync_vid_mode && drm_edid))
9230 		return;
9231 
9232 	if (!amdgpu_dm_connector->dc_sink || !amdgpu_dm_connector->dc_link)
9233 		return;
9234 
9235 	if (!dc_supports_vrr(amdgpu_dm_connector->dc_sink->ctx->dce_version))
9236 		return;
9237 
9238 	if (dc_connector_supports_analog(amdgpu_dm_connector->dc_link->link_id.id) &&
9239 	    amdgpu_dm_connector->dc_sink->edid_caps.analog)
9240 		return;
9241 
9242 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
9243 		amdgpu_dm_connector->num_modes +=
9244 			add_fs_modes(amdgpu_dm_connector);
9245 }
9246 
9247 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
9248 {
9249 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9250 			to_amdgpu_dm_connector(connector);
9251 	struct dc_link *dc_link = amdgpu_dm_connector->dc_link;
9252 	struct drm_encoder *encoder;
9253 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
9254 	struct dc_link_settings *verified_link_cap = &dc_link->verified_link_cap;
9255 	const struct dc *dc = dc_link->dc;
9256 
9257 	encoder = amdgpu_dm_connector_to_encoder(connector);
9258 
9259 	if (!drm_edid) {
9260 		amdgpu_dm_connector->num_modes =
9261 				drm_add_modes_noedid(connector, 640, 480);
9262 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
9263 			amdgpu_dm_connector->num_modes +=
9264 				drm_add_modes_noedid(connector, 1920, 1080);
9265 
9266 		if (amdgpu_dm_connector->dc_sink &&
9267 		    amdgpu_dm_connector->dc_sink->edid_caps.analog &&
9268 		    dc_connector_supports_analog(dc_link->link_id.id)) {
9269 			/* Analog monitor connected by DAC load detection.
9270 			 * Add common modes. It will be up to the user to select one that works.
9271 			 */
9272 			for (int i = 0; i < ARRAY_SIZE(common_modes); i++)
9273 				amdgpu_dm_connector->num_modes += drm_add_modes_noedid(
9274 					connector, common_modes[i].w, common_modes[i].h);
9275 		}
9276 	} else {
9277 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
9278 		if (encoder)
9279 			amdgpu_dm_connector_add_common_modes(encoder, connector);
9280 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
9281 	}
9282 	amdgpu_dm_fbc_init(connector);
9283 
9284 	return amdgpu_dm_connector->num_modes;
9285 }
9286 
9287 static const u32 supported_colorspaces =
9288 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
9289 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
9290 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
9291 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
9292 
9293 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
9294 				     struct amdgpu_dm_connector *aconnector,
9295 				     int connector_type,
9296 				     struct dc_link *link,
9297 				     int link_index)
9298 {
9299 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
9300 
9301 	/*
9302 	 * Some of the properties below require access to state, like bpc.
9303 	 * Allocate some default initial connector state with our reset helper.
9304 	 */
9305 	if (aconnector->base.funcs->reset)
9306 		aconnector->base.funcs->reset(&aconnector->base);
9307 
9308 	aconnector->connector_id = link_index;
9309 	aconnector->bl_idx = -1;
9310 	aconnector->dc_link = link;
9311 	aconnector->base.interlace_allowed = false;
9312 	aconnector->base.doublescan_allowed = false;
9313 	aconnector->base.stereo_allowed = false;
9314 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
9315 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
9316 	aconnector->audio_inst = -1;
9317 	aconnector->pack_sdp_v1_3 = false;
9318 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
9319 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
9320 	mutex_init(&aconnector->hpd_lock);
9321 	mutex_init(&aconnector->handle_mst_msg_ready);
9322 
9323 	/*
9324 	 * If HDMI HPD debounce delay is set, use the minimum between selected
9325 	 * value and AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS
9326 	 */
9327 	if (amdgpu_hdmi_hpd_debounce_delay_ms) {
9328 		aconnector->hdmi_hpd_debounce_delay_ms = min(amdgpu_hdmi_hpd_debounce_delay_ms,
9329 							     AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS);
9330 		INIT_DELAYED_WORK(&aconnector->hdmi_hpd_debounce_work, hdmi_hpd_debounce_work);
9331 		aconnector->hdmi_prev_sink = NULL;
9332 	} else {
9333 		aconnector->hdmi_hpd_debounce_delay_ms = 0;
9334 	}
9335 
9336 	/*
9337 	 * configure support HPD hot plug connector_>polled default value is 0
9338 	 * which means HPD hot plug not supported
9339 	 */
9340 	switch (connector_type) {
9341 	case DRM_MODE_CONNECTOR_HDMIA:
9342 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9343 		aconnector->base.ycbcr_420_allowed =
9344 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
9345 		break;
9346 	case DRM_MODE_CONNECTOR_DisplayPort:
9347 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9348 		link->link_enc = link_enc_cfg_get_link_enc(link);
9349 		ASSERT(link->link_enc);
9350 		if (link->link_enc)
9351 			aconnector->base.ycbcr_420_allowed =
9352 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
9353 		break;
9354 	case DRM_MODE_CONNECTOR_DVID:
9355 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9356 		break;
9357 	case DRM_MODE_CONNECTOR_DVII:
9358 	case DRM_MODE_CONNECTOR_VGA:
9359 		aconnector->base.polled =
9360 			DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT;
9361 		break;
9362 	default:
9363 		break;
9364 	}
9365 
9366 	drm_object_attach_property(&aconnector->base.base,
9367 				dm->ddev->mode_config.scaling_mode_property,
9368 				DRM_MODE_SCALE_NONE);
9369 
9370 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA
9371 		|| (connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root))
9372 		drm_connector_attach_broadcast_rgb_property(&aconnector->base);
9373 
9374 	drm_object_attach_property(&aconnector->base.base,
9375 				adev->mode_info.underscan_property,
9376 				UNDERSCAN_OFF);
9377 	drm_object_attach_property(&aconnector->base.base,
9378 				adev->mode_info.underscan_hborder_property,
9379 				0);
9380 	drm_object_attach_property(&aconnector->base.base,
9381 				adev->mode_info.underscan_vborder_property,
9382 				0);
9383 
9384 	if (!aconnector->mst_root)
9385 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
9386 
9387 	aconnector->base.state->max_bpc = 16;
9388 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
9389 
9390 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9391 		/* Content Type is currently only implemented for HDMI. */
9392 		drm_connector_attach_content_type_property(&aconnector->base);
9393 	}
9394 
9395 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9396 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
9397 			drm_connector_attach_colorspace_property(&aconnector->base);
9398 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
9399 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
9400 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
9401 			drm_connector_attach_colorspace_property(&aconnector->base);
9402 	}
9403 
9404 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9405 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
9406 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
9407 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
9408 
9409 		if (!aconnector->mst_root)
9410 			drm_connector_attach_vrr_capable_property(&aconnector->base);
9411 
9412 		if (adev->dm.hdcp_workqueue)
9413 			drm_connector_attach_content_protection_property(&aconnector->base, true);
9414 	}
9415 
9416 	if (connector_type == DRM_MODE_CONNECTOR_eDP) {
9417 		struct drm_privacy_screen *privacy_screen;
9418 
9419 		drm_connector_attach_panel_type_property(&aconnector->base);
9420 
9421 		privacy_screen = drm_privacy_screen_get(adev_to_drm(adev)->dev, NULL);
9422 		if (!IS_ERR(privacy_screen)) {
9423 			drm_connector_attach_privacy_screen_provider(&aconnector->base,
9424 								     privacy_screen);
9425 		} else if (PTR_ERR(privacy_screen) != -ENODEV) {
9426 			drm_warn(adev_to_drm(adev), "Error getting privacy-screen\n");
9427 		}
9428 	}
9429 }
9430 
9431 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
9432 			      struct i2c_msg *msgs, int num)
9433 {
9434 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
9435 	struct ddc_service *ddc_service = i2c->ddc_service;
9436 	struct i2c_command cmd;
9437 	int i;
9438 	int result = -EIO;
9439 
9440 	if (!ddc_service->ddc_pin)
9441 		return result;
9442 
9443 	cmd.payloads = kzalloc_objs(struct i2c_payload, num);
9444 
9445 	if (!cmd.payloads)
9446 		return result;
9447 
9448 	cmd.number_of_payloads = num;
9449 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
9450 	cmd.speed = 100;
9451 
9452 	for (i = 0; i < num; i++) {
9453 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
9454 		cmd.payloads[i].address = msgs[i].addr;
9455 		cmd.payloads[i].length = msgs[i].len;
9456 		cmd.payloads[i].data = msgs[i].buf;
9457 	}
9458 
9459 	if (i2c->oem) {
9460 		if (dc_submit_i2c_oem(
9461 			    ddc_service->ctx->dc,
9462 			    &cmd))
9463 			result = num;
9464 	} else {
9465 		if (dc_submit_i2c(
9466 			    ddc_service->ctx->dc,
9467 			    ddc_service->link->link_index,
9468 			    &cmd))
9469 			result = num;
9470 	}
9471 
9472 	kfree(cmd.payloads);
9473 	return result;
9474 }
9475 
9476 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
9477 {
9478 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
9479 }
9480 
9481 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
9482 	.master_xfer = amdgpu_dm_i2c_xfer,
9483 	.functionality = amdgpu_dm_i2c_func,
9484 };
9485 
9486 static struct amdgpu_i2c_adapter *
9487 create_i2c(struct ddc_service *ddc_service, bool oem)
9488 {
9489 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
9490 	struct amdgpu_i2c_adapter *i2c;
9491 
9492 	i2c = kzalloc_obj(struct amdgpu_i2c_adapter);
9493 	if (!i2c)
9494 		return NULL;
9495 	i2c->base.owner = THIS_MODULE;
9496 	i2c->base.dev.parent = &adev->pdev->dev;
9497 	i2c->base.algo = &amdgpu_dm_i2c_algo;
9498 	if (oem)
9499 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c OEM bus");
9500 	else
9501 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d",
9502 			 ddc_service->link->link_index);
9503 	i2c_set_adapdata(&i2c->base, i2c);
9504 	i2c->ddc_service = ddc_service;
9505 	i2c->oem = oem;
9506 
9507 	return i2c;
9508 }
9509 
9510 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
9511 {
9512 	struct cec_connector_info conn_info;
9513 	struct drm_device *ddev = aconnector->base.dev;
9514 	struct device *hdmi_dev = ddev->dev;
9515 
9516 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
9517 		drm_info(ddev, "HDMI-CEC feature masked\n");
9518 		return -EINVAL;
9519 	}
9520 
9521 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
9522 	aconnector->notifier =
9523 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
9524 	if (!aconnector->notifier) {
9525 		drm_err(ddev, "Failed to create cec notifier\n");
9526 		return -ENOMEM;
9527 	}
9528 
9529 	return 0;
9530 }
9531 
9532 /*
9533  * Note: this function assumes that dc_link_detect() was called for the
9534  * dc_link which will be represented by this aconnector.
9535  */
9536 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
9537 				    struct amdgpu_dm_connector *aconnector,
9538 				    u32 link_index,
9539 				    struct amdgpu_encoder *aencoder)
9540 {
9541 	int res = 0;
9542 	int connector_type;
9543 	struct dc *dc = dm->dc;
9544 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
9545 	struct amdgpu_i2c_adapter *i2c;
9546 
9547 	/* Not needed for writeback connector */
9548 	link->priv = aconnector;
9549 
9550 
9551 	i2c = create_i2c(link->ddc, false);
9552 	if (!i2c) {
9553 		drm_err(adev_to_drm(dm->adev), "Failed to create i2c adapter data\n");
9554 		return -ENOMEM;
9555 	}
9556 
9557 	aconnector->i2c = i2c;
9558 	res = devm_i2c_add_adapter(dm->adev->dev, &i2c->base);
9559 
9560 	if (res) {
9561 		drm_err(adev_to_drm(dm->adev), "Failed to register hw i2c %d\n", link->link_index);
9562 		goto out_free;
9563 	}
9564 
9565 	connector_type = to_drm_connector_type(link->connector_signal, link->link_id.id);
9566 
9567 	res = drm_connector_init_with_ddc(
9568 			dm->ddev,
9569 			&aconnector->base,
9570 			&amdgpu_dm_connector_funcs,
9571 			connector_type,
9572 			&i2c->base);
9573 
9574 	if (res) {
9575 		drm_err(adev_to_drm(dm->adev), "connector_init failed\n");
9576 		aconnector->connector_id = -1;
9577 		goto out_free;
9578 	}
9579 
9580 	drm_connector_helper_add(
9581 			&aconnector->base,
9582 			&amdgpu_dm_connector_helper_funcs);
9583 
9584 	amdgpu_dm_connector_init_helper(
9585 		dm,
9586 		aconnector,
9587 		connector_type,
9588 		link,
9589 		link_index);
9590 
9591 	drm_connector_attach_encoder(
9592 		&aconnector->base, &aencoder->base);
9593 
9594 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9595 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
9596 		amdgpu_dm_initialize_hdmi_connector(aconnector);
9597 
9598 	if (dc_is_dp_signal(link->connector_signal))
9599 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
9600 
9601 out_free:
9602 	if (res) {
9603 		kfree(i2c);
9604 		aconnector->i2c = NULL;
9605 	}
9606 	return res;
9607 }
9608 
9609 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
9610 {
9611 	switch (adev->mode_info.num_crtc) {
9612 	case 1:
9613 		return 0x1;
9614 	case 2:
9615 		return 0x3;
9616 	case 3:
9617 		return 0x7;
9618 	case 4:
9619 		return 0xf;
9620 	case 5:
9621 		return 0x1f;
9622 	case 6:
9623 	default:
9624 		return 0x3f;
9625 	}
9626 }
9627 
9628 static int amdgpu_dm_encoder_init(struct drm_device *dev,
9629 				  struct amdgpu_encoder *aencoder,
9630 				  uint32_t link_index)
9631 {
9632 	struct amdgpu_device *adev = drm_to_adev(dev);
9633 
9634 	int res = drm_encoder_init(dev,
9635 				   &aencoder->base,
9636 				   &amdgpu_dm_encoder_funcs,
9637 				   DRM_MODE_ENCODER_TMDS,
9638 				   NULL);
9639 
9640 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
9641 
9642 	if (!res)
9643 		aencoder->encoder_id = link_index;
9644 	else
9645 		aencoder->encoder_id = -1;
9646 
9647 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
9648 
9649 	return res;
9650 }
9651 
9652 static void manage_dm_interrupts(struct amdgpu_device *adev,
9653 				 struct amdgpu_crtc *acrtc,
9654 				 struct dm_crtc_state *acrtc_state)
9655 {	/*
9656 	 * We cannot be sure that the frontend index maps to the same
9657 	 * backend index - some even map to more than one.
9658 	 * So we have to go through the CRTC to find the right IRQ.
9659 	 */
9660 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
9661 			adev,
9662 			acrtc->crtc_id);
9663 	struct drm_device *dev = adev_to_drm(adev);
9664 
9665 	struct drm_vblank_crtc_config config = {0};
9666 	struct dc_crtc_timing *timing;
9667 	int offdelay;
9668 
9669 	if (acrtc_state) {
9670 		timing = &acrtc_state->stream->timing;
9671 
9672 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) >=
9673 		      IP_VERSION(3, 2, 0) &&
9674 		      !(adev->flags & AMD_IS_APU)) {
9675 			/*
9676 			 * DGPUs NV3x and newer that support idle optimizations
9677 			 * experience intermittent flip-done timeouts on cursor
9678 			 * updates. Restore 5s offdelay behavior for now.
9679 			 *
9680 			 * Discussion on the issue:
9681 			 * https://lore.kernel.org/amd-gfx/20260217191632.1243826-1-sysdadmin@m1k.cloud/
9682 			 */
9683 			config.offdelay_ms = 5000;
9684 			config.disable_immediate = false;
9685 		} else if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
9686 			     IP_VERSION(3, 5, 0)) {
9687 			/*
9688 			 * Older HW and DGPU have issues with instant off;
9689 			 * use a 2 frame offdelay.
9690 			 */
9691 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
9692 						      timing->v_total *
9693 						      timing->h_total,
9694 						      timing->pix_clk_100hz);
9695 
9696 			config.offdelay_ms = offdelay ?: 30;
9697 		} else {
9698 			/* offdelay_ms = 0 will never disable vblank */
9699 			config.offdelay_ms = 1;
9700 			config.disable_immediate = true;
9701 		}
9702 
9703 		drm_crtc_vblank_on_config(&acrtc->base,
9704 					  &config);
9705 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_get.*/
9706 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9707 		case IP_VERSION(3, 0, 0):
9708 		case IP_VERSION(3, 0, 2):
9709 		case IP_VERSION(3, 0, 3):
9710 		case IP_VERSION(3, 2, 0):
9711 			if (amdgpu_irq_get(adev, &adev->pageflip_irq, irq_type))
9712 				drm_err(dev, "DM_IRQ: Cannot get pageflip irq!\n");
9713 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9714 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
9715 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
9716 #endif
9717 		}
9718 
9719 	} else {
9720 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
9721 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9722 		case IP_VERSION(3, 0, 0):
9723 		case IP_VERSION(3, 0, 2):
9724 		case IP_VERSION(3, 0, 3):
9725 		case IP_VERSION(3, 2, 0):
9726 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9727 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
9728 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
9729 #endif
9730 			if (amdgpu_irq_put(adev, &adev->pageflip_irq, irq_type))
9731 				drm_err(dev, "DM_IRQ: Cannot put pageflip irq!\n");
9732 		}
9733 
9734 		drm_crtc_vblank_off(&acrtc->base);
9735 	}
9736 }
9737 
9738 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
9739 				      struct amdgpu_crtc *acrtc)
9740 {
9741 	int irq_type =
9742 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
9743 
9744 	/**
9745 	 * This reads the current state for the IRQ and force reapplies
9746 	 * the setting to hardware.
9747 	 */
9748 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
9749 }
9750 
9751 static bool
9752 is_scaling_state_different(const struct dm_connector_state *dm_state,
9753 			   const struct dm_connector_state *old_dm_state)
9754 {
9755 	if (dm_state->scaling != old_dm_state->scaling)
9756 		return true;
9757 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
9758 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
9759 			return true;
9760 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
9761 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
9762 			return true;
9763 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
9764 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
9765 		return true;
9766 	return false;
9767 }
9768 
9769 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
9770 					    struct drm_crtc_state *old_crtc_state,
9771 					    struct drm_connector_state *new_conn_state,
9772 					    struct drm_connector_state *old_conn_state,
9773 					    const struct drm_connector *connector,
9774 					    struct hdcp_workqueue *hdcp_w)
9775 {
9776 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
9777 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
9778 
9779 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
9780 		connector->index, connector->status, connector->dpms);
9781 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
9782 		old_conn_state->content_protection, new_conn_state->content_protection);
9783 
9784 	if (old_crtc_state)
9785 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9786 		old_crtc_state->enable,
9787 		old_crtc_state->active,
9788 		old_crtc_state->mode_changed,
9789 		old_crtc_state->active_changed,
9790 		old_crtc_state->connectors_changed);
9791 
9792 	if (new_crtc_state)
9793 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9794 		new_crtc_state->enable,
9795 		new_crtc_state->active,
9796 		new_crtc_state->mode_changed,
9797 		new_crtc_state->active_changed,
9798 		new_crtc_state->connectors_changed);
9799 
9800 	/* hdcp content type change */
9801 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
9802 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
9803 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9804 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
9805 		return true;
9806 	}
9807 
9808 	/* CP is being re enabled, ignore this */
9809 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
9810 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9811 		if (new_crtc_state && new_crtc_state->mode_changed) {
9812 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9813 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
9814 			return true;
9815 		}
9816 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
9817 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
9818 		return false;
9819 	}
9820 
9821 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
9822 	 *
9823 	 * Handles:	UNDESIRED -> ENABLED
9824 	 */
9825 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
9826 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
9827 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9828 
9829 	/* Stream removed and re-enabled
9830 	 *
9831 	 * Can sometimes overlap with the HPD case,
9832 	 * thus set update_hdcp to false to avoid
9833 	 * setting HDCP multiple times.
9834 	 *
9835 	 * Handles:	DESIRED -> DESIRED (Special case)
9836 	 */
9837 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
9838 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
9839 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9840 		dm_con_state->update_hdcp = false;
9841 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
9842 			__func__);
9843 		return true;
9844 	}
9845 
9846 	/* Hot-plug, headless s3, dpms
9847 	 *
9848 	 * Only start HDCP if the display is connected/enabled.
9849 	 * update_hdcp flag will be set to false until the next
9850 	 * HPD comes in.
9851 	 *
9852 	 * Handles:	DESIRED -> DESIRED (Special case)
9853 	 */
9854 	if (dm_con_state->update_hdcp &&
9855 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
9856 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
9857 		dm_con_state->update_hdcp = false;
9858 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
9859 			__func__);
9860 		return true;
9861 	}
9862 
9863 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
9864 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9865 			if (new_crtc_state && new_crtc_state->mode_changed) {
9866 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
9867 					__func__);
9868 				return true;
9869 			}
9870 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
9871 				__func__);
9872 			return false;
9873 		}
9874 
9875 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
9876 		return false;
9877 	}
9878 
9879 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9880 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
9881 			__func__);
9882 		return true;
9883 	}
9884 
9885 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
9886 	return false;
9887 }
9888 
9889 static void remove_stream(struct amdgpu_device *adev,
9890 			  struct amdgpu_crtc *acrtc,
9891 			  struct dc_stream_state *stream)
9892 {
9893 	/* this is the update mode case */
9894 
9895 	acrtc->otg_inst = -1;
9896 	acrtc->enabled = false;
9897 }
9898 
9899 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
9900 {
9901 
9902 	assert_spin_locked(&acrtc->base.dev->event_lock);
9903 	WARN_ON(acrtc->event);
9904 
9905 	acrtc->event = acrtc->base.state->event;
9906 
9907 	/* Set the flip status */
9908 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
9909 
9910 	/* Mark this event as consumed */
9911 	acrtc->base.state->event = NULL;
9912 
9913 	drm_dbg_state(acrtc->base.dev,
9914 		      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
9915 		      acrtc->crtc_id);
9916 }
9917 
9918 static void update_freesync_state_on_stream(
9919 	struct amdgpu_display_manager *dm,
9920 	struct dm_crtc_state *new_crtc_state,
9921 	struct dc_stream_state *new_stream,
9922 	struct dc_plane_state *surface,
9923 	u32 flip_timestamp_in_us)
9924 {
9925 	struct mod_vrr_params vrr_params;
9926 	struct dc_info_packet vrr_infopacket = {0};
9927 	struct amdgpu_device *adev = dm->adev;
9928 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9929 	unsigned long flags;
9930 	bool pack_sdp_v1_3 = false;
9931 	struct amdgpu_dm_connector *aconn;
9932 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
9933 
9934 	if (!new_stream)
9935 		return;
9936 
9937 	/*
9938 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9939 	 * For now it's sufficient to just guard against these conditions.
9940 	 */
9941 
9942 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9943 		return;
9944 
9945 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9946 	vrr_params = acrtc->dm_irq_params.vrr_params;
9947 
9948 	if (surface) {
9949 		mod_freesync_handle_preflip(
9950 			dm->freesync_module,
9951 			surface,
9952 			new_stream,
9953 			flip_timestamp_in_us,
9954 			&vrr_params);
9955 
9956 		if (adev->family < AMDGPU_FAMILY_AI &&
9957 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
9958 			mod_freesync_handle_v_update(dm->freesync_module,
9959 						     new_stream, &vrr_params);
9960 
9961 			/* Need to call this before the frame ends. */
9962 			dc_stream_adjust_vmin_vmax(dm->dc,
9963 						   new_crtc_state->stream,
9964 						   &vrr_params.adjust);
9965 		}
9966 	}
9967 
9968 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
9969 
9970 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
9971 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
9972 
9973 		if (aconn->vsdb_info.amd_vsdb_version == 1)
9974 			packet_type = PACKET_TYPE_FS_V1;
9975 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
9976 			packet_type = PACKET_TYPE_FS_V2;
9977 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
9978 			packet_type = PACKET_TYPE_FS_V3;
9979 
9980 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
9981 					&new_stream->adaptive_sync_infopacket);
9982 	}
9983 
9984 	mod_freesync_build_vrr_infopacket(
9985 		dm->freesync_module,
9986 		new_stream,
9987 		&vrr_params,
9988 		packet_type,
9989 		TRANSFER_FUNC_UNKNOWN,
9990 		&vrr_infopacket,
9991 		pack_sdp_v1_3);
9992 
9993 	new_crtc_state->freesync_vrr_info_changed |=
9994 		(memcmp(&new_crtc_state->vrr_infopacket,
9995 			&vrr_infopacket,
9996 			sizeof(vrr_infopacket)) != 0);
9997 
9998 	acrtc->dm_irq_params.vrr_params = vrr_params;
9999 	new_crtc_state->vrr_infopacket = vrr_infopacket;
10000 
10001 	new_stream->vrr_infopacket = vrr_infopacket;
10002 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
10003 
10004 	if (new_crtc_state->freesync_vrr_info_changed)
10005 		drm_dbg_kms(adev_to_drm(adev), "VRR packet update: crtc=%u enabled=%d state=%d",
10006 			      new_crtc_state->base.crtc->base.id,
10007 			      (int)new_crtc_state->base.vrr_enabled,
10008 			      (int)vrr_params.state);
10009 
10010 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10011 }
10012 
10013 static void update_stream_irq_parameters(
10014 	struct amdgpu_display_manager *dm,
10015 	struct dm_crtc_state *new_crtc_state)
10016 {
10017 	struct dc_stream_state *new_stream = new_crtc_state->stream;
10018 	struct mod_vrr_params vrr_params;
10019 	struct mod_freesync_config config = new_crtc_state->freesync_config;
10020 	struct amdgpu_device *adev = dm->adev;
10021 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
10022 	unsigned long flags;
10023 
10024 	if (!new_stream)
10025 		return;
10026 
10027 	/*
10028 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
10029 	 * For now it's sufficient to just guard against these conditions.
10030 	 */
10031 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
10032 		return;
10033 
10034 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
10035 	vrr_params = acrtc->dm_irq_params.vrr_params;
10036 
10037 	if (new_crtc_state->vrr_supported &&
10038 	    config.min_refresh_in_uhz &&
10039 	    config.max_refresh_in_uhz) {
10040 		/*
10041 		 * if freesync compatible mode was set, config.state will be set
10042 		 * in atomic check
10043 		 */
10044 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
10045 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
10046 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
10047 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
10048 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
10049 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
10050 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
10051 		} else {
10052 			config.state = new_crtc_state->base.vrr_enabled ?
10053 						     VRR_STATE_ACTIVE_VARIABLE :
10054 						     VRR_STATE_INACTIVE;
10055 		}
10056 	} else {
10057 		config.state = VRR_STATE_UNSUPPORTED;
10058 	}
10059 
10060 	mod_freesync_build_vrr_params(dm->freesync_module,
10061 				      new_stream,
10062 				      &config, &vrr_params);
10063 
10064 	new_crtc_state->freesync_config = config;
10065 	/* Copy state for access from DM IRQ handler */
10066 	acrtc->dm_irq_params.freesync_config = config;
10067 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
10068 	acrtc->dm_irq_params.vrr_params = vrr_params;
10069 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10070 }
10071 
10072 static void amdgpu_dm_handle_vrr_transition(struct amdgpu_display_manager *dm,
10073 					    struct dm_crtc_state *old_state,
10074 					    struct dm_crtc_state *new_state)
10075 {
10076 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
10077 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
10078 
10079 	if (!old_vrr_active && new_vrr_active) {
10080 		/* Transition VRR inactive -> active:
10081 		 * While VRR is active, we must not disable vblank irq, as a
10082 		 * reenable after disable would compute bogus vblank/pflip
10083 		 * timestamps if it likely happened inside display front-porch.
10084 		 *
10085 		 * We also need vupdate irq for the actual core vblank handling
10086 		 * at end of vblank.
10087 		 */
10088 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
10089 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
10090 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR off->on: Get vblank ref\n",
10091 				 __func__, new_state->base.crtc->base.id);
10092 
10093 		scoped_guard(mutex, &dm->dc_lock) {
10094 			dc_exit_ips_for_hw_access(dm->dc);
10095 			amdgpu_dm_psr_set_event(dm, new_state->stream, true,
10096 				psr_event_vrr_transition, true);
10097 			amdgpu_dm_replay_set_event(dm, new_state->stream, true,
10098 				replay_event_vrr, true);
10099 		}
10100 	} else if (old_vrr_active && !new_vrr_active) {
10101 		/* Transition VRR active -> inactive:
10102 		 * Allow vblank irq disable again for fixed refresh rate.
10103 		 */
10104 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
10105 		drm_crtc_vblank_put(new_state->base.crtc);
10106 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR on->off: Drop vblank ref\n",
10107 				 __func__, new_state->base.crtc->base.id);
10108 
10109 		scoped_guard(mutex, &dm->dc_lock) {
10110 			dc_exit_ips_for_hw_access(dm->dc);
10111 			amdgpu_dm_psr_set_event(dm, new_state->stream, false,
10112 				psr_event_vrr_transition, false);
10113 			amdgpu_dm_replay_set_event(dm, new_state->stream, false,
10114 				replay_event_vrr, false);
10115 		}
10116 	}
10117 }
10118 
10119 static void amdgpu_dm_commit_cursors(struct drm_atomic_commit *state)
10120 {
10121 	struct drm_plane *plane;
10122 	struct drm_plane_state *old_plane_state;
10123 	int i;
10124 
10125 	/*
10126 	 * TODO: Make this per-stream so we don't issue redundant updates for
10127 	 * commits with multiple streams.
10128 	 */
10129 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
10130 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
10131 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
10132 }
10133 
10134 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
10135 {
10136 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
10137 
10138 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
10139 }
10140 
10141 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
10142 				    struct drm_plane_state *old_plane_state,
10143 				    struct dc_stream_update *update)
10144 {
10145 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
10146 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
10147 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
10148 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
10149 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
10150 	uint64_t address = afb ? afb->address : 0;
10151 	struct dc_cursor_position position = {0};
10152 	struct dc_cursor_attributes attributes;
10153 	int ret;
10154 
10155 	if (!plane->state->fb && !old_plane_state->fb)
10156 		return;
10157 
10158 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
10159 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
10160 		       plane->state->crtc_h);
10161 
10162 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
10163 	if (ret)
10164 		return;
10165 
10166 	if (!position.enable) {
10167 		/* turn off cursor */
10168 		if (crtc_state && crtc_state->stream) {
10169 			dc_stream_set_cursor_position(crtc_state->stream,
10170 						      &position);
10171 			update->cursor_position = &crtc_state->stream->cursor_position;
10172 		}
10173 		return;
10174 	}
10175 
10176 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
10177 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
10178 
10179 	memset(&attributes, 0, sizeof(attributes));
10180 	attributes.address.high_part = upper_32_bits(address);
10181 	attributes.address.low_part  = lower_32_bits(address);
10182 	attributes.width             = plane->state->crtc_w;
10183 	attributes.height            = plane->state->crtc_h;
10184 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
10185 	attributes.rotation_angle    = 0;
10186 	attributes.attribute_flags.value = 0;
10187 
10188 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
10189 	 * legacy gamma setup.
10190 	 */
10191 	if (crtc_state->cm_is_degamma_srgb &&
10192 	    adev->dm.dc->caps.color.dpp.gamma_corr)
10193 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
10194 
10195 	if (afb)
10196 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
10197 
10198 	if (crtc_state->stream) {
10199 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
10200 						     &attributes))
10201 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
10202 
10203 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
10204 
10205 		if (!dc_stream_set_cursor_position(crtc_state->stream,
10206 						   &position))
10207 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
10208 
10209 		update->cursor_position = &crtc_state->stream->cursor_position;
10210 	}
10211 }
10212 
10213 static void amdgpu_dm_enable_self_refresh(struct amdgpu_display_manager *dm,
10214 					  struct amdgpu_crtc *acrtc_attach,
10215 					  const struct dm_crtc_state *acrtc_state,
10216 					  const u64 current_ts)
10217 {
10218 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
10219 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
10220 	struct amdgpu_dm_connector *aconn =
10221 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
10222 
10223 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
10224 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
10225 	    (psr->psr_feature_enabled || pr->replay_feature_enabled)) {
10226 		if (aconn->sr_skip_count > 0)
10227 			aconn->sr_skip_count--;
10228 
10229 		/* Allow SR when skip count is 0. */
10230 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
10231 
10232 		/*
10233 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
10234 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
10235 		 * can be enabled immediately once OS demonstrates an
10236 		 * adequate number of fast atomic commits to notify KMD
10237 		 * of update events.
10238 		 * See `amdgpu_dm_crtc_vblank_control_worker()`.
10239 		 */
10240 		if (acrtc_attach->dm_irq_params.allow_sr_entry &&
10241 			(current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
10242 			amdgpu_dm_psr_set_event(dm, acrtc_state->stream, false,
10243 				psr_event_hw_programming, false);
10244 
10245 			amdgpu_dm_replay_set_event(dm, acrtc_state->stream, false,
10246 				replay_event_hw_programming, false);
10247 		}
10248 	} else {
10249 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
10250 	}
10251 }
10252 
10253 static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state,
10254 				    struct drm_device *dev,
10255 				    struct amdgpu_display_manager *dm,
10256 				    struct drm_crtc *pcrtc,
10257 				    bool wait_for_vblank)
10258 {
10259 	u32 i;
10260 	u64 timestamp_ns = ktime_get_ns();
10261 	struct drm_plane *plane;
10262 	struct drm_plane_state *old_plane_state, *new_plane_state;
10263 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
10264 	struct drm_crtc_state *new_pcrtc_state =
10265 			drm_atomic_get_new_crtc_state(state, pcrtc);
10266 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
10267 	struct dm_crtc_state *dm_old_crtc_state =
10268 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
10269 	int planes_count = 0, vpos, hpos;
10270 	unsigned long flags;
10271 	u32 target_vblank, last_flip_vblank;
10272 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
10273 	bool cursor_update = false;
10274 	bool pflip_present = false;
10275 	bool dirty_rects_changed = false;
10276 	bool updated_planes_and_streams = false;
10277 	struct {
10278 		struct dc_surface_update surface_updates[MAX_SURFACES];
10279 		struct dc_plane_info plane_infos[MAX_SURFACES];
10280 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
10281 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
10282 		struct dc_stream_update stream_update;
10283 	} *bundle;
10284 
10285 	bundle = kzalloc_obj(*bundle);
10286 
10287 	if (!bundle) {
10288 		drm_err(dev, "Failed to allocate update bundle\n");
10289 		goto cleanup;
10290 	}
10291 
10292 	/*
10293 	 * Disable the cursor first if we're disabling all the planes.
10294 	 * It'll remain on the screen after the planes are re-enabled
10295 	 * if we don't.
10296 	 *
10297 	 * If the cursor is transitioning from native to overlay mode, the
10298 	 * native cursor needs to be disabled first.
10299 	 */
10300 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
10301 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10302 		struct dc_cursor_position cursor_position = {0};
10303 
10304 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
10305 						   &cursor_position))
10306 			drm_err(dev, "DC failed to disable native cursor\n");
10307 
10308 		bundle->stream_update.cursor_position =
10309 				&acrtc_state->stream->cursor_position;
10310 	}
10311 
10312 	if (acrtc_state->active_planes == 0 &&
10313 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10314 		amdgpu_dm_commit_cursors(state);
10315 
10316 	/* update planes when needed */
10317 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
10318 		struct drm_crtc *crtc = new_plane_state->crtc;
10319 		struct drm_crtc_state *new_crtc_state;
10320 		struct drm_framebuffer *fb = new_plane_state->fb;
10321 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
10322 		bool plane_needs_flip;
10323 		struct dc_plane_state *dc_plane;
10324 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
10325 
10326 		/* Cursor plane is handled after stream updates */
10327 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
10328 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10329 			if ((fb && crtc == pcrtc) ||
10330 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
10331 				cursor_update = true;
10332 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
10333 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
10334 			}
10335 
10336 			continue;
10337 		}
10338 
10339 		if (!fb || !crtc || pcrtc != crtc)
10340 			continue;
10341 
10342 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
10343 		if (!new_crtc_state->active)
10344 			continue;
10345 
10346 		dc_plane = dm_new_plane_state->dc_state;
10347 		if (!dc_plane)
10348 			continue;
10349 
10350 		bundle->surface_updates[planes_count].surface = dc_plane;
10351 		if (new_pcrtc_state->color_mgmt_changed) {
10352 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
10353 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
10354 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
10355 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
10356 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
10357 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
10358 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
10359 		}
10360 
10361 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
10362 				     &bundle->scaling_infos[planes_count]);
10363 
10364 		bundle->surface_updates[planes_count].scaling_info =
10365 			&bundle->scaling_infos[planes_count];
10366 
10367 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
10368 
10369 		pflip_present = pflip_present || plane_needs_flip;
10370 
10371 		if (!plane_needs_flip) {
10372 			planes_count += 1;
10373 			continue;
10374 		}
10375 
10376 		fill_dc_plane_info_and_addr(
10377 			dm->adev, new_plane_state,
10378 			afb->tiling_flags,
10379 			&bundle->plane_infos[planes_count],
10380 			&bundle->flip_addrs[planes_count].address,
10381 			afb->tmz_surface);
10382 
10383 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
10384 				 new_plane_state->plane->index,
10385 				 bundle->plane_infos[planes_count].dcc.enable);
10386 
10387 		bundle->surface_updates[planes_count].plane_info =
10388 			&bundle->plane_infos[planes_count];
10389 
10390 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
10391 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
10392 			fill_dc_dirty_rects(plane, old_plane_state,
10393 					    new_plane_state, new_crtc_state,
10394 					    &bundle->flip_addrs[planes_count],
10395 					    acrtc_state->stream->link->psr_settings.psr_version ==
10396 					    DC_PSR_VERSION_SU_1,
10397 					    &dirty_rects_changed);
10398 
10399 			/*
10400 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
10401 			 * and enabled it again after dirty regions are stable to avoid video glitch.
10402 			 * PSR-SU will be enabled in
10403 			 * amdgpu_dm_crtc_vblank_control_worker() if user
10404 			 * pause the video during the PSR-SU was disabled.
10405 			 */
10406 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
10407 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
10408 			    dirty_rects_changed) {
10409 				mutex_lock(&dm->dc_lock);
10410 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
10411 				timestamp_ns;
10412 				dc_exit_ips_for_hw_access(dm->dc);
10413 				amdgpu_dm_psr_set_event(dm, acrtc_state->stream, true,
10414 					psr_event_hw_programming, true);
10415 				mutex_unlock(&dm->dc_lock);
10416 			}
10417 		}
10418 
10419 		/*
10420 		 * Only allow immediate flips for fast updates that don't
10421 		 * change memory domain, FB pitch, DCC state, rotation or
10422 		 * mirroring.
10423 		 *
10424 		 * dm_crtc_helper_atomic_check() only accepts async flips with
10425 		 * fast updates.
10426 		 */
10427 		if (crtc->state->async_flip &&
10428 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
10429 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
10430 			drm_warn_once(state->dev,
10431 				      "[PLANE:%d:%s] async flip with non-fast update\n",
10432 				      plane->base.id, plane->name);
10433 
10434 		bundle->flip_addrs[planes_count].flip_immediate =
10435 			crtc->state->async_flip &&
10436 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
10437 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
10438 
10439 		timestamp_ns = ktime_get_ns();
10440 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
10441 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
10442 		bundle->surface_updates[planes_count].surface = dc_plane;
10443 
10444 		if (!bundle->surface_updates[planes_count].surface) {
10445 			drm_err(dev, "No surface for CRTC: id=%d\n",
10446 					acrtc_attach->crtc_id);
10447 			continue;
10448 		}
10449 
10450 		if (plane == pcrtc->primary)
10451 			update_freesync_state_on_stream(
10452 				dm,
10453 				acrtc_state,
10454 				acrtc_state->stream,
10455 				dc_plane,
10456 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
10457 
10458 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
10459 				 __func__,
10460 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
10461 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
10462 
10463 		planes_count += 1;
10464 
10465 	}
10466 
10467 	if (pflip_present) {
10468 		if (!vrr_active) {
10469 			/* Use old throttling in non-vrr fixed refresh rate mode
10470 			 * to keep flip scheduling based on target vblank counts
10471 			 * working in a backwards compatible way, e.g., for
10472 			 * clients using the GLX_OML_sync_control extension or
10473 			 * DRI3/Present extension with defined target_msc.
10474 			 */
10475 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
10476 		} else {
10477 			/* For variable refresh rate mode only:
10478 			 * Get vblank of last completed flip to avoid > 1 vrr
10479 			 * flips per video frame by use of throttling, but allow
10480 			 * flip programming anywhere in the possibly large
10481 			 * variable vrr vblank interval for fine-grained flip
10482 			 * timing control and more opportunity to avoid stutter
10483 			 * on late submission of flips.
10484 			 */
10485 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10486 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
10487 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10488 		}
10489 
10490 		target_vblank = last_flip_vblank + wait_for_vblank;
10491 
10492 		/*
10493 		 * Wait until we're out of the vertical blank period before the one
10494 		 * targeted by the flip
10495 		 */
10496 		while ((acrtc_attach->enabled &&
10497 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
10498 							    0, &vpos, &hpos, NULL,
10499 							    NULL, &pcrtc->hwmode)
10500 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
10501 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
10502 			(int)(target_vblank -
10503 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
10504 			usleep_range(1000, 1100);
10505 		}
10506 
10507 		/**
10508 		 * Prepare the flip event for the pageflip interrupt to handle.
10509 		 *
10510 		 * This only works in the case where we've already turned on the
10511 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
10512 		 * from 0 -> n planes we have to skip a hardware generated event
10513 		 * and rely on sending it from software.
10514 		 */
10515 		if (acrtc_attach->base.state->event &&
10516 		    acrtc_state->active_planes > 0) {
10517 			drm_crtc_vblank_get(pcrtc);
10518 
10519 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10520 
10521 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
10522 			prepare_flip_isr(acrtc_attach);
10523 
10524 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10525 		}
10526 
10527 		if (acrtc_state->stream) {
10528 			if (acrtc_state->freesync_vrr_info_changed)
10529 				bundle->stream_update.vrr_infopacket =
10530 					&acrtc_state->stream->vrr_infopacket;
10531 		}
10532 	} else if (cursor_update && acrtc_state->active_planes > 0) {
10533 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10534 		if (acrtc_attach->base.state->event) {
10535 			drm_crtc_vblank_get(pcrtc);
10536 			acrtc_attach->event = acrtc_attach->base.state->event;
10537 			acrtc_attach->base.state->event = NULL;
10538 		}
10539 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10540 	}
10541 
10542 	/* Update the planes if changed or disable if we don't have any. */
10543 	if ((planes_count || acrtc_state->active_planes == 0) &&
10544 		acrtc_state->stream) {
10545 		/*
10546 		 * If PSR or idle optimizations are enabled then flush out
10547 		 * any pending work before hardware programming.
10548 		 */
10549 		if (dm->vblank_control_workqueue)
10550 			flush_workqueue(dm->vblank_control_workqueue);
10551 
10552 		bundle->stream_update.stream = acrtc_state->stream;
10553 		if (new_pcrtc_state->mode_changed) {
10554 			bundle->stream_update.src = acrtc_state->stream->src;
10555 			bundle->stream_update.dst = acrtc_state->stream->dst;
10556 		}
10557 
10558 		if (new_pcrtc_state->color_mgmt_changed) {
10559 			/*
10560 			 * TODO: This isn't fully correct since we've actually
10561 			 * already modified the stream in place.
10562 			 */
10563 			bundle->stream_update.gamut_remap =
10564 				&acrtc_state->stream->gamut_remap_matrix;
10565 			bundle->stream_update.output_csc_transform =
10566 				&acrtc_state->stream->csc_color_matrix;
10567 			bundle->stream_update.out_transfer_func =
10568 				&acrtc_state->stream->out_transfer_func;
10569 			bundle->stream_update.lut3d_func =
10570 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
10571 			bundle->stream_update.func_shaper =
10572 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
10573 		}
10574 
10575 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
10576 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
10577 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
10578 
10579 		/*
10580 		 * If FreeSync state on the stream has changed then we need to
10581 		 * re-adjust the min/max bounds now that DC doesn't handle this
10582 		 * as part of commit.
10583 		 */
10584 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
10585 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10586 			dc_stream_adjust_vmin_vmax(
10587 				dm->dc, acrtc_state->stream,
10588 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
10589 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10590 		}
10591 		mutex_lock(&dm->dc_lock);
10592 		update_planes_and_stream_adapter(dm->dc,
10593 					 acrtc_state->update_type,
10594 					 planes_count,
10595 					 acrtc_state->stream,
10596 					 &bundle->stream_update,
10597 					 bundle->surface_updates);
10598 		updated_planes_and_streams = true;
10599 
10600 		/**
10601 		 * Enable or disable the interrupts on the backend.
10602 		 *
10603 		 * Most pipes are put into power gating when unused.
10604 		 *
10605 		 * When power gating is enabled on a pipe we lose the
10606 		 * interrupt enablement state when power gating is disabled.
10607 		 *
10608 		 * So we need to update the IRQ control state in hardware
10609 		 * whenever the pipe turns on (since it could be previously
10610 		 * power gated) or off (since some pipes can't be power gated
10611 		 * on some ASICs).
10612 		 */
10613 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
10614 			dm_update_pflip_irq_state(drm_to_adev(dev),
10615 						  acrtc_attach);
10616 		amdgpu_dm_enable_self_refresh(dm, acrtc_attach, acrtc_state,
10617 					      timestamp_ns);
10618 		mutex_unlock(&dm->dc_lock);
10619 	}
10620 
10621 	/*
10622 	 * Update cursor state *after* programming all the planes.
10623 	 * This avoids redundant programming in the case where we're going
10624 	 * to be disabling a single plane - those pipes are being disabled.
10625 	 */
10626 	if (acrtc_state->active_planes &&
10627 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
10628 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10629 		amdgpu_dm_commit_cursors(state);
10630 
10631 cleanup:
10632 	kfree(bundle);
10633 }
10634 
10635 static void amdgpu_dm_commit_audio(struct drm_device *dev,
10636 				   struct drm_atomic_commit *state)
10637 {
10638 	struct amdgpu_device *adev = drm_to_adev(dev);
10639 	struct amdgpu_dm_connector *aconnector;
10640 	struct drm_connector *connector;
10641 	struct drm_connector_state *old_con_state, *new_con_state;
10642 	struct drm_crtc_state *new_crtc_state;
10643 	struct dm_crtc_state *new_dm_crtc_state;
10644 	const struct dc_stream_status *status;
10645 	int i, inst;
10646 
10647 	/* Notify device removals. */
10648 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10649 		if (old_con_state->crtc != new_con_state->crtc) {
10650 			/* CRTC changes require notification. */
10651 			goto notify;
10652 		}
10653 
10654 		if (!new_con_state->crtc)
10655 			continue;
10656 
10657 		new_crtc_state = drm_atomic_get_new_crtc_state(
10658 			state, new_con_state->crtc);
10659 
10660 		if (!new_crtc_state)
10661 			continue;
10662 
10663 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10664 			continue;
10665 
10666 notify:
10667 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10668 			continue;
10669 
10670 		aconnector = to_amdgpu_dm_connector(connector);
10671 
10672 		mutex_lock(&adev->dm.audio_lock);
10673 		inst = aconnector->audio_inst;
10674 		aconnector->audio_inst = -1;
10675 		mutex_unlock(&adev->dm.audio_lock);
10676 
10677 		amdgpu_dm_audio_eld_notify(adev, inst);
10678 	}
10679 
10680 	/* Notify audio device additions. */
10681 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10682 		if (!new_con_state->crtc)
10683 			continue;
10684 
10685 		new_crtc_state = drm_atomic_get_new_crtc_state(
10686 			state, new_con_state->crtc);
10687 
10688 		if (!new_crtc_state)
10689 			continue;
10690 
10691 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10692 			continue;
10693 
10694 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
10695 		if (!new_dm_crtc_state->stream)
10696 			continue;
10697 
10698 		status = dc_stream_get_status(new_dm_crtc_state->stream);
10699 		if (!status)
10700 			continue;
10701 
10702 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10703 			continue;
10704 
10705 		aconnector = to_amdgpu_dm_connector(connector);
10706 
10707 		mutex_lock(&adev->dm.audio_lock);
10708 		inst = status->audio_inst;
10709 		aconnector->audio_inst = inst;
10710 		mutex_unlock(&adev->dm.audio_lock);
10711 
10712 		amdgpu_dm_audio_eld_notify(adev, inst);
10713 	}
10714 }
10715 
10716 /*
10717  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
10718  * @crtc_state: the DRM CRTC state
10719  * @stream_state: the DC stream state.
10720  *
10721  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
10722  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
10723  */
10724 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
10725 						struct dc_stream_state *stream_state)
10726 {
10727 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
10728 }
10729 
10730 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
10731 			      struct dm_crtc_state *crtc_state)
10732 {
10733 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
10734 }
10735 
10736 /**
10737  * amdgpu_dm_mod_power_update_streams - update mod_power stream state on modeset
10738  * @state: the drm atomic state
10739  * @dm: the display manager to update mod_power on
10740  *
10741  * Notify mod_power of stream changes on modeset events, and disable PSR/Replay
10742  * in preparation for hardware programming. See also
10743  * amdgpu_dm_mod_power_setup_streams() for post-modeset mod_power setup.
10744  */
10745 static void amdgpu_dm_mod_power_update_streams(struct drm_atomic_commit *state,
10746 					       struct amdgpu_display_manager *dm)
10747 {
10748 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10749 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10750 	struct amdgpu_dm_connector *aconnector;
10751 	struct drm_crtc *crtc;
10752 	int i = 0;
10753 
10754 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10755 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10756 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10757 
10758 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10759 			continue;
10760 
10761 		/*
10762 		 * Update mod_power on modeset event in preparation for hw
10763 		 * programming. Always use the old stream, since it would have
10764 		 * been previously added to mod_power. If old stream is null (on
10765 		 * crtc enable, for example), mod_power will no-op, which is the
10766 		 * desried behavior.
10767 		 */
10768 		if (old_crtc_state->active) {
10769 			scoped_guard(mutex, &dm->dc_lock) {
10770 				dc_exit_ips_for_hw_access(dm->dc);
10771 				amdgpu_dm_psr_set_event(dm, dm_old_crtc_state->stream, true,
10772 					psr_event_hw_programming, true);
10773 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, true,
10774 					replay_event_hw_programming, true);
10775 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, false,
10776 					replay_event_general_ui, false);
10777 			}
10778 		}
10779 
10780 		if (new_crtc_state->active) {
10781 			aconnector = (struct amdgpu_dm_connector *)
10782 				dm_new_crtc_state->stream->dm_stream_context;
10783 			if (old_crtc_state->active) {
10784 				mod_power_replace_stream(dm->power_module,
10785 					dm_old_crtc_state->stream,
10786 					dm_new_crtc_state->stream,
10787 					&aconnector->psr_caps);
10788 			} else {
10789 				mod_power_add_stream(dm->power_module,
10790 					dm_new_crtc_state->stream,
10791 					&aconnector->psr_caps);
10792 			}
10793 		} else if (old_crtc_state->active) {
10794 			mod_power_remove_stream(dm->power_module,
10795 				dm_old_crtc_state->stream);
10796 		}
10797 	}
10798 }
10799 
10800 /**
10801  * amdgpu_dm_mod_power_setup_streams - setup mod_power stream state post modeset
10802  * @state: the drm atomic state
10803  * @dm: the display manager to update mod_power on
10804  *
10805  * Notify mod_power of mode_change. This needs to be done after dc_stream
10806  * updates have been committed, and VRR parameters have been updated.
10807  */
10808 static void amdgpu_dm_mod_power_setup_streams(struct drm_atomic_commit *state,
10809 					      struct amdgpu_display_manager *dm)
10810 {
10811 	struct dm_crtc_state *dm_new_crtc_state;
10812 	struct drm_crtc_state *new_crtc_state;
10813 	struct amdgpu_crtc *acrtc;
10814 	struct drm_crtc *crtc;
10815 	int i = 0;
10816 
10817 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10818 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10819 		acrtc = to_amdgpu_crtc(crtc);
10820 
10821 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10822 			continue;
10823 
10824 		if (new_crtc_state->active) {
10825 			amdgpu_dm_link_setup_replay(dm_new_crtc_state->stream,
10826 					&acrtc->dm_irq_params.vrr_params);
10827 			mod_power_notify_mode_change(dm->power_module,
10828 						dm_new_crtc_state->stream,
10829 						false);
10830 
10831 			/*
10832 			 * Block PSR / Replay on the new stream until display settles post-modeset.
10833 			 * These events will be cleared by amdgpu_dm_enable_self_refresh() once
10834 			 * allow_sr_entry becomes true.
10835 			 */
10836 			amdgpu_dm_psr_set_event(dm, dm_new_crtc_state->stream, true,
10837 				psr_event_hw_programming, true);
10838 
10839 			amdgpu_dm_replay_set_event(dm, dm_new_crtc_state->stream, true,
10840 				replay_event_hw_programming | replay_event_general_ui,
10841 				true);
10842 		}
10843 	}
10844 
10845 }
10846 
10847 static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state,
10848 					struct dc_state *dc_state)
10849 {
10850 	struct drm_device *dev = state->dev;
10851 	struct amdgpu_device *adev = drm_to_adev(dev);
10852 	struct amdgpu_display_manager *dm = &adev->dm;
10853 	struct drm_crtc *crtc;
10854 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10855 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10856 	struct drm_connector_state *old_con_state;
10857 	struct drm_connector *connector;
10858 	bool mode_set_reset_required = false;
10859 	u32 i;
10860 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
10861 	bool set_backlight_level = false;
10862 
10863 	/* Disable writeback */
10864 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
10865 		struct dm_connector_state *dm_old_con_state;
10866 		struct amdgpu_crtc *acrtc;
10867 
10868 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
10869 			continue;
10870 
10871 		old_crtc_state = NULL;
10872 
10873 		dm_old_con_state = to_dm_connector_state(old_con_state);
10874 		if (!dm_old_con_state->base.crtc)
10875 			continue;
10876 
10877 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
10878 		if (acrtc)
10879 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10880 
10881 		if (!acrtc || !acrtc->wb_enabled)
10882 			continue;
10883 
10884 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10885 
10886 		dm_clear_writeback(dm, dm_old_crtc_state);
10887 		acrtc->wb_enabled = false;
10888 	}
10889 
10890 	amdgpu_dm_mod_power_update_streams(state, dm);
10891 
10892 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
10893 				      new_crtc_state, i) {
10894 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10895 
10896 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10897 
10898 		if (old_crtc_state->active &&
10899 		    (!new_crtc_state->active ||
10900 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10901 			manage_dm_interrupts(adev, acrtc, NULL);
10902 			dc_stream_release(dm_old_crtc_state->stream);
10903 		}
10904 	}
10905 
10906 	drm_atomic_helper_calc_timestamping_constants(state);
10907 
10908 	/* update changed items */
10909 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10910 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10911 
10912 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10913 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10914 
10915 		drm_dbg_state(state->dev,
10916 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
10917 			acrtc->crtc_id,
10918 			new_crtc_state->enable,
10919 			new_crtc_state->active,
10920 			new_crtc_state->planes_changed,
10921 			new_crtc_state->mode_changed,
10922 			new_crtc_state->active_changed,
10923 			new_crtc_state->connectors_changed);
10924 
10925 		/* Disable cursor if disabling crtc */
10926 		if (old_crtc_state->active && !new_crtc_state->active) {
10927 			struct dc_cursor_position position;
10928 
10929 			memset(&position, 0, sizeof(position));
10930 			mutex_lock(&dm->dc_lock);
10931 			dc_exit_ips_for_hw_access(dm->dc);
10932 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
10933 			mutex_unlock(&dm->dc_lock);
10934 		}
10935 
10936 		/* Copy all transient state flags into dc state */
10937 		if (dm_new_crtc_state->stream) {
10938 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
10939 							    dm_new_crtc_state->stream);
10940 		}
10941 
10942 		/* handles headless hotplug case, updating new_state and
10943 		 * aconnector as needed
10944 		 */
10945 
10946 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
10947 
10948 			drm_dbg_atomic(dev,
10949 				       "Atomic commit: SET crtc id %d: [%p]\n",
10950 				       acrtc->crtc_id, acrtc);
10951 
10952 			if (!dm_new_crtc_state->stream) {
10953 				/*
10954 				 * this could happen because of issues with
10955 				 * userspace notifications delivery.
10956 				 * In this case userspace tries to set mode on
10957 				 * display which is disconnected in fact.
10958 				 * dc_sink is NULL in this case on aconnector.
10959 				 * We expect reset mode will come soon.
10960 				 *
10961 				 * This can also happen when unplug is done
10962 				 * during resume sequence ended
10963 				 *
10964 				 * In this case, we want to pretend we still
10965 				 * have a sink to keep the pipe running so that
10966 				 * hw state is consistent with the sw state
10967 				 */
10968 				drm_dbg_atomic(dev,
10969 					       "Failed to create new stream for crtc %d\n",
10970 						acrtc->base.base.id);
10971 				continue;
10972 			}
10973 
10974 			if (dm_old_crtc_state->stream)
10975 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10976 
10977 			pm_runtime_get_noresume(dev->dev);
10978 
10979 			acrtc->enabled = true;
10980 			acrtc->hw_mode = new_crtc_state->mode;
10981 			crtc->hwmode = new_crtc_state->mode;
10982 			mode_set_reset_required = true;
10983 			set_backlight_level = true;
10984 		} else if (modereset_required(new_crtc_state)) {
10985 			drm_dbg_atomic(dev,
10986 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
10987 				       acrtc->crtc_id, acrtc);
10988 			/* i.e. reset mode */
10989 			if (dm_old_crtc_state->stream)
10990 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10991 
10992 			mode_set_reset_required = true;
10993 		}
10994 	} /* for_each_crtc_in_state() */
10995 
10996 	/* if there mode set or reset, flush vblank work queue */
10997 	if (mode_set_reset_required) {
10998 		if (dm->vblank_control_workqueue)
10999 			flush_workqueue(dm->vblank_control_workqueue);
11000 	}
11001 
11002 	dm_enable_per_frame_crtc_master_sync(dc_state);
11003 	mutex_lock(&dm->dc_lock);
11004 	dc_exit_ips_for_hw_access(dm->dc);
11005 	WARN_ON(!dc_commit_streams(dm->dc, &params));
11006 
11007 	bool frl_stream_found = false;
11008 
11009 	for (i = 0; i < params.stream_count; i++) {
11010 		struct dc_stream_state *stream = params.streams[i];
11011 
11012 		if (stream->signal == SIGNAL_TYPE_HDMI_FRL) {
11013 			frl_stream_found = true;
11014 			break;
11015 		}
11016 	}
11017 	if (frl_stream_found) {
11018 		if (queue_delayed_work(dm->hdmi_frl_status_polling_wq,
11019 				       &dm->hdmi_frl_status_polling_work,
11020 				       msecs_to_jiffies(dm->hdmi_frl_status_polling_delay_ms)))
11021 			drm_dbg_kms(dev, "200ms frl status polling starts ...\n");
11022 	} else {
11023 		if (cancel_delayed_work_sync(&dm->hdmi_frl_status_polling_work))
11024 			drm_dbg_kms(dev, "200ms frl status polling stops ...\n");
11025 	}
11026 	/* Allow idle optimization when vblank count is 0 for display off */
11027 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
11028 		dc_allow_idle_optimizations(dm->dc, true);
11029 	mutex_unlock(&dm->dc_lock);
11030 
11031 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11032 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11033 
11034 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11035 
11036 		if (dm_new_crtc_state->stream != NULL) {
11037 			const struct dc_stream_status *status =
11038 					dc_stream_get_status(dm_new_crtc_state->stream);
11039 
11040 			if (!status)
11041 				status = dc_state_get_stream_status(dc_state,
11042 									 dm_new_crtc_state->stream);
11043 			if (!status)
11044 				drm_err(dev,
11045 					"got no status for stream %p on acrtc%p\n",
11046 					dm_new_crtc_state->stream, acrtc);
11047 			else
11048 				acrtc->otg_inst = status->primary_otg_inst;
11049 		}
11050 	}
11051 
11052 	/* During boot up and resume the DC layer will reset the panel brightness
11053 	 * to fix a flicker issue.
11054 	 * It will cause the dm->actual_brightness is not the current panel brightness
11055 	 * level. (the dm->brightness is the correct panel level)
11056 	 * So we set the backlight level with dm->brightness value after set mode
11057 	 */
11058 	if (set_backlight_level) {
11059 		for (i = 0; i < dm->num_of_edps; i++) {
11060 			if (dm->backlight_dev[i])
11061 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11062 		}
11063 	}
11064 }
11065 
11066 static void dm_set_writeback(struct amdgpu_display_manager *dm,
11067 			      struct dm_crtc_state *crtc_state,
11068 			      struct drm_connector *connector,
11069 			      struct drm_connector_state *new_con_state)
11070 {
11071 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
11072 	struct amdgpu_device *adev = dm->adev;
11073 	struct amdgpu_crtc *acrtc;
11074 	struct dc_writeback_info *wb_info;
11075 	struct pipe_ctx *pipe = NULL;
11076 	struct amdgpu_framebuffer *afb;
11077 	int i = 0;
11078 
11079 	wb_info = kzalloc_obj(*wb_info);
11080 	if (!wb_info) {
11081 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
11082 		return;
11083 	}
11084 
11085 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
11086 	if (!acrtc) {
11087 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
11088 		kfree(wb_info);
11089 		return;
11090 	}
11091 
11092 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
11093 	if (!afb) {
11094 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
11095 		kfree(wb_info);
11096 		return;
11097 	}
11098 
11099 	for (i = 0; i < MAX_PIPES; i++) {
11100 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
11101 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
11102 			break;
11103 		}
11104 	}
11105 
11106 	/* fill in wb_info */
11107 	wb_info->wb_enabled = true;
11108 
11109 	wb_info->dwb_pipe_inst = 0;
11110 	wb_info->dwb_params.dwbscl_black_color = 0;
11111 	wb_info->dwb_params.hdr_mult = 0x1F000;
11112 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
11113 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
11114 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
11115 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
11116 
11117 	/* width & height from crtc */
11118 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
11119 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
11120 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
11121 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
11122 
11123 	wb_info->dwb_params.cnv_params.crop_en = false;
11124 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
11125 
11126 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
11127 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
11128 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
11129 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
11130 
11131 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
11132 
11133 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
11134 
11135 	wb_info->dwb_params.scaler_taps.h_taps = 1;
11136 	wb_info->dwb_params.scaler_taps.v_taps = 1;
11137 	wb_info->dwb_params.scaler_taps.h_taps_c = 1;
11138 	wb_info->dwb_params.scaler_taps.v_taps_c = 1;
11139 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
11140 
11141 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
11142 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
11143 
11144 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
11145 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
11146 		wb_info->mcif_buf_params.chroma_address[i] = 0;
11147 	}
11148 
11149 	wb_info->mcif_buf_params.p_vmid = 1;
11150 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
11151 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
11152 		wb_info->mcif_warmup_params.region_size =
11153 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
11154 	}
11155 	wb_info->mcif_warmup_params.p_vmid = 1;
11156 	wb_info->writeback_source_plane = pipe->plane_state;
11157 
11158 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
11159 
11160 	acrtc->wb_pending = true;
11161 	acrtc->wb_conn = wb_conn;
11162 	drm_writeback_queue_job(wb_conn, new_con_state);
11163 }
11164 
11165 static void amdgpu_dm_update_hdcp(struct drm_atomic_commit *state)
11166 {
11167 	struct drm_connector_state *old_con_state, *new_con_state;
11168 	struct drm_device *dev = state->dev;
11169 	struct drm_connector *connector;
11170 	struct amdgpu_device *adev = drm_to_adev(dev);
11171 	int i;
11172 
11173 	if (!adev->dm.hdcp_workqueue)
11174 		return;
11175 
11176 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11177 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11178 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11179 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11180 		struct dm_crtc_state *dm_new_crtc_state;
11181 		struct amdgpu_dm_connector *aconnector;
11182 
11183 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11184 			continue;
11185 
11186 		aconnector = to_amdgpu_dm_connector(connector);
11187 
11188 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
11189 
11190 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
11191 			connector->index, connector->status, connector->dpms);
11192 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
11193 			old_con_state->content_protection, new_con_state->content_protection);
11194 
11195 		if (aconnector->dc_sink) {
11196 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
11197 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
11198 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
11199 				aconnector->dc_sink->edid_caps.display_name);
11200 			}
11201 		}
11202 
11203 		new_crtc_state = NULL;
11204 		old_crtc_state = NULL;
11205 
11206 		if (acrtc) {
11207 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11208 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11209 		}
11210 
11211 		if (old_crtc_state)
11212 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11213 			old_crtc_state->enable,
11214 			old_crtc_state->active,
11215 			old_crtc_state->mode_changed,
11216 			old_crtc_state->active_changed,
11217 			old_crtc_state->connectors_changed);
11218 
11219 		if (new_crtc_state)
11220 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11221 			new_crtc_state->enable,
11222 			new_crtc_state->active,
11223 			new_crtc_state->mode_changed,
11224 			new_crtc_state->active_changed,
11225 			new_crtc_state->connectors_changed);
11226 
11227 
11228 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11229 
11230 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
11231 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
11232 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
11233 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
11234 			dm_new_con_state->update_hdcp = true;
11235 			continue;
11236 		}
11237 
11238 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
11239 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
11240 			/* when display is unplugged from mst hub, connctor will
11241 			 * be destroyed within dm_dp_mst_connector_destroy. connector
11242 			 * hdcp perperties, like type, undesired, desired, enabled,
11243 			 * will be lost. So, save hdcp properties into hdcp_work within
11244 			 * amdgpu_dm_atomic_commit_tail. if the same display is
11245 			 * plugged back with same display index, its hdcp properties
11246 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
11247 			 */
11248 
11249 			bool enable_encryption = false;
11250 
11251 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
11252 				enable_encryption = true;
11253 
11254 			if (aconnector->dc_link && aconnector->dc_sink &&
11255 				aconnector->dc_link->type == dc_connection_mst_branch) {
11256 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
11257 				struct hdcp_workqueue *hdcp_w =
11258 					&hdcp_work[aconnector->dc_link->link_index];
11259 
11260 				hdcp_w->hdcp_content_type[connector->index] =
11261 					new_con_state->hdcp_content_type;
11262 				hdcp_w->content_protection[connector->index] =
11263 					new_con_state->content_protection;
11264 			}
11265 
11266 			if (new_crtc_state && new_crtc_state->mode_changed &&
11267 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
11268 				enable_encryption = true;
11269 
11270 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
11271 
11272 			if (aconnector->dc_link)
11273 				hdcp_update_display(
11274 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
11275 					new_con_state->hdcp_content_type, enable_encryption);
11276 		}
11277 	}
11278 }
11279 
11280 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state)
11281 {
11282 	struct drm_crtc *crtc;
11283 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11284 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11285 	int i, ret;
11286 
11287 	ret = drm_dp_mst_atomic_setup_commit(state);
11288 	if (ret)
11289 		return ret;
11290 
11291 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11292 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11293 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11294 		/*
11295 		 * Color management settings. We also update color properties
11296 		 * when a modeset is needed, to ensure it gets reprogrammed.
11297 		 */
11298 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
11299 		    (dm_new_crtc_state->base.color_mgmt_changed ||
11300 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11301 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11302 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
11303 			if (ret) {
11304 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
11305 				return ret;
11306 			}
11307 		}
11308 	}
11309 
11310 	return 0;
11311 }
11312 
11313 /**
11314  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
11315  * @state: The atomic state to commit
11316  *
11317  * This will tell DC to commit the constructed DC state from atomic_check,
11318  * programming the hardware. Any failures here implies a hardware failure, since
11319  * atomic check should have filtered anything non-kosher.
11320  */
11321 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state)
11322 {
11323 	struct drm_device *dev = state->dev;
11324 	struct amdgpu_device *adev = drm_to_adev(dev);
11325 	struct amdgpu_display_manager *dm = &adev->dm;
11326 	struct dm_atomic_state *dm_state;
11327 	struct dc_state *dc_state = NULL;
11328 	u32 i, j;
11329 	struct drm_crtc *crtc;
11330 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11331 	unsigned long flags;
11332 	bool wait_for_vblank = true;
11333 	struct drm_connector *connector;
11334 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
11335 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11336 	int crtc_disable_count = 0;
11337 
11338 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
11339 
11340 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
11341 	drm_dp_mst_atomic_wait_for_dependencies(state);
11342 
11343 	dm_state = dm_atomic_get_new_state(state);
11344 	if (dm_state && dm_state->context) {
11345 		dc_state = dm_state->context;
11346 		amdgpu_dm_commit_streams(state, dc_state);
11347 	}
11348 
11349 	amdgpu_dm_update_hdcp(state);
11350 
11351 	/* Handle connector state changes */
11352 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11353 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11354 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
11355 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11356 		struct dc_surface_update *dummy_updates;
11357 		struct dc_stream_update stream_update;
11358 		struct dc_info_packet hdr_packet;
11359 		struct dc_stream_status *status = NULL;
11360 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
11361 
11362 		memset(&stream_update, 0, sizeof(stream_update));
11363 
11364 		if (acrtc) {
11365 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11366 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11367 		}
11368 
11369 		/* Skip any modesets/resets */
11370 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
11371 			continue;
11372 
11373 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11374 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11375 
11376 		scaling_changed = is_scaling_state_different(dm_new_con_state,
11377 							     dm_old_con_state);
11378 
11379 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
11380 			(dm_old_crtc_state->stream->output_color_space !=
11381 				get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
11382 			output_color_space_changed = true;
11383 
11384 		abm_changed = dm_new_crtc_state->abm_level !=
11385 			      dm_old_crtc_state->abm_level;
11386 
11387 		hdr_changed =
11388 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
11389 
11390 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
11391 			continue;
11392 
11393 		stream_update.stream = dm_new_crtc_state->stream;
11394 		if (scaling_changed) {
11395 			update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
11396 					dm_new_con_state, dm_new_crtc_state->stream);
11397 
11398 			stream_update.src = dm_new_crtc_state->stream->src;
11399 			stream_update.dst = dm_new_crtc_state->stream->dst;
11400 		}
11401 
11402 		if (output_color_space_changed) {
11403 			dm_new_crtc_state->stream->output_color_space
11404 				= get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
11405 
11406 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
11407 		}
11408 
11409 		if (abm_changed) {
11410 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
11411 
11412 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
11413 		}
11414 
11415 		if (hdr_changed) {
11416 			fill_hdr_info_packet(new_con_state, &hdr_packet);
11417 			stream_update.hdr_static_metadata = &hdr_packet;
11418 		}
11419 
11420 		status = dc_stream_get_status(dm_new_crtc_state->stream);
11421 
11422 		if (WARN_ON(!status))
11423 			continue;
11424 
11425 		WARN_ON(!status->plane_count);
11426 
11427 		/*
11428 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
11429 		 * Here we create an empty update on each plane.
11430 		 * To fix this, DC should permit updating only stream properties.
11431 		 */
11432 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
11433 		if (!dummy_updates) {
11434 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
11435 			continue;
11436 		}
11437 		for (j = 0; j < status->plane_count; j++)
11438 			dummy_updates[j].surface = status->plane_states[j];
11439 
11440 		sort(dummy_updates, status->plane_count,
11441 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
11442 
11443 		mutex_lock(&dm->dc_lock);
11444 		dc_exit_ips_for_hw_access(dm->dc);
11445 		dc_update_planes_and_stream(dm->dc,
11446 					    dummy_updates,
11447 					    status->plane_count,
11448 					    dm_new_crtc_state->stream,
11449 					    &stream_update);
11450 		mutex_unlock(&dm->dc_lock);
11451 		kfree(dummy_updates);
11452 
11453 		drm_connector_update_privacy_screen(new_con_state);
11454 	}
11455 
11456 	/**
11457 	 * Enable interrupts for CRTCs that are newly enabled or went through
11458 	 * a modeset. It was intentionally deferred until after the front end
11459 	 * state was modified to wait until the OTG was on and so the IRQ
11460 	 * handlers didn't access stale or invalid state.
11461 	 */
11462 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11463 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11464 #ifdef CONFIG_DEBUG_FS
11465 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
11466 #endif
11467 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
11468 		if (old_crtc_state->active && !new_crtc_state->active)
11469 			crtc_disable_count++;
11470 
11471 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11472 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11473 
11474 		/* For freesync config update on crtc state and params for irq */
11475 		update_stream_irq_parameters(dm, dm_new_crtc_state);
11476 
11477 #ifdef CONFIG_DEBUG_FS
11478 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11479 		cur_crc_src = acrtc->dm_irq_params.crc_src;
11480 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11481 #endif
11482 
11483 		if (new_crtc_state->active &&
11484 		    (!old_crtc_state->active ||
11485 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11486 			dc_stream_retain(dm_new_crtc_state->stream);
11487 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
11488 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
11489 		}
11490 		/* Handle vrr on->off / off->on transitions */
11491 		amdgpu_dm_handle_vrr_transition(dm, dm_old_crtc_state, dm_new_crtc_state);
11492 
11493 #ifdef CONFIG_DEBUG_FS
11494 		if (new_crtc_state->active &&
11495 		    (!old_crtc_state->active ||
11496 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11497 			/**
11498 			 * Frontend may have changed so reapply the CRC capture
11499 			 * settings for the stream.
11500 			 */
11501 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
11502 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
11503 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
11504 					uint8_t cnt;
11505 
11506 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11507 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
11508 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
11509 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
11510 
11511 							/**
11512 							 * It takes 2 frames for HW to stably generate CRC when
11513 							 * resuming from suspend, so we set skip_frame_cnt 2.
11514 							 */
11515 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
11516 						}
11517 					}
11518 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11519 				}
11520 #endif
11521 				if (amdgpu_dm_crtc_configure_crc_source(
11522 					crtc, dm_new_crtc_state, cur_crc_src))
11523 					drm_dbg_atomic(dev, "Failed to configure crc source");
11524 			}
11525 		}
11526 #endif
11527 	}
11528 
11529 	amdgpu_dm_mod_power_setup_streams(state, dm);
11530 
11531 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
11532 		if (new_crtc_state->async_flip)
11533 			wait_for_vblank = false;
11534 
11535 	/* update planes when needed per crtc*/
11536 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
11537 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11538 
11539 		if (dm_new_crtc_state->stream)
11540 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
11541 	}
11542 
11543 	/* Enable writeback */
11544 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11545 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11546 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11547 
11548 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11549 			continue;
11550 
11551 		if (!new_con_state->writeback_job)
11552 			continue;
11553 
11554 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11555 
11556 		if (!new_crtc_state)
11557 			continue;
11558 
11559 		if (acrtc->wb_enabled)
11560 			continue;
11561 
11562 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11563 
11564 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
11565 		acrtc->wb_enabled = true;
11566 	}
11567 
11568 	/* Update audio instances for each connector. */
11569 	amdgpu_dm_commit_audio(dev, state);
11570 
11571 	/* restore the backlight level */
11572 	for (i = 0; i < dm->num_of_edps; i++) {
11573 		if (dm->backlight_dev[i] &&
11574 		    (dm->actual_brightness[i] != dm->brightness[i]))
11575 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11576 	}
11577 
11578 	/*
11579 	 * send vblank event on all events not handled in flip and
11580 	 * mark consumed event for drm_atomic_helper_commit_hw_done
11581 	 */
11582 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11583 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11584 
11585 		if (new_crtc_state->event)
11586 			drm_send_event_locked(dev, &new_crtc_state->event->base);
11587 
11588 		new_crtc_state->event = NULL;
11589 	}
11590 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11591 
11592 	/* Signal HW programming completion */
11593 	drm_atomic_helper_commit_hw_done(state);
11594 
11595 	if (wait_for_vblank)
11596 		drm_atomic_helper_wait_for_flip_done(dev, state);
11597 
11598 	drm_atomic_helper_cleanup_planes(dev, state);
11599 
11600 	/* Don't free the memory if we are hitting this as part of suspend.
11601 	 * This way we don't free any memory during suspend; see
11602 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
11603 	 * non-suspend modeset or when the driver is torn down.
11604 	 */
11605 	if (!adev->in_suspend) {
11606 		/* return the stolen vga memory back to VRAM */
11607 		if (!adev->mman.keep_stolen_vga_memory)
11608 			amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_VGA);
11609 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_EXTENDED);
11610 	}
11611 
11612 	/*
11613 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
11614 	 * so we can put the GPU into runtime suspend if we're not driving any
11615 	 * displays anymore
11616 	 */
11617 	for (i = 0; i < crtc_disable_count; i++)
11618 		pm_runtime_put_autosuspend(dev->dev);
11619 	pm_runtime_mark_last_busy(dev->dev);
11620 
11621 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
11622 }
11623 
11624 static int dm_force_atomic_commit(struct drm_connector *connector)
11625 {
11626 	int ret = 0;
11627 	struct drm_device *ddev = connector->dev;
11628 	struct drm_atomic_commit *state = drm_atomic_commit_alloc(ddev);
11629 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11630 	struct drm_plane *plane = disconnected_acrtc->base.primary;
11631 	struct drm_connector_state *conn_state;
11632 	struct drm_crtc_state *crtc_state;
11633 	struct drm_plane_state *plane_state;
11634 
11635 	if (!state)
11636 		return -ENOMEM;
11637 
11638 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
11639 
11640 	/* Construct an atomic state to restore previous display setting */
11641 
11642 	/*
11643 	 * Attach connectors to drm_atomic_commit
11644 	 */
11645 	conn_state = drm_atomic_get_connector_state(state, connector);
11646 
11647 	/* Check for error in getting connector state */
11648 	if (IS_ERR(conn_state)) {
11649 		ret = PTR_ERR(conn_state);
11650 		goto out;
11651 	}
11652 
11653 	/* Attach crtc to drm_atomic_commit*/
11654 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
11655 
11656 	/* Check for error in getting crtc state */
11657 	if (IS_ERR(crtc_state)) {
11658 		ret = PTR_ERR(crtc_state);
11659 		goto out;
11660 	}
11661 
11662 	/* force a restore */
11663 	crtc_state->mode_changed = true;
11664 
11665 	/* Attach plane to drm_atomic_commit */
11666 	plane_state = drm_atomic_get_plane_state(state, plane);
11667 
11668 	/* Check for error in getting plane state */
11669 	if (IS_ERR(plane_state)) {
11670 		ret = PTR_ERR(plane_state);
11671 		goto out;
11672 	}
11673 
11674 	/* Call commit internally with the state we just constructed */
11675 	ret = drm_atomic_commit(state);
11676 
11677 out:
11678 	drm_atomic_commit_put(state);
11679 	if (ret)
11680 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
11681 
11682 	return ret;
11683 }
11684 
11685 /*
11686  * This function handles all cases when set mode does not come upon hotplug.
11687  * This includes when a display is unplugged then plugged back into the
11688  * same port and when running without usermode desktop manager supprot
11689  */
11690 void dm_restore_drm_connector_state(struct drm_device *dev,
11691 				    struct drm_connector *connector)
11692 {
11693 	struct amdgpu_dm_connector *aconnector;
11694 	struct amdgpu_crtc *disconnected_acrtc;
11695 	struct dm_crtc_state *acrtc_state;
11696 
11697 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11698 		return;
11699 
11700 	aconnector = to_amdgpu_dm_connector(connector);
11701 
11702 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
11703 		return;
11704 
11705 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11706 	if (!disconnected_acrtc)
11707 		return;
11708 
11709 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
11710 	if (!acrtc_state->stream)
11711 		return;
11712 
11713 	/*
11714 	 * If the previous sink is not released and different from the current,
11715 	 * we deduce we are in a state where we can not rely on usermode call
11716 	 * to turn on the display, so we do it here
11717 	 */
11718 	if (acrtc_state->stream->sink != aconnector->dc_sink)
11719 		dm_force_atomic_commit(&aconnector->base);
11720 }
11721 
11722 /*
11723  * Grabs all modesetting locks to serialize against any blocking commits,
11724  * Waits for completion of all non blocking commits.
11725  */
11726 static int do_aquire_global_lock(struct drm_device *dev,
11727 				 struct drm_atomic_commit *state)
11728 {
11729 	struct drm_crtc *crtc;
11730 	struct drm_crtc_commit *commit;
11731 	long ret;
11732 
11733 	/*
11734 	 * Adding all modeset locks to aquire_ctx will
11735 	 * ensure that when the framework release it the
11736 	 * extra locks we are locking here will get released to
11737 	 */
11738 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
11739 	if (ret)
11740 		return ret;
11741 
11742 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
11743 		spin_lock(&crtc->commit_lock);
11744 		commit = list_first_entry_or_null(&crtc->commit_list,
11745 				struct drm_crtc_commit, commit_entry);
11746 		if (commit)
11747 			drm_crtc_commit_get(commit);
11748 		spin_unlock(&crtc->commit_lock);
11749 
11750 		if (!commit)
11751 			continue;
11752 
11753 		/*
11754 		 * Make sure all pending HW programming completed and
11755 		 * page flips done
11756 		 */
11757 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
11758 
11759 		if (ret > 0)
11760 			ret = wait_for_completion_interruptible_timeout(
11761 					&commit->flip_done, 10*HZ);
11762 
11763 		if (ret == 0)
11764 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
11765 				  crtc->base.id, crtc->name);
11766 
11767 		drm_crtc_commit_put(commit);
11768 	}
11769 
11770 	return ret < 0 ? ret : 0;
11771 }
11772 
11773 static void get_freesync_config_for_crtc(
11774 	struct dm_crtc_state *new_crtc_state,
11775 	struct dm_connector_state *new_con_state)
11776 {
11777 	struct mod_freesync_config config = {0};
11778 	struct amdgpu_dm_connector *aconnector;
11779 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
11780 	int vrefresh = drm_mode_vrefresh(mode);
11781 	bool fs_vid_mode = false;
11782 
11783 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11784 		return;
11785 
11786 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
11787 
11788 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
11789 					vrefresh >= aconnector->min_vfreq &&
11790 					vrefresh <= aconnector->max_vfreq;
11791 
11792 	if (new_crtc_state->vrr_supported) {
11793 		new_crtc_state->stream->ignore_msa_timing_param = true;
11794 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
11795 
11796 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
11797 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
11798 		config.vsif_supported = true;
11799 		config.btr = true;
11800 
11801 		if (fs_vid_mode) {
11802 			config.state = VRR_STATE_ACTIVE_FIXED;
11803 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
11804 			goto out;
11805 		} else if (new_crtc_state->base.vrr_enabled) {
11806 			config.state = VRR_STATE_ACTIVE_VARIABLE;
11807 		} else {
11808 			config.state = VRR_STATE_INACTIVE;
11809 		}
11810 	} else {
11811 		config.state = VRR_STATE_UNSUPPORTED;
11812 	}
11813 out:
11814 	new_crtc_state->freesync_config = config;
11815 }
11816 
11817 static void reset_freesync_config_for_crtc(
11818 	struct dm_crtc_state *new_crtc_state)
11819 {
11820 	new_crtc_state->vrr_supported = false;
11821 
11822 	memset(&new_crtc_state->vrr_infopacket, 0,
11823 	       sizeof(new_crtc_state->vrr_infopacket));
11824 }
11825 
11826 static bool
11827 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
11828 				 struct drm_crtc_state *new_crtc_state)
11829 {
11830 	const struct drm_display_mode *old_mode, *new_mode;
11831 
11832 	if (!old_crtc_state || !new_crtc_state)
11833 		return false;
11834 
11835 	old_mode = &old_crtc_state->mode;
11836 	new_mode = &new_crtc_state->mode;
11837 
11838 	if (old_mode->clock       == new_mode->clock &&
11839 	    old_mode->hdisplay    == new_mode->hdisplay &&
11840 	    old_mode->vdisplay    == new_mode->vdisplay &&
11841 	    old_mode->htotal      == new_mode->htotal &&
11842 	    old_mode->vtotal      != new_mode->vtotal &&
11843 	    old_mode->hsync_start == new_mode->hsync_start &&
11844 	    old_mode->vsync_start != new_mode->vsync_start &&
11845 	    old_mode->hsync_end   == new_mode->hsync_end &&
11846 	    old_mode->vsync_end   != new_mode->vsync_end &&
11847 	    old_mode->hskew       == new_mode->hskew &&
11848 	    old_mode->vscan       == new_mode->vscan &&
11849 	    (old_mode->vsync_end - old_mode->vsync_start) ==
11850 	    (new_mode->vsync_end - new_mode->vsync_start))
11851 		return true;
11852 
11853 	return false;
11854 }
11855 
11856 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
11857 {
11858 	u64 num, den, res;
11859 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
11860 
11861 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
11862 
11863 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
11864 	den = (unsigned long long)new_crtc_state->mode.htotal *
11865 	      (unsigned long long)new_crtc_state->mode.vtotal;
11866 
11867 	res = div_u64(num, den);
11868 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
11869 }
11870 
11871 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
11872 			 struct drm_atomic_commit *state,
11873 			 struct drm_crtc *crtc,
11874 			 struct drm_crtc_state *old_crtc_state,
11875 			 struct drm_crtc_state *new_crtc_state,
11876 			 bool enable,
11877 			 bool *lock_and_validation_needed)
11878 {
11879 	struct dm_atomic_state *dm_state = NULL;
11880 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11881 	struct dc_stream_state *new_stream;
11882 	struct amdgpu_device *adev = dm->adev;
11883 	int ret = 0;
11884 
11885 	/*
11886 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
11887 	 * update changed items
11888 	 */
11889 	struct amdgpu_crtc *acrtc = NULL;
11890 	struct drm_connector *connector = NULL;
11891 	struct amdgpu_dm_connector *aconnector = NULL;
11892 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
11893 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
11894 
11895 	new_stream = NULL;
11896 
11897 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11898 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11899 	acrtc = to_amdgpu_crtc(crtc);
11900 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
11901 	if (connector)
11902 		aconnector = to_amdgpu_dm_connector(connector);
11903 
11904 	/* TODO This hack should go away */
11905 	if (connector && enable) {
11906 		/* Make sure fake sink is created in plug-in scenario */
11907 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
11908 									connector);
11909 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
11910 									connector);
11911 
11912 		if (WARN_ON(!drm_new_conn_state)) {
11913 			ret = -EINVAL;
11914 			goto fail;
11915 		}
11916 
11917 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
11918 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
11919 
11920 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11921 			goto skip_modeset;
11922 
11923 		new_stream = create_validate_stream_for_sink(connector,
11924 							     &new_crtc_state->mode,
11925 							     dm_new_conn_state,
11926 							     dm_old_crtc_state->stream);
11927 
11928 		/*
11929 		 * we can have no stream on ACTION_SET if a display
11930 		 * was disconnected during S3, in this case it is not an
11931 		 * error, the OS will be updated after detection, and
11932 		 * will do the right thing on next atomic commit
11933 		 */
11934 
11935 		if (!new_stream) {
11936 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
11937 					__func__, acrtc->base.base.id);
11938 			ret = -ENOMEM;
11939 			goto fail;
11940 		}
11941 
11942 		/*
11943 		 * TODO: Check VSDB bits to decide whether this should
11944 		 * be enabled or not.
11945 		 */
11946 		new_stream->triggered_crtc_reset.enabled =
11947 			dm->force_timing_sync;
11948 
11949 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11950 
11951 		ret = fill_hdr_info_packet(drm_new_conn_state,
11952 					   &new_stream->hdr_static_metadata);
11953 		if (ret)
11954 			goto fail;
11955 
11956 		/*
11957 		 * If we already removed the old stream from the context
11958 		 * (and set the new stream to NULL) then we can't reuse
11959 		 * the old stream even if the stream and scaling are unchanged.
11960 		 * We'll hit the BUG_ON and black screen.
11961 		 *
11962 		 * TODO: Refactor this function to allow this check to work
11963 		 * in all conditions.
11964 		 */
11965 		if (amdgpu_freesync_vid_mode &&
11966 		    dm_new_crtc_state->stream &&
11967 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
11968 			goto skip_modeset;
11969 
11970 		if (dm_new_crtc_state->stream &&
11971 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11972 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
11973 			new_crtc_state->mode_changed = false;
11974 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
11975 					 new_crtc_state->mode_changed);
11976 		}
11977 	}
11978 
11979 	/* mode_changed flag may get updated above, need to check again */
11980 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11981 		goto skip_modeset;
11982 
11983 	drm_dbg_state(state->dev,
11984 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
11985 		acrtc->crtc_id,
11986 		new_crtc_state->enable,
11987 		new_crtc_state->active,
11988 		new_crtc_state->planes_changed,
11989 		new_crtc_state->mode_changed,
11990 		new_crtc_state->active_changed,
11991 		new_crtc_state->connectors_changed);
11992 
11993 	/* Remove stream for any changed/disabled CRTC */
11994 	if (!enable) {
11995 
11996 		if (!dm_old_crtc_state->stream)
11997 			goto skip_modeset;
11998 
11999 		/* Unset freesync video if it was active before */
12000 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
12001 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
12002 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
12003 		}
12004 
12005 		/* Now check if we should set freesync video mode */
12006 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
12007 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
12008 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
12009 		    is_timing_unchanged_for_freesync(new_crtc_state,
12010 						     old_crtc_state)) {
12011 			new_crtc_state->mode_changed = false;
12012 			drm_dbg_driver(adev_to_drm(adev),
12013 				"Mode change not required for front porch change, setting mode_changed to %d",
12014 				new_crtc_state->mode_changed);
12015 
12016 			set_freesync_fixed_config(dm_new_crtc_state);
12017 
12018 			goto skip_modeset;
12019 		} else if (amdgpu_freesync_vid_mode && aconnector &&
12020 			   is_freesync_video_mode(&new_crtc_state->mode,
12021 						  aconnector)) {
12022 			struct drm_display_mode *high_mode;
12023 
12024 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
12025 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
12026 				set_freesync_fixed_config(dm_new_crtc_state);
12027 		}
12028 
12029 		ret = dm_atomic_get_state(state, &dm_state);
12030 		if (ret)
12031 			goto fail;
12032 
12033 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
12034 				crtc->base.id);
12035 
12036 		/* i.e. reset mode */
12037 		if (dc_state_remove_stream(
12038 				dm->dc,
12039 				dm_state->context,
12040 				dm_old_crtc_state->stream) != DC_OK) {
12041 			ret = -EINVAL;
12042 			goto fail;
12043 		}
12044 
12045 		dc_stream_release(dm_old_crtc_state->stream);
12046 		dm_new_crtc_state->stream = NULL;
12047 
12048 		reset_freesync_config_for_crtc(dm_new_crtc_state);
12049 
12050 		*lock_and_validation_needed = true;
12051 
12052 	} else {/* Add stream for any updated/enabled CRTC */
12053 		/*
12054 		 * Quick fix to prevent NULL pointer on new_stream when
12055 		 * added MST connectors not found in existing crtc_state in the chained mode
12056 		 * TODO: need to dig out the root cause of that
12057 		 */
12058 		if (!connector)
12059 			goto skip_modeset;
12060 
12061 		if (modereset_required(new_crtc_state))
12062 			goto skip_modeset;
12063 
12064 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
12065 				     dm_old_crtc_state->stream)) {
12066 
12067 			WARN_ON(dm_new_crtc_state->stream);
12068 
12069 			ret = dm_atomic_get_state(state, &dm_state);
12070 			if (ret)
12071 				goto fail;
12072 
12073 			dm_new_crtc_state->stream = new_stream;
12074 
12075 			dc_stream_retain(new_stream);
12076 
12077 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
12078 					 crtc->base.id);
12079 
12080 			if (dc_state_add_stream(
12081 					dm->dc,
12082 					dm_state->context,
12083 					dm_new_crtc_state->stream) != DC_OK) {
12084 				ret = -EINVAL;
12085 				goto fail;
12086 			}
12087 
12088 			*lock_and_validation_needed = true;
12089 		}
12090 	}
12091 
12092 skip_modeset:
12093 	/* Release extra reference */
12094 	if (new_stream)
12095 		dc_stream_release(new_stream);
12096 
12097 	/*
12098 	 * We want to do dc stream updates that do not require a
12099 	 * full modeset below.
12100 	 */
12101 	if (!(enable && connector && new_crtc_state->active))
12102 		return 0;
12103 	/*
12104 	 * Given above conditions, the dc state cannot be NULL because:
12105 	 * 1. We're in the process of enabling CRTCs (just been added
12106 	 *    to the dc context, or already is on the context)
12107 	 * 2. Has a valid connector attached, and
12108 	 * 3. Is currently active and enabled.
12109 	 * => The dc stream state currently exists.
12110 	 */
12111 	BUG_ON(dm_new_crtc_state->stream == NULL);
12112 
12113 	/* Scaling or underscan settings */
12114 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
12115 				drm_atomic_crtc_needs_modeset(new_crtc_state))
12116 		update_stream_scaling_settings(adev_to_drm(adev),
12117 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
12118 
12119 	/* ABM settings */
12120 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
12121 
12122 	/*
12123 	 * Color management settings. We also update color properties
12124 	 * when a modeset is needed, to ensure it gets reprogrammed.
12125 	 */
12126 	if (dm_new_crtc_state->base.color_mgmt_changed ||
12127 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
12128 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
12129 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
12130 		if (ret)
12131 			goto fail;
12132 	}
12133 
12134 	/* Update Freesync settings. */
12135 	get_freesync_config_for_crtc(dm_new_crtc_state,
12136 				     dm_new_conn_state);
12137 
12138 	return ret;
12139 
12140 fail:
12141 	if (new_stream)
12142 		dc_stream_release(new_stream);
12143 	return ret;
12144 }
12145 
12146 static bool should_reset_plane(struct drm_atomic_commit *state,
12147 			       struct drm_plane *plane,
12148 			       struct drm_plane_state *old_plane_state,
12149 			       struct drm_plane_state *new_plane_state)
12150 {
12151 	struct drm_plane *other;
12152 	struct drm_plane_state *old_other_state, *new_other_state;
12153 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12154 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
12155 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
12156 	struct drm_connector_state *new_con_state;
12157 	struct drm_connector *connector;
12158 	int i;
12159 
12160 	/*
12161 	 * TODO: Remove this hack for all asics once it proves that the
12162 	 * fast updates works fine on DCN3.2+.
12163 	 */
12164 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
12165 	    state->allow_modeset)
12166 		return true;
12167 
12168 	/* Check for writeback commit */
12169 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
12170 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
12171 			continue;
12172 
12173 		if (new_con_state->writeback_job)
12174 			return true;
12175 	}
12176 
12177 	if (amdgpu_in_reset(adev) && state->allow_modeset)
12178 		return true;
12179 
12180 	/* Exit early if we know that we're adding or removing the plane. */
12181 	if (old_plane_state->crtc != new_plane_state->crtc)
12182 		return true;
12183 
12184 	/* old crtc == new_crtc == NULL, plane not in context. */
12185 	if (!new_plane_state->crtc)
12186 		return false;
12187 
12188 	new_crtc_state =
12189 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
12190 	old_crtc_state =
12191 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
12192 
12193 	if (!new_crtc_state)
12194 		return true;
12195 
12196 	/*
12197 	 * A change in cursor mode means a new dc pipe needs to be acquired or
12198 	 * released from the state
12199 	 */
12200 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
12201 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
12202 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
12203 	    old_dm_crtc_state != NULL &&
12204 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
12205 		return true;
12206 	}
12207 
12208 	/* CRTC Degamma changes currently require us to recreate planes. */
12209 	if (new_crtc_state->color_mgmt_changed)
12210 		return true;
12211 
12212 	/*
12213 	 * On zpos change, planes need to be reordered by removing and re-adding
12214 	 * them one by one to the dc state, in order of descending zpos.
12215 	 *
12216 	 * TODO: We can likely skip bandwidth validation if the only thing that
12217 	 * changed about the plane was it'z z-ordering.
12218 	 */
12219 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
12220 		return true;
12221 
12222 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
12223 		return true;
12224 
12225 	/*
12226 	 * If there are any new primary or overlay planes being added or
12227 	 * removed then the z-order can potentially change. To ensure
12228 	 * correct z-order and pipe acquisition the current DC architecture
12229 	 * requires us to remove and recreate all existing planes.
12230 	 *
12231 	 * TODO: Come up with a more elegant solution for this.
12232 	 */
12233 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
12234 		struct amdgpu_framebuffer *old_afb, *new_afb;
12235 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
12236 
12237 		dm_new_other_state = to_dm_plane_state(new_other_state);
12238 		dm_old_other_state = to_dm_plane_state(old_other_state);
12239 
12240 		if (other->type == DRM_PLANE_TYPE_CURSOR)
12241 			continue;
12242 
12243 		if (old_other_state->crtc != new_plane_state->crtc &&
12244 		    new_other_state->crtc != new_plane_state->crtc)
12245 			continue;
12246 
12247 		if (old_other_state->crtc != new_other_state->crtc)
12248 			return true;
12249 
12250 		/* Src/dst size and scaling updates. */
12251 		if (old_other_state->src_w != new_other_state->src_w ||
12252 		    old_other_state->src_h != new_other_state->src_h ||
12253 		    old_other_state->crtc_w != new_other_state->crtc_w ||
12254 		    old_other_state->crtc_h != new_other_state->crtc_h)
12255 			return true;
12256 
12257 		/* Rotation / mirroring updates. */
12258 		if (old_other_state->rotation != new_other_state->rotation)
12259 			return true;
12260 
12261 		/* Blending updates. */
12262 		if (old_other_state->pixel_blend_mode !=
12263 		    new_other_state->pixel_blend_mode)
12264 			return true;
12265 
12266 		/* Alpha updates. */
12267 		if (old_other_state->alpha != new_other_state->alpha)
12268 			return true;
12269 
12270 		/* Colorspace changes. */
12271 		if (old_other_state->color_range != new_other_state->color_range ||
12272 		    old_other_state->color_encoding != new_other_state->color_encoding)
12273 			return true;
12274 
12275 		/* HDR/Transfer Function changes. */
12276 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
12277 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
12278 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
12279 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
12280 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
12281 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
12282 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
12283 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
12284 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
12285 			return true;
12286 
12287 		/* Framebuffer checks fall at the end. */
12288 		if (!old_other_state->fb || !new_other_state->fb)
12289 			continue;
12290 
12291 		/* Pixel format changes can require bandwidth updates. */
12292 		if (old_other_state->fb->format != new_other_state->fb->format)
12293 			return true;
12294 
12295 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
12296 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
12297 
12298 		/* Tiling and DCC changes also require bandwidth updates. */
12299 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
12300 		    old_afb->base.modifier != new_afb->base.modifier)
12301 			return true;
12302 	}
12303 
12304 	return false;
12305 }
12306 
12307 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
12308 			      struct drm_plane_state *new_plane_state,
12309 			      struct drm_framebuffer *fb)
12310 {
12311 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
12312 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
12313 	unsigned int pitch;
12314 	bool linear;
12315 
12316 	if (fb->width > new_acrtc->max_cursor_width ||
12317 	    fb->height > new_acrtc->max_cursor_height) {
12318 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB size %dx%d\n",
12319 				 new_plane_state->fb->width,
12320 				 new_plane_state->fb->height);
12321 		return -EINVAL;
12322 	}
12323 	if (new_plane_state->src_w != fb->width << 16 ||
12324 	    new_plane_state->src_h != fb->height << 16) {
12325 		drm_dbg_atomic(adev_to_drm(adev), "Cropping not supported for cursor plane\n");
12326 		return -EINVAL;
12327 	}
12328 
12329 	/* Pitch in pixels */
12330 	pitch = fb->pitches[0] / fb->format->cpp[0];
12331 
12332 	if (fb->width != pitch) {
12333 		drm_dbg_atomic(adev_to_drm(adev), "Cursor FB width %d doesn't match pitch %d",
12334 				 fb->width, pitch);
12335 		return -EINVAL;
12336 	}
12337 
12338 	switch (pitch) {
12339 	case 64:
12340 	case 128:
12341 	case 256:
12342 		/* FB pitch is supported by cursor plane */
12343 		break;
12344 	default:
12345 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB pitch %d px\n", pitch);
12346 		return -EINVAL;
12347 	}
12348 
12349 	/* Core DRM takes care of checking FB modifiers, so we only need to
12350 	 * check tiling flags when the FB doesn't have a modifier.
12351 	 */
12352 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
12353 		if (adev->family == AMDGPU_FAMILY_GC_12_0_0) {
12354 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
12355 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
12356 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
12357 		} else {
12358 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
12359 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
12360 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
12361 		}
12362 		if (!linear) {
12363 			drm_dbg_atomic(adev_to_drm(adev), "Cursor FB not linear");
12364 			return -EINVAL;
12365 		}
12366 	}
12367 
12368 	return 0;
12369 }
12370 
12371 /*
12372  * Helper function for checking the cursor in native mode
12373  */
12374 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
12375 					struct drm_plane *plane,
12376 					struct drm_plane_state *new_plane_state,
12377 					bool enable)
12378 {
12379 
12380 	struct amdgpu_crtc *new_acrtc;
12381 	int ret;
12382 
12383 	if (!enable || !new_plane_crtc ||
12384 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
12385 		return 0;
12386 
12387 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
12388 
12389 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
12390 		drm_dbg_atomic(new_plane_crtc->dev, "Cropping not supported for cursor plane\n");
12391 		return -EINVAL;
12392 	}
12393 
12394 	if (new_plane_state->fb) {
12395 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
12396 						new_plane_state->fb);
12397 		if (ret)
12398 			return ret;
12399 	}
12400 
12401 	return 0;
12402 }
12403 
12404 static bool dm_should_update_native_cursor(struct drm_atomic_commit *state,
12405 					   struct drm_crtc *old_plane_crtc,
12406 					   struct drm_crtc *new_plane_crtc,
12407 					   bool enable)
12408 {
12409 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12410 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12411 
12412 	if (!enable) {
12413 		if (old_plane_crtc == NULL)
12414 			return true;
12415 
12416 		old_crtc_state = drm_atomic_get_old_crtc_state(
12417 			state, old_plane_crtc);
12418 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12419 
12420 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12421 	} else {
12422 		if (new_plane_crtc == NULL)
12423 			return true;
12424 
12425 		new_crtc_state = drm_atomic_get_new_crtc_state(
12426 			state, new_plane_crtc);
12427 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12428 
12429 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12430 	}
12431 }
12432 
12433 static int dm_update_plane_state(struct dc *dc,
12434 				 struct drm_atomic_commit *state,
12435 				 struct drm_plane *plane,
12436 				 struct drm_plane_state *old_plane_state,
12437 				 struct drm_plane_state *new_plane_state,
12438 				 bool enable,
12439 				 bool *lock_and_validation_needed,
12440 				 bool *is_top_most_overlay)
12441 {
12442 
12443 	struct dm_atomic_state *dm_state = NULL;
12444 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
12445 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12446 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
12447 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
12448 	bool needs_reset, update_native_cursor;
12449 	int ret = 0;
12450 
12451 
12452 	new_plane_crtc = new_plane_state->crtc;
12453 	old_plane_crtc = old_plane_state->crtc;
12454 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
12455 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
12456 
12457 	update_native_cursor = dm_should_update_native_cursor(state,
12458 							      old_plane_crtc,
12459 							      new_plane_crtc,
12460 							      enable);
12461 
12462 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
12463 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12464 						    new_plane_state, enable);
12465 		if (ret)
12466 			return ret;
12467 
12468 		return 0;
12469 	}
12470 
12471 	needs_reset = should_reset_plane(state, plane, old_plane_state,
12472 					 new_plane_state);
12473 
12474 	/* Remove any changed/removed planes */
12475 	if (!enable) {
12476 		if (!needs_reset)
12477 			return 0;
12478 
12479 		if (!old_plane_crtc)
12480 			return 0;
12481 
12482 		old_crtc_state = drm_atomic_get_old_crtc_state(
12483 				state, old_plane_crtc);
12484 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12485 
12486 		if (!dm_old_crtc_state->stream)
12487 			return 0;
12488 
12489 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
12490 				plane->base.id, old_plane_crtc->base.id);
12491 
12492 		ret = dm_atomic_get_state(state, &dm_state);
12493 		if (ret)
12494 			return ret;
12495 
12496 		if (!dc_state_remove_plane(
12497 				dc,
12498 				dm_old_crtc_state->stream,
12499 				dm_old_plane_state->dc_state,
12500 				dm_state->context)) {
12501 
12502 			return -EINVAL;
12503 		}
12504 
12505 		if (dm_old_plane_state->dc_state)
12506 			dc_plane_state_release(dm_old_plane_state->dc_state);
12507 
12508 		dm_new_plane_state->dc_state = NULL;
12509 
12510 		*lock_and_validation_needed = true;
12511 
12512 	} else { /* Add new planes */
12513 		struct dc_plane_state *dc_new_plane_state;
12514 
12515 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
12516 			return 0;
12517 
12518 		if (!new_plane_crtc)
12519 			return 0;
12520 
12521 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
12522 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12523 
12524 		if (!dm_new_crtc_state->stream)
12525 			return 0;
12526 
12527 		if (!needs_reset)
12528 			return 0;
12529 
12530 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
12531 		if (ret)
12532 			goto out;
12533 
12534 		WARN_ON(dm_new_plane_state->dc_state);
12535 
12536 		dc_new_plane_state = dc_create_plane_state(dc);
12537 		if (!dc_new_plane_state) {
12538 			ret = -ENOMEM;
12539 			goto out;
12540 		}
12541 
12542 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
12543 				 plane->base.id, new_plane_crtc->base.id);
12544 
12545 		ret = fill_dc_plane_attributes(
12546 			drm_to_adev(new_plane_crtc->dev),
12547 			dc_new_plane_state,
12548 			new_plane_state,
12549 			new_crtc_state);
12550 		if (ret) {
12551 			dc_plane_state_release(dc_new_plane_state);
12552 			goto out;
12553 		}
12554 
12555 		ret = dm_atomic_get_state(state, &dm_state);
12556 		if (ret) {
12557 			dc_plane_state_release(dc_new_plane_state);
12558 			goto out;
12559 		}
12560 
12561 		/*
12562 		 * Any atomic check errors that occur after this will
12563 		 * not need a release. The plane state will be attached
12564 		 * to the stream, and therefore part of the atomic
12565 		 * state. It'll be released when the atomic state is
12566 		 * cleaned.
12567 		 */
12568 		if (!dc_state_add_plane(
12569 				dc,
12570 				dm_new_crtc_state->stream,
12571 				dc_new_plane_state,
12572 				dm_state->context)) {
12573 
12574 			dc_plane_state_release(dc_new_plane_state);
12575 			ret = -EINVAL;
12576 			goto out;
12577 		}
12578 
12579 		dm_new_plane_state->dc_state = dc_new_plane_state;
12580 
12581 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
12582 
12583 		/* Tell DC to do a full surface update every time there
12584 		 * is a plane change. Inefficient, but works for now.
12585 		 */
12586 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
12587 
12588 		*lock_and_validation_needed = true;
12589 	}
12590 
12591 out:
12592 	/* If enabling cursor overlay failed, attempt fallback to native mode */
12593 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
12594 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12595 						    new_plane_state, enable);
12596 		if (ret)
12597 			return ret;
12598 
12599 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
12600 	}
12601 
12602 	return ret;
12603 }
12604 
12605 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
12606 				       int *src_w, int *src_h)
12607 {
12608 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
12609 	case DRM_MODE_ROTATE_90:
12610 	case DRM_MODE_ROTATE_270:
12611 		*src_w = plane_state->src_h >> 16;
12612 		*src_h = plane_state->src_w >> 16;
12613 		break;
12614 	case DRM_MODE_ROTATE_0:
12615 	case DRM_MODE_ROTATE_180:
12616 	default:
12617 		*src_w = plane_state->src_w >> 16;
12618 		*src_h = plane_state->src_h >> 16;
12619 		break;
12620 	}
12621 }
12622 
12623 static void
12624 dm_get_plane_scale(struct drm_plane_state *plane_state,
12625 		   int *out_plane_scale_w, int *out_plane_scale_h)
12626 {
12627 	int plane_src_w, plane_src_h;
12628 
12629 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
12630 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
12631 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
12632 }
12633 
12634 /*
12635  * The normalized_zpos value cannot be used by this iterator directly. It's only
12636  * calculated for enabled planes, potentially causing normalized_zpos collisions
12637  * between enabled/disabled planes in the atomic state. We need a unique value
12638  * so that the iterator will not generate the same object twice, or loop
12639  * indefinitely.
12640  */
12641 static inline struct __drm_planes_state *__get_next_zpos(
12642 	struct drm_atomic_commit *state,
12643 	struct __drm_planes_state *prev)
12644 {
12645 	unsigned int highest_zpos = 0, prev_zpos = 256;
12646 	uint32_t highest_id = 0, prev_id = UINT_MAX;
12647 	struct drm_plane_state *new_plane_state;
12648 	struct drm_plane *plane;
12649 	int i, highest_i = -1;
12650 
12651 	if (prev != NULL) {
12652 		prev_zpos = prev->new_state->zpos;
12653 		prev_id = prev->ptr->base.id;
12654 	}
12655 
12656 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
12657 		/* Skip planes with higher zpos than the previously returned */
12658 		if (new_plane_state->zpos > prev_zpos ||
12659 		    (new_plane_state->zpos == prev_zpos &&
12660 		     plane->base.id >= prev_id))
12661 			continue;
12662 
12663 		/* Save the index of the plane with highest zpos */
12664 		if (new_plane_state->zpos > highest_zpos ||
12665 		    (new_plane_state->zpos == highest_zpos &&
12666 		     plane->base.id > highest_id)) {
12667 			highest_zpos = new_plane_state->zpos;
12668 			highest_id = plane->base.id;
12669 			highest_i = i;
12670 		}
12671 	}
12672 
12673 	if (highest_i < 0)
12674 		return NULL;
12675 
12676 	return &state->planes[highest_i];
12677 }
12678 
12679 /*
12680  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
12681  * by descending zpos, as read from the new plane state. This is the same
12682  * ordering as defined by drm_atomic_normalize_zpos().
12683  */
12684 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
12685 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
12686 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
12687 		for_each_if(((plane) = __i->ptr,				\
12688 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
12689 			     (old_plane_state) = __i->old_state,		\
12690 			     (new_plane_state) = __i->new_state, 1))
12691 
12692 static int add_affected_mst_dsc_crtcs(struct drm_atomic_commit *state, struct drm_crtc *crtc)
12693 {
12694 	struct drm_connector *connector;
12695 	struct drm_connector_state *conn_state, *old_conn_state;
12696 	struct amdgpu_dm_connector *aconnector = NULL;
12697 	int i;
12698 
12699 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
12700 		if (!conn_state->crtc)
12701 			conn_state = old_conn_state;
12702 
12703 		if (conn_state->crtc != crtc)
12704 			continue;
12705 
12706 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
12707 			continue;
12708 
12709 		aconnector = to_amdgpu_dm_connector(connector);
12710 		if (!aconnector->mst_output_port || !aconnector->mst_root)
12711 			aconnector = NULL;
12712 		else
12713 			break;
12714 	}
12715 
12716 	if (!aconnector)
12717 		return 0;
12718 
12719 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
12720 }
12721 
12722 /**
12723  * DOC: Cursor Modes - Native vs Overlay
12724  *
12725  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
12726  * plane. It does not require a dedicated hw plane to enable, but it is
12727  * subjected to the same z-order and scaling as the hw plane. It also has format
12728  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
12729  * hw plane.
12730  *
12731  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
12732  * own scaling and z-pos. It also has no blending restrictions. It lends to a
12733  * cursor behavior more akin to a DRM client's expectations. However, it does
12734  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
12735  * available.
12736  */
12737 
12738 /**
12739  * dm_plane_color_pipeline_active() - Check if a plane's color pipeline active.
12740  * @state: DRM atomic state
12741  * @plane: DRM plane to check
12742  * @use_old: if true, inspect the old colorop states; otherwise the new ones
12743  *
12744  * A color pipeline may be selected (color_pipeline != NULL) but still is
12745  * inactive if every colorop in the chain is bypassed.  Only return
12746  * true when at least one colorop has bypass == false, meaning the cursor
12747  * would be subjected to the transformation in native mode.
12748  *
12749  * Return: true if the pipeline modifies pixels, false otherwise.
12750  */
12751 static bool dm_plane_color_pipeline_active(struct drm_atomic_commit *state,
12752 					   struct drm_plane *plane,
12753 					   bool use_old)
12754 {
12755 	struct drm_colorop *colorop;
12756 	struct drm_colorop_state *old_colorop_state, *new_colorop_state;
12757 	int i;
12758 
12759 	for_each_oldnew_colorop_in_state(state, colorop, old_colorop_state, new_colorop_state, i) {
12760 		struct drm_colorop_state *cstate = use_old ? old_colorop_state : new_colorop_state;
12761 
12762 		if (cstate->colorop->plane != plane)
12763 			continue;
12764 		if (!cstate->bypass)
12765 			return true;
12766 	}
12767 	return false;
12768 }
12769 
12770 /**
12771  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
12772  * @adev: amdgpu device
12773  * @state: DRM atomic state
12774  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
12775  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
12776  *
12777  * Get whether the cursor should be enabled in native mode, or overlay mode, on
12778  * the dm_crtc_state.
12779  *
12780  * The cursor should be enabled in overlay mode if there exists an underlying
12781  * plane - on which the cursor may be blended - that is either YUV formatted,
12782  * scaled differently from the cursor, or has a color pipeline active.
12783  *
12784  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
12785  * calling this function.
12786  *
12787  * Return: 0 on success, or an error code if getting the cursor plane state
12788  * failed.
12789  */
12790 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
12791 				   struct drm_atomic_commit *state,
12792 				   struct dm_crtc_state *dm_crtc_state,
12793 				   enum amdgpu_dm_cursor_mode *cursor_mode)
12794 {
12795 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
12796 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
12797 	struct drm_plane *plane;
12798 	bool consider_mode_change = false;
12799 	bool entire_crtc_covered = false;
12800 	bool cursor_changed = false;
12801 	int underlying_scale_w, underlying_scale_h;
12802 	int cursor_scale_w, cursor_scale_h;
12803 	int i;
12804 
12805 	/* Overlay cursor not supported on HW before DCN
12806 	 * DCN401/420 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
12807 	 * as previous DCN generations, so enable native mode on DCN401/420
12808 	 */
12809 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1) ||
12810 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
12811 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 1)) {
12812 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12813 		return 0;
12814 	}
12815 
12816 	/* Init cursor_mode to be the same as current */
12817 	*cursor_mode = dm_crtc_state->cursor_mode;
12818 
12819 	/*
12820 	 * Cursor mode can change if a plane's format changes, scale changes, is
12821 	 * enabled/disabled, z-order changes, or color management properties change.
12822 	 */
12823 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
12824 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
12825 
12826 		/* Only care about planes on this CRTC */
12827 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
12828 			continue;
12829 
12830 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
12831 			cursor_changed = true;
12832 
12833 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
12834 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
12835 		    old_plane_state->fb->format != plane_state->fb->format) {
12836 			consider_mode_change = true;
12837 			break;
12838 		}
12839 
12840 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
12841 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
12842 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
12843 			consider_mode_change = true;
12844 			break;
12845 		}
12846 
12847 		if (dm_plane_color_pipeline_active(state, plane, true) !=
12848 		    dm_plane_color_pipeline_active(state, plane, false)) {
12849 			consider_mode_change = true;
12850 			break;
12851 		}
12852 	}
12853 
12854 	if (!consider_mode_change && !crtc_state->zpos_changed)
12855 		return 0;
12856 
12857 	/*
12858 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
12859 	 * no need to set cursor mode. This avoids needlessly locking the cursor
12860 	 * state.
12861 	 */
12862 	if (!cursor_changed &&
12863 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
12864 		return 0;
12865 	}
12866 
12867 	cursor_state = drm_atomic_get_plane_state(state,
12868 						  crtc_state->crtc->cursor);
12869 	if (IS_ERR(cursor_state))
12870 		return PTR_ERR(cursor_state);
12871 
12872 	/* Cursor is disabled */
12873 	if (!cursor_state->fb)
12874 		return 0;
12875 
12876 	/* For all planes in descending z-order (all of which are below cursor
12877 	 * as per zpos definitions), check their scaling and format
12878 	 */
12879 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
12880 
12881 		/* Only care about non-cursor planes on this CRTC */
12882 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
12883 		    plane->type == DRM_PLANE_TYPE_CURSOR)
12884 			continue;
12885 
12886 		/* Underlying plane is YUV format - use overlay cursor */
12887 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
12888 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12889 			return 0;
12890 		}
12891 
12892 		/* Underlying plane has an active color pipeline - cursor would be transformed */
12893 		if (dm_plane_color_pipeline_active(state, plane, false)) {
12894 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12895 			return 0;
12896 		}
12897 
12898 		dm_get_plane_scale(plane_state,
12899 				   &underlying_scale_w, &underlying_scale_h);
12900 		dm_get_plane_scale(cursor_state,
12901 				   &cursor_scale_w, &cursor_scale_h);
12902 
12903 		/* Underlying plane has different scale - use overlay cursor */
12904 		if (cursor_scale_w != underlying_scale_w &&
12905 		    cursor_scale_h != underlying_scale_h) {
12906 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12907 			return 0;
12908 		}
12909 
12910 		/* If this plane covers the whole CRTC, no need to check planes underneath */
12911 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
12912 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
12913 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
12914 			entire_crtc_covered = true;
12915 			break;
12916 		}
12917 	}
12918 
12919 	/* If planes do not cover the entire CRTC, use overlay mode to enable
12920 	 * cursor over holes
12921 	 */
12922 	if (entire_crtc_covered)
12923 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12924 	else
12925 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12926 
12927 	return 0;
12928 }
12929 
12930 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
12931 					    struct drm_atomic_commit *state,
12932 					    struct drm_crtc_state *crtc_state)
12933 {
12934 	struct drm_plane *plane;
12935 	struct drm_plane_state *new_plane_state, *old_plane_state;
12936 
12937 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
12938 		new_plane_state = drm_atomic_get_plane_state(state, plane);
12939 		old_plane_state = drm_atomic_get_plane_state(state, plane);
12940 
12941 		if (IS_ERR(new_plane_state) || IS_ERR(old_plane_state)) {
12942 			drm_err(dev, "Failed to get plane state for plane %s\n", plane->name);
12943 			return false;
12944 		}
12945 
12946 		if (old_plane_state->fb && new_plane_state->fb &&
12947 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
12948 			return true;
12949 	}
12950 
12951 	return false;
12952 }
12953 
12954 /**
12955  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
12956  *
12957  * @dev: The DRM device
12958  * @state: The atomic state to commit
12959  *
12960  * Validate that the given atomic state is programmable by DC into hardware.
12961  * This involves constructing a &struct dc_state reflecting the new hardware
12962  * state we wish to commit, then querying DC to see if it is programmable. It's
12963  * important not to modify the existing DC state. Otherwise, atomic_check
12964  * may unexpectedly commit hardware changes.
12965  *
12966  * When validating the DC state, it's important that the right locks are
12967  * acquired. For full updates case which removes/adds/updates streams on one
12968  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
12969  * that any such full update commit will wait for completion of any outstanding
12970  * flip using DRMs synchronization events.
12971  *
12972  * Note that DM adds the affected connectors for all CRTCs in state, when that
12973  * might not seem necessary. This is because DC stream creation requires the
12974  * DC sink, which is tied to the DRM connector state. Cleaning this up should
12975  * be possible but non-trivial - a possible TODO item.
12976  *
12977  * Return: -Error code if validation failed.
12978  */
12979 static int amdgpu_dm_atomic_check(struct drm_device *dev,
12980 				  struct drm_atomic_commit *state)
12981 {
12982 	struct amdgpu_device *adev = drm_to_adev(dev);
12983 	struct dm_atomic_state *dm_state = NULL;
12984 	struct dc *dc = adev->dm.dc;
12985 	struct drm_connector *connector;
12986 	struct drm_connector_state *old_con_state, *new_con_state;
12987 	struct drm_crtc *crtc;
12988 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12989 	struct drm_plane *plane;
12990 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
12991 	enum dc_status status;
12992 	int ret, i;
12993 	bool lock_and_validation_needed = false;
12994 	bool is_top_most_overlay = true;
12995 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12996 	struct drm_dp_mst_topology_mgr *mgr;
12997 	struct drm_dp_mst_topology_state *mst_state;
12998 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
12999 
13000 	trace_amdgpu_dm_atomic_check_begin(state);
13001 
13002 	ret = drm_atomic_helper_check_modeset(dev, state);
13003 	if (ret) {
13004 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
13005 		goto fail;
13006 	}
13007 
13008 	/* Check connector changes */
13009 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
13010 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
13011 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
13012 
13013 		/* Skip connectors that are disabled or part of modeset already. */
13014 		if (!new_con_state->crtc)
13015 			continue;
13016 
13017 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
13018 		if (IS_ERR(new_crtc_state)) {
13019 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
13020 			ret = PTR_ERR(new_crtc_state);
13021 			goto fail;
13022 		}
13023 
13024 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
13025 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
13026 			new_crtc_state->connectors_changed = true;
13027 	}
13028 
13029 	if (dc_resource_is_dsc_encoding_supported(dc)) {
13030 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13031 			dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13032 			dm_new_crtc_state->mode_changed_independent_from_dsc = new_crtc_state->mode_changed;
13033 		}
13034 
13035 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13036 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
13037 				ret = add_affected_mst_dsc_crtcs(state, crtc);
13038 				if (ret) {
13039 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
13040 					goto fail;
13041 				}
13042 			}
13043 		}
13044 	}
13045 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13046 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
13047 
13048 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
13049 		    !new_crtc_state->color_mgmt_changed &&
13050 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
13051 			dm_old_crtc_state->dsc_force_changed == false)
13052 			continue;
13053 
13054 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
13055 		if (ret) {
13056 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
13057 			goto fail;
13058 		}
13059 
13060 		if (!new_crtc_state->enable)
13061 			continue;
13062 
13063 		ret = drm_atomic_add_affected_connectors(state, crtc);
13064 		if (ret) {
13065 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
13066 			goto fail;
13067 		}
13068 
13069 		ret = drm_atomic_add_affected_planes(state, crtc);
13070 		if (ret) {
13071 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
13072 			goto fail;
13073 		}
13074 
13075 		if (dm_old_crtc_state->dsc_force_changed)
13076 			new_crtc_state->mode_changed = true;
13077 	}
13078 
13079 	/*
13080 	 * Add all primary and overlay planes on the CRTC to the state
13081 	 * whenever a plane is enabled to maintain correct z-ordering
13082 	 * and to enable fast surface updates.
13083 	 */
13084 	drm_for_each_crtc(crtc, dev) {
13085 		bool modified = false;
13086 
13087 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
13088 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
13089 				continue;
13090 
13091 			if (new_plane_state->crtc == crtc ||
13092 			    old_plane_state->crtc == crtc) {
13093 				modified = true;
13094 				break;
13095 			}
13096 		}
13097 
13098 		if (!modified)
13099 			continue;
13100 
13101 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
13102 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
13103 				continue;
13104 
13105 			new_plane_state =
13106 				drm_atomic_get_plane_state(state, plane);
13107 
13108 			if (IS_ERR(new_plane_state)) {
13109 				ret = PTR_ERR(new_plane_state);
13110 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
13111 				goto fail;
13112 			}
13113 		}
13114 	}
13115 
13116 	/*
13117 	 * DC consults the zpos (layer_index in DC terminology) to determine the
13118 	 * hw plane on which to enable the hw cursor (see
13119 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
13120 	 * atomic state, so call drm helper to normalize zpos.
13121 	 */
13122 	ret = drm_atomic_normalize_zpos(dev, state);
13123 	if (ret) {
13124 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
13125 		goto fail;
13126 	}
13127 
13128 	/*
13129 	 * Determine whether cursors on each CRTC should be enabled in native or
13130 	 * overlay mode.
13131 	 */
13132 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13133 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13134 
13135 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
13136 					      &dm_new_crtc_state->cursor_mode);
13137 		if (ret) {
13138 			drm_dbg(dev, "Failed to determine cursor mode\n");
13139 			goto fail;
13140 		}
13141 
13142 		/*
13143 		 * If overlay cursor is needed, DC cannot go through the
13144 		 * native cursor update path. All enabled planes on the CRTC
13145 		 * need to be added for DC to not disable a plane by mistake
13146 		 */
13147 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
13148 			if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
13149 				drm_dbg(dev, "Overlay cursor not supported on DCE\n");
13150 				ret = -EINVAL;
13151 				goto fail;
13152 			}
13153 
13154 			ret = drm_atomic_add_affected_planes(state, crtc);
13155 			if (ret)
13156 				goto fail;
13157 		}
13158 	}
13159 
13160 	/* Remove exiting planes if they are modified */
13161 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13162 
13163 		ret = dm_update_plane_state(dc, state, plane,
13164 					    old_plane_state,
13165 					    new_plane_state,
13166 					    false,
13167 					    &lock_and_validation_needed,
13168 					    &is_top_most_overlay);
13169 		if (ret) {
13170 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13171 			goto fail;
13172 		}
13173 	}
13174 
13175 	/* Disable all crtcs which require disable */
13176 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13177 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
13178 					   old_crtc_state,
13179 					   new_crtc_state,
13180 					   false,
13181 					   &lock_and_validation_needed);
13182 		if (ret) {
13183 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
13184 			goto fail;
13185 		}
13186 	}
13187 
13188 	/* Enable all crtcs which require enable */
13189 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13190 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
13191 					   old_crtc_state,
13192 					   new_crtc_state,
13193 					   true,
13194 					   &lock_and_validation_needed);
13195 		if (ret) {
13196 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
13197 			goto fail;
13198 		}
13199 	}
13200 
13201 	/* Add new/modified planes */
13202 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13203 		ret = dm_update_plane_state(dc, state, plane,
13204 					    old_plane_state,
13205 					    new_plane_state,
13206 					    true,
13207 					    &lock_and_validation_needed,
13208 					    &is_top_most_overlay);
13209 		if (ret) {
13210 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13211 			goto fail;
13212 		}
13213 	}
13214 
13215 #if defined(CONFIG_DRM_AMD_DC_FP)
13216 	if (dc_resource_is_dsc_encoding_supported(dc)) {
13217 		ret = pre_validate_dsc(state, &dm_state, vars);
13218 		if (ret != 0)
13219 			goto fail;
13220 	}
13221 #endif
13222 
13223 	/* Run this here since we want to validate the streams we created */
13224 	ret = drm_atomic_helper_check_planes(dev, state);
13225 	if (ret) {
13226 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
13227 		goto fail;
13228 	}
13229 
13230 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13231 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13232 		if (dm_new_crtc_state->mpo_requested)
13233 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
13234 	}
13235 
13236 	/* Check cursor restrictions */
13237 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13238 		enum amdgpu_dm_cursor_mode required_cursor_mode;
13239 		int is_rotated, is_scaled;
13240 
13241 		/* Overlay cusor not subject to native cursor restrictions */
13242 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13243 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
13244 			continue;
13245 
13246 		/* Check if rotation or scaling is enabled on DCN401 */
13247 		if ((drm_plane_mask(crtc->cursor) &
13248 		     new_crtc_state->plane_mask) &&
13249 		    (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 1) ||
13250 		     amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
13251 		     amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1))) {
13252 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
13253 
13254 			is_rotated = new_cursor_state &&
13255 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
13256 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
13257 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
13258 
13259 			if (is_rotated || is_scaled) {
13260 				drm_dbg_driver(
13261 					crtc->dev,
13262 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
13263 					crtc->base.id, crtc->name);
13264 				ret = -EINVAL;
13265 				goto fail;
13266 			}
13267 		}
13268 
13269 		/* If HW can only do native cursor, check restrictions again */
13270 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
13271 					      &required_cursor_mode);
13272 		if (ret) {
13273 			drm_dbg_driver(crtc->dev,
13274 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
13275 				       crtc->base.id, crtc->name);
13276 			goto fail;
13277 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
13278 			drm_dbg_driver(crtc->dev,
13279 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling, YUV, or color pipeline restrictions\n",
13280 				       crtc->base.id, crtc->name);
13281 			ret = -EINVAL;
13282 			goto fail;
13283 		}
13284 	}
13285 
13286 	if (state->legacy_cursor_update) {
13287 		/*
13288 		 * This is a fast cursor update coming from the plane update
13289 		 * helper, check if it can be done asynchronously for better
13290 		 * performance.
13291 		 */
13292 		state->async_update =
13293 			!drm_atomic_helper_async_check(dev, state);
13294 
13295 		/*
13296 		 * Skip the remaining global validation if this is an async
13297 		 * update. Cursor updates can be done without affecting
13298 		 * state or bandwidth calcs and this avoids the performance
13299 		 * penalty of locking the private state object and
13300 		 * allocating a new dc_state.
13301 		 */
13302 		if (state->async_update)
13303 			return 0;
13304 	}
13305 
13306 	/* Check scaling and underscan changes*/
13307 	/* TODO Removed scaling changes validation due to inability to commit
13308 	 * new stream into context w\o causing full reset. Need to
13309 	 * decide how to handle.
13310 	 */
13311 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
13312 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
13313 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
13314 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
13315 
13316 		/* Skip any modesets/resets */
13317 		if (!acrtc || drm_atomic_crtc_needs_modeset(
13318 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
13319 			continue;
13320 
13321 		/* Skip any thing not scale or underscan changes */
13322 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
13323 			continue;
13324 
13325 		lock_and_validation_needed = true;
13326 	}
13327 
13328 	/* set the slot info for each mst_state based on the link encoding format */
13329 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
13330 		struct amdgpu_dm_connector *aconnector;
13331 		struct drm_connector *connector;
13332 		struct drm_connector_list_iter iter;
13333 		u8 link_coding_cap;
13334 
13335 		drm_connector_list_iter_begin(dev, &iter);
13336 		drm_for_each_connector_iter(connector, &iter) {
13337 			if (connector->index == mst_state->mgr->conn_base_id) {
13338 				aconnector = to_amdgpu_dm_connector(connector);
13339 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
13340 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
13341 
13342 				break;
13343 			}
13344 		}
13345 		drm_connector_list_iter_end(&iter);
13346 	}
13347 
13348 	/**
13349 	 * Streams and planes are reset when there are changes that affect
13350 	 * bandwidth. Anything that affects bandwidth needs to go through
13351 	 * DC global validation to ensure that the configuration can be applied
13352 	 * to hardware.
13353 	 *
13354 	 * We have to currently stall out here in atomic_check for outstanding
13355 	 * commits to finish in this case because our IRQ handlers reference
13356 	 * DRM state directly - we can end up disabling interrupts too early
13357 	 * if we don't.
13358 	 *
13359 	 * TODO: Remove this stall and drop DM state private objects.
13360 	 */
13361 	if (lock_and_validation_needed) {
13362 		ret = dm_atomic_get_state(state, &dm_state);
13363 		if (ret) {
13364 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
13365 			goto fail;
13366 		}
13367 
13368 		ret = do_aquire_global_lock(dev, state);
13369 		if (ret) {
13370 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
13371 			goto fail;
13372 		}
13373 
13374 #if defined(CONFIG_DRM_AMD_DC_FP)
13375 		if (dc_resource_is_dsc_encoding_supported(dc)) {
13376 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
13377 			if (ret) {
13378 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
13379 				ret = -EINVAL;
13380 				goto fail;
13381 			}
13382 		}
13383 #endif
13384 
13385 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
13386 		if (ret) {
13387 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
13388 			goto fail;
13389 		}
13390 
13391 		/*
13392 		 * Perform validation of MST topology in the state:
13393 		 * We need to perform MST atomic check before calling
13394 		 * dc_validate_global_state(), or there is a chance
13395 		 * to get stuck in an infinite loop and hang eventually.
13396 		 */
13397 		ret = drm_dp_mst_atomic_check(state);
13398 		if (ret) {
13399 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
13400 			goto fail;
13401 		}
13402 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
13403 		if (status != DC_OK) {
13404 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
13405 				       dc_status_to_str(status), status);
13406 			ret = -EINVAL;
13407 			goto fail;
13408 		}
13409 	} else {
13410 		/*
13411 		 * The commit is a fast update. Fast updates shouldn't change
13412 		 * the DC context, affect global validation, and can have their
13413 		 * commit work done in parallel with other commits not touching
13414 		 * the same resource. If we have a new DC context as part of
13415 		 * the DM atomic state from validation we need to free it and
13416 		 * retain the existing one instead.
13417 		 *
13418 		 * Furthermore, since the DM atomic state only contains the DC
13419 		 * context and can safely be annulled, we can free the state
13420 		 * and clear the associated private object now to free
13421 		 * some memory and avoid a possible use-after-free later.
13422 		 */
13423 
13424 		for (i = 0; i < state->num_private_objs; i++) {
13425 			struct drm_private_obj *obj = state->private_objs[i].ptr;
13426 
13427 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
13428 				int j = state->num_private_objs-1;
13429 
13430 				dm_atomic_destroy_state(obj,
13431 						state->private_objs[i].state_to_destroy);
13432 
13433 				/* If i is not at the end of the array then the
13434 				 * last element needs to be moved to where i was
13435 				 * before the array can safely be truncated.
13436 				 */
13437 				if (i != j)
13438 					state->private_objs[i] =
13439 						state->private_objs[j];
13440 
13441 				state->private_objs[j].ptr = NULL;
13442 				state->private_objs[j].state_to_destroy = NULL;
13443 				state->private_objs[j].old_state = NULL;
13444 				state->private_objs[j].new_state = NULL;
13445 
13446 				state->num_private_objs = j;
13447 				break;
13448 			}
13449 		}
13450 	}
13451 
13452 	/* Store the overall update type for use later in atomic check. */
13453 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13454 		struct dm_crtc_state *dm_new_crtc_state =
13455 			to_dm_crtc_state(new_crtc_state);
13456 
13457 		/*
13458 		 * Only allow async flips for fast updates that don't change
13459 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
13460 		 */
13461 		if (new_crtc_state->async_flip &&
13462 		    (lock_and_validation_needed ||
13463 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
13464 			drm_dbg_atomic(crtc->dev,
13465 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
13466 				       crtc->base.id, crtc->name);
13467 			ret = -EINVAL;
13468 			goto fail;
13469 		}
13470 
13471 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
13472 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
13473 	}
13474 
13475 	/* Must be success */
13476 	WARN_ON(ret);
13477 
13478 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13479 
13480 	return ret;
13481 
13482 fail:
13483 	if (ret == -EDEADLK)
13484 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
13485 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
13486 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
13487 	else
13488 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
13489 
13490 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13491 
13492 	return ret;
13493 }
13494 
13495 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
13496 		unsigned int offset,
13497 		unsigned int total_length,
13498 		u8 *data,
13499 		unsigned int length,
13500 		struct amdgpu_hdmi_vsdb_info *vsdb)
13501 {
13502 	bool res;
13503 	union dmub_rb_cmd cmd;
13504 	struct dmub_cmd_send_edid_cea *input;
13505 	struct dmub_cmd_edid_cea_output *output;
13506 
13507 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
13508 		return false;
13509 
13510 	memset(&cmd, 0, sizeof(cmd));
13511 
13512 	input = &cmd.edid_cea.data.input;
13513 
13514 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
13515 	cmd.edid_cea.header.sub_type = 0;
13516 	cmd.edid_cea.header.payload_bytes =
13517 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
13518 	input->offset = offset;
13519 	input->length = length;
13520 	input->cea_total_length = total_length;
13521 	memcpy(input->payload, data, length);
13522 
13523 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
13524 	if (!res) {
13525 		drm_err(adev_to_drm(dm->adev), "EDID CEA parser failed\n");
13526 		return false;
13527 	}
13528 
13529 	output = &cmd.edid_cea.data.output;
13530 
13531 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
13532 		if (!output->ack.success) {
13533 			drm_err(adev_to_drm(dm->adev), "EDID CEA ack failed at offset %d\n",
13534 					output->ack.offset);
13535 		}
13536 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
13537 		if (!output->amd_vsdb.vsdb_found)
13538 			return false;
13539 
13540 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
13541 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
13542 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
13543 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
13544 		vsdb->freesync_mccs_vcp_code = output->amd_vsdb.freesync_mccs_vcp_code;
13545 	} else {
13546 		drm_warn(adev_to_drm(dm->adev), "Unknown EDID CEA parser results\n");
13547 		return false;
13548 	}
13549 
13550 	return true;
13551 }
13552 
13553 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
13554 		u8 *edid_ext, int len,
13555 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13556 {
13557 	int i;
13558 
13559 	/* send extension block to DMCU for parsing */
13560 	for (i = 0; i < len; i += 8) {
13561 		bool res;
13562 		int offset;
13563 
13564 		/* send 8 bytes a time */
13565 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
13566 			return false;
13567 
13568 		if (i+8 == len) {
13569 			/* EDID block sent completed, expect result */
13570 			int version, min_rate, max_rate;
13571 
13572 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
13573 			if (res) {
13574 				/* amd vsdb found */
13575 				vsdb_info->freesync_supported = 1;
13576 				vsdb_info->amd_vsdb_version = version;
13577 				vsdb_info->min_refresh_rate_hz = min_rate;
13578 				vsdb_info->max_refresh_rate_hz = max_rate;
13579 				/* Not enabled on DMCU*/
13580 				vsdb_info->freesync_mccs_vcp_code = 0;
13581 				return true;
13582 			}
13583 			/* not amd vsdb */
13584 			return false;
13585 		}
13586 
13587 		/* check for ack*/
13588 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
13589 		if (!res)
13590 			return false;
13591 	}
13592 
13593 	return false;
13594 }
13595 
13596 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
13597 		u8 *edid_ext, int len,
13598 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13599 {
13600 	int i;
13601 
13602 	/* send extension block to DMCU for parsing */
13603 	for (i = 0; i < len; i += 8) {
13604 		/* send 8 bytes a time */
13605 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
13606 			return false;
13607 	}
13608 
13609 	return vsdb_info->freesync_supported;
13610 }
13611 
13612 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
13613 		u8 *edid_ext, int len,
13614 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13615 {
13616 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
13617 	bool ret;
13618 
13619 	mutex_lock(&adev->dm.dc_lock);
13620 	if (adev->dm.dmub_srv)
13621 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
13622 	else
13623 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
13624 	mutex_unlock(&adev->dm.dc_lock);
13625 	return ret;
13626 }
13627 
13628 static void parse_edid_displayid_vrr(struct drm_connector *connector,
13629 				     const struct edid *edid)
13630 {
13631 	u8 *edid_ext = NULL;
13632 	int i;
13633 	int j = 0;
13634 	u16 min_vfreq;
13635 	u16 max_vfreq;
13636 
13637 	if (!edid || !edid->extensions)
13638 		return;
13639 
13640 	/* Find DisplayID extension */
13641 	for (i = 0; i < edid->extensions; i++) {
13642 		edid_ext = (void *)(edid + (i + 1));
13643 		if (edid_ext[0] == DISPLAYID_EXT)
13644 			break;
13645 	}
13646 
13647 	if (i == edid->extensions)
13648 		return;
13649 
13650 	while (j < EDID_LENGTH) {
13651 		/* Get dynamic video timing range from DisplayID if available */
13652 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
13653 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
13654 			min_vfreq = edid_ext[j+9];
13655 			if (edid_ext[j+1] & 7)
13656 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
13657 			else
13658 				max_vfreq = edid_ext[j+10];
13659 
13660 			if (max_vfreq && min_vfreq) {
13661 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
13662 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
13663 
13664 				return;
13665 			}
13666 		}
13667 		j++;
13668 	}
13669 }
13670 
13671 static int get_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13672 			struct amdgpu_hdmi_vsdb_info *vsdb_info)
13673 {
13674 	struct drm_connector *connector = &aconnector->base;
13675 
13676 	vsdb_info->replay_mode = connector->display_info.amd_vsdb.replay_mode;
13677 	vsdb_info->amd_vsdb_version = connector->display_info.amd_vsdb.version;
13678 
13679 	return connector->display_info.amd_vsdb.version != 0;
13680 }
13681 
13682 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13683 			       const struct edid *edid,
13684 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
13685 {
13686 	u8 *edid_ext = NULL;
13687 	int i;
13688 	bool valid_vsdb_found = false;
13689 
13690 	/*----- drm_find_cea_extension() -----*/
13691 	/* No EDID or EDID extensions */
13692 	if (edid == NULL || edid->extensions == 0)
13693 		return -ENODEV;
13694 
13695 	/* Find CEA extension */
13696 	for (i = 0; i < edid->extensions; i++) {
13697 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
13698 		if (edid_ext[0] == CEA_EXT)
13699 			break;
13700 	}
13701 
13702 	if (i == edid->extensions)
13703 		return -ENODEV;
13704 
13705 	/*----- cea_db_offsets() -----*/
13706 	if (edid_ext[0] != CEA_EXT)
13707 		return -ENODEV;
13708 
13709 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
13710 
13711 	return valid_vsdb_found ? i : -ENODEV;
13712 }
13713 
13714 /**
13715  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
13716  *
13717  * @connector: Connector to query.
13718  * @drm_edid: DRM EDID from monitor
13719  * @do_mccs: Controls whether MCCS (Monitor Control Command Set) over
13720  *	      DDC (Display Data Channel) transactions are performed. When true,
13721  *	      the driver queries the monitor to get or update additional FreeSync
13722  *	      capability information. When false, these transactions are skipped.
13723  *
13724  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
13725  * track of some of the display information in the internal data struct used by
13726  * amdgpu_dm. This function checks which type of connector we need to set the
13727  * FreeSync parameters.
13728  */
13729 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
13730 				    const struct drm_edid *drm_edid, bool do_mccs)
13731 {
13732 	int i = 0;
13733 	struct amdgpu_dm_connector *amdgpu_dm_connector =
13734 			to_amdgpu_dm_connector(connector);
13735 	struct dm_connector_state *dm_con_state = NULL;
13736 	struct dc_sink *sink;
13737 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
13738 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
13739 	const struct edid *edid;
13740 	bool freesync_capable = false;
13741 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
13742 
13743 	if (!connector->state) {
13744 		drm_err(adev_to_drm(adev), "%s - Connector has no state", __func__);
13745 		goto update;
13746 	}
13747 
13748 	sink = amdgpu_dm_connector->dc_sink ?
13749 		amdgpu_dm_connector->dc_sink :
13750 		amdgpu_dm_connector->dc_em_sink;
13751 
13752 	drm_edid_connector_update(connector, drm_edid);
13753 
13754 	if (!drm_edid || !sink) {
13755 		dm_con_state = to_dm_connector_state(connector->state);
13756 
13757 		amdgpu_dm_connector->min_vfreq = 0;
13758 		amdgpu_dm_connector->max_vfreq = 0;
13759 		freesync_capable = false;
13760 
13761 		goto update;
13762 	}
13763 
13764 	dm_con_state = to_dm_connector_state(connector->state);
13765 
13766 	if (!adev->dm.freesync_module || !dc_supports_vrr(sink->ctx->dce_version))
13767 		goto update;
13768 
13769 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
13770 
13771 	/* Some eDP panels only have the refresh rate range info in DisplayID */
13772 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
13773 	     connector->display_info.monitor_range.max_vfreq == 0))
13774 		parse_edid_displayid_vrr(connector, edid);
13775 
13776 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
13777 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
13778 		if (amdgpu_dm_connector->dc_link &&
13779 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
13780 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
13781 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
13782 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13783 				freesync_capable = true;
13784 		}
13785 
13786 		get_amd_vsdb(amdgpu_dm_connector, &vsdb_info);
13787 
13788 		if (vsdb_info.replay_mode) {
13789 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
13790 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
13791 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
13792 		}
13793 
13794 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
13795 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13796 		if (i >= 0) {
13797 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13798 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13799 
13800 			if (vsdb_info.freesync_supported) {
13801 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13802 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13803 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13804 					freesync_capable = true;
13805 
13806 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13807 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13808 			}
13809 		}
13810 	}
13811 
13812 	if (amdgpu_dm_connector->dc_link)
13813 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
13814 
13815 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
13816 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13817 		if (i >= 0) {
13818 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13819 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13820 
13821 			if (vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
13822 				amdgpu_dm_connector->pack_sdp_v1_3 = true;
13823 				amdgpu_dm_connector->as_type = as_type;
13824 
13825 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13826 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13827 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13828 					freesync_capable = true;
13829 
13830 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13831 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13832 			}
13833 		}
13834 	}
13835 
13836 	/* Handle MCCS */
13837 	if (do_mccs)
13838 		dm_helpers_read_mccs_caps(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13839 
13840 	if ((sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
13841 		as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) &&
13842 		(!sink->edid_caps.freesync_vcp_code ||
13843 		(sink->edid_caps.freesync_vcp_code && !sink->mccs_caps.freesync_supported)))
13844 		freesync_capable = false;
13845 
13846 	if (do_mccs && sink->mccs_caps.freesync_supported && freesync_capable)
13847 		dm_helpers_mccs_vcp_set(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13848 
13849 update:
13850 	if (dm_con_state)
13851 		dm_con_state->freesync_capable = freesync_capable;
13852 
13853 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
13854 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
13855 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
13856 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
13857 	}
13858 
13859 	if (connector->vrr_capable_property)
13860 		drm_connector_set_vrr_capable_property(connector,
13861 						       freesync_capable);
13862 }
13863 
13864 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
13865 {
13866 	struct amdgpu_device *adev = drm_to_adev(dev);
13867 	struct dc *dc = adev->dm.dc;
13868 	int i;
13869 
13870 	mutex_lock(&adev->dm.dc_lock);
13871 	if (dc->current_state) {
13872 		for (i = 0; i < dc->current_state->stream_count; ++i)
13873 			dc->current_state->streams[i]
13874 				->triggered_crtc_reset.enabled =
13875 				adev->dm.force_timing_sync;
13876 
13877 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
13878 		dc_trigger_sync(dc, dc->current_state);
13879 	}
13880 	mutex_unlock(&adev->dm.dc_lock);
13881 }
13882 
13883 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
13884 {
13885 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
13886 		dc_exit_ips_for_hw_access(dc);
13887 }
13888 
13889 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
13890 		       u32 value, const char *func_name)
13891 {
13892 #ifdef DM_CHECK_ADDR_0
13893 	if (address == 0) {
13894 		drm_err(adev_to_drm(ctx->driver_context),
13895 			"invalid register write. address = 0");
13896 		return;
13897 	}
13898 #endif
13899 
13900 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13901 	cgs_write_register(ctx->cgs_device, address, value);
13902 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
13903 }
13904 
13905 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
13906 			  const char *func_name)
13907 {
13908 	u32 value;
13909 #ifdef DM_CHECK_ADDR_0
13910 	if (address == 0) {
13911 		drm_err(adev_to_drm(ctx->driver_context),
13912 			"invalid register read; address = 0\n");
13913 		return 0;
13914 	}
13915 #endif
13916 
13917 	if (ctx->dmub_srv &&
13918 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
13919 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
13920 		ASSERT(false);
13921 		return 0;
13922 	}
13923 
13924 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13925 
13926 	value = cgs_read_register(ctx->cgs_device, address);
13927 
13928 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
13929 
13930 	return value;
13931 }
13932 
13933 int amdgpu_dm_process_dmub_aux_transfer_sync(
13934 		struct dc_context *ctx,
13935 		unsigned int link_index,
13936 		struct aux_payload *payload,
13937 		enum aux_return_code_type *operation_result)
13938 {
13939 	struct amdgpu_device *adev = ctx->driver_context;
13940 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
13941 	int ret = -1;
13942 
13943 	mutex_lock(&adev->dm.dpia_aux_lock);
13944 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
13945 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
13946 		goto out;
13947 	}
13948 
13949 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13950 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13951 		*operation_result = AUX_RET_ERROR_TIMEOUT;
13952 		goto out;
13953 	}
13954 
13955 	if (p_notify->result != AUX_RET_SUCCESS) {
13956 		/*
13957 		 * Transient states before tunneling is enabled could
13958 		 * lead to this error. We can ignore this for now.
13959 		 */
13960 		if (p_notify->result == AUX_RET_ERROR_PROTOCOL_ERROR) {
13961 			drm_warn(adev_to_drm(adev), "DPIA AUX failed on 0x%x(%d), error %d\n",
13962 					payload->address, payload->length,
13963 					p_notify->result);
13964 		}
13965 		*operation_result = p_notify->result;
13966 		goto out;
13967 	}
13968 
13969 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command & 0xF;
13970 	if (adev->dm.dmub_notify->aux_reply.command & 0xF0)
13971 		/* The reply is stored in the top nibble of the command. */
13972 		payload->reply[0] = (adev->dm.dmub_notify->aux_reply.command >> 4) & 0xF;
13973 
13974 	/*write req may receive a byte indicating partially written number as well*/
13975 	if (p_notify->aux_reply.length)
13976 		memcpy(payload->data, p_notify->aux_reply.data,
13977 				p_notify->aux_reply.length);
13978 
13979 	/* success */
13980 	ret = p_notify->aux_reply.length;
13981 	*operation_result = p_notify->result;
13982 out:
13983 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
13984 	mutex_unlock(&adev->dm.dpia_aux_lock);
13985 	return ret;
13986 }
13987 
13988 static void abort_fused_io(
13989 		struct dc_context *ctx,
13990 		const struct dmub_cmd_fused_request *request
13991 )
13992 {
13993 	union dmub_rb_cmd command = { 0 };
13994 	struct dmub_rb_cmd_fused_io *io = &command.fused_io;
13995 
13996 	io->header.type = DMUB_CMD__FUSED_IO;
13997 	io->header.sub_type = DMUB_CMD__FUSED_IO_ABORT;
13998 	io->header.payload_bytes = sizeof(*io) - sizeof(io->header);
13999 	io->request = *request;
14000 	dm_execute_dmub_cmd(ctx, &command, DM_DMUB_WAIT_TYPE_NO_WAIT);
14001 }
14002 
14003 static bool execute_fused_io(
14004 		struct amdgpu_device *dev,
14005 		struct dc_context *ctx,
14006 		union dmub_rb_cmd *commands,
14007 		uint8_t count,
14008 		uint32_t timeout_us
14009 )
14010 {
14011 	const uint8_t ddc_line = commands[0].fused_io.request.u.aux.ddc_line;
14012 
14013 	if (ddc_line >= ARRAY_SIZE(dev->dm.fused_io))
14014 		return false;
14015 
14016 	struct fused_io_sync *sync = &dev->dm.fused_io[ddc_line];
14017 	struct dmub_rb_cmd_fused_io *first = &commands[0].fused_io;
14018 	const bool result = dm_execute_dmub_cmd_list(ctx, count, commands, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY)
14019 			&& first->header.ret_status
14020 			&& first->request.status == FUSED_REQUEST_STATUS_SUCCESS;
14021 
14022 	if (!result)
14023 		return false;
14024 
14025 	while (wait_for_completion_timeout(&sync->replied, usecs_to_jiffies(timeout_us))) {
14026 		reinit_completion(&sync->replied);
14027 
14028 		struct dmub_cmd_fused_request *reply = (struct dmub_cmd_fused_request *) sync->reply_data;
14029 
14030 		static_assert(sizeof(*reply) <= sizeof(sync->reply_data), "Size mismatch");
14031 
14032 		if (reply->identifier == first->request.identifier) {
14033 			first->request = *reply;
14034 			return true;
14035 		}
14036 	}
14037 
14038 	reinit_completion(&sync->replied);
14039 	first->request.status = FUSED_REQUEST_STATUS_TIMEOUT;
14040 	abort_fused_io(ctx, &first->request);
14041 	return false;
14042 }
14043 
14044 bool amdgpu_dm_execute_fused_io(
14045 		struct amdgpu_device *dev,
14046 		struct dc_link *link,
14047 		union dmub_rb_cmd *commands,
14048 		uint8_t count,
14049 		uint32_t timeout_us)
14050 {
14051 	struct amdgpu_display_manager *dm = &dev->dm;
14052 
14053 	mutex_lock(&dm->dpia_aux_lock);
14054 
14055 	const bool result = execute_fused_io(dev, link->ctx, commands, count, timeout_us);
14056 
14057 	mutex_unlock(&dm->dpia_aux_lock);
14058 	return result;
14059 }
14060 
14061 int amdgpu_dm_process_dmub_set_config_sync(
14062 		struct dc_context *ctx,
14063 		unsigned int link_index,
14064 		struct set_config_cmd_payload *payload,
14065 		enum set_config_status *operation_result)
14066 {
14067 	struct amdgpu_device *adev = ctx->driver_context;
14068 	bool is_cmd_complete;
14069 	int ret;
14070 
14071 	mutex_lock(&adev->dm.dpia_aux_lock);
14072 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
14073 			link_index, payload, adev->dm.dmub_notify);
14074 
14075 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
14076 		ret = 0;
14077 		*operation_result = adev->dm.dmub_notify->sc_status;
14078 	} else {
14079 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
14080 		ret = -1;
14081 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
14082 	}
14083 
14084 	if (!is_cmd_complete)
14085 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
14086 	mutex_unlock(&adev->dm.dpia_aux_lock);
14087 	return ret;
14088 }
14089 
14090 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
14091 {
14092 	struct amdgpu_device *adev = ctx->driver_context;
14093 
14094 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
14095 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
14096 }
14097 
14098 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)
14099 {
14100 	struct amdgpu_device *adev = ctx->driver_context;
14101 
14102 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
14103 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
14104 }
14105 
14106 void dm_acpi_process_phy_transition_interlock(
14107 	const struct dc_context *ctx,
14108 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
14109 {
14110 	// Not yet implemented
14111 }
14112