xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision 59e6295fac26b8e85c1ea859cdd89fa1e47519d7)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright 2015-2026 Advanced Micro Devices, Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  * Authors: AMD
24  *
25  */
26 
27 /* The caprices of the preprocessor require that this be declared right here */
28 #define CREATE_TRACE_POINTS
29 
30 #include "dm_services_types.h"
31 #include "dc.h"
32 #include "link_enc_cfg.h"
33 #include "dc/inc/core_types.h"
34 #include "dal_asic_id.h"
35 #include "dmub/dmub_srv.h"
36 #include "dc/inc/hw/dmcu.h"
37 #include "dc/inc/hw/abm.h"
38 #include "dc/dc_dmub_srv.h"
39 #include "dc/dc_edid_parser.h"
40 #include "dc/dc_stat.h"
41 #include "dc/dc_state.h"
42 #include "amdgpu_dm_trace.h"
43 #include "link/protocols/link_dpcd.h"
44 #include "link_service_types.h"
45 #include "link/protocols/link_dp_capability.h"
46 #include "link/protocols/link_ddc.h"
47 
48 #include "amdgpu.h"
49 #include "amdgpu_display.h"
50 #include "amdgpu_ucode.h"
51 #include "atom.h"
52 #include "amdgpu_dm.h"
53 #include "amdgpu_dm_plane.h"
54 #include "amdgpu_dm_crtc.h"
55 #include "amdgpu_dm_hdcp.h"
56 #include <drm/display/drm_hdcp_helper.h>
57 #include "amdgpu_dm_wb.h"
58 #include "amdgpu_atombios.h"
59 
60 #include "amd_shared.h"
61 #include "amdgpu_dm_irq.h"
62 #include "dm_helpers.h"
63 #include "amdgpu_dm_mst_types.h"
64 #if defined(CONFIG_DEBUG_FS)
65 #include "amdgpu_dm_debugfs.h"
66 #endif
67 #include "amdgpu_dm_psr.h"
68 #include "amdgpu_dm_replay.h"
69 
70 #include "ivsrcid/ivsrcid_vislands30.h"
71 
72 #include <linux/backlight.h>
73 #include <linux/module.h>
74 #include <linux/moduleparam.h>
75 #include <linux/types.h>
76 #include <linux/pm_runtime.h>
77 #include <linux/pci.h>
78 #include <linux/power_supply.h>
79 #include <linux/firmware.h>
80 #include <linux/component.h>
81 #include <linux/sort.h>
82 
83 #include <drm/drm_privacy_screen_consumer.h>
84 #include <drm/display/drm_dp_mst_helper.h>
85 #include <drm/display/drm_hdmi_helper.h>
86 #include <drm/drm_atomic.h>
87 #include <drm/drm_atomic_uapi.h>
88 #include <drm/drm_atomic_helper.h>
89 #include <drm/drm_blend.h>
90 #include <drm/drm_fixed.h>
91 #include <drm/drm_fourcc.h>
92 #include <drm/drm_edid.h>
93 #include <drm/drm_eld.h>
94 #include <drm/drm_mode.h>
95 #include <drm/drm_utils.h>
96 #include <drm/drm_vblank.h>
97 #include <drm/drm_audio_component.h>
98 #include <drm/drm_colorop.h>
99 #include <drm/drm_gem_atomic_helper.h>
100 
101 #include <media/cec-notifier.h>
102 #include <acpi/video.h>
103 
104 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
105 
106 #include "modules/inc/mod_freesync.h"
107 #include "modules/inc/mod_power.h"
108 #include "modules/power/power_helpers.h"
109 
110 static_assert(AMDGPU_DMUB_NOTIFICATION_MAX == DMUB_NOTIFICATION_MAX, "AMDGPU_DMUB_NOTIFICATION_MAX mismatch");
111 
112 #define FIRMWARE_RENOIR_DMUB "amdgpu/renoir_dmcub.bin"
113 MODULE_FIRMWARE(FIRMWARE_RENOIR_DMUB);
114 #define FIRMWARE_SIENNA_CICHLID_DMUB "amdgpu/sienna_cichlid_dmcub.bin"
115 MODULE_FIRMWARE(FIRMWARE_SIENNA_CICHLID_DMUB);
116 #define FIRMWARE_NAVY_FLOUNDER_DMUB "amdgpu/navy_flounder_dmcub.bin"
117 MODULE_FIRMWARE(FIRMWARE_NAVY_FLOUNDER_DMUB);
118 #define FIRMWARE_GREEN_SARDINE_DMUB "amdgpu/green_sardine_dmcub.bin"
119 MODULE_FIRMWARE(FIRMWARE_GREEN_SARDINE_DMUB);
120 #define FIRMWARE_VANGOGH_DMUB "amdgpu/vangogh_dmcub.bin"
121 MODULE_FIRMWARE(FIRMWARE_VANGOGH_DMUB);
122 #define FIRMWARE_DIMGREY_CAVEFISH_DMUB "amdgpu/dimgrey_cavefish_dmcub.bin"
123 MODULE_FIRMWARE(FIRMWARE_DIMGREY_CAVEFISH_DMUB);
124 #define FIRMWARE_BEIGE_GOBY_DMUB "amdgpu/beige_goby_dmcub.bin"
125 MODULE_FIRMWARE(FIRMWARE_BEIGE_GOBY_DMUB);
126 #define FIRMWARE_YELLOW_CARP_DMUB "amdgpu/yellow_carp_dmcub.bin"
127 MODULE_FIRMWARE(FIRMWARE_YELLOW_CARP_DMUB);
128 #define FIRMWARE_DCN_314_DMUB "amdgpu/dcn_3_1_4_dmcub.bin"
129 MODULE_FIRMWARE(FIRMWARE_DCN_314_DMUB);
130 #define FIRMWARE_DCN_315_DMUB "amdgpu/dcn_3_1_5_dmcub.bin"
131 MODULE_FIRMWARE(FIRMWARE_DCN_315_DMUB);
132 #define FIRMWARE_DCN316_DMUB "amdgpu/dcn_3_1_6_dmcub.bin"
133 MODULE_FIRMWARE(FIRMWARE_DCN316_DMUB);
134 
135 #define FIRMWARE_DCN_V3_2_0_DMCUB "amdgpu/dcn_3_2_0_dmcub.bin"
136 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_0_DMCUB);
137 #define FIRMWARE_DCN_V3_2_1_DMCUB "amdgpu/dcn_3_2_1_dmcub.bin"
138 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_1_DMCUB);
139 
140 #define FIRMWARE_RAVEN_DMCU		"amdgpu/raven_dmcu.bin"
141 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
142 
143 #define FIRMWARE_NAVI12_DMCU            "amdgpu/navi12_dmcu.bin"
144 MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
145 
146 #define FIRMWARE_DCN_35_DMUB "amdgpu/dcn_3_5_dmcub.bin"
147 MODULE_FIRMWARE(FIRMWARE_DCN_35_DMUB);
148 
149 #define FIRMWARE_DCN_351_DMUB "amdgpu/dcn_3_5_1_dmcub.bin"
150 MODULE_FIRMWARE(FIRMWARE_DCN_351_DMUB);
151 
152 #define FIRMWARE_DCN_36_DMUB "amdgpu/dcn_3_6_dmcub.bin"
153 MODULE_FIRMWARE(FIRMWARE_DCN_36_DMUB);
154 
155 #define FIRMWARE_DCN_401_DMUB "amdgpu/dcn_4_0_1_dmcub.bin"
156 MODULE_FIRMWARE(FIRMWARE_DCN_401_DMUB);
157 
158 #define FIRMWARE_DCN_42_DMUB "amdgpu/dcn_4_2_dmcub.bin"
159 MODULE_FIRMWARE(FIRMWARE_DCN_42_DMUB);
160 
161 #define FIRMWARE_DCN_42B_DMUB "amdgpu/dcn_4_2_1_dmcub.bin"
162 MODULE_FIRMWARE(FIRMWARE_DCN_42B_DMUB);
163 
164 /**
165  * DOC: overview
166  *
167  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
168  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
169  * requests into DC requests, and DC responses into DRM responses.
170  *
171  * The root control structure is &struct amdgpu_display_manager.
172  */
173 
174 /* basic init/fini API */
175 static int amdgpu_dm_init(struct amdgpu_device *adev);
176 static void amdgpu_dm_fini(struct amdgpu_device *adev);
177 static bool is_freesync_video_mode(const struct drm_display_mode *mode, struct amdgpu_dm_connector *aconnector);
178 static void reset_freesync_config_for_crtc(struct dm_crtc_state *new_crtc_state);
179 static struct amdgpu_i2c_adapter *
180 create_i2c(struct ddc_service *ddc_service, bool oem);
181 
182 static enum drm_mode_subconnector get_subconnector_type(struct dc_link *link)
183 {
184 	switch (link->dpcd_caps.dongle_type) {
185 	case DISPLAY_DONGLE_NONE:
186 		return DRM_MODE_SUBCONNECTOR_Native;
187 	case DISPLAY_DONGLE_DP_VGA_CONVERTER:
188 		return DRM_MODE_SUBCONNECTOR_VGA;
189 	case DISPLAY_DONGLE_DP_DVI_CONVERTER:
190 	case DISPLAY_DONGLE_DP_DVI_DONGLE:
191 		return DRM_MODE_SUBCONNECTOR_DVID;
192 	case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
193 	case DISPLAY_DONGLE_DP_HDMI_DONGLE:
194 		return DRM_MODE_SUBCONNECTOR_HDMIA;
195 	case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
196 	default:
197 		return DRM_MODE_SUBCONNECTOR_Unknown;
198 	}
199 }
200 
201 static void update_subconnector_property(struct amdgpu_dm_connector *aconnector)
202 {
203 	struct dc_link *link = aconnector->dc_link;
204 	struct drm_connector *connector = &aconnector->base;
205 	enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
206 
207 	if (connector->connector_type != DRM_MODE_CONNECTOR_DisplayPort)
208 		return;
209 
210 	if (aconnector->dc_sink)
211 		subconnector = get_subconnector_type(link);
212 
213 	drm_object_property_set_value(&connector->base,
214 			connector->dev->mode_config.dp_subconnector_property,
215 			subconnector);
216 }
217 
218 /*
219  * initializes drm_device display related structures, based on the information
220  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
221  * drm_encoder, drm_mode_config
222  *
223  * Returns 0 on success
224  */
225 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
226 /* removes and deallocates the drm structures, created by the above function */
227 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
228 
229 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
230 				    struct amdgpu_dm_connector *amdgpu_dm_connector,
231 				    u32 link_index,
232 				    struct amdgpu_encoder *amdgpu_encoder);
233 static int amdgpu_dm_encoder_init(struct drm_device *dev,
234 				  struct amdgpu_encoder *aencoder,
235 				  uint32_t link_index);
236 
237 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
238 
239 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state);
240 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state);
241 
242 static int amdgpu_dm_atomic_check(struct drm_device *dev,
243 				  struct drm_atomic_commit *state);
244 
245 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector);
246 static void handle_hpd_rx_irq(void *param);
247 
248 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
249 					 int bl_idx,
250 					 u32 user_brightness);
251 
252 static bool
253 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
254 				 struct drm_crtc_state *new_crtc_state);
255 /*
256  * dm_vblank_get_counter
257  *
258  * @brief
259  * Get counter for number of vertical blanks
260  *
261  * @param
262  * struct amdgpu_device *adev - [in] desired amdgpu device
263  * int disp_idx - [in] which CRTC to get the counter from
264  *
265  * @return
266  * Counter for vertical blanks
267  */
268 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
269 {
270 	struct amdgpu_crtc *acrtc = NULL;
271 
272 	if (crtc >= adev->mode_info.num_crtc)
273 		return 0;
274 
275 	acrtc = adev->mode_info.crtcs[crtc];
276 
277 	if (!acrtc->dm_irq_params.stream) {
278 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
279 			  crtc);
280 		return 0;
281 	}
282 
283 	return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
284 }
285 
286 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
287 				  u32 *vbl, u32 *position)
288 {
289 	u32 v_blank_start = 0, v_blank_end = 0, h_position = 0, v_position = 0;
290 	struct amdgpu_crtc *acrtc = NULL;
291 	struct dc *dc = adev->dm.dc;
292 
293 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
294 		return -EINVAL;
295 
296 	acrtc = adev->mode_info.crtcs[crtc];
297 
298 	if (!acrtc->dm_irq_params.stream) {
299 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
300 			  crtc);
301 		return 0;
302 	}
303 
304 	if (dc && dc->caps.ips_support && dc->idle_optimizations_allowed)
305 		dc_allow_idle_optimizations(dc, false);
306 
307 	/*
308 	 * TODO rework base driver to use values directly.
309 	 * for now parse it back into reg-format
310 	 */
311 	dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
312 				 &v_blank_start,
313 				 &v_blank_end,
314 				 &h_position,
315 				 &v_position);
316 
317 	*position = v_position | (h_position << 16);
318 	*vbl = v_blank_start | (v_blank_end << 16);
319 
320 	return 0;
321 }
322 
323 static bool dm_is_idle(struct amdgpu_ip_block *ip_block)
324 {
325 	/* XXX todo */
326 	return true;
327 }
328 
329 static int dm_wait_for_idle(struct amdgpu_ip_block *ip_block)
330 {
331 	/* XXX todo */
332 	return 0;
333 }
334 
335 static bool dm_check_soft_reset(struct amdgpu_ip_block *ip_block)
336 {
337 	return false;
338 }
339 
340 static int dm_soft_reset(struct amdgpu_ip_block *ip_block)
341 {
342 	/* XXX todo */
343 	return 0;
344 }
345 
346 static struct amdgpu_crtc *
347 get_crtc_by_otg_inst(struct amdgpu_device *adev,
348 		     int otg_inst)
349 {
350 	struct drm_device *dev = adev_to_drm(adev);
351 	struct drm_crtc *crtc;
352 	struct amdgpu_crtc *amdgpu_crtc;
353 
354 	if (WARN_ON(otg_inst == -1))
355 		return adev->mode_info.crtcs[0];
356 
357 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
358 		amdgpu_crtc = to_amdgpu_crtc(crtc);
359 
360 		if (amdgpu_crtc->otg_inst == otg_inst)
361 			return amdgpu_crtc;
362 	}
363 
364 	return NULL;
365 }
366 
367 static inline bool is_dc_timing_adjust_needed(struct dm_crtc_state *old_state,
368 					      struct dm_crtc_state *new_state)
369 {
370 	if (new_state->stream->adjust.timing_adjust_pending)
371 		return true;
372 	if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
373 		return true;
374 	else if (amdgpu_dm_crtc_vrr_active(old_state) != amdgpu_dm_crtc_vrr_active(new_state))
375 		return true;
376 	else
377 		return false;
378 }
379 
380 /*
381  * DC will program planes with their z-order determined by their ordering
382  * in the dc_surface_updates array. This comparator is used to sort them
383  * by descending zpos.
384  */
385 static int dm_plane_layer_index_cmp(const void *a, const void *b)
386 {
387 	const struct dc_surface_update *sa = (struct dc_surface_update *)a;
388 	const struct dc_surface_update *sb = (struct dc_surface_update *)b;
389 
390 	/* Sort by descending dc_plane layer_index (i.e. normalized_zpos) */
391 	return sb->surface->layer_index - sa->surface->layer_index;
392 }
393 
394 /**
395  * update_planes_and_stream_adapter() - Send planes to be updated in DC
396  *
397  * DC has a generic way to update planes and stream via
398  * dc_update_planes_and_stream function; however, DM might need some
399  * adjustments and preparation before calling it. This function is a wrapper
400  * for the dc_update_planes_and_stream that does any required configuration
401  * before passing control to DC.
402  *
403  * @dc: Display Core control structure
404  * @update_type: specify whether it is FULL/MEDIUM/FAST update
405  * @planes_count: planes count to update
406  * @stream: stream state
407  * @stream_update: stream update
408  * @array_of_surface_update: dc surface update pointer
409  *
410  */
411 static inline bool update_planes_and_stream_adapter(struct dc *dc,
412 						    int update_type,
413 						    int planes_count,
414 						    struct dc_stream_state *stream,
415 						    struct dc_stream_update *stream_update,
416 						    struct dc_surface_update *array_of_surface_update)
417 {
418 	sort(array_of_surface_update, planes_count,
419 	     sizeof(*array_of_surface_update), dm_plane_layer_index_cmp, NULL);
420 
421 	/*
422 	 * Previous frame finished and HW is ready for optimization.
423 	 */
424 	dc_post_update_surfaces_to_stream(dc);
425 
426 	return dc_update_planes_and_stream(dc,
427 					   array_of_surface_update,
428 					   planes_count,
429 					   stream,
430 					   stream_update);
431 }
432 
433 /**
434  * dm_pflip_high_irq() - Handle pageflip interrupt
435  * @interrupt_params: ignored
436  *
437  * Handles the pageflip interrupt by notifying all interested parties
438  * that the pageflip has been completed.
439  */
440 static void dm_pflip_high_irq(void *interrupt_params)
441 {
442 	struct amdgpu_crtc *amdgpu_crtc;
443 	struct common_irq_params *irq_params = interrupt_params;
444 	struct amdgpu_device *adev = irq_params->adev;
445 	struct drm_device *dev = adev_to_drm(adev);
446 	unsigned long flags;
447 	struct drm_pending_vblank_event *e;
448 	u32 vpos, hpos, v_blank_start, v_blank_end;
449 	bool vrr_active;
450 
451 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
452 
453 	/* IRQ could occur when in initial stage */
454 	/* TODO work and BO cleanup */
455 	if (amdgpu_crtc == NULL) {
456 		drm_dbg_state(dev, "CRTC is null, returning.\n");
457 		return;
458 	}
459 
460 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
461 
462 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED) {
463 		drm_dbg_state(dev,
464 			      "amdgpu_crtc->pflip_status = %d != AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p]\n",
465 			      amdgpu_crtc->pflip_status, AMDGPU_FLIP_SUBMITTED,
466 			      amdgpu_crtc->crtc_id, amdgpu_crtc);
467 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
468 		return;
469 	}
470 
471 	/* page flip completed. */
472 	e = amdgpu_crtc->event;
473 	amdgpu_crtc->event = NULL;
474 
475 	WARN_ON(!e);
476 
477 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(amdgpu_crtc);
478 
479 	/* Fixed refresh rate, or VRR scanout position outside front-porch? */
480 	if (!vrr_active ||
481 	    !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
482 				      &v_blank_end, &hpos, &vpos) ||
483 	    (vpos < v_blank_start)) {
484 		/* Update to correct count and vblank timestamp if racing with
485 		 * vblank irq. This also updates to the correct vblank timestamp
486 		 * even in VRR mode, as scanout is past the front-porch atm.
487 		 */
488 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
489 
490 		/* Wake up userspace by sending the pageflip event with proper
491 		 * count and timestamp of vblank of flip completion.
492 		 */
493 		if (e) {
494 			drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
495 
496 			/* Event sent, so done with vblank for this flip */
497 			drm_crtc_vblank_put(&amdgpu_crtc->base);
498 		}
499 	} else if (e) {
500 		/* VRR active and inside front-porch: vblank count and
501 		 * timestamp for pageflip event will only be up to date after
502 		 * drm_crtc_handle_vblank() has been executed from late vblank
503 		 * irq handler after start of back-porch (vline 0). We queue the
504 		 * pageflip event for send-out by drm_crtc_handle_vblank() with
505 		 * updated timestamp and count, once it runs after us.
506 		 *
507 		 * We need to open-code this instead of using the helper
508 		 * drm_crtc_arm_vblank_event(), as that helper would
509 		 * call drm_crtc_accurate_vblank_count(), which we must
510 		 * not call in VRR mode while we are in front-porch!
511 		 */
512 
513 		/* sequence will be replaced by real count during send-out. */
514 		e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
515 		e->pipe = amdgpu_crtc->crtc_id;
516 
517 		list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
518 		e = NULL;
519 	}
520 
521 	/* Keep track of vblank of this flip for flip throttling. We use the
522 	 * cooked hw counter, as that one incremented at start of this vblank
523 	 * of pageflip completion, so last_flip_vblank is the forbidden count
524 	 * for queueing new pageflips if vsync + VRR is enabled.
525 	 */
526 	amdgpu_crtc->dm_irq_params.last_flip_vblank =
527 		amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
528 
529 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
530 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
531 
532 	drm_dbg_state(dev,
533 		      "crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
534 		      amdgpu_crtc->crtc_id, amdgpu_crtc, vrr_active, (int)!e);
535 }
536 
537 static void dm_handle_vmin_vmax_update(struct work_struct *offload_work)
538 {
539 	struct vupdate_offload_work *work = container_of(offload_work, struct vupdate_offload_work, work);
540 	struct amdgpu_device *adev = work->adev;
541 	struct dc_stream_state *stream = work->stream;
542 	struct dc_crtc_timing_adjust *adjust = work->adjust;
543 
544 	mutex_lock(&adev->dm.dc_lock);
545 	dc_stream_adjust_vmin_vmax(adev->dm.dc, stream, adjust);
546 	mutex_unlock(&adev->dm.dc_lock);
547 
548 	dc_stream_release(stream);
549 	kfree(work->adjust);
550 	kfree(work);
551 }
552 
553 static void schedule_dc_vmin_vmax(struct amdgpu_device *adev,
554 	struct dc_stream_state *stream,
555 	struct dc_crtc_timing_adjust *adjust)
556 {
557 	struct vupdate_offload_work *offload_work = kzalloc_obj(*offload_work,
558 								GFP_NOWAIT);
559 	if (!offload_work) {
560 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate vupdate_offload_work\n");
561 		return;
562 	}
563 
564 	struct dc_crtc_timing_adjust *adjust_copy = kzalloc_obj(*adjust_copy,
565 								GFP_NOWAIT);
566 	if (!adjust_copy) {
567 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate adjust_copy\n");
568 		kfree(offload_work);
569 		return;
570 	}
571 
572 	dc_stream_retain(stream);
573 	memcpy(adjust_copy, adjust, sizeof(*adjust_copy));
574 
575 	INIT_WORK(&offload_work->work, dm_handle_vmin_vmax_update);
576 	offload_work->adev = adev;
577 	offload_work->stream = stream;
578 	offload_work->adjust = adjust_copy;
579 
580 	queue_work(system_percpu_wq, &offload_work->work);
581 }
582 
583 /**
584  * dm_crtc_high_irq_handler() - Common OTG vblank/flip event handling
585  * @adev: amdgpu device
586  * @acrtc: the CRTC to service
587  *
588  * Performs writeback completion, vblank event handling, CRC processing, VRR BTR
589  * updates and pageflip completion delivery.
590  *
591  * On DCN this is driven by VUPDATE_NO_LOCK (the register latch point) from
592  * dm_vupdate_high_irq(); on DCE it is driven by VLINE0 at the start of vblank
593  * from dm_crtc_high_irq().
594  */
595 static void dm_crtc_high_irq_handler(struct amdgpu_device *adev,
596 				     struct amdgpu_crtc *acrtc)
597 {
598 	struct drm_writeback_job *job;
599 	unsigned long flags;
600 	int vrr_active;
601 	bool is_dcn = amdgpu_ip_version(adev, DCE_HWIP, 0) != 0;
602 
603 	if (acrtc->wb_conn) {
604 		spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
605 
606 		if (acrtc->wb_pending) {
607 			job = list_first_entry_or_null(&acrtc->wb_conn->job_queue,
608 						       struct drm_writeback_job,
609 						       list_entry);
610 			acrtc->wb_pending = false;
611 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
612 
613 			if (job) {
614 				unsigned int v_total, refresh_hz;
615 				struct dc_stream_state *stream = acrtc->dm_irq_params.stream;
616 
617 				v_total = stream->adjust.v_total_max ?
618 					  stream->adjust.v_total_max : stream->timing.v_total;
619 				refresh_hz = div_u64((uint64_t) stream->timing.pix_clk_100hz *
620 					     100LL, (v_total * stream->timing.h_total));
621 				mdelay(1000 / refresh_hz);
622 
623 				drm_writeback_signal_completion(acrtc->wb_conn, 0);
624 				dc_stream_fc_disable_writeback(adev->dm.dc,
625 							       acrtc->dm_irq_params.stream, 0);
626 			}
627 		} else
628 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
629 	}
630 
631 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
632 
633 	drm_dbg_vbl(adev_to_drm(adev),
634 		    "crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
635 		    vrr_active, acrtc->dm_irq_params.active_planes);
636 
637 	/**
638 	 * Core vblank handling.
639 	 *
640 	 * On DCN this handler runs at VUPDATE_NO_LOCK, the register latch
641 	 * point, which is the correct place to timestamp both VRR and non-VRR
642 	 * vblanks.
643 	 *
644 	 * On DCE this handler runs at the start of front-porch, where only
645 	 * non-VRR timestamping is valid; VRR vblank is deferred to
646 	 * dm_vupdate_high_irq() after end of front-porch.
647 	 */
648 	if (is_dcn || !vrr_active)
649 		amdgpu_dm_crtc_handle_vblank(acrtc);
650 
651 	/**
652 	 * Following stuff must happen at start of vblank, for crc
653 	 * computation and below-the-range btr support in vrr mode.
654 	 */
655 	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
656 
657 	/* BTR updates need to happen before VUPDATE on Vega and above. */
658 	if (adev->family < AMDGPU_FAMILY_AI)
659 		return;
660 
661 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
662 
663 	if (acrtc->dm_irq_params.stream &&
664 		acrtc->dm_irq_params.vrr_params.supported) {
665 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
666 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
667 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state == VRR_STATE_ACTIVE_VARIABLE;
668 
669 		mod_freesync_handle_v_update(adev->dm.freesync_module,
670 					     acrtc->dm_irq_params.stream,
671 					     &acrtc->dm_irq_params.vrr_params);
672 
673 		/* update vmin_vmax only if freesync is enabled, or only if PSR and REPLAY are disabled */
674 		if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
675 			schedule_dc_vmin_vmax(adev, acrtc->dm_irq_params.stream,
676 					&acrtc->dm_irq_params.vrr_params.adjust);
677 		}
678 	}
679 
680 	/*
681 	 * Deliver pageflip completion events (DCN only).
682 	 *
683 	 * Since GRPH_PFLIP is not used, VUPDATE_NO_LOCK is the flip latch
684 	 * point. Deliver any pending pageflip completion event from here,
685 	 * once HW has consumed the new address (the OTG no longer reports a
686 	 * pending flip).
687 	 *
688 	 * Also handle the case here where there aren't any active planes and
689 	 * DCN HUBP may be clock-gated, so the flip-pending status may be
690 	 * undefined.
691 	 */
692 	if (is_dcn && acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
693 	    acrtc->event) {
694 
695 		if (!dc_get_flip_pending_on_otg(adev->dm.dc, acrtc->otg_inst)) {
696 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
697 			acrtc->event = NULL;
698 			drm_crtc_vblank_put(&acrtc->base);
699 			acrtc->pflip_status = AMDGPU_FLIP_NONE;
700 		}
701 		/*
702 		 * If the flip is still pending, leave it armed and
703 		 * retry on the next vupdate.
704 		 */
705 	} else if (is_dcn && acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
706 		   acrtc->dm_irq_params.active_planes == 0) {
707 
708 		if (acrtc->event) {
709 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
710 			acrtc->event = NULL;
711 			drm_crtc_vblank_put(&acrtc->base);
712 		}
713 		acrtc->pflip_status = AMDGPU_FLIP_NONE;
714 	}
715 
716 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
717 }
718 
719 static void dm_vupdate_high_irq(void *interrupt_params)
720 {
721 	struct common_irq_params *irq_params = interrupt_params;
722 	struct amdgpu_device *adev = irq_params->adev;
723 	struct amdgpu_crtc *acrtc;
724 	struct drm_device *drm_dev;
725 	struct drm_vblank_crtc *vblank;
726 	ktime_t frame_duration_ns, previous_timestamp;
727 	unsigned long flags;
728 	int vrr_active;
729 
730 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
731 	if (!acrtc)
732 		return;
733 
734 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
735 	drm_dev = acrtc->base.dev;
736 	vblank = drm_crtc_vblank_crtc(&acrtc->base);
737 	previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
738 	frame_duration_ns = vblank->time - previous_timestamp;
739 
740 	if (frame_duration_ns > 0) {
741 		trace_amdgpu_refresh_rate_track(acrtc->base.index,
742 					frame_duration_ns,
743 					ktime_divns(NSEC_PER_SEC, frame_duration_ns));
744 		atomic64_set(&irq_params->previous_timestamp, vblank->time);
745 	}
746 
747 	drm_dbg_vbl(drm_dev,
748 		    "crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
749 		    vrr_active);
750 
751 	/*
752 	 * On DCN, VUPDATE_NO_LOCK is the single OTG interrupt used to deliver
753 	 * vblank and pageflip completion events; VSTARTUP and GRPH_PFLIP are
754 	 * not used. Run the full handler here.
755 	 */
756 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) != 0) {
757 		dm_crtc_high_irq_handler(adev, acrtc);
758 		return;
759 	}
760 
761 	/* DCE only below. */
762 
763 	/* Core vblank handling is done here after end of front-porch in
764 	 * vrr mode, as vblank timestamping will give valid results
765 	 * while now done after front-porch. This will also deliver
766 	 * page-flip completion events that have been queued to us
767 	 * if a pageflip happened inside front-porch.
768 	 */
769 	if (vrr_active && acrtc->dm_irq_params.stream) {
770 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
771 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
772 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state
773 			== VRR_STATE_ACTIVE_VARIABLE;
774 
775 		amdgpu_dm_crtc_handle_vblank(acrtc);
776 
777 		/* BTR processing for pre-DCE12 ASICs */
778 		if (adev->family < AMDGPU_FAMILY_AI) {
779 			spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
780 			mod_freesync_handle_v_update(
781 				adev->dm.freesync_module,
782 				acrtc->dm_irq_params.stream,
783 				&acrtc->dm_irq_params.vrr_params);
784 
785 			if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
786 				schedule_dc_vmin_vmax(adev,
787 					acrtc->dm_irq_params.stream,
788 					&acrtc->dm_irq_params.vrr_params.adjust);
789 			}
790 			spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
791 		}
792 	}
793 }
794 
795 /**
796  * dm_crtc_high_irq() - Handles CRTC interrupt
797  * @interrupt_params: used for determining the CRTC instance
798  *
799  * Handles the CRTC/VSYNC interrupt by notifying DRM's VBLANK event handler.
800  *
801  * Used on DCE (VLINE0, set to vblank start). On DCN the equivalent handling is
802  * driven by VUPDATE_NO_LOCK in dm_vupdate_high_irq().
803  */
804 static void dm_crtc_high_irq(void *interrupt_params)
805 {
806 	struct common_irq_params *irq_params = interrupt_params;
807 	struct amdgpu_device *adev = irq_params->adev;
808 	struct amdgpu_crtc *acrtc;
809 
810 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
811 	if (!acrtc)
812 		return;
813 
814 	dm_crtc_high_irq_handler(adev, acrtc);
815 }
816 
817 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
818 /**
819  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
820  * DCN generation ASICs
821  * @interrupt_params: interrupt parameters
822  *
823  * Used to set crc window/read out crc value at vertical line 0 position
824  */
825 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
826 {
827 	struct common_irq_params *irq_params = interrupt_params;
828 	struct amdgpu_device *adev = irq_params->adev;
829 	struct amdgpu_crtc *acrtc;
830 
831 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
832 
833 	if (!acrtc)
834 		return;
835 
836 	amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
837 }
838 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
839 
840 /**
841  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
842  * @adev: amdgpu_device pointer
843  * @notify: dmub notification structure
844  *
845  * Dmub AUX or SET_CONFIG command completion processing callback
846  * Copies dmub notification to DM which is to be read by AUX command.
847  * issuing thread and also signals the event to wake up the thread.
848  */
849 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
850 					struct dmub_notification *notify)
851 {
852 	if (adev->dm.dmub_notify)
853 		memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
854 	if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
855 		complete(&adev->dm.dmub_aux_transfer_done);
856 }
857 
858 static void dmub_aux_fused_io_callback(struct amdgpu_device *adev,
859 					struct dmub_notification *notify)
860 {
861 	if (!adev || !notify) {
862 		ASSERT(false);
863 		return;
864 	}
865 
866 	const struct dmub_cmd_fused_request *req = &notify->fused_request;
867 	const uint8_t ddc_line = req->u.aux.ddc_line;
868 
869 	if (ddc_line >= ARRAY_SIZE(adev->dm.fused_io)) {
870 		ASSERT(false);
871 		return;
872 	}
873 
874 	struct fused_io_sync *sync = &adev->dm.fused_io[ddc_line];
875 
876 	static_assert(sizeof(*req) <= sizeof(sync->reply_data), "Size mismatch");
877 	memcpy(sync->reply_data, req, sizeof(*req));
878 	complete(&sync->replied);
879 }
880 
881 /**
882  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
883  * @adev: amdgpu_device pointer
884  * @notify: dmub notification structure
885  *
886  * Dmub Hpd interrupt processing callback. Gets displayindex through the
887  * ink index and calls helper to do the processing.
888  */
889 static void dmub_hpd_callback(struct amdgpu_device *adev,
890 			      struct dmub_notification *notify)
891 {
892 	struct amdgpu_dm_connector *aconnector;
893 	struct amdgpu_dm_connector *hpd_aconnector = NULL;
894 	struct drm_connector *connector;
895 	struct drm_connector_list_iter iter;
896 	struct dc_link *link;
897 	u8 link_index = 0;
898 	struct drm_device *dev;
899 
900 	if (adev == NULL)
901 		return;
902 
903 	if (notify == NULL) {
904 		drm_err(adev_to_drm(adev), "DMUB HPD callback notification was NULL");
905 		return;
906 	}
907 
908 	if (notify->link_index > adev->dm.dc->link_count) {
909 		drm_err(adev_to_drm(adev), "DMUB HPD index (%u)is abnormal", notify->link_index);
910 		return;
911 	}
912 
913 	/* Skip DMUB HPD IRQ in suspend/resume. We will probe them later. */
914 	if (notify->type == DMUB_NOTIFICATION_HPD && adev->in_suspend) {
915 		drm_info(adev_to_drm(adev), "Skip DMUB HPD IRQ callback in suspend/resume\n");
916 		return;
917 	}
918 
919 	link_index = notify->link_index;
920 	link = adev->dm.dc->links[link_index];
921 	dev = adev->dm.ddev;
922 
923 	drm_connector_list_iter_begin(dev, &iter);
924 	drm_for_each_connector_iter(connector, &iter) {
925 
926 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
927 			continue;
928 
929 		aconnector = to_amdgpu_dm_connector(connector);
930 		if (link && aconnector->dc_link == link) {
931 			if (notify->type == DMUB_NOTIFICATION_HPD)
932 				drm_info(adev_to_drm(adev), "DMUB HPD IRQ callback: link_index=%u\n", link_index);
933 			else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
934 				drm_info(adev_to_drm(adev), "DMUB HPD RX IRQ callback: link_index=%u\n", link_index);
935 			else
936 				drm_warn(adev_to_drm(adev), "DMUB Unknown HPD callback type %d, link_index=%u\n",
937 						notify->type, link_index);
938 
939 			hpd_aconnector = aconnector;
940 			break;
941 		}
942 	}
943 	drm_connector_list_iter_end(&iter);
944 
945 	if (hpd_aconnector) {
946 		if (notify->type == DMUB_NOTIFICATION_HPD) {
947 			if (hpd_aconnector->dc_link->hpd_status == (notify->hpd_status == DP_HPD_PLUG))
948 				drm_warn(adev_to_drm(adev), "DMUB reported hpd status unchanged. link_index=%u\n", link_index);
949 			handle_hpd_irq_helper(hpd_aconnector);
950 		} else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ) {
951 			handle_hpd_rx_irq(hpd_aconnector);
952 		}
953 	}
954 }
955 
956 /**
957  * dmub_hpd_sense_callback - DMUB HPD sense processing callback.
958  * @adev: amdgpu_device pointer
959  * @notify: dmub notification structure
960  *
961  * HPD sense changes can occur during low power states and need to be
962  * notified from firmware to driver.
963  */
964 static void dmub_hpd_sense_callback(struct amdgpu_device *adev,
965 			      struct dmub_notification *notify)
966 {
967 	drm_dbg_driver(adev_to_drm(adev), "DMUB HPD SENSE callback.\n");
968 }
969 
970 /**
971  * register_dmub_notify_callback - Sets callback for DMUB notify
972  * @adev: amdgpu_device pointer
973  * @type: Type of dmub notification
974  * @callback: Dmub interrupt callback function
975  * @dmub_int_thread_offload: offload indicator
976  *
977  * API to register a dmub callback handler for a dmub notification
978  * Also sets indicator whether callback processing to be offloaded.
979  * to dmub interrupt handling thread
980  * Return: true if successfully registered, false if there is existing registration
981  */
982 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
983 					  enum dmub_notification_type type,
984 					  dmub_notify_interrupt_callback_t callback,
985 					  bool dmub_int_thread_offload)
986 {
987 	if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
988 		adev->dm.dmub_callback[type] = callback;
989 		adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
990 	} else
991 		return false;
992 
993 	return true;
994 }
995 
996 static void dm_handle_hpd_work(struct work_struct *work)
997 {
998 	struct dmub_hpd_work *dmub_hpd_wrk;
999 
1000 	dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
1001 
1002 	if (!dmub_hpd_wrk->dmub_notify) {
1003 		drm_err(adev_to_drm(dmub_hpd_wrk->adev), "dmub_hpd_wrk dmub_notify is NULL");
1004 		return;
1005 	}
1006 
1007 	if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
1008 		dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
1009 		dmub_hpd_wrk->dmub_notify);
1010 	}
1011 
1012 	kfree(dmub_hpd_wrk->dmub_notify);
1013 	kfree(dmub_hpd_wrk);
1014 
1015 }
1016 
1017 static const char *dmub_notification_type_str(enum dmub_notification_type e)
1018 {
1019 	switch (e) {
1020 	case DMUB_NOTIFICATION_NO_DATA:
1021 		return "NO_DATA";
1022 	case DMUB_NOTIFICATION_AUX_REPLY:
1023 		return "AUX_REPLY";
1024 	case DMUB_NOTIFICATION_HPD:
1025 		return "HPD";
1026 	case DMUB_NOTIFICATION_HPD_IRQ:
1027 		return "HPD_IRQ";
1028 	case DMUB_NOTIFICATION_SET_CONFIG_REPLY:
1029 		return "SET_CONFIG_REPLY";
1030 	case DMUB_NOTIFICATION_DPIA_NOTIFICATION:
1031 		return "DPIA_NOTIFICATION";
1032 	case DMUB_NOTIFICATION_HPD_SENSE_NOTIFY:
1033 		return "HPD_SENSE_NOTIFY";
1034 	case DMUB_NOTIFICATION_FUSED_IO:
1035 		return "FUSED_IO";
1036 	default:
1037 		return "<unknown>";
1038 	}
1039 }
1040 
1041 #define DMUB_TRACE_MAX_READ 64
1042 /**
1043  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
1044  * @interrupt_params: used for determining the Outbox instance
1045  *
1046  * Handles the Outbox Interrupt
1047  * event handler.
1048  */
1049 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
1050 {
1051 	struct dmub_notification notify = {0};
1052 	struct common_irq_params *irq_params = interrupt_params;
1053 	struct amdgpu_device *adev = irq_params->adev;
1054 	struct amdgpu_display_manager *dm = &adev->dm;
1055 	struct dmcub_trace_buf_entry entry = { 0 };
1056 	u32 count = 0;
1057 	struct dmub_hpd_work *dmub_hpd_wrk;
1058 
1059 	do {
1060 		if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
1061 			trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
1062 							entry.param0, entry.param1);
1063 
1064 			drm_dbg_driver(adev_to_drm(adev), "trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
1065 				 entry.trace_code, entry.tick_count, entry.param0, entry.param1);
1066 		} else
1067 			break;
1068 
1069 		count++;
1070 
1071 	} while (count <= DMUB_TRACE_MAX_READ);
1072 
1073 	if (count > DMUB_TRACE_MAX_READ)
1074 		drm_dbg_driver(adev_to_drm(adev), "Warning : count > DMUB_TRACE_MAX_READ");
1075 
1076 	if (dc_enable_dmub_notifications(adev->dm.dc) &&
1077 		irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
1078 
1079 		do {
1080 			dc_stat_get_dmub_notification(adev->dm.dc, &notify);
1081 			if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
1082 				drm_err(adev_to_drm(adev), "DM: notify type %d invalid!", notify.type);
1083 				continue;
1084 			}
1085 			if (!dm->dmub_callback[notify.type]) {
1086 				drm_warn(adev_to_drm(adev), "DMUB notification skipped due to no handler: type=%s\n",
1087 					dmub_notification_type_str(notify.type));
1088 				continue;
1089 			}
1090 			if (dm->dmub_thread_offload[notify.type] == true) {
1091 				dmub_hpd_wrk = kzalloc_obj(*dmub_hpd_wrk,
1092 							   GFP_ATOMIC);
1093 				if (!dmub_hpd_wrk) {
1094 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk");
1095 					return;
1096 				}
1097 				dmub_hpd_wrk->dmub_notify = kmemdup(&notify, sizeof(struct dmub_notification),
1098 								    GFP_ATOMIC);
1099 				if (!dmub_hpd_wrk->dmub_notify) {
1100 					kfree(dmub_hpd_wrk);
1101 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk->dmub_notify");
1102 					return;
1103 				}
1104 				INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
1105 				dmub_hpd_wrk->adev = adev;
1106 				queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
1107 			} else {
1108 				dm->dmub_callback[notify.type](adev, &notify);
1109 			}
1110 		} while (notify.pending_notification);
1111 	}
1112 }
1113 
1114 static int dm_set_clockgating_state(struct amdgpu_ip_block *ip_block,
1115 		  enum amd_clockgating_state state)
1116 {
1117 	return 0;
1118 }
1119 
1120 static int dm_set_powergating_state(struct amdgpu_ip_block *ip_block,
1121 		  enum amd_powergating_state state)
1122 {
1123 	return 0;
1124 }
1125 
1126 /* Prototypes of private functions */
1127 static int dm_early_init(struct amdgpu_ip_block *ip_block);
1128 
1129 /* Allocate memory for FBC compressed data  */
1130 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
1131 {
1132 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
1133 	struct dm_compressor_info *compressor = &adev->dm.compressor;
1134 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
1135 	struct drm_display_mode *mode;
1136 	unsigned long max_size = 0;
1137 
1138 	if (adev->dm.dc->fbc_compressor == NULL)
1139 		return;
1140 
1141 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
1142 		return;
1143 
1144 	if (compressor->bo_ptr)
1145 		return;
1146 
1147 
1148 	list_for_each_entry(mode, &connector->modes, head) {
1149 		if (max_size < (unsigned long) mode->htotal * mode->vtotal)
1150 			max_size = (unsigned long) mode->htotal * mode->vtotal;
1151 	}
1152 
1153 	if (max_size) {
1154 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
1155 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
1156 			    &compressor->gpu_addr, &compressor->cpu_addr);
1157 
1158 		if (r)
1159 			drm_err(adev_to_drm(adev), "DM: Failed to initialize FBC\n");
1160 		else {
1161 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
1162 			drm_info(adev_to_drm(adev), "DM: FBC alloc %lu\n", max_size*4);
1163 		}
1164 
1165 	}
1166 
1167 }
1168 
1169 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
1170 					  int pipe, bool *enabled,
1171 					  unsigned char *buf, int max_bytes)
1172 {
1173 	struct drm_device *dev = dev_get_drvdata(kdev);
1174 	struct amdgpu_device *adev = drm_to_adev(dev);
1175 	struct drm_connector *connector;
1176 	struct drm_connector_list_iter conn_iter;
1177 	struct amdgpu_dm_connector *aconnector;
1178 	int ret = 0;
1179 
1180 	*enabled = false;
1181 
1182 	mutex_lock(&adev->dm.audio_lock);
1183 
1184 	drm_connector_list_iter_begin(dev, &conn_iter);
1185 	drm_for_each_connector_iter(connector, &conn_iter) {
1186 
1187 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1188 			continue;
1189 
1190 		aconnector = to_amdgpu_dm_connector(connector);
1191 		if (aconnector->audio_inst != port)
1192 			continue;
1193 
1194 		*enabled = true;
1195 		mutex_lock(&connector->eld_mutex);
1196 		ret = drm_eld_size(connector->eld);
1197 		memcpy(buf, connector->eld, min(max_bytes, ret));
1198 		mutex_unlock(&connector->eld_mutex);
1199 
1200 		break;
1201 	}
1202 	drm_connector_list_iter_end(&conn_iter);
1203 
1204 	mutex_unlock(&adev->dm.audio_lock);
1205 
1206 	drm_dbg_kms(adev_to_drm(adev), "Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
1207 
1208 	return ret;
1209 }
1210 
1211 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
1212 	.get_eld = amdgpu_dm_audio_component_get_eld,
1213 };
1214 
1215 static int amdgpu_dm_audio_component_bind(struct device *kdev,
1216 				       struct device *hda_kdev, void *data)
1217 {
1218 	struct drm_device *dev = dev_get_drvdata(kdev);
1219 	struct amdgpu_device *adev = drm_to_adev(dev);
1220 	struct drm_audio_component *acomp = data;
1221 
1222 	acomp->ops = &amdgpu_dm_audio_component_ops;
1223 	acomp->dev = kdev;
1224 	adev->dm.audio_component = acomp;
1225 
1226 	return 0;
1227 }
1228 
1229 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
1230 					  struct device *hda_kdev, void *data)
1231 {
1232 	struct amdgpu_device *adev = drm_to_adev(dev_get_drvdata(kdev));
1233 	struct drm_audio_component *acomp = data;
1234 
1235 	acomp->ops = NULL;
1236 	acomp->dev = NULL;
1237 	adev->dm.audio_component = NULL;
1238 }
1239 
1240 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
1241 	.bind	= amdgpu_dm_audio_component_bind,
1242 	.unbind	= amdgpu_dm_audio_component_unbind,
1243 };
1244 
1245 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
1246 {
1247 	int i, ret;
1248 
1249 	if (!amdgpu_audio)
1250 		return 0;
1251 
1252 	adev->mode_info.audio.enabled = true;
1253 
1254 	adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
1255 
1256 	for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
1257 		adev->mode_info.audio.pin[i].channels = -1;
1258 		adev->mode_info.audio.pin[i].rate = -1;
1259 		adev->mode_info.audio.pin[i].bits_per_sample = -1;
1260 		adev->mode_info.audio.pin[i].status_bits = 0;
1261 		adev->mode_info.audio.pin[i].category_code = 0;
1262 		adev->mode_info.audio.pin[i].connected = false;
1263 		adev->mode_info.audio.pin[i].id =
1264 			adev->dm.dc->res_pool->audios[i]->inst;
1265 		adev->mode_info.audio.pin[i].offset = 0;
1266 	}
1267 
1268 	ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1269 	if (ret < 0)
1270 		return ret;
1271 
1272 	adev->dm.audio_registered = true;
1273 
1274 	return 0;
1275 }
1276 
1277 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
1278 {
1279 	if (!amdgpu_audio)
1280 		return;
1281 
1282 	if (!adev->mode_info.audio.enabled)
1283 		return;
1284 
1285 	if (adev->dm.audio_registered) {
1286 		component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1287 		adev->dm.audio_registered = false;
1288 	}
1289 
1290 	/* TODO: Disable audio? */
1291 
1292 	adev->mode_info.audio.enabled = false;
1293 }
1294 
1295 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
1296 {
1297 	struct drm_audio_component *acomp = adev->dm.audio_component;
1298 
1299 	if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
1300 		drm_dbg_kms(adev_to_drm(adev), "Notify ELD: %d\n", pin);
1301 
1302 		acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1303 						 pin, -1);
1304 	}
1305 }
1306 
1307 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1308 {
1309 	const struct dmcub_firmware_header_v1_0 *hdr;
1310 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1311 	struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1312 	const struct firmware *dmub_fw = adev->dm.dmub_fw;
1313 	struct dc *dc = adev->dm.dc;
1314 	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1315 	struct abm *abm = adev->dm.dc->res_pool->abm;
1316 	struct dc_context *ctx = adev->dm.dc->ctx;
1317 	struct dmub_srv_hw_params hw_params;
1318 	enum dmub_status status;
1319 	const unsigned char *fw_inst_const, *fw_bss_data;
1320 	u32 i, fw_inst_const_size, fw_bss_data_size;
1321 	bool has_hw_support;
1322 
1323 	if (!dmub_srv)
1324 		/* DMUB isn't supported on the ASIC. */
1325 		return 0;
1326 
1327 	if (!fb_info) {
1328 		drm_err(adev_to_drm(adev), "No framebuffer info for DMUB service.\n");
1329 		return -EINVAL;
1330 	}
1331 
1332 	if (!dmub_fw) {
1333 		/* Firmware required for DMUB support. */
1334 		drm_err(adev_to_drm(adev), "No firmware provided for DMUB.\n");
1335 		return -EINVAL;
1336 	}
1337 
1338 	/* initialize register offsets for ASICs with runtime initialization available */
1339 	if (dmub_srv->hw_funcs.init_reg_offsets)
1340 		dmub_srv->hw_funcs.init_reg_offsets(dmub_srv, ctx);
1341 
1342 	status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1343 	if (status != DMUB_STATUS_OK) {
1344 		drm_err(adev_to_drm(adev), "Error checking HW support for DMUB: %d\n", status);
1345 		return -EINVAL;
1346 	}
1347 
1348 	if (!has_hw_support) {
1349 		drm_info(adev_to_drm(adev), "DMUB unsupported on ASIC\n");
1350 		return 0;
1351 	}
1352 
1353 	/* Reset DMCUB if it was previously running - before we overwrite its memory. */
1354 	status = dmub_srv_hw_reset(dmub_srv);
1355 	if (status != DMUB_STATUS_OK)
1356 		drm_warn(adev_to_drm(adev), "Error resetting DMUB HW: %d\n", status);
1357 
1358 	hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1359 
1360 	fw_inst_const = dmub_fw->data +
1361 			le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1362 			PSP_HEADER_BYTES_256;
1363 
1364 	fw_bss_data = dmub_fw->data +
1365 		      le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1366 		      le32_to_cpu(hdr->inst_const_bytes);
1367 
1368 	/* Copy firmware and bios info into FB memory. */
1369 	fw_inst_const_size = adev->dm.fw_inst_size;
1370 
1371 	fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1372 
1373 	/* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1374 	 * amdgpu_ucode_init_single_fw will load dmub firmware
1375 	 * fw_inst_const part to cw0; otherwise, the firmware back door load
1376 	 * will be done by dm_dmub_hw_init
1377 	 */
1378 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1379 		memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1380 				fw_inst_const_size);
1381 	}
1382 
1383 	if (fw_bss_data_size)
1384 		memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1385 		       fw_bss_data, fw_bss_data_size);
1386 
1387 	/* Copy firmware bios info into FB memory. */
1388 	memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1389 	       adev->bios_size);
1390 
1391 	/* Reset regions that need to be reset. */
1392 	memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1393 	fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1394 
1395 	memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1396 	       fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1397 
1398 	memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1399 	       fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1400 
1401 	memset(fb_info->fb[DMUB_WINDOW_SHARED_STATE].cpu_addr, 0,
1402 	       fb_info->fb[DMUB_WINDOW_SHARED_STATE].size);
1403 
1404 	/* Initialize hardware. */
1405 	memset(&hw_params, 0, sizeof(hw_params));
1406 	hw_params.soc_fb_info.fb_base = adev->gmc.fb_start;
1407 	hw_params.soc_fb_info.fb_offset = adev->vm_manager.vram_base_offset;
1408 
1409 	/* backdoor load firmware and trigger dmub running */
1410 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1411 		hw_params.load_inst_const = true;
1412 
1413 	if (dmcu)
1414 		hw_params.psp_version = dmcu->psp_version;
1415 
1416 	for (i = 0; i < fb_info->num_fb; ++i)
1417 		hw_params.fb[i] = &fb_info->fb[i];
1418 
1419 	/* Enable usb4 dpia in the FW APU */
1420 	if (dc->caps.is_apu &&
1421 		dc->res_pool->usb4_dpia_count != 0 &&
1422 		!dc->debug.dpia_debug.bits.disable_dpia) {
1423 		hw_params.dpia_supported = true;
1424 		hw_params.disable_dpia = dc->debug.dpia_debug.bits.disable_dpia;
1425 		hw_params.dpia_hpd_int_enable_supported = false;
1426 		hw_params.enable_non_transparent_setconfig = dc->config.consolidated_dpia_dp_lt;
1427 		hw_params.disable_dpia_bw_allocation = !dc->config.usb4_bw_alloc_support;
1428 	}
1429 
1430 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1431 	case IP_VERSION(3, 5, 0):
1432 	case IP_VERSION(3, 5, 1):
1433 	case IP_VERSION(3, 6, 0):
1434 	case IP_VERSION(4, 2, 0):
1435 	case IP_VERSION(4, 2, 1):
1436 		hw_params.ips_sequential_ono = adev->external_rev_id > 0x10;
1437 		hw_params.lower_hbr3_phy_ssc = true;
1438 		break;
1439 	default:
1440 		break;
1441 	}
1442 
1443 	status = dmub_srv_hw_init(dmub_srv, &hw_params);
1444 	if (status != DMUB_STATUS_OK) {
1445 		drm_err(adev_to_drm(adev), "Error initializing DMUB HW: %d\n", status);
1446 		return -EINVAL;
1447 	}
1448 
1449 	/* Wait for firmware load to finish. */
1450 	status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1451 	if (status != DMUB_STATUS_OK)
1452 		drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1453 
1454 	/* Init DMCU and ABM if available. */
1455 	if (dmcu && abm) {
1456 		dmcu->funcs->dmcu_init(dmcu);
1457 		abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1458 	}
1459 
1460 	if (!adev->dm.dc->ctx->dmub_srv)
1461 		adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1462 	if (!adev->dm.dc->ctx->dmub_srv) {
1463 		drm_err(adev_to_drm(adev), "Couldn't allocate DC DMUB server!\n");
1464 		return -ENOMEM;
1465 	}
1466 
1467 	drm_info(adev_to_drm(adev), "DMUB hardware initialized: version=0x%08X\n",
1468 		 adev->dm.dmcub_fw_version);
1469 
1470 	/* Keeping sanity checks off if
1471 	 * DCN31 >= 4.0.59.0
1472 	 * DCN314 >= 8.0.16.0
1473 	 * Otherwise, turn on sanity checks
1474 	 */
1475 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1476 	case IP_VERSION(3, 1, 2):
1477 	case IP_VERSION(3, 1, 3):
1478 		if (adev->dm.dmcub_fw_version &&
1479 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1480 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(4, 0, 59))
1481 				adev->dm.dc->debug.sanity_checks = true;
1482 		break;
1483 	case IP_VERSION(3, 1, 4):
1484 		if (adev->dm.dmcub_fw_version &&
1485 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1486 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(8, 0, 16))
1487 				adev->dm.dc->debug.sanity_checks = true;
1488 		break;
1489 	default:
1490 		break;
1491 	}
1492 
1493 	return 0;
1494 }
1495 
1496 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1497 {
1498 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1499 	enum dmub_status status;
1500 	bool init;
1501 	int r;
1502 
1503 	if (!dmub_srv) {
1504 		/* DMUB isn't supported on the ASIC. */
1505 		return;
1506 	}
1507 
1508 	status = dmub_srv_is_hw_init(dmub_srv, &init);
1509 	if (status != DMUB_STATUS_OK)
1510 		drm_warn(adev_to_drm(adev), "DMUB hardware init check failed: %d\n", status);
1511 
1512 	if (status == DMUB_STATUS_OK && init) {
1513 		/* Wait for firmware load to finish. */
1514 		status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1515 		if (status != DMUB_STATUS_OK)
1516 			drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1517 	} else {
1518 		/* Perform the full hardware initialization. */
1519 		r = dm_dmub_hw_init(adev);
1520 		if (r)
1521 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
1522 	}
1523 }
1524 
1525 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1526 {
1527 	u64 pt_base;
1528 	u32 logical_addr_low;
1529 	u32 logical_addr_high;
1530 	u32 agp_base, agp_bot, agp_top;
1531 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1532 
1533 	memset(pa_config, 0, sizeof(*pa_config));
1534 
1535 	agp_base = 0;
1536 	agp_bot = adev->gmc.agp_start >> 24;
1537 	agp_top = adev->gmc.agp_end >> 24;
1538 
1539 	/* AGP aperture is disabled */
1540 	if (agp_bot > agp_top) {
1541 		logical_addr_low = adev->gmc.fb_start >> 18;
1542 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1543 				       AMD_APU_IS_RENOIR |
1544 				       AMD_APU_IS_GREEN_SARDINE))
1545 			/*
1546 			 * Raven2 has a HW issue that it is unable to use the vram which
1547 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1548 			 * workaround that increase system aperture high address (add 1)
1549 			 * to get rid of the VM fault and hardware hang.
1550 			 */
1551 			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
1552 		else
1553 			logical_addr_high = adev->gmc.fb_end >> 18;
1554 	} else {
1555 		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1556 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1557 				       AMD_APU_IS_RENOIR |
1558 				       AMD_APU_IS_GREEN_SARDINE))
1559 			/*
1560 			 * Raven2 has a HW issue that it is unable to use the vram which
1561 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1562 			 * workaround that increase system aperture high address (add 1)
1563 			 * to get rid of the VM fault and hardware hang.
1564 			 */
1565 			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1566 		else
1567 			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1568 	}
1569 
1570 	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1571 
1572 	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
1573 						   AMDGPU_GPU_PAGE_SHIFT);
1574 	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
1575 						  AMDGPU_GPU_PAGE_SHIFT);
1576 	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
1577 						 AMDGPU_GPU_PAGE_SHIFT);
1578 	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
1579 						AMDGPU_GPU_PAGE_SHIFT);
1580 	page_table_base.high_part = upper_32_bits(pt_base);
1581 	page_table_base.low_part = lower_32_bits(pt_base);
1582 
1583 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1584 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1585 
1586 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
1587 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1588 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1589 
1590 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1591 	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
1592 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1593 
1594 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1595 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1596 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1597 
1598 	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
1599 
1600 }
1601 
1602 static void force_connector_state(
1603 	struct amdgpu_dm_connector *aconnector,
1604 	enum drm_connector_force force_state)
1605 {
1606 	struct drm_connector *connector = &aconnector->base;
1607 
1608 	mutex_lock(&connector->dev->mode_config.mutex);
1609 	aconnector->base.force = force_state;
1610 	mutex_unlock(&connector->dev->mode_config.mutex);
1611 
1612 	mutex_lock(&aconnector->hpd_lock);
1613 	drm_kms_helper_connector_hotplug_event(connector);
1614 	mutex_unlock(&aconnector->hpd_lock);
1615 }
1616 
1617 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1618 {
1619 	struct hpd_rx_irq_offload_work *offload_work;
1620 	struct amdgpu_dm_connector *aconnector;
1621 	struct dc_link *dc_link;
1622 	struct amdgpu_device *adev;
1623 	enum dc_connection_type new_connection_type = dc_connection_none;
1624 	unsigned long flags;
1625 	union test_response test_response;
1626 
1627 	memset(&test_response, 0, sizeof(test_response));
1628 
1629 	offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1630 	aconnector = offload_work->offload_wq->aconnector;
1631 	adev = offload_work->adev;
1632 
1633 	if (!aconnector) {
1634 		drm_err(adev_to_drm(adev), "Can't retrieve aconnector in hpd_rx_irq_offload_work");
1635 		goto skip;
1636 	}
1637 
1638 	dc_link = aconnector->dc_link;
1639 
1640 	mutex_lock(&aconnector->hpd_lock);
1641 	if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
1642 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
1643 	mutex_unlock(&aconnector->hpd_lock);
1644 
1645 	if (new_connection_type == dc_connection_none)
1646 		goto skip;
1647 
1648 	if (amdgpu_in_reset(adev))
1649 		goto skip;
1650 
1651 	if (offload_work->data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
1652 		offload_work->data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
1653 		dm_handle_mst_sideband_msg_ready_event(&aconnector->mst_mgr, DOWN_OR_UP_MSG_RDY_EVENT);
1654 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1655 		offload_work->offload_wq->is_handling_mst_msg_rdy_event = false;
1656 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1657 		goto skip;
1658 	}
1659 
1660 	mutex_lock(&adev->dm.dc_lock);
1661 	if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
1662 		dc_link_dp_handle_automated_test(dc_link);
1663 
1664 		if (aconnector->timing_changed) {
1665 			/* force connector disconnect and reconnect */
1666 			force_connector_state(aconnector, DRM_FORCE_OFF);
1667 			msleep(100);
1668 			force_connector_state(aconnector, DRM_FORCE_UNSPECIFIED);
1669 		}
1670 
1671 		test_response.bits.ACK = 1;
1672 
1673 		core_link_write_dpcd(
1674 		dc_link,
1675 		DP_TEST_RESPONSE,
1676 		&test_response.raw,
1677 		sizeof(test_response));
1678 	} else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1679 			dc_link_check_link_loss_status(dc_link, &offload_work->data) &&
1680 			dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1681 		/* offload_work->data is from handle_hpd_rx_irq->
1682 		 * schedule_hpd_rx_offload_work.this is defer handle
1683 		 * for hpd short pulse. upon here, link status may be
1684 		 * changed, need get latest link status from dpcd
1685 		 * registers. if link status is good, skip run link
1686 		 * training again.
1687 		 */
1688 		union hpd_irq_data irq_data;
1689 
1690 		memset(&irq_data, 0, sizeof(irq_data));
1691 
1692 		/* before dc_link_dp_handle_link_loss, allow new link lost handle
1693 		 * request be added to work queue if link lost at end of dc_link_
1694 		 * dp_handle_link_loss
1695 		 */
1696 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1697 		offload_work->offload_wq->is_handling_link_loss = false;
1698 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1699 
1700 		if ((dc_link_dp_read_hpd_rx_irq_data(dc_link, &irq_data) == DC_OK) &&
1701 			dc_link_check_link_loss_status(dc_link, &irq_data))
1702 			dc_link_dp_handle_link_loss(dc_link);
1703 	}
1704 	mutex_unlock(&adev->dm.dc_lock);
1705 
1706 skip:
1707 	kfree(offload_work);
1708 
1709 }
1710 
1711 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct amdgpu_device *adev)
1712 {
1713 	struct dc *dc = adev->dm.dc;
1714 	int max_caps = dc->caps.max_links;
1715 	int i = 0;
1716 	struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1717 
1718 	hpd_rx_offload_wq = kzalloc_objs(*hpd_rx_offload_wq, max_caps);
1719 
1720 	if (!hpd_rx_offload_wq)
1721 		return NULL;
1722 
1723 
1724 	for (i = 0; i < max_caps; i++) {
1725 		hpd_rx_offload_wq[i].wq =
1726 				    create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1727 
1728 		if (hpd_rx_offload_wq[i].wq == NULL) {
1729 			drm_err(adev_to_drm(adev), "create amdgpu_dm_hpd_rx_offload_wq fail!");
1730 			goto out_err;
1731 		}
1732 
1733 		spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
1734 	}
1735 
1736 	return hpd_rx_offload_wq;
1737 
1738 out_err:
1739 	for (i = 0; i < max_caps; i++) {
1740 		if (hpd_rx_offload_wq[i].wq)
1741 			destroy_workqueue(hpd_rx_offload_wq[i].wq);
1742 	}
1743 	kfree(hpd_rx_offload_wq);
1744 	return NULL;
1745 }
1746 
1747 struct amdgpu_stutter_quirk {
1748 	u16 chip_vendor;
1749 	u16 chip_device;
1750 	u16 subsys_vendor;
1751 	u16 subsys_device;
1752 	u8 revision;
1753 };
1754 
1755 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1756 	/* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1757 	{ 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1758 	{ 0, 0, 0, 0, 0 },
1759 };
1760 
1761 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1762 {
1763 	const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1764 
1765 	while (p && p->chip_device != 0) {
1766 		if (pdev->vendor == p->chip_vendor &&
1767 		    pdev->device == p->chip_device &&
1768 		    pdev->subsystem_vendor == p->subsys_vendor &&
1769 		    pdev->subsystem_device == p->subsys_device &&
1770 		    pdev->revision == p->revision) {
1771 			return true;
1772 		}
1773 		++p;
1774 	}
1775 	return false;
1776 }
1777 
1778 
1779 void*
1780 dm_allocate_gpu_mem(
1781 		struct amdgpu_device *adev,
1782 		enum dc_gpu_mem_alloc_type type,
1783 		size_t size,
1784 		long long *addr)
1785 {
1786 	struct dal_allocation *da;
1787 	u32 domain = (type == DC_MEM_ALLOC_TYPE_GART) ?
1788 		AMDGPU_GEM_DOMAIN_GTT : AMDGPU_GEM_DOMAIN_VRAM;
1789 	int ret;
1790 
1791 	da = kzalloc_obj(struct dal_allocation);
1792 	if (!da)
1793 		return NULL;
1794 
1795 	ret = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
1796 				      domain, &da->bo,
1797 				      &da->gpu_addr, &da->cpu_ptr);
1798 
1799 	*addr = da->gpu_addr;
1800 
1801 	if (ret) {
1802 		kfree(da);
1803 		return NULL;
1804 	}
1805 
1806 	/* add da to list in dm */
1807 	list_add(&da->list, &adev->dm.da_list);
1808 
1809 	return da->cpu_ptr;
1810 }
1811 
1812 void
1813 dm_free_gpu_mem(
1814 		struct amdgpu_device *adev,
1815 		enum dc_gpu_mem_alloc_type type,
1816 		void *pvMem)
1817 {
1818 	struct dal_allocation *da;
1819 
1820 	/* walk the da list in DM */
1821 	list_for_each_entry(da, &adev->dm.da_list, list) {
1822 		if (pvMem == da->cpu_ptr) {
1823 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
1824 			list_del(&da->list);
1825 			kfree(da);
1826 			break;
1827 		}
1828 	}
1829 
1830 }
1831 
1832 static enum dmub_status
1833 dm_dmub_send_vbios_gpint_command(struct amdgpu_device *adev,
1834 				 enum dmub_gpint_command command_code,
1835 				 uint16_t param,
1836 				 uint32_t timeout_us)
1837 {
1838 	union dmub_gpint_data_register reg, test;
1839 	uint32_t i;
1840 
1841 	/* Assume that VBIOS DMUB is ready to take commands */
1842 
1843 	reg.bits.status = 1;
1844 	reg.bits.command_code = command_code;
1845 	reg.bits.param = param;
1846 
1847 	cgs_write_register(adev->dm.cgs_device, 0x34c0 + 0x01f8, reg.all);
1848 
1849 	for (i = 0; i < timeout_us; ++i) {
1850 		udelay(1);
1851 
1852 		/* Check if our GPINT got acked */
1853 		reg.bits.status = 0;
1854 		test = (union dmub_gpint_data_register)
1855 			cgs_read_register(adev->dm.cgs_device, 0x34c0 + 0x01f8);
1856 
1857 		if (test.all == reg.all)
1858 			return DMUB_STATUS_OK;
1859 	}
1860 
1861 	return DMUB_STATUS_TIMEOUT;
1862 }
1863 
1864 static void *dm_dmub_get_vbios_bounding_box(struct amdgpu_device *adev)
1865 {
1866 	void *bb;
1867 	long long addr;
1868 	unsigned int bb_size;
1869 	int i = 0;
1870 	uint16_t chunk;
1871 	enum dmub_gpint_command send_addrs[] = {
1872 		DMUB_GPINT__SET_BB_ADDR_WORD0,
1873 		DMUB_GPINT__SET_BB_ADDR_WORD1,
1874 		DMUB_GPINT__SET_BB_ADDR_WORD2,
1875 		DMUB_GPINT__SET_BB_ADDR_WORD3,
1876 	};
1877 	enum dmub_status ret;
1878 
1879 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1880 	case IP_VERSION(4, 0, 1):
1881 		bb_size = sizeof(struct dml2_soc_bb);
1882 		break;
1883 	case IP_VERSION(4, 2, 0):
1884 	case IP_VERSION(4, 2, 1):
1885 		bb_size = sizeof(struct dml2_soc_bb);
1886 		break;
1887 	default:
1888 		return NULL;
1889 	}
1890 
1891 	bb =  dm_allocate_gpu_mem(adev,
1892 				  DC_MEM_ALLOC_TYPE_GART,
1893 				  bb_size,
1894 				  &addr);
1895 	if (!bb)
1896 		return NULL;
1897 
1898 	for (i = 0; i < 4; i++) {
1899 		/* Extract 16-bit chunk */
1900 		chunk = ((uint64_t) addr >> (i * 16)) & 0xFFFF;
1901 		/* Send the chunk */
1902 		ret = dm_dmub_send_vbios_gpint_command(adev, send_addrs[i], chunk, 30000);
1903 		if (ret != DMUB_STATUS_OK)
1904 			goto free_bb;
1905 	}
1906 
1907 	/* Now ask DMUB to copy the bb */
1908 	ret = dm_dmub_send_vbios_gpint_command(adev, DMUB_GPINT__BB_COPY, 1, 200000);
1909 	if (ret != DMUB_STATUS_OK)
1910 		goto free_bb;
1911 
1912 	return bb;
1913 
1914 free_bb:
1915 	dm_free_gpu_mem(adev, DC_MEM_ALLOC_TYPE_GART, (void *) bb);
1916 	return NULL;
1917 
1918 }
1919 
1920 static enum dmub_ips_disable_type dm_get_default_ips_mode(
1921 	struct amdgpu_device *adev)
1922 {
1923 	enum dmub_ips_disable_type ret = DMUB_IPS_ENABLE;
1924 
1925 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1926 	case IP_VERSION(3, 5, 0):
1927 	case IP_VERSION(3, 6, 0):
1928 	case IP_VERSION(3, 5, 1):
1929 		ret =  DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
1930 		break;
1931 	case IP_VERSION(4, 2, 0):
1932 	case IP_VERSION(4, 2, 1):
1933 		ret =  DMUB_IPS_ENABLE;
1934 		break;
1935 	default:
1936 		/* ASICs older than DCN35 do not have IPSs */
1937 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 5, 0))
1938 			ret = DMUB_IPS_DISABLE_ALL;
1939 		break;
1940 	}
1941 
1942 	return ret;
1943 }
1944 
1945 static int amdgpu_dm_init_power_module(struct amdgpu_display_manager *dm)
1946 {
1947 	struct mod_power_init_params init_data[MAX_NUM_EDP];
1948 
1949 	if (dm->num_of_edps == 0) {
1950 		drm_dbg_driver(
1951 			dm->ddev,
1952 			"amdgpu: No eDP detected, skip initializing power module\n");
1953 		return 0;
1954 	}
1955 
1956 	/* Initialize all the power module parameters */
1957 	for (int i = 0; i < dm->num_of_edps; i++) {
1958 		init_data[i].allow_psr_smu_optimizations =
1959 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_SMU_OPT);
1960 		init_data[i].allow_psr_multi_disp_optimizations =
1961 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_MULTI_DISP_OPT);
1962 		/* See dm_late_init */
1963 		init_data[i].backlight_ramping_override = false;
1964 		init_data[i].backlight_ramping_start = 0xCCCC;
1965 		init_data[i].backlight_ramping_reduction = 0xCCCCCCCC;
1966 		init_data[i].def_varibright_level = 0;
1967 		init_data[i].abm_config_setting = 0;
1968 		init_data[i].num_backlight_levels = 101;
1969 		init_data[i].use_nits_based_brightness = false;
1970 		init_data[i].panel_max_millinits = 0;
1971 		init_data[i].panel_min_millinits = 0;
1972 		init_data[i].disable_fractional_pwm =
1973 			!(amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK);
1974 		init_data[i].use_custom_backlight_caps = false;
1975 		init_data[i].custom_backlight_caps_config_no = 0;
1976 		init_data[i].use_linear_backlight_curve = false;
1977 		init_data[i].def_varibright_enable = 0;
1978 		init_data[i].varibright_level = 0;
1979 		/*
1980 		 * Power module uses 16-bit backlight levels (0xFFFF max) rather
1981 		 * than 8-bit(0XFF max)
1982 		 */
1983 		init_data[i].min_backlight_pwm =
1984 			dm->backlight_caps[i].min_input_signal * 0x101;
1985 		init_data[i].max_backlight_pwm =
1986 			dm->backlight_caps[i].max_input_signal * 0x101;
1987 		init_data[i].min_abm_backlight =
1988 			dm->backlight_caps[i].min_input_signal * 0x101;
1989 
1990 		/* Min backlight level after ABM reduction,  Don't allow below 1%
1991 		 * 0xFFFF x 0.01 = 0x28F
1992 		 */
1993 		init_data[i].min_abm_backlight = (init_data[i].min_abm_backlight < 0x28F) ?
1994 			0x28F : init_data[i].min_abm_backlight;
1995 	}
1996 
1997 	dm->power_module = mod_power_create(dm->dc, init_data, dm->num_of_edps);
1998 	if (!dm->power_module) {
1999 		drm_err(dm->ddev, "amdgpu: Error allocating memory for power module\n");
2000 		return -ENOMEM;
2001 	}
2002 
2003 	mod_power_hw_init(dm->power_module);
2004 	drm_dbg_driver(dm->ddev, "amdgpu: Power module init done\n");
2005 
2006 	return 0;
2007 }
2008 
2009 static void hdmi_frl_status_polling_work(struct work_struct *work)
2010 {
2011 	struct amdgpu_display_manager *dm =
2012 		container_of(to_delayed_work(work), struct amdgpu_display_manager,
2013 				hdmi_frl_status_polling_work);
2014 	struct dc *dc = dm->dc;
2015 	struct dc_link *dc_link;
2016 	bool link_update = false;
2017 
2018 	for (int i = 0; i < MAX_LINKS; i++) {
2019 		dc_link = dc->links[i];
2020 
2021 		if (!dc_link || !dc_link->local_sink)
2022 			continue;
2023 
2024 		if (!dc_is_hdmi_signal(dc_link->connector_signal))
2025 			continue;
2026 
2027 		if (dc_link->connector_signal != SIGNAL_TYPE_HDMI_FRL)
2028 			continue;
2029 
2030 		link_update = dc_link_frl_poll_status_flag(dc_link);
2031 		if (link_update) {
2032 			mutex_lock(&dm->dc_lock);
2033 			dc_link_detect(dc_link, DETECT_REASON_RETRAIN);
2034 			mutex_unlock(&dm->dc_lock);
2035 		}
2036 	}
2037 
2038 	queue_delayed_work(dm->hdmi_frl_status_polling_wq,
2039 			   &dm->hdmi_frl_status_polling_work,
2040 			   msecs_to_jiffies(dm->hdmi_frl_status_polling_delay_ms));
2041 }
2042 
2043 static int amdgpu_dm_init(struct amdgpu_device *adev)
2044 {
2045 	struct dc_init_data init_data;
2046 	struct dc_callback_init init_params;
2047 	int r;
2048 
2049 	adev->dm.ddev = adev_to_drm(adev);
2050 	adev->dm.adev = adev;
2051 
2052 	/* Zero all the fields */
2053 	memset(&init_data, 0, sizeof(init_data));
2054 	memset(&init_params, 0, sizeof(init_params));
2055 
2056 	mutex_init(&adev->dm.dpia_aux_lock);
2057 	mutex_init(&adev->dm.dc_lock);
2058 	mutex_init(&adev->dm.audio_lock);
2059 
2060 	spin_lock_init(&adev->dm.dmub_lock);
2061 
2062 	if (amdgpu_dm_irq_init(adev)) {
2063 		drm_err(adev_to_drm(adev), "failed to initialize DM IRQ support.\n");
2064 		goto error;
2065 	}
2066 
2067 	/* special handling for early revisions of GC 11.5.4 */
2068 	if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(11, 5, 4))
2069 		init_data.asic_id.chip_family = AMDGPU_FAMILY_GC_11_5_4;
2070 	else
2071 		init_data.asic_id.chip_family = adev->family;
2072 
2073 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
2074 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
2075 	init_data.asic_id.chip_id = adev->pdev->device;
2076 
2077 	init_data.asic_id.vram_width = adev->gmc.vram_width;
2078 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
2079 	init_data.asic_id.atombios_base_address =
2080 		adev->mode_info.atom_context->bios;
2081 
2082 	init_data.driver = adev;
2083 
2084 	/* cgs_device was created in dm_sw_init() */
2085 	init_data.cgs_device = adev->dm.cgs_device;
2086 
2087 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
2088 
2089 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2090 	case IP_VERSION(2, 1, 0):
2091 		switch (adev->dm.dmcub_fw_version) {
2092 		case 0: /* development */
2093 		case 0x1: /* linux-firmware.git hash 6d9f399 */
2094 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
2095 			init_data.flags.disable_dmcu = false;
2096 			break;
2097 		default:
2098 			init_data.flags.disable_dmcu = true;
2099 		}
2100 		break;
2101 	case IP_VERSION(2, 0, 3):
2102 		init_data.flags.disable_dmcu = true;
2103 		break;
2104 	default:
2105 		break;
2106 	}
2107 
2108 	/* APU support S/G display by default except:
2109 	 * ASICs before Carrizo,
2110 	 * RAVEN1 (Users reported stability issue)
2111 	 */
2112 
2113 	if (adev->asic_type < CHIP_CARRIZO) {
2114 		init_data.flags.gpu_vm_support = false;
2115 	} else if (adev->asic_type == CHIP_RAVEN) {
2116 		if (adev->apu_flags & AMD_APU_IS_RAVEN)
2117 			init_data.flags.gpu_vm_support = false;
2118 		else
2119 			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
2120 	} else {
2121 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(2, 0, 3))
2122 			init_data.flags.gpu_vm_support = (amdgpu_sg_display == 1);
2123 		else
2124 			init_data.flags.gpu_vm_support =
2125 				(amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
2126 	}
2127 
2128 	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
2129 
2130 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
2131 		init_data.flags.fbc_support = true;
2132 
2133 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
2134 		init_data.flags.multi_mon_pp_mclk_switch = true;
2135 
2136 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
2137 		init_data.flags.disable_fractional_pwm = true;
2138 
2139 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
2140 		init_data.flags.edp_no_power_sequencing = true;
2141 
2142 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
2143 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
2144 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
2145 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
2146 
2147 	if (amdgpu_dc_feature_mask & DC_FRL_MASK)
2148 		init_data.flags.enable_frl = true;
2149 
2150 	init_data.flags.seamless_boot_edp_requested = false;
2151 
2152 	if (amdgpu_device_seamless_boot_supported(adev)) {
2153 		init_data.flags.seamless_boot_edp_requested = true;
2154 		init_data.flags.allow_seamless_boot_optimization = true;
2155 		drm_dbg(adev->dm.ddev, "Seamless boot requested\n");
2156 	}
2157 
2158 	init_data.flags.enable_mipi_converter_optimization = true;
2159 
2160 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
2161 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
2162 	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
2163 
2164 	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
2165 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
2166 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS_DYNAMIC)
2167 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_DYNAMIC;
2168 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS2_DYNAMIC)
2169 		init_data.flags.disable_ips = DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
2170 	else if (amdgpu_dc_debug_mask & DC_FORCE_IPS_ENABLE)
2171 		init_data.flags.disable_ips = DMUB_IPS_ENABLE;
2172 	else
2173 		init_data.flags.disable_ips = dm_get_default_ips_mode(adev);
2174 
2175 	init_data.flags.disable_ips_in_vpb = 0;
2176 
2177 	/* DCN35 and above supports dynamic DTBCLK switch */
2178 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 5, 0))
2179 		init_data.flags.allow_0_dtb_clk = true;
2180 
2181 	/* Enable DWB for tested platforms only */
2182 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
2183 		init_data.num_virtual_links = 1;
2184 
2185 	/* DCN42 and above dpia switch to unified link training path */
2186 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 2, 0)) {
2187 		init_data.flags.consolidated_dpia_dp_lt = true;
2188 		init_data.flags.enable_dpia_pre_training = true;
2189 		init_data.flags.unify_link_enc_assignment = true;
2190 		init_data.flags.usb4_bw_alloc_support = true;
2191 	}
2192 
2193 	/* DCN201 audio desyncs using DP SS */
2194 	if (adev->apu_flags & AMD_APU_IS_CYAN_SKILLFISH2)
2195 		init_data.flags.ignore_dpref_ss = true;
2196 
2197 	retrieve_dmi_info(&adev->dm);
2198 	if (adev->dm.edp0_on_dp1_quirk)
2199 		init_data.flags.support_edp0_on_dp1 = true;
2200 
2201 	if (adev->dm.bb_from_dmub)
2202 		init_data.bb_from_dmub = adev->dm.bb_from_dmub;
2203 	else
2204 		init_data.bb_from_dmub = NULL;
2205 
2206 	/* Display Core create. */
2207 	adev->dm.dc = dc_create(&init_data);
2208 
2209 	if (adev->dm.dc) {
2210 		drm_info(adev_to_drm(adev), "Display Core v%s initialized on %s\n", DC_VER,
2211 			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
2212 	} else {
2213 		drm_info(adev_to_drm(adev), "Display Core failed to initialize with v%s!\n", DC_VER);
2214 		goto error;
2215 	}
2216 
2217 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
2218 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
2219 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
2220 	}
2221 
2222 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2223 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2224 	if (dm_should_disable_stutter(adev->pdev))
2225 		adev->dm.dc->debug.disable_stutter = true;
2226 
2227 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
2228 		adev->dm.dc->debug.disable_stutter = true;
2229 
2230 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
2231 		adev->dm.dc->debug.disable_dsc = true;
2232 
2233 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
2234 		adev->dm.dc->debug.disable_clock_gate = true;
2235 
2236 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
2237 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
2238 
2239 	if (amdgpu_dc_debug_mask & DC_DISABLE_SUBVP_FAMS) {
2240 		adev->dm.dc->debug.force_disable_subvp = true;
2241 		adev->dm.dc->debug.fams2_config.bits.enable = false;
2242 	}
2243 
2244 	if (amdgpu_dc_debug_mask & DC_ENABLE_DML2) {
2245 		adev->dm.dc->debug.using_dml2 = true;
2246 		adev->dm.dc->debug.using_dml21 = true;
2247 	}
2248 
2249 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_FORCE_FW_ENABLE)
2250 		adev->dm.dc->debug.hdcp_lc_force_fw_enable = true;
2251 
2252 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_ENABLE_SW_FALLBACK)
2253 		adev->dm.dc->debug.hdcp_lc_enable_sw_fallback = true;
2254 
2255 	if (amdgpu_dc_debug_mask & DC_SKIP_DETECTION_LT)
2256 		adev->dm.dc->debug.skip_detection_link_training = true;
2257 
2258 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
2259 
2260 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
2261 	adev->dm.dc->debug.ignore_cable_id = true;
2262 
2263 	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
2264 		drm_info(adev_to_drm(adev), "DP-HDMI FRL PCON supported\n");
2265 
2266 	r = dm_dmub_hw_init(adev);
2267 	if (r) {
2268 		drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
2269 		goto error;
2270 	}
2271 
2272 	dc_hardware_init(adev->dm.dc);
2273 
2274 	adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev);
2275 	if (!adev->dm.hpd_rx_offload_wq) {
2276 		drm_err(adev_to_drm(adev), "failed to create hpd rx offload workqueue.\n");
2277 		goto error;
2278 	}
2279 
2280 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
2281 		struct dc_phy_addr_space_config pa_config;
2282 
2283 		mmhub_read_system_context(adev, &pa_config);
2284 
2285 		// Call the DC init_memory func
2286 		dc_setup_system_context(adev->dm.dc, &pa_config);
2287 	}
2288 
2289 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
2290 	if (!adev->dm.freesync_module) {
2291 		drm_err(adev_to_drm(adev),
2292 		"failed to initialize freesync_module.\n");
2293 	} else
2294 		drm_dbg_driver(adev_to_drm(adev), "freesync_module init done %p.\n",
2295 				adev->dm.freesync_module);
2296 
2297 	amdgpu_dm_init_color_mod();
2298 
2299 	if (adev->dm.dc->caps.max_links > 0) {
2300 		adev->dm.vblank_control_workqueue =
2301 			create_singlethread_workqueue("dm_vblank_control_workqueue");
2302 		if (!adev->dm.vblank_control_workqueue)
2303 			drm_err(adev_to_drm(adev), "failed to initialize vblank_workqueue.\n");
2304 	}
2305 
2306 	if (adev->dm.dc->caps.ips_support &&
2307 	    adev->dm.dc->config.disable_ips != DMUB_IPS_DISABLE_ALL)
2308 		adev->dm.idle_workqueue = idle_create_workqueue(adev);
2309 
2310 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
2311 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
2312 
2313 		if (!adev->dm.hdcp_workqueue)
2314 			drm_err(adev_to_drm(adev), "failed to initialize hdcp_workqueue.\n");
2315 		else
2316 			drm_dbg_driver(adev_to_drm(adev),
2317 				       "hdcp_workqueue init done %p.\n",
2318 				       adev->dm.hdcp_workqueue);
2319 
2320 		dc_init_callbacks(adev->dm.dc, &init_params);
2321 	}
2322 	if (adev->dm.dc->caps.max_links > 0) {
2323 		adev->dm.hdmi_frl_status_polling_wq =
2324 			create_singlethread_workqueue("hdmi_frl_status_polling_workqueue");
2325 		if (!adev->dm.hdmi_frl_status_polling_wq)
2326 			drm_err(adev_to_drm(adev), "failed to initialize hdmi_frl_status_polling_workqueue\n");
2327 		adev->dm.hdmi_frl_status_polling_delay_ms = 200;
2328 		INIT_DELAYED_WORK(&adev->dm.hdmi_frl_status_polling_work, hdmi_frl_status_polling_work);
2329 	}
2330 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2331 		init_completion(&adev->dm.dmub_aux_transfer_done);
2332 		adev->dm.dmub_notify = kzalloc_obj(struct dmub_notification);
2333 		if (!adev->dm.dmub_notify) {
2334 			drm_info(adev_to_drm(adev), "fail to allocate adev->dm.dmub_notify");
2335 			goto error;
2336 		}
2337 
2338 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
2339 		if (!adev->dm.delayed_hpd_wq) {
2340 			drm_err(adev_to_drm(adev), "failed to create hpd offload workqueue.\n");
2341 			goto error;
2342 		}
2343 
2344 		amdgpu_dm_outbox_init(adev);
2345 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
2346 			dmub_aux_setconfig_callback, false)) {
2347 			drm_err(adev_to_drm(adev), "fail to register dmub aux callback");
2348 			goto error;
2349 		}
2350 
2351 		for (size_t i = 0; i < ARRAY_SIZE(adev->dm.fused_io); i++)
2352 			init_completion(&adev->dm.fused_io[i].replied);
2353 
2354 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_FUSED_IO,
2355 			dmub_aux_fused_io_callback, false)) {
2356 			drm_err(adev_to_drm(adev), "fail to register dmub fused io callback");
2357 			goto error;
2358 		}
2359 		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
2360 		 * It is expected that DMUB will resend any pending notifications at this point. Note
2361 		 * that hpd and hpd_irq handler registration are deferred to register_hpd_handlers() to
2362 		 * align legacy interface initialization sequence. Connection status will be proactivly
2363 		 * detected once in the amdgpu_dm_initialize_drm_device.
2364 		 */
2365 		dc_enable_dmub_outbox(adev->dm.dc);
2366 
2367 		/* DPIA trace goes to dmesg logs only if outbox is enabled */
2368 		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
2369 			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
2370 	}
2371 
2372 	if (amdgpu_dm_initialize_drm_device(adev)) {
2373 		drm_err(adev_to_drm(adev),
2374 		"failed to initialize sw for display support.\n");
2375 		goto error;
2376 	}
2377 
2378 	if (amdgpu_dm_init_power_module(&adev->dm))
2379 		goto error;
2380 
2381 	/* create fake encoders for MST */
2382 	dm_dp_create_fake_mst_encoders(adev);
2383 
2384 	/* TODO: Add_display_info? */
2385 
2386 	/* TODO use dynamic cursor width */
2387 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
2388 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
2389 
2390 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
2391 		drm_err(adev_to_drm(adev),
2392 		"failed to initialize vblank for display support.\n");
2393 		goto error;
2394 	}
2395 
2396 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2397 	amdgpu_dm_crtc_secure_display_create_contexts(adev);
2398 	if (!adev->dm.secure_display_ctx.crtc_ctx)
2399 		drm_err(adev_to_drm(adev), "failed to initialize secure display contexts.\n");
2400 
2401 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))
2402 		adev->dm.secure_display_ctx.support_mul_roi = true;
2403 
2404 #endif
2405 
2406 	drm_dbg_driver(adev_to_drm(adev), "KMS initialized.\n");
2407 
2408 	return 0;
2409 error:
2410 	amdgpu_dm_fini(adev);
2411 
2412 	return -EINVAL;
2413 }
2414 
2415 static int amdgpu_dm_early_fini(struct amdgpu_ip_block *ip_block)
2416 {
2417 	struct amdgpu_device *adev = ip_block->adev;
2418 
2419 	amdgpu_dm_audio_fini(adev);
2420 
2421 	return 0;
2422 }
2423 
2424 static void amdgpu_dm_fini(struct amdgpu_device *adev)
2425 {
2426 	int i;
2427 
2428 	if (adev->dm.vblank_control_workqueue) {
2429 		destroy_workqueue(adev->dm.vblank_control_workqueue);
2430 		adev->dm.vblank_control_workqueue = NULL;
2431 	}
2432 
2433 	if (adev->dm.idle_workqueue) {
2434 		if (adev->dm.idle_workqueue->running) {
2435 			adev->dm.idle_workqueue->enable = false;
2436 			flush_work(&adev->dm.idle_workqueue->work);
2437 		}
2438 
2439 		kfree(adev->dm.idle_workqueue);
2440 		adev->dm.idle_workqueue = NULL;
2441 	}
2442 
2443 	/*
2444 	 * Disable ISM before dc_destroy() invalidates dm->dc.
2445 	 *
2446 	 * Quiesce workers first without dc_lock (they take dc_lock
2447 	 * themselves, so syncing under it would deadlock), then drive the
2448 	 * FSM back to FULL_POWER_RUNNING under dc_lock.
2449 	 */
2450 	amdgpu_dm_ism_disable(&adev->dm);
2451 	scoped_guard(mutex, &adev->dm.dc_lock)
2452 		amdgpu_dm_ism_force_full_power(&adev->dm);
2453 
2454 	amdgpu_dm_destroy_drm_device(&adev->dm);
2455 
2456 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2457 	if (adev->dm.secure_display_ctx.crtc_ctx) {
2458 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
2459 			if (adev->dm.secure_display_ctx.crtc_ctx[i].crtc) {
2460 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].notify_ta_work);
2461 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].forward_roi_work);
2462 			}
2463 		}
2464 		kfree(adev->dm.secure_display_ctx.crtc_ctx);
2465 		adev->dm.secure_display_ctx.crtc_ctx = NULL;
2466 	}
2467 #endif
2468 	if (adev->dm.hdcp_workqueue) {
2469 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
2470 		adev->dm.hdcp_workqueue = NULL;
2471 	}
2472 
2473 	if (adev->dm.dc) {
2474 		dc_deinit_callbacks(adev->dm.dc);
2475 		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
2476 		if (dc_enable_dmub_notifications(adev->dm.dc)) {
2477 			kfree(adev->dm.dmub_notify);
2478 			adev->dm.dmub_notify = NULL;
2479 			destroy_workqueue(adev->dm.delayed_hpd_wq);
2480 			adev->dm.delayed_hpd_wq = NULL;
2481 		}
2482 	}
2483 
2484 	if (adev->dm.dmub_bo)
2485 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
2486 				      &adev->dm.dmub_bo_gpu_addr,
2487 				      &adev->dm.dmub_bo_cpu_addr);
2488 
2489 	if (adev->dm.boot_time_crc_info.bo_ptr)
2490 		amdgpu_bo_free_kernel(&adev->dm.boot_time_crc_info.bo_ptr,
2491 					&adev->dm.boot_time_crc_info.gpu_addr,
2492 					&adev->dm.boot_time_crc_info.cpu_addr);
2493 
2494 	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
2495 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
2496 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
2497 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
2498 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
2499 			}
2500 		}
2501 
2502 		kfree(adev->dm.hpd_rx_offload_wq);
2503 		adev->dm.hpd_rx_offload_wq = NULL;
2504 	}
2505 
2506 	/* DC Destroy TODO: Replace destroy DAL */
2507 	if (adev->dm.dc)
2508 		dc_destroy(&adev->dm.dc);
2509 	/*
2510 	 * TODO: pageflip, vlank interrupt
2511 	 *
2512 	 * amdgpu_dm_irq_fini(adev);
2513 	 */
2514 
2515 	if (adev->dm.cgs_device) {
2516 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
2517 		adev->dm.cgs_device = NULL;
2518 	}
2519 	if (adev->dm.freesync_module) {
2520 		mod_freesync_destroy(adev->dm.freesync_module);
2521 		adev->dm.freesync_module = NULL;
2522 	}
2523 
2524 	if (adev->dm.power_module) {
2525 		mod_power_destroy(adev->dm.power_module);
2526 		adev->dm.power_module = NULL;
2527 	}
2528 	mutex_destroy(&adev->dm.audio_lock);
2529 	mutex_destroy(&adev->dm.dc_lock);
2530 	mutex_destroy(&adev->dm.dpia_aux_lock);
2531 }
2532 
2533 static int load_dmcu_fw(struct amdgpu_device *adev)
2534 {
2535 	const char *fw_name_dmcu = NULL;
2536 	int r;
2537 	const struct dmcu_firmware_header_v1_0 *hdr;
2538 
2539 	switch (adev->asic_type) {
2540 #if defined(CONFIG_DRM_AMD_DC_SI)
2541 	case CHIP_TAHITI:
2542 	case CHIP_PITCAIRN:
2543 	case CHIP_VERDE:
2544 	case CHIP_OLAND:
2545 #endif
2546 	case CHIP_BONAIRE:
2547 	case CHIP_HAWAII:
2548 	case CHIP_KAVERI:
2549 	case CHIP_KABINI:
2550 	case CHIP_MULLINS:
2551 	case CHIP_TONGA:
2552 	case CHIP_FIJI:
2553 	case CHIP_CARRIZO:
2554 	case CHIP_STONEY:
2555 	case CHIP_POLARIS11:
2556 	case CHIP_POLARIS10:
2557 	case CHIP_POLARIS12:
2558 	case CHIP_VEGAM:
2559 	case CHIP_VEGA10:
2560 	case CHIP_VEGA12:
2561 	case CHIP_VEGA20:
2562 		return 0;
2563 	case CHIP_NAVI12:
2564 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
2565 		break;
2566 	case CHIP_RAVEN:
2567 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
2568 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2569 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
2570 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2571 		else
2572 			return 0;
2573 		break;
2574 	default:
2575 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2576 		case IP_VERSION(2, 0, 2):
2577 		case IP_VERSION(2, 0, 3):
2578 		case IP_VERSION(2, 0, 0):
2579 		case IP_VERSION(2, 1, 0):
2580 		case IP_VERSION(3, 0, 0):
2581 		case IP_VERSION(3, 0, 2):
2582 		case IP_VERSION(3, 0, 3):
2583 		case IP_VERSION(3, 0, 1):
2584 		case IP_VERSION(3, 1, 2):
2585 		case IP_VERSION(3, 1, 3):
2586 		case IP_VERSION(3, 1, 4):
2587 		case IP_VERSION(3, 1, 5):
2588 		case IP_VERSION(3, 1, 6):
2589 		case IP_VERSION(3, 2, 0):
2590 		case IP_VERSION(3, 2, 1):
2591 		case IP_VERSION(3, 5, 0):
2592 		case IP_VERSION(3, 5, 1):
2593 		case IP_VERSION(3, 6, 0):
2594 		case IP_VERSION(4, 0, 1):
2595 		case IP_VERSION(4, 2, 0):
2596 		case IP_VERSION(4, 2, 1):
2597 			return 0;
2598 		default:
2599 			break;
2600 		}
2601 		drm_err(adev_to_drm(adev), "Unsupported ASIC type: 0x%X\n", adev->asic_type);
2602 		return -EINVAL;
2603 	}
2604 
2605 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
2606 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not supported on direct or SMU loading\n");
2607 		return 0;
2608 	}
2609 
2610 	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, AMDGPU_UCODE_REQUIRED,
2611 				 "%s", fw_name_dmcu);
2612 	if (r == -ENODEV) {
2613 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
2614 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not found\n");
2615 		adev->dm.fw_dmcu = NULL;
2616 		return 0;
2617 	}
2618 	if (r) {
2619 		drm_err(adev_to_drm(adev), "amdgpu_dm: Can't validate firmware \"%s\"\n",
2620 			fw_name_dmcu);
2621 		amdgpu_ucode_release(&adev->dm.fw_dmcu);
2622 		return r;
2623 	}
2624 
2625 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
2626 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
2627 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
2628 	adev->firmware.fw_size +=
2629 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2630 
2631 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
2632 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
2633 	adev->firmware.fw_size +=
2634 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2635 
2636 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
2637 
2638 	drm_dbg_kms(adev_to_drm(adev), "PSP loading DMCU firmware\n");
2639 
2640 	return 0;
2641 }
2642 
2643 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
2644 {
2645 	struct amdgpu_device *adev = ctx;
2646 
2647 	return dm_read_reg(adev->dm.dc->ctx, address);
2648 }
2649 
2650 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
2651 				     uint32_t value)
2652 {
2653 	struct amdgpu_device *adev = ctx;
2654 
2655 	return dm_write_reg(adev->dm.dc->ctx, address, value);
2656 }
2657 
2658 static int dm_dmub_sw_init(struct amdgpu_device *adev)
2659 {
2660 	struct dmub_srv_create_params create_params;
2661 	struct dmub_srv_fw_meta_info_params fw_meta_info_params;
2662 	struct dmub_srv_region_params region_params;
2663 	struct dmub_srv_region_info region_info;
2664 	struct dmub_srv_memory_params memory_params;
2665 	struct dmub_fw_meta_info fw_info;
2666 	struct dmub_srv_fb_info *fb_info;
2667 	struct dmub_srv *dmub_srv;
2668 	const struct dmcub_firmware_header_v1_0 *hdr;
2669 	enum dmub_asic dmub_asic;
2670 	enum dmub_status status;
2671 	static enum dmub_window_memory_type window_memory_type[DMUB_WINDOW_TOTAL] = {
2672 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_0_INST_CONST
2673 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_1_STACK
2674 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_2_BSS_DATA
2675 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_3_VBIOS
2676 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_4_MAILBOX
2677 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_5_TRACEBUFF
2678 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_6_FW_STATE
2679 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_7_SCRATCH_MEM
2680 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_IB_MEM
2681 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_SHARED_STATE
2682 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_LSDMA_BUFFER
2683 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_CURSOR_OFFLOAD
2684 	};
2685 	int r;
2686 
2687 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2688 	case IP_VERSION(2, 1, 0):
2689 		dmub_asic = DMUB_ASIC_DCN21;
2690 		break;
2691 	case IP_VERSION(3, 0, 0):
2692 		dmub_asic = DMUB_ASIC_DCN30;
2693 		break;
2694 	case IP_VERSION(3, 0, 1):
2695 		dmub_asic = DMUB_ASIC_DCN301;
2696 		break;
2697 	case IP_VERSION(3, 0, 2):
2698 		dmub_asic = DMUB_ASIC_DCN302;
2699 		break;
2700 	case IP_VERSION(3, 0, 3):
2701 		dmub_asic = DMUB_ASIC_DCN303;
2702 		break;
2703 	case IP_VERSION(3, 1, 2):
2704 	case IP_VERSION(3, 1, 3):
2705 		dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
2706 		break;
2707 	case IP_VERSION(3, 1, 4):
2708 		dmub_asic = DMUB_ASIC_DCN314;
2709 		break;
2710 	case IP_VERSION(3, 1, 5):
2711 		dmub_asic = DMUB_ASIC_DCN315;
2712 		break;
2713 	case IP_VERSION(3, 1, 6):
2714 		dmub_asic = DMUB_ASIC_DCN316;
2715 		break;
2716 	case IP_VERSION(3, 2, 0):
2717 		dmub_asic = DMUB_ASIC_DCN32;
2718 		break;
2719 	case IP_VERSION(3, 2, 1):
2720 		dmub_asic = DMUB_ASIC_DCN321;
2721 		break;
2722 	case IP_VERSION(3, 5, 0):
2723 	case IP_VERSION(3, 5, 1):
2724 		dmub_asic = DMUB_ASIC_DCN35;
2725 		break;
2726 	case IP_VERSION(3, 6, 0):
2727 		dmub_asic = DMUB_ASIC_DCN36;
2728 		break;
2729 	case IP_VERSION(4, 0, 1):
2730 		dmub_asic = DMUB_ASIC_DCN401;
2731 		break;
2732 	case IP_VERSION(4, 2, 0):
2733 		dmub_asic = DMUB_ASIC_DCN42;
2734 		break;
2735 	case IP_VERSION(4, 2, 1):
2736 		dmub_asic = DMUB_ASIC_DCN42B;
2737 		break;
2738 	default:
2739 		/* ASIC doesn't support DMUB. */
2740 		return 0;
2741 	}
2742 
2743 	hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
2744 	adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
2745 
2746 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
2747 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
2748 			AMDGPU_UCODE_ID_DMCUB;
2749 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
2750 			adev->dm.dmub_fw;
2751 		adev->firmware.fw_size +=
2752 			ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
2753 
2754 		drm_info(adev_to_drm(adev), "Loading DMUB firmware via PSP: version=0x%08X\n",
2755 			 adev->dm.dmcub_fw_version);
2756 	}
2757 
2758 
2759 	adev->dm.dmub_srv = kzalloc_obj(*adev->dm.dmub_srv);
2760 	dmub_srv = adev->dm.dmub_srv;
2761 
2762 	if (!dmub_srv) {
2763 		drm_err(adev_to_drm(adev), "Failed to allocate DMUB service!\n");
2764 		return -ENOMEM;
2765 	}
2766 
2767 	memset(&create_params, 0, sizeof(create_params));
2768 	create_params.user_ctx = adev;
2769 	create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2770 	create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2771 	create_params.asic = dmub_asic;
2772 
2773 	/* Create the DMUB service. */
2774 	status = dmub_srv_create(dmub_srv, &create_params);
2775 	if (status != DMUB_STATUS_OK) {
2776 		drm_err(adev_to_drm(adev), "Error creating DMUB service: %d\n", status);
2777 		return -EINVAL;
2778 	}
2779 
2780 	/* Extract the FW meta info. */
2781 	memset(&fw_meta_info_params, 0, sizeof(fw_meta_info_params));
2782 
2783 	fw_meta_info_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2784 					      PSP_HEADER_BYTES_256;
2785 	fw_meta_info_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2786 	fw_meta_info_params.fw_inst_const = adev->dm.dmub_fw->data +
2787 					    le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2788 					    PSP_HEADER_BYTES_256;
2789 	fw_meta_info_params.fw_bss_data = fw_meta_info_params.bss_data_size ? adev->dm.dmub_fw->data +
2790 					  le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2791 					  le32_to_cpu(hdr->inst_const_bytes) : NULL;
2792 	fw_meta_info_params.custom_psp_footer_size = 0;
2793 
2794 	status = dmub_srv_get_fw_meta_info_from_raw_fw(&fw_meta_info_params, &fw_info);
2795 	if (status != DMUB_STATUS_OK) {
2796 		/* Skip returning early, just log the error. */
2797 		drm_err(adev_to_drm(adev), "Error getting DMUB FW meta info: %d\n", status);
2798 		// return -EINVAL;
2799 	}
2800 
2801 	/* Calculate the size of all the regions for the DMUB service. */
2802 	memset(&region_params, 0, sizeof(region_params));
2803 
2804 	region_params.inst_const_size = fw_meta_info_params.inst_const_size;
2805 	region_params.bss_data_size = fw_meta_info_params.bss_data_size;
2806 	region_params.vbios_size = adev->bios_size;
2807 	region_params.fw_bss_data = fw_meta_info_params.fw_bss_data;
2808 	region_params.fw_inst_const = fw_meta_info_params.fw_inst_const;
2809 	region_params.window_memory_type = window_memory_type;
2810 	region_params.fw_info = (status == DMUB_STATUS_OK) ? &fw_info : NULL;
2811 
2812 	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2813 					   &region_info);
2814 
2815 	if (status != DMUB_STATUS_OK) {
2816 		drm_err(adev_to_drm(adev), "Error calculating DMUB region info: %d\n", status);
2817 		return -EINVAL;
2818 	}
2819 
2820 	/*
2821 	 * Allocate a framebuffer based on the total size of all the regions.
2822 	 * TODO: Move this into GART.
2823 	 */
2824 	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2825 				    AMDGPU_GEM_DOMAIN_VRAM |
2826 				    AMDGPU_GEM_DOMAIN_GTT,
2827 				    &adev->dm.dmub_bo,
2828 				    &adev->dm.dmub_bo_gpu_addr,
2829 				    &adev->dm.dmub_bo_cpu_addr);
2830 	if (r)
2831 		return r;
2832 
2833 	/* Rebase the regions on the framebuffer address. */
2834 	memset(&memory_params, 0, sizeof(memory_params));
2835 	memory_params.cpu_fb_addr = adev->dm.dmub_bo_cpu_addr;
2836 	memory_params.gpu_fb_addr = adev->dm.dmub_bo_gpu_addr;
2837 	memory_params.region_info = &region_info;
2838 	memory_params.window_memory_type = window_memory_type;
2839 
2840 	adev->dm.dmub_fb_info = kzalloc_obj(*adev->dm.dmub_fb_info);
2841 	fb_info = adev->dm.dmub_fb_info;
2842 
2843 	if (!fb_info) {
2844 		drm_err(adev_to_drm(adev),
2845 			"Failed to allocate framebuffer info for DMUB service!\n");
2846 		return -ENOMEM;
2847 	}
2848 
2849 	status = dmub_srv_calc_mem_info(dmub_srv, &memory_params, fb_info);
2850 	if (status != DMUB_STATUS_OK) {
2851 		drm_err(adev_to_drm(adev), "Error calculating DMUB FB info: %d\n", status);
2852 		return -EINVAL;
2853 	}
2854 
2855 	adev->dm.bb_from_dmub = dm_dmub_get_vbios_bounding_box(adev);
2856 	adev->dm.fw_inst_size = fw_meta_info_params.inst_const_size;
2857 
2858 	return 0;
2859 }
2860 
2861 static int dm_sw_init(struct amdgpu_ip_block *ip_block)
2862 {
2863 	struct amdgpu_device *adev = ip_block->adev;
2864 	int r;
2865 
2866 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
2867 
2868 	if (!adev->dm.cgs_device) {
2869 		drm_err(adev_to_drm(adev), "failed to create cgs device.\n");
2870 		return -EINVAL;
2871 	}
2872 
2873 	/* Moved from dm init since we need to use allocations for storing bounding box data */
2874 	INIT_LIST_HEAD(&adev->dm.da_list);
2875 
2876 	r = dm_dmub_sw_init(adev);
2877 	if (r)
2878 		return r;
2879 
2880 	return load_dmcu_fw(adev);
2881 }
2882 
2883 static int dm_sw_fini(struct amdgpu_ip_block *ip_block)
2884 {
2885 	struct amdgpu_device *adev = ip_block->adev;
2886 	struct dal_allocation *da;
2887 
2888 	list_for_each_entry(da, &adev->dm.da_list, list) {
2889 		if (adev->dm.bb_from_dmub == (void *) da->cpu_ptr) {
2890 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
2891 			list_del(&da->list);
2892 			kfree(da);
2893 			adev->dm.bb_from_dmub = NULL;
2894 			break;
2895 		}
2896 	}
2897 
2898 
2899 	kfree(adev->dm.dmub_fb_info);
2900 	adev->dm.dmub_fb_info = NULL;
2901 
2902 	if (adev->dm.dmub_srv) {
2903 		dmub_srv_destroy(adev->dm.dmub_srv);
2904 		kfree(adev->dm.dmub_srv);
2905 		adev->dm.dmub_srv = NULL;
2906 	}
2907 
2908 	amdgpu_ucode_release(&adev->dm.dmub_fw);
2909 	amdgpu_ucode_release(&adev->dm.fw_dmcu);
2910 
2911 	return 0;
2912 }
2913 
2914 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2915 {
2916 	struct amdgpu_dm_connector *aconnector;
2917 	struct drm_connector *connector;
2918 	struct drm_connector_list_iter iter;
2919 	int ret = 0;
2920 
2921 	drm_connector_list_iter_begin(dev, &iter);
2922 	drm_for_each_connector_iter(connector, &iter) {
2923 
2924 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2925 			continue;
2926 
2927 		aconnector = to_amdgpu_dm_connector(connector);
2928 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
2929 		    aconnector->mst_mgr.aux) {
2930 			drm_dbg_kms(dev, "DM_MST: starting TM on aconnector: %p [id: %d]\n",
2931 					 aconnector,
2932 					 aconnector->base.base.id);
2933 
2934 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2935 			if (ret < 0) {
2936 				drm_err(dev, "DM_MST: Failed to start MST\n");
2937 				aconnector->dc_link->type =
2938 					dc_connection_single;
2939 				ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2940 								     aconnector->dc_link);
2941 				break;
2942 			}
2943 		}
2944 	}
2945 	drm_connector_list_iter_end(&iter);
2946 
2947 	return ret;
2948 }
2949 
2950 static void amdgpu_dm_boot_time_crc_init(struct amdgpu_device *adev)
2951 {
2952 	struct dm_boot_time_crc_info *bootcrc_info = NULL;
2953 	struct dmub_srv *dmub = NULL;
2954 	union dmub_fw_boot_options option = {0};
2955 	int ret = 0;
2956 	const uint32_t fb_size = 3 * 1024 * 1024;	/* 3MB for DCC pattern */
2957 
2958 	if (!adev || !adev->dm.dc || !adev->dm.dc->ctx ||
2959 		!adev->dm.dc->ctx->dmub_srv) {
2960 		return;
2961 	}
2962 
2963 	dmub = adev->dm.dc->ctx->dmub_srv->dmub;
2964 	bootcrc_info = &adev->dm.boot_time_crc_info;
2965 
2966 	if (!dmub || !dmub->hw_funcs.get_fw_boot_option) {
2967 		drm_dbg(adev_to_drm(adev), "failed to init boot time crc buffer\n");
2968 		return;
2969 	}
2970 
2971 	option = dmub->hw_funcs.get_fw_boot_option(dmub);
2972 
2973 	/* Return if boot time CRC is not enabled */
2974 	if (option.bits.bootcrc_en_at_S0i3 == 0)
2975 		return;
2976 
2977 	/* Create a buffer for boot time CRC */
2978 	ret = amdgpu_bo_create_kernel(adev, fb_size, PAGE_SIZE,
2979 		AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT,
2980 		&bootcrc_info->bo_ptr,
2981 		&bootcrc_info->gpu_addr,
2982 		&bootcrc_info->cpu_addr);
2983 
2984 	if (ret) {
2985 		drm_dbg(adev_to_drm(adev), "failed to create boot time crc buffer\n");
2986 	} else {
2987 		bootcrc_info->size = fb_size;
2988 
2989 		drm_dbg(adev_to_drm(adev), "boot time crc buffer created addr 0x%llx, size %u\n",
2990 			bootcrc_info->gpu_addr, bootcrc_info->size);
2991 
2992 		/* Send the buffer info to DMUB */
2993 		dc_dmub_srv_boot_time_crc_init(adev->dm.dc,
2994 			bootcrc_info->gpu_addr, bootcrc_info->size);
2995 	}
2996 }
2997 
2998 static int dm_late_init(struct amdgpu_ip_block *ip_block)
2999 {
3000 	struct amdgpu_device *adev = ip_block->adev;
3001 
3002 	struct dmcu_iram_parameters params;
3003 	unsigned int linear_lut[16];
3004 	int i;
3005 	struct dmcu *dmcu = NULL;
3006 
3007 	dmcu = adev->dm.dc->res_pool->dmcu;
3008 
3009 	/* Init the boot time CRC (skip in resume) */
3010 	if ((adev->in_suspend == 0) &&
3011 		(amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(3, 6, 0)))
3012 		amdgpu_dm_boot_time_crc_init(adev);
3013 
3014 	for (i = 0; i < 16; i++)
3015 		linear_lut[i] = 0xFFFF * i / 15;
3016 
3017 	params.set = 0;
3018 	params.backlight_ramping_override = false;
3019 	params.backlight_ramping_start = 0xCCCC;
3020 	params.backlight_ramping_reduction = 0xCCCCCCCC;
3021 	params.backlight_lut_array_size = 16;
3022 	params.backlight_lut_array = linear_lut;
3023 
3024 	/* Min backlight level after ABM reduction,  Don't allow below 1%
3025 	 * 0xFFFF x 0.01 = 0x28F
3026 	 */
3027 	params.min_abm_backlight = 0x28F;
3028 	/* In the case where abm is implemented on dmcub,
3029 	 * dmcu object will be null.
3030 	 * ABM 2.4 and up are implemented on dmcub.
3031 	 */
3032 	if (dmcu) {
3033 		if (!dmcu_load_iram(dmcu, params))
3034 			return -EINVAL;
3035 	} else if (adev->dm.dc->ctx->dmub_srv) {
3036 		struct dc_link *edp_links[MAX_NUM_EDP];
3037 		int edp_num;
3038 
3039 		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
3040 		for (i = 0; i < edp_num; i++) {
3041 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
3042 				return -EINVAL;
3043 		}
3044 	}
3045 
3046 	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
3047 }
3048 
3049 static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
3050 {
3051 	u8 buf[UUID_SIZE];
3052 	guid_t guid;
3053 	int ret;
3054 
3055 	mutex_lock(&mgr->lock);
3056 	if (!mgr->mst_primary)
3057 		goto out_fail;
3058 
3059 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
3060 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
3061 		goto out_fail;
3062 	}
3063 
3064 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
3065 				 DP_MST_EN |
3066 				 DP_UP_REQ_EN |
3067 				 DP_UPSTREAM_IS_SRC);
3068 	if (ret < 0) {
3069 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
3070 		goto out_fail;
3071 	}
3072 
3073 	/* Some hubs forget their guids after they resume */
3074 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, buf, sizeof(buf));
3075 	if (ret != sizeof(buf)) {
3076 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
3077 		goto out_fail;
3078 	}
3079 
3080 	import_guid(&guid, buf);
3081 
3082 	if (guid_is_null(&guid)) {
3083 		guid_gen(&guid);
3084 		export_guid(buf, &guid);
3085 
3086 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, buf, sizeof(buf));
3087 
3088 		if (ret != sizeof(buf)) {
3089 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
3090 			goto out_fail;
3091 		}
3092 	}
3093 
3094 	guid_copy(&mgr->mst_primary->guid, &guid);
3095 
3096 out_fail:
3097 	mutex_unlock(&mgr->lock);
3098 }
3099 
3100 void hdmi_cec_unset_edid(struct amdgpu_dm_connector *aconnector)
3101 {
3102 	struct cec_notifier *n = aconnector->notifier;
3103 
3104 	if (!n)
3105 		return;
3106 
3107 	cec_notifier_phys_addr_invalidate(n);
3108 }
3109 
3110 void hdmi_cec_set_edid(struct amdgpu_dm_connector *aconnector)
3111 {
3112 	struct drm_connector *connector = &aconnector->base;
3113 	struct cec_notifier *n = aconnector->notifier;
3114 
3115 	if (!n)
3116 		return;
3117 
3118 	cec_notifier_set_phys_addr(n,
3119 				   connector->display_info.source_physical_address);
3120 }
3121 
3122 static void s3_handle_hdmi_cec(struct drm_device *ddev, bool suspend)
3123 {
3124 	struct amdgpu_dm_connector *aconnector;
3125 	struct drm_connector *connector;
3126 	struct drm_connector_list_iter conn_iter;
3127 
3128 	drm_connector_list_iter_begin(ddev, &conn_iter);
3129 	drm_for_each_connector_iter(connector, &conn_iter) {
3130 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3131 			continue;
3132 
3133 		aconnector = to_amdgpu_dm_connector(connector);
3134 		if (suspend)
3135 			hdmi_cec_unset_edid(aconnector);
3136 		else
3137 			hdmi_cec_set_edid(aconnector);
3138 	}
3139 	drm_connector_list_iter_end(&conn_iter);
3140 }
3141 
3142 static void s3_handle_mst(struct drm_device *dev, bool suspend)
3143 {
3144 	struct amdgpu_dm_connector *aconnector;
3145 	struct drm_connector *connector;
3146 	struct drm_connector_list_iter iter;
3147 	struct drm_dp_mst_topology_mgr *mgr;
3148 
3149 	drm_connector_list_iter_begin(dev, &iter);
3150 	drm_for_each_connector_iter(connector, &iter) {
3151 
3152 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3153 			continue;
3154 
3155 		aconnector = to_amdgpu_dm_connector(connector);
3156 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3157 		    aconnector->mst_root)
3158 			continue;
3159 
3160 		mgr = &aconnector->mst_mgr;
3161 
3162 		if (suspend) {
3163 			drm_dp_mst_topology_mgr_suspend(mgr);
3164 		} else {
3165 			/* if extended timeout is supported in hardware,
3166 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
3167 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
3168 			 */
3169 			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
3170 			if (!dp_is_lttpr_present(aconnector->dc_link))
3171 				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
3172 
3173 			/* TODO: move resume_mst_branch_status() into drm mst resume again
3174 			 * once topology probing work is pulled out from mst resume into mst
3175 			 * resume 2nd step. mst resume 2nd step should be called after old
3176 			 * state getting restored (i.e. drm_atomic_helper_resume()).
3177 			 */
3178 			resume_mst_branch_status(mgr);
3179 		}
3180 	}
3181 	drm_connector_list_iter_end(&iter);
3182 }
3183 
3184 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
3185 {
3186 	int ret = 0;
3187 
3188 	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
3189 	 * on window driver dc implementation.
3190 	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
3191 	 * should be passed to smu during boot up and resume from s3.
3192 	 * boot up: dc calculate dcn watermark clock settings within dc_create,
3193 	 * dcn20_resource_construct
3194 	 * then call pplib functions below to pass the settings to smu:
3195 	 * smu_set_watermarks_for_clock_ranges
3196 	 * smu_set_watermarks_table
3197 	 * navi10_set_watermarks_table
3198 	 * smu_write_watermarks_table
3199 	 *
3200 	 * For Renoir, clock settings of dcn watermark are also fixed values.
3201 	 * dc has implemented different flow for window driver:
3202 	 * dc_hardware_init / dc_set_power_state
3203 	 * dcn10_init_hw
3204 	 * notify_wm_ranges
3205 	 * set_wm_ranges
3206 	 * -- Linux
3207 	 * smu_set_watermarks_for_clock_ranges
3208 	 * renoir_set_watermarks_table
3209 	 * smu_write_watermarks_table
3210 	 *
3211 	 * For Linux,
3212 	 * dc_hardware_init -> amdgpu_dm_init
3213 	 * dc_set_power_state --> dm_resume
3214 	 *
3215 	 * therefore, this function apply to navi10/12/14 but not Renoir
3216 	 * *
3217 	 */
3218 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
3219 	case IP_VERSION(2, 0, 2):
3220 	case IP_VERSION(2, 0, 0):
3221 		break;
3222 	default:
3223 		return 0;
3224 	}
3225 
3226 	ret = amdgpu_dpm_write_watermarks_table(adev);
3227 	if (ret) {
3228 		drm_err(adev_to_drm(adev), "Failed to update WMTABLE!\n");
3229 		return ret;
3230 	}
3231 
3232 	return 0;
3233 }
3234 
3235 static int dm_oem_i2c_hw_init(struct amdgpu_device *adev)
3236 {
3237 	struct amdgpu_display_manager *dm = &adev->dm;
3238 	struct amdgpu_i2c_adapter *oem_i2c;
3239 	struct ddc_service *oem_ddc_service;
3240 	int r;
3241 
3242 	oem_ddc_service = dc_get_oem_i2c_device(adev->dm.dc);
3243 	if (oem_ddc_service) {
3244 		oem_i2c = create_i2c(oem_ddc_service, true);
3245 		if (!oem_i2c) {
3246 			drm_info(adev_to_drm(adev), "Failed to create oem i2c adapter data\n");
3247 			return -ENOMEM;
3248 		}
3249 
3250 		r = devm_i2c_add_adapter(adev->dev, &oem_i2c->base);
3251 		if (r) {
3252 			drm_info(adev_to_drm(adev), "Failed to register oem i2c\n");
3253 			kfree(oem_i2c);
3254 			return r;
3255 		}
3256 		dm->oem_i2c = oem_i2c;
3257 	}
3258 
3259 	return 0;
3260 }
3261 
3262 /**
3263  * dm_hw_init() - Initialize DC device
3264  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3265  *
3266  * Initialize the &struct amdgpu_display_manager device. This involves calling
3267  * the initializers of each DM component, then populating the struct with them.
3268  *
3269  * Although the function implies hardware initialization, both hardware and
3270  * software are initialized here. Splitting them out to their relevant init
3271  * hooks is a future TODO item.
3272  *
3273  * Some notable things that are initialized here:
3274  *
3275  * - Display Core, both software and hardware
3276  * - DC modules that we need (freesync and color management)
3277  * - DRM software states
3278  * - Interrupt sources and handlers
3279  * - Vblank support
3280  * - Debug FS entries, if enabled
3281  */
3282 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
3283 {
3284 	struct amdgpu_device *adev = ip_block->adev;
3285 	int r;
3286 
3287 	/* Create DAL display manager */
3288 	r = amdgpu_dm_init(adev);
3289 	if (r)
3290 		return r;
3291 	amdgpu_dm_hpd_init(adev);
3292 
3293 	r = dm_oem_i2c_hw_init(adev);
3294 	if (r)
3295 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
3296 
3297 	return 0;
3298 }
3299 
3300 /**
3301  * dm_hw_fini() - Teardown DC device
3302  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3303  *
3304  * Teardown components within &struct amdgpu_display_manager that require
3305  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
3306  * were loaded. Also flush IRQ workqueues and disable them.
3307  */
3308 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
3309 {
3310 	struct amdgpu_device *adev = ip_block->adev;
3311 
3312 	amdgpu_dm_hpd_fini(adev);
3313 
3314 	amdgpu_dm_irq_fini(adev);
3315 	amdgpu_dm_fini(adev);
3316 	return 0;
3317 }
3318 
3319 
3320 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
3321 				 struct dc_state *state, bool enable)
3322 {
3323 	enum dc_irq_source irq_source;
3324 	struct amdgpu_crtc *acrtc;
3325 	int rc = -EBUSY;
3326 	int i = 0;
3327 
3328 	for (i = 0; i < state->stream_count; i++) {
3329 		acrtc = get_crtc_by_otg_inst(
3330 				adev, state->stream_status[i].primary_otg_inst);
3331 
3332 		if (acrtc && state->stream_status[i].plane_count != 0 &&
3333 		    amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
3334 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
3335 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3336 			if (rc)
3337 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
3338 					 enable ? "enable" : "disable");
3339 
3340 			if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
3341 				if (enable) {
3342 					if (amdgpu_dm_crtc_vrr_active(
3343 							to_dm_crtc_state(acrtc->base.state)))
3344 						rc = amdgpu_dm_crtc_set_vupdate_irq(
3345 							&acrtc->base, true);
3346 				} else
3347 					rc = amdgpu_dm_crtc_set_vupdate_irq(
3348 							&acrtc->base, false);
3349 
3350 				if (rc)
3351 					drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
3352 						enable ? "en" : "dis");
3353 			}
3354 
3355 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3356 			/* During gpu-reset we disable and then enable vblank irq, so
3357 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
3358 			 */
3359 			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
3360 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
3361 
3362 		} else if (acrtc && state->stream_status[i].plane_count != 0) {
3363 			/* DCN only needs to toggle VUPDATE_NO_LOCK */
3364 			rc = amdgpu_dm_crtc_set_vupdate_irq(&acrtc->base, enable);
3365 			if (rc)
3366 				drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
3367 					 enable ? "en" : "dis");
3368 		}
3369 	}
3370 
3371 }
3372 
3373 DEFINE_FREE(state_release, struct dc_state *, if (_T) dc_state_release(_T))
3374 
3375 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
3376 {
3377 	struct dc_state *context __free(state_release) = NULL;
3378 	int i;
3379 	struct dc_stream_state *del_streams[MAX_PIPES];
3380 	int del_streams_count = 0;
3381 	struct dc_commit_streams_params params = {};
3382 
3383 	memset(del_streams, 0, sizeof(del_streams));
3384 
3385 	context = dc_state_create_current_copy(dc);
3386 	if (context == NULL)
3387 		return DC_ERROR_UNEXPECTED;
3388 
3389 	/* First remove from context all streams */
3390 	for (i = 0; i < context->stream_count; i++) {
3391 		struct dc_stream_state *stream = context->streams[i];
3392 
3393 		del_streams[del_streams_count++] = stream;
3394 	}
3395 
3396 	/* Remove all planes for removed streams and then remove the streams */
3397 	for (i = 0; i < del_streams_count; i++) {
3398 		enum dc_status res;
3399 
3400 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
3401 			return DC_FAIL_DETACH_SURFACES;
3402 
3403 		res = dc_state_remove_stream(dc, context, del_streams[i]);
3404 		if (res != DC_OK)
3405 			return res;
3406 	}
3407 
3408 	params.streams = context->streams;
3409 	params.stream_count = context->stream_count;
3410 
3411 	return dc_commit_streams(dc, &params);
3412 }
3413 
3414 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
3415 {
3416 	int i;
3417 
3418 	if (dm->hpd_rx_offload_wq) {
3419 		for (i = 0; i < dm->dc->caps.max_links; i++)
3420 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
3421 	}
3422 }
3423 
3424 static int dm_cache_state(struct amdgpu_device *adev)
3425 {
3426 	int r;
3427 
3428 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
3429 	if (IS_ERR(adev->dm.cached_state)) {
3430 		r = PTR_ERR(adev->dm.cached_state);
3431 		adev->dm.cached_state = NULL;
3432 	}
3433 
3434 	return adev->dm.cached_state ? 0 : r;
3435 }
3436 
3437 static void dm_destroy_cached_state(struct amdgpu_device *adev)
3438 {
3439 	struct amdgpu_display_manager *dm = &adev->dm;
3440 	struct drm_device *ddev = adev_to_drm(adev);
3441 	struct dm_plane_state *dm_new_plane_state;
3442 	struct drm_plane_state *new_plane_state;
3443 	struct dm_crtc_state *dm_new_crtc_state;
3444 	struct drm_crtc_state *new_crtc_state;
3445 	struct drm_plane *plane;
3446 	struct drm_crtc *crtc;
3447 	int i;
3448 
3449 	if (!dm->cached_state)
3450 		return;
3451 
3452 	/* Force mode set in atomic commit */
3453 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3454 		new_crtc_state->active_changed = true;
3455 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3456 		reset_freesync_config_for_crtc(dm_new_crtc_state);
3457 	}
3458 
3459 	/*
3460 	 * atomic_check is expected to create the dc states. We need to release
3461 	 * them here, since they were duplicated as part of the suspend
3462 	 * procedure.
3463 	 */
3464 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3465 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3466 		if (dm_new_crtc_state->stream) {
3467 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
3468 			dc_stream_release(dm_new_crtc_state->stream);
3469 			dm_new_crtc_state->stream = NULL;
3470 		}
3471 		dm_new_crtc_state->base.color_mgmt_changed = true;
3472 	}
3473 
3474 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
3475 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
3476 		if (dm_new_plane_state->dc_state) {
3477 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
3478 			dc_plane_state_release(dm_new_plane_state->dc_state);
3479 			dm_new_plane_state->dc_state = NULL;
3480 		}
3481 	}
3482 
3483 	drm_atomic_helper_resume(ddev, dm->cached_state);
3484 
3485 	dm->cached_state = NULL;
3486 }
3487 
3488 static int dm_suspend(struct amdgpu_ip_block *ip_block)
3489 {
3490 	struct amdgpu_device *adev = ip_block->adev;
3491 	struct amdgpu_display_manager *dm = &adev->dm;
3492 
3493 	if (amdgpu_in_reset(adev)) {
3494 		enum dc_status res;
3495 
3496 		/* Quiesce ISM workers before taking dc_lock (workers take
3497 		 * dc_lock themselves; syncing under it would deadlock).
3498 		 */
3499 		amdgpu_dm_ism_disable(dm);
3500 
3501 		mutex_lock(&dm->dc_lock);
3502 
3503 		amdgpu_dm_ism_force_full_power(dm);
3504 		dc_allow_idle_optimizations(adev->dm.dc, false);
3505 
3506 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
3507 
3508 		if (dm->cached_dc_state)
3509 			dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
3510 
3511 		res = amdgpu_dm_commit_zero_streams(dm->dc);
3512 		if (res != DC_OK) {
3513 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
3514 			return -EINVAL;
3515 		}
3516 
3517 		amdgpu_dm_irq_suspend(adev);
3518 
3519 		hpd_rx_irq_work_suspend(dm);
3520 
3521 		return 0;
3522 	}
3523 
3524 	if (!adev->dm.cached_state) {
3525 		int r = dm_cache_state(adev);
3526 
3527 		if (r)
3528 			return r;
3529 	}
3530 
3531 	s3_handle_hdmi_cec(adev_to_drm(adev), true);
3532 
3533 	s3_handle_mst(adev_to_drm(adev), true);
3534 
3535 	amdgpu_dm_irq_suspend(adev);
3536 
3537 	/*
3538 	 * Quiesce ISM workers before taking dc_lock (workers take dc_lock
3539 	 * themselves; syncing under it would deadlock).
3540 	 */
3541 	amdgpu_dm_ism_disable(dm);
3542 	scoped_guard(mutex, &dm->dc_lock)
3543 		amdgpu_dm_ism_force_full_power(dm);
3544 
3545 	hpd_rx_irq_work_suspend(dm);
3546 
3547 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
3548 
3549 	if (dm->dc->caps.ips_support && adev->in_s0ix)
3550 		dc_allow_idle_optimizations(dm->dc, true);
3551 
3552 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
3553 
3554 	return 0;
3555 }
3556 
3557 struct drm_connector *
3558 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_commit *state,
3559 					     struct drm_crtc *crtc)
3560 {
3561 	u32 i;
3562 	struct drm_connector_state *new_con_state;
3563 	struct drm_connector *connector;
3564 	struct drm_crtc *crtc_from_state;
3565 
3566 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3567 		crtc_from_state = new_con_state->crtc;
3568 
3569 		if (crtc_from_state == crtc)
3570 			return connector;
3571 	}
3572 
3573 	return NULL;
3574 }
3575 
3576 static void emulated_link_detect(struct dc_link *link)
3577 {
3578 	struct dc_sink_init_data sink_init_data = { 0 };
3579 	struct display_sink_capability sink_caps = { 0 };
3580 	enum dc_edid_status edid_status;
3581 	struct dc_context *dc_ctx = link->ctx;
3582 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
3583 	struct dc_sink *sink = NULL;
3584 	struct dc_sink *prev_sink = NULL;
3585 
3586 	link->type = dc_connection_none;
3587 	prev_sink = link->local_sink;
3588 
3589 	if (prev_sink)
3590 		dc_sink_release(prev_sink);
3591 
3592 	switch (link->connector_signal) {
3593 	case SIGNAL_TYPE_HDMI_TYPE_A: {
3594 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3595 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
3596 		break;
3597 	}
3598 
3599 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
3600 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3601 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
3602 		break;
3603 	}
3604 
3605 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
3606 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3607 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
3608 		break;
3609 	}
3610 
3611 	case SIGNAL_TYPE_LVDS: {
3612 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3613 		sink_caps.signal = SIGNAL_TYPE_LVDS;
3614 		break;
3615 	}
3616 
3617 	case SIGNAL_TYPE_EDP: {
3618 		sink_caps.transaction_type =
3619 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3620 		sink_caps.signal = SIGNAL_TYPE_EDP;
3621 		break;
3622 	}
3623 
3624 	case SIGNAL_TYPE_DISPLAY_PORT: {
3625 		sink_caps.transaction_type =
3626 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3627 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
3628 		break;
3629 	}
3630 
3631 	default:
3632 		drm_err(dev, "Invalid connector type! signal:%d\n",
3633 			link->connector_signal);
3634 		return;
3635 	}
3636 
3637 	sink_init_data.link = link;
3638 	sink_init_data.sink_signal = sink_caps.signal;
3639 
3640 	sink = dc_sink_create(&sink_init_data);
3641 	if (!sink) {
3642 		drm_err(dev, "Failed to create sink!\n");
3643 		return;
3644 	}
3645 
3646 	/* dc_sink_create returns a new reference */
3647 	link->local_sink = sink;
3648 
3649 	edid_status = dm_helpers_read_local_edid(
3650 			link->ctx,
3651 			link,
3652 			sink);
3653 
3654 	if (edid_status != EDID_OK)
3655 		drm_err(dev, "Failed to read EDID\n");
3656 
3657 }
3658 
3659 static void dm_gpureset_commit_state(struct dc_state *dc_state,
3660 				     struct amdgpu_display_manager *dm)
3661 {
3662 	struct {
3663 		struct dc_surface_update surface_updates[MAX_SURFACES];
3664 		struct dc_plane_info plane_infos[MAX_SURFACES];
3665 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3666 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3667 		struct dc_stream_update stream_update;
3668 	} *bundle __free(kfree);
3669 	int k, m;
3670 
3671 	bundle = kzalloc_obj(*bundle);
3672 
3673 	if (!bundle) {
3674 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
3675 		return;
3676 	}
3677 
3678 	for (k = 0; k < dc_state->stream_count; k++) {
3679 		bundle->stream_update.stream = dc_state->streams[k];
3680 
3681 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
3682 			bundle->surface_updates[m].surface =
3683 				dc_state->stream_status[k].plane_states[m];
3684 			bundle->surface_updates[m].surface->force_full_update =
3685 				true;
3686 		}
3687 
3688 		update_planes_and_stream_adapter(dm->dc,
3689 					 UPDATE_TYPE_FULL,
3690 					 dc_state->stream_status[k].plane_count,
3691 					 dc_state->streams[k],
3692 					 &bundle->stream_update,
3693 					 bundle->surface_updates);
3694 	}
3695 }
3696 
3697 static void apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
3698 					    struct dc_sink *sink)
3699 {
3700 	struct dc_panel_patch *ppatch = NULL;
3701 
3702 	if (!sink)
3703 		return;
3704 
3705 	ppatch = &sink->edid_caps.panel_patch;
3706 	if (ppatch->wait_after_dpcd_poweroff_ms) {
3707 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
3708 		drm_dbg_driver(adev_to_drm(adev),
3709 			       "%s: adding a %ds delay as w/a for panel\n",
3710 			       __func__,
3711 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
3712 	}
3713 }
3714 
3715 /**
3716  * amdgpu_dm_dump_links_and_sinks - Debug dump of all DC links and their sinks
3717  * @adev: amdgpu device pointer
3718  *
3719  * Iterates through all DC links and dumps information about local and remote
3720  * (MST) sinks. Should be called after connector detection is complete to see
3721  * the final state of all links.
3722  */
3723 static void amdgpu_dm_dump_links_and_sinks(struct amdgpu_device *adev)
3724 {
3725 	struct dc *dc = adev->dm.dc;
3726 	struct drm_device *dev = adev_to_drm(adev);
3727 	int li;
3728 
3729 	if (!dc)
3730 		return;
3731 
3732 	for (li = 0; li < dc->link_count; li++) {
3733 		struct dc_link *l = dc->links[li];
3734 		const char *name = NULL;
3735 		int rs;
3736 
3737 		if (!l)
3738 			continue;
3739 		if (l->local_sink && l->local_sink->edid_caps.display_name[0])
3740 			name = l->local_sink->edid_caps.display_name;
3741 		else
3742 			name = "n/a";
3743 
3744 		drm_dbg_kms(dev,
3745 			"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",
3746 			li,
3747 			l->local_sink,
3748 			l->type,
3749 			l->local_sink ? l->local_sink->sink_signal : SIGNAL_TYPE_NONE,
3750 			l->sink_count,
3751 			name,
3752 			l->dpcd_caps.is_mst_capable,
3753 			l->mst_stream_alloc_table.stream_count);
3754 
3755 		/* Dump remote (MST) sinks if any */
3756 		for (rs = 0; rs < l->sink_count; rs++) {
3757 			struct dc_sink *rsink = l->remote_sinks[rs];
3758 			const char *rname = NULL;
3759 
3760 			if (!rsink)
3761 				continue;
3762 			if (rsink->edid_caps.display_name[0])
3763 				rname = rsink->edid_caps.display_name;
3764 			else
3765 				rname = "n/a";
3766 			drm_dbg_kms(dev,
3767 				"  REMOTE_SINK[%d:%d]: sink=%p signal=%d edid_name=%s\n",
3768 				li, rs,
3769 				rsink,
3770 				rsink->sink_signal,
3771 				rname);
3772 		}
3773 	}
3774 }
3775 
3776 static int dm_resume(struct amdgpu_ip_block *ip_block)
3777 {
3778 	struct amdgpu_device *adev = ip_block->adev;
3779 	struct drm_device *ddev = adev_to_drm(adev);
3780 	struct amdgpu_display_manager *dm = &adev->dm;
3781 	struct amdgpu_dm_connector *aconnector;
3782 	struct drm_connector *connector;
3783 	struct drm_connector_list_iter iter;
3784 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
3785 	enum dc_connection_type new_connection_type = dc_connection_none;
3786 	struct dc_state *dc_state;
3787 	int i, r, j;
3788 	struct dc_commit_streams_params commit_params = {};
3789 
3790 	if (dm->dc->caps.ips_support) {
3791 		if (!amdgpu_in_reset(adev))
3792 			mutex_lock(&dm->dc_lock);
3793 
3794 		/* Need to set POWER_STATE_D0 first or it will not execute
3795 		 * idle_power_optimizations command to DMUB.
3796 		 */
3797 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3798 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
3799 
3800 		if (!amdgpu_in_reset(adev))
3801 			mutex_unlock(&dm->dc_lock);
3802 	}
3803 
3804 	if (amdgpu_in_reset(adev)) {
3805 		dc_state = dm->cached_dc_state;
3806 
3807 		/*
3808 		 * The dc->current_state is backed up into dm->cached_dc_state
3809 		 * before we commit 0 streams.
3810 		 *
3811 		 * DC will clear link encoder assignments on the real state
3812 		 * but the changes won't propagate over to the copy we made
3813 		 * before the 0 streams commit.
3814 		 *
3815 		 * DC expects that link encoder assignments are *not* valid
3816 		 * when committing a state, so as a workaround we can copy
3817 		 * off of the current state.
3818 		 *
3819 		 * We lose the previous assignments, but we had already
3820 		 * commit 0 streams anyway.
3821 		 */
3822 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
3823 
3824 		r = dm_dmub_hw_init(adev);
3825 		if (r) {
3826 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
3827 			return r;
3828 		}
3829 
3830 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3831 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3832 
3833 		dc_resume(dm->dc);
3834 
3835 		amdgpu_dm_ism_enable(dm);
3836 		amdgpu_dm_irq_resume_early(adev);
3837 
3838 		for (i = 0; i < dc_state->stream_count; i++) {
3839 			dc_state->streams[i]->mode_changed = true;
3840 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
3841 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
3842 					= 0xffffffff;
3843 			}
3844 		}
3845 
3846 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3847 			amdgpu_dm_outbox_init(adev);
3848 			dc_enable_dmub_outbox(adev->dm.dc);
3849 		}
3850 
3851 		commit_params.streams = dc_state->streams;
3852 		commit_params.stream_count = dc_state->stream_count;
3853 		dc_exit_ips_for_hw_access(dm->dc);
3854 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
3855 
3856 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
3857 
3858 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
3859 
3860 		dc_state_release(dm->cached_dc_state);
3861 		dm->cached_dc_state = NULL;
3862 
3863 		amdgpu_dm_irq_resume_late(adev);
3864 
3865 		mutex_unlock(&dm->dc_lock);
3866 
3867 		/* set the backlight after a reset */
3868 		for (i = 0; i < dm->num_of_edps; i++) {
3869 			if (dm->backlight_dev[i])
3870 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
3871 		}
3872 
3873 		return 0;
3874 	}
3875 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
3876 	dc_state_release(dm_state->context);
3877 	dm_state->context = dc_state_create(dm->dc, NULL);
3878 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
3879 
3880 	/* Before powering on DC we need to re-initialize DMUB. */
3881 	dm_dmub_hw_resume(adev);
3882 
3883 	/* Re-enable outbox interrupts for DPIA. */
3884 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3885 		amdgpu_dm_outbox_init(adev);
3886 		dc_enable_dmub_outbox(adev->dm.dc);
3887 	}
3888 
3889 	/* power on hardware */
3890 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3891 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3892 
3893 	/* program HPD filter */
3894 	dc_resume(dm->dc);
3895 
3896 	scoped_guard(mutex, &dm->dc_lock)
3897 		amdgpu_dm_ism_enable(dm);
3898 
3899 	/*
3900 	 * early enable HPD Rx IRQ, should be done before set mode as short
3901 	 * pulse interrupts are used for MST
3902 	 */
3903 	amdgpu_dm_irq_resume_early(adev);
3904 
3905 	s3_handle_hdmi_cec(ddev, false);
3906 
3907 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
3908 	s3_handle_mst(ddev, false);
3909 
3910 	/* Do detection*/
3911 	drm_connector_list_iter_begin(ddev, &iter);
3912 	drm_for_each_connector_iter(connector, &iter) {
3913 		bool ret;
3914 
3915 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3916 			continue;
3917 
3918 		aconnector = to_amdgpu_dm_connector(connector);
3919 
3920 		if (!aconnector->dc_link)
3921 			continue;
3922 
3923 		/*
3924 		 * this is the case when traversing through already created end sink
3925 		 * MST connectors, should be skipped
3926 		 */
3927 		if (aconnector->mst_root)
3928 			continue;
3929 
3930 		/* Skip eDP detection, when there is no sink present */
3931 		if (aconnector->dc_link->connector_signal == SIGNAL_TYPE_EDP &&
3932 		    !aconnector->dc_link->edp_sink_present)
3933 			continue;
3934 
3935 		guard(mutex)(&aconnector->hpd_lock);
3936 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3937 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3938 
3939 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3940 			emulated_link_detect(aconnector->dc_link);
3941 		} else {
3942 			guard(mutex)(&dm->dc_lock);
3943 			dc_exit_ips_for_hw_access(dm->dc);
3944 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
3945 			if (ret) {
3946 				/* w/a delay for certain panels */
3947 				apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3948 			}
3949 		}
3950 
3951 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
3952 			aconnector->fake_enable = false;
3953 
3954 		if (aconnector->dc_sink)
3955 			dc_sink_release(aconnector->dc_sink);
3956 		aconnector->dc_sink = NULL;
3957 		amdgpu_dm_update_connector_after_detect(aconnector);
3958 	}
3959 	drm_connector_list_iter_end(&iter);
3960 
3961 	dm_destroy_cached_state(adev);
3962 
3963 	/* Do mst topology probing after resuming cached state*/
3964 	drm_connector_list_iter_begin(ddev, &iter);
3965 	drm_for_each_connector_iter(connector, &iter) {
3966 		bool init = false;
3967 
3968 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3969 			continue;
3970 
3971 		aconnector = to_amdgpu_dm_connector(connector);
3972 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3973 		    aconnector->mst_root)
3974 			continue;
3975 
3976 		scoped_guard(mutex, &aconnector->mst_mgr.lock) {
3977 			init = !aconnector->mst_mgr.mst_primary;
3978 		}
3979 		if (init)
3980 			dm_helpers_dp_mst_start_top_mgr(aconnector->dc_link->ctx,
3981 				aconnector->dc_link, false);
3982 		else
3983 			drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
3984 	}
3985 	drm_connector_list_iter_end(&iter);
3986 
3987 	/* Debug dump: list all DC links and their associated sinks after detection
3988 	 * is complete for all connectors. This provides a comprehensive view of the
3989 	 * final state without repeating the dump for each connector.
3990 	 */
3991 	amdgpu_dm_dump_links_and_sinks(adev);
3992 
3993 	amdgpu_dm_irq_resume_late(adev);
3994 
3995 	amdgpu_dm_smu_write_watermarks_table(adev);
3996 
3997 	drm_kms_helper_hotplug_event(ddev);
3998 
3999 	return 0;
4000 }
4001 
4002 /**
4003  * DOC: DM Lifecycle
4004  *
4005  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
4006  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
4007  * the base driver's device list to be initialized and torn down accordingly.
4008  *
4009  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
4010  */
4011 
4012 static const struct amd_ip_funcs amdgpu_dm_funcs = {
4013 	.name = "dm",
4014 	.early_init = dm_early_init,
4015 	.late_init = dm_late_init,
4016 	.sw_init = dm_sw_init,
4017 	.sw_fini = dm_sw_fini,
4018 	.early_fini = amdgpu_dm_early_fini,
4019 	.hw_init = dm_hw_init,
4020 	.hw_fini = dm_hw_fini,
4021 	.suspend = dm_suspend,
4022 	.resume = dm_resume,
4023 	.is_idle = dm_is_idle,
4024 	.wait_for_idle = dm_wait_for_idle,
4025 	.check_soft_reset = dm_check_soft_reset,
4026 	.soft_reset = dm_soft_reset,
4027 	.set_clockgating_state = dm_set_clockgating_state,
4028 	.set_powergating_state = dm_set_powergating_state,
4029 };
4030 
4031 const struct amdgpu_ip_block_version dm_ip_block = {
4032 	.type = AMD_IP_BLOCK_TYPE_DCE,
4033 	.major = 1,
4034 	.minor = 0,
4035 	.rev = 0,
4036 	.funcs = &amdgpu_dm_funcs,
4037 };
4038 
4039 
4040 /**
4041  * DOC: atomic
4042  *
4043  * *WIP*
4044  */
4045 
4046 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
4047 	.fb_create = amdgpu_display_user_framebuffer_create,
4048 	.get_format_info = amdgpu_dm_plane_get_format_info,
4049 	.atomic_check = amdgpu_dm_atomic_check,
4050 	.atomic_commit = drm_atomic_helper_commit,
4051 };
4052 
4053 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
4054 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
4055 	.atomic_commit_setup = amdgpu_dm_atomic_setup_commit,
4056 };
4057 
4058 #define DDC_MANUFACTURERNAME_SAMSUNG 0x2D4C
4059 
4060 static void dm_set_panel_type(struct amdgpu_dm_connector *aconnector)
4061 {
4062 	struct drm_connector *connector = &aconnector->base;
4063 	struct drm_display_info *display_info = &connector->display_info;
4064 	struct dc_link *link = aconnector->dc_link;
4065 	struct amdgpu_device *adev;
4066 
4067 	adev = drm_to_adev(connector->dev);
4068 
4069 	link->panel_type = PANEL_TYPE_NONE;
4070 
4071 	switch (display_info->amd_vsdb.panel_type) {
4072 	case AMD_VSDB_PANEL_TYPE_OLED:
4073 		link->panel_type = PANEL_TYPE_OLED;
4074 		break;
4075 	case AMD_VSDB_PANEL_TYPE_MINILED:
4076 		link->panel_type = PANEL_TYPE_MINILED;
4077 		break;
4078 	}
4079 
4080 	/* If VSDB didn't determine panel type, check DPCD ext caps */
4081 	if (link->panel_type == PANEL_TYPE_NONE) {
4082 		if (link->dpcd_sink_ext_caps.bits.miniled == 1)
4083 			link->panel_type = PANEL_TYPE_MINILED;
4084 		if (link->dpcd_sink_ext_caps.bits.oled == 1)
4085 			link->panel_type = PANEL_TYPE_OLED;
4086 	}
4087 
4088 	/*
4089 	 * TODO: get panel type from DID2 that has device technology field
4090 	 * to specify if it's OLED or not. But we need to wait for DID2
4091 	 * support in DC and EDID parser to be able to use it here.
4092 	 */
4093 
4094 	if (link->panel_type == PANEL_TYPE_NONE) {
4095 		struct drm_amd_vsdb_info *vsdb = &display_info->amd_vsdb;
4096 		u32 lum1_max = vsdb->luminance_range1.max_luminance;
4097 		u32 lum2_max = vsdb->luminance_range2.max_luminance;
4098 
4099 		if (vsdb->version && link->local_sink &&
4100 		    link->local_sink->edid_caps.manufacturer_id ==
4101 		    DDC_MANUFACTURERNAME_SAMSUNG &&
4102 		    lum1_max >= ((lum2_max * 3) / 2))
4103 			link->panel_type = PANEL_TYPE_MINILED;
4104 	}
4105 
4106 	if (link->panel_type == PANEL_TYPE_OLED)
4107 		drm_object_property_set_value(&connector->base,
4108 		    adev_to_drm(adev)->mode_config.panel_type_property,
4109 		    DRM_MODE_PANEL_TYPE_OLED);
4110 	else
4111 		drm_object_property_set_value(&connector->base,
4112 		    adev_to_drm(adev)->mode_config.panel_type_property,
4113 		    DRM_MODE_PANEL_TYPE_UNKNOWN);
4114 
4115 	drm_dbg_kms(aconnector->base.dev, "Panel type: %d\n", link->panel_type);
4116 }
4117 
4118 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
4119 {
4120 	const struct drm_panel_backlight_quirk *panel_backlight_quirk;
4121 	struct amdgpu_dm_backlight_caps *caps;
4122 	struct drm_connector *conn_base;
4123 	struct amdgpu_device *adev;
4124 	struct drm_luminance_range_info *luminance_range;
4125 	struct drm_device *drm;
4126 
4127 	if (aconnector->bl_idx == -1 ||
4128 	    aconnector->dc_link->connector_signal != SIGNAL_TYPE_EDP)
4129 		return;
4130 
4131 	conn_base = &aconnector->base;
4132 	drm = conn_base->dev;
4133 	adev = drm_to_adev(drm);
4134 
4135 	caps = &adev->dm.backlight_caps[aconnector->bl_idx];
4136 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
4137 	caps->aux_support = false;
4138 
4139 	panel_backlight_quirk = drm_get_panel_backlight_quirk(aconnector->drm_edid);
4140 
4141 	if (caps->ext_caps->bits.oled == 1
4142 	    /*
4143 	     * ||
4144 	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
4145 	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
4146 	     */)
4147 		caps->aux_support = true;
4148 
4149 	if (amdgpu_backlight == 0)
4150 		caps->aux_support = false;
4151 	else if (amdgpu_backlight == 1)
4152 		caps->aux_support = true;
4153 	else if (!IS_ERR_OR_NULL(panel_backlight_quirk) &&
4154 		 panel_backlight_quirk->force_pwm)
4155 		caps->aux_support = false;
4156 	if (caps->aux_support)
4157 		aconnector->dc_link->backlight_control_type = BACKLIGHT_CONTROL_AMD_AUX;
4158 
4159 	luminance_range = &conn_base->display_info.luminance_range;
4160 
4161 	if (luminance_range->max_luminance)
4162 		caps->aux_max_input_signal = luminance_range->max_luminance;
4163 	else
4164 		caps->aux_max_input_signal = 512;
4165 
4166 	if (luminance_range->min_luminance)
4167 		caps->aux_min_input_signal = luminance_range->min_luminance;
4168 	else
4169 		caps->aux_min_input_signal = 1;
4170 
4171 	if (!IS_ERR_OR_NULL(panel_backlight_quirk)) {
4172 		if (panel_backlight_quirk->min_brightness) {
4173 			caps->min_input_signal =
4174 				panel_backlight_quirk->min_brightness - 1;
4175 			drm_info(drm,
4176 				 "Applying panel backlight quirk, min_brightness: %d\n",
4177 				 caps->min_input_signal);
4178 		}
4179 		if (panel_backlight_quirk->brightness_mask) {
4180 			drm_info(drm,
4181 				 "Applying panel backlight quirk, brightness_mask: 0x%X\n",
4182 				 panel_backlight_quirk->brightness_mask);
4183 			caps->brightness_mask =
4184 				panel_backlight_quirk->brightness_mask;
4185 		}
4186 	}
4187 }
4188 
4189 DEFINE_FREE(sink_release, struct dc_sink *, if (_T) dc_sink_release(_T))
4190 
4191 void amdgpu_dm_update_connector_after_detect(
4192 		struct amdgpu_dm_connector *aconnector)
4193 {
4194 	struct drm_connector *connector = &aconnector->base;
4195 	struct dc_sink *sink __free(sink_release) = NULL;
4196 	struct drm_device *dev = connector->dev;
4197 
4198 	/* MST handled by drm_mst framework */
4199 	if (aconnector->mst_mgr.mst_state == true)
4200 		return;
4201 
4202 	sink = aconnector->dc_link->local_sink;
4203 	if (sink)
4204 		dc_sink_retain(sink);
4205 
4206 	/*
4207 	 * Edid mgmt connector gets first update only in mode_valid hook and then
4208 	 * the connector sink is set to either fake or physical sink depends on link status.
4209 	 * Skip if already done during boot.
4210 	 */
4211 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
4212 			&& aconnector->dc_em_sink) {
4213 
4214 		/*
4215 		 * For S3 resume with headless use eml_sink to fake stream
4216 		 * because on resume connector->sink is set to NULL
4217 		 */
4218 		guard(mutex)(&dev->mode_config.mutex);
4219 
4220 		if (sink) {
4221 			if (aconnector->dc_sink) {
4222 				amdgpu_dm_update_freesync_caps(connector, NULL, true);
4223 				/*
4224 				 * retain and release below are used to
4225 				 * bump up refcount for sink because the link doesn't point
4226 				 * to it anymore after disconnect, so on next crtc to connector
4227 				 * reshuffle by UMD we will get into unwanted dc_sink release
4228 				 */
4229 				dc_sink_release(aconnector->dc_sink);
4230 			}
4231 			aconnector->dc_sink = sink;
4232 			dc_sink_retain(aconnector->dc_sink);
4233 			amdgpu_dm_update_freesync_caps(connector,
4234 					aconnector->drm_edid, true);
4235 		} else {
4236 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4237 			if (!aconnector->dc_sink) {
4238 				aconnector->dc_sink = aconnector->dc_em_sink;
4239 				dc_sink_retain(aconnector->dc_sink);
4240 			}
4241 		}
4242 
4243 		return;
4244 	}
4245 
4246 	/*
4247 	 * TODO: temporary guard to look for proper fix
4248 	 * if this sink is MST sink, we should not do anything
4249 	 */
4250 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
4251 		return;
4252 
4253 	if (aconnector->dc_sink == sink) {
4254 		/*
4255 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
4256 		 * Do nothing!!
4257 		 */
4258 		drm_dbg_kms(dev, "DCHPD: connector_id=%d: dc_sink didn't change.\n",
4259 				 aconnector->connector_id);
4260 		return;
4261 	}
4262 
4263 	drm_dbg_kms(dev, "DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
4264 		    aconnector->connector_id, aconnector->dc_sink, sink);
4265 
4266 	/* When polling, DRM has already locked the mutex for us. */
4267 	if (!drm_kms_helper_is_poll_worker())
4268 		mutex_lock(&dev->mode_config.mutex);
4269 
4270 	/*
4271 	 * 1. Update status of the drm connector
4272 	 * 2. Send an event and let userspace tell us what to do
4273 	 */
4274 	if (sink) {
4275 		/*
4276 		 * TODO: check if we still need the S3 mode update workaround.
4277 		 * If yes, put it here.
4278 		 */
4279 		if (aconnector->dc_sink) {
4280 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4281 			dc_sink_release(aconnector->dc_sink);
4282 		}
4283 
4284 		aconnector->dc_sink = sink;
4285 		dc_sink_retain(aconnector->dc_sink);
4286 		drm_edid_free(aconnector->drm_edid);
4287 		aconnector->drm_edid = NULL;
4288 		if (sink->dc_edid.length == 0) {
4289 			hdmi_cec_unset_edid(aconnector);
4290 			if (aconnector->dc_link->aux_mode) {
4291 				drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4292 			}
4293 		} else {
4294 			const struct edid *edid = (const struct edid *)sink->dc_edid.raw_edid;
4295 
4296 			aconnector->drm_edid = drm_edid_alloc(edid, sink->dc_edid.length);
4297 			drm_edid_connector_update(connector, aconnector->drm_edid);
4298 
4299 			hdmi_cec_set_edid(aconnector);
4300 			if (aconnector->dc_link->aux_mode)
4301 				drm_dp_cec_attach(&aconnector->dm_dp_aux.aux,
4302 						  connector->display_info.source_physical_address);
4303 		}
4304 
4305 		if (!aconnector->timing_requested) {
4306 			aconnector->timing_requested =
4307 				kzalloc_obj(struct dc_crtc_timing);
4308 			if (!aconnector->timing_requested)
4309 				drm_err(dev,
4310 					"failed to create aconnector->requested_timing\n");
4311 		}
4312 
4313 		amdgpu_dm_update_freesync_caps(connector, aconnector->drm_edid, true);
4314 		update_connector_ext_caps(aconnector);
4315 		dm_set_panel_type(aconnector);
4316 	} else {
4317 		hdmi_cec_unset_edid(aconnector);
4318 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4319 		amdgpu_dm_update_freesync_caps(connector, NULL, true);
4320 		aconnector->num_modes = 0;
4321 		dc_sink_release(aconnector->dc_sink);
4322 		aconnector->dc_sink = NULL;
4323 		drm_edid_free(aconnector->drm_edid);
4324 		aconnector->drm_edid = NULL;
4325 		kfree(aconnector->timing_requested);
4326 		aconnector->timing_requested = NULL;
4327 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
4328 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
4329 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
4330 	}
4331 
4332 	update_subconnector_property(aconnector);
4333 
4334 	/* When polling, the mutex will be unlocked for us by DRM. */
4335 	if (!drm_kms_helper_is_poll_worker())
4336 		mutex_unlock(&dev->mode_config.mutex);
4337 }
4338 
4339 static bool are_sinks_equal(const struct dc_sink *sink1, const struct dc_sink *sink2)
4340 {
4341 	if (!sink1 || !sink2)
4342 		return false;
4343 	if (sink1->sink_signal != sink2->sink_signal)
4344 		return false;
4345 
4346 	if (sink1->dc_edid.length != sink2->dc_edid.length)
4347 		return false;
4348 
4349 	if (memcmp(sink1->dc_edid.raw_edid, sink2->dc_edid.raw_edid,
4350 		   sink1->dc_edid.length) != 0)
4351 		return false;
4352 	return true;
4353 }
4354 
4355 
4356 /**
4357  * DOC: hdmi_hpd_debounce_work
4358  *
4359  * HDMI HPD debounce delay in milliseconds. When an HDMI display toggles HPD
4360  * (such as during power save transitions), this delay determines how long to
4361  * wait before processing the HPD event. This allows distinguishing between a
4362  * physical unplug (>hdmi_hpd_debounce_delay)
4363  * and a spontaneous RX HPD toggle (<hdmi_hpd_debounce_delay).
4364  *
4365  * If the toggle is less than this delay, the driver compares sink capabilities
4366  * and permits a hotplug event if they changed.
4367  *
4368  * The default value of 1500ms was chosen based on experimental testing with
4369  * various monitors that exhibit spontaneous HPD toggling behavior.
4370  */
4371 static void hdmi_hpd_debounce_work(struct work_struct *work)
4372 {
4373 	struct amdgpu_dm_connector *aconnector =
4374 		container_of(to_delayed_work(work), struct amdgpu_dm_connector,
4375 			     hdmi_hpd_debounce_work);
4376 	struct drm_connector *connector = &aconnector->base;
4377 	struct drm_device *dev = connector->dev;
4378 	struct amdgpu_device *adev = drm_to_adev(dev);
4379 	struct dc *dc = aconnector->dc_link->ctx->dc;
4380 	bool fake_reconnect = false;
4381 	bool reallow_idle = false;
4382 	bool ret = false;
4383 	guard(mutex)(&aconnector->hpd_lock);
4384 
4385 	/* Re-detect the display */
4386 	scoped_guard(mutex, &adev->dm.dc_lock) {
4387 		if (dc->caps.ips_support && dc->ctx->dmub_srv->idle_allowed) {
4388 			dc_allow_idle_optimizations(dc, false);
4389 			reallow_idle = true;
4390 		}
4391 		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4392 	}
4393 
4394 	if (ret) {
4395 		/* Apply workaround delay for certain panels */
4396 		apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4397 		/* Compare sinks to determine if this was a spontaneous HPD toggle */
4398 		if (are_sinks_equal(aconnector->dc_link->local_sink, aconnector->hdmi_prev_sink)) {
4399 			/*
4400 			* Sinks match - this was a spontaneous HDMI HPD toggle.
4401 			*/
4402 			drm_dbg_kms(dev, "HDMI HPD: Sink unchanged after debounce, internal re-enable\n");
4403 			fake_reconnect = true;
4404 		}
4405 
4406 		/* Update connector state */
4407 		amdgpu_dm_update_connector_after_detect(aconnector);
4408 
4409 		drm_modeset_lock_all(dev);
4410 		dm_restore_drm_connector_state(dev, connector);
4411 		drm_modeset_unlock_all(dev);
4412 
4413 		/* Only notify OS if sink actually changed */
4414 		if (!fake_reconnect && aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4415 			drm_kms_helper_hotplug_event(dev);
4416 	}
4417 
4418 	/* Release the cached sink reference */
4419 	if (aconnector->hdmi_prev_sink) {
4420 		dc_sink_release(aconnector->hdmi_prev_sink);
4421 		aconnector->hdmi_prev_sink = NULL;
4422 	}
4423 
4424 	scoped_guard(mutex, &adev->dm.dc_lock) {
4425 		if (reallow_idle && dc->caps.ips_support)
4426 			dc_allow_idle_optimizations(dc, true);
4427 	}
4428 }
4429 
4430 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
4431 {
4432 	struct drm_connector *connector = &aconnector->base;
4433 	struct drm_device *dev = connector->dev;
4434 	enum dc_connection_type new_connection_type = dc_connection_none;
4435 	struct amdgpu_device *adev = drm_to_adev(dev);
4436 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
4437 	struct dc *dc = aconnector->dc_link->ctx->dc;
4438 	bool ret = false;
4439 	bool debounce_required = false;
4440 
4441 	if (adev->dm.disable_hpd_irq)
4442 		return;
4443 
4444 	/*
4445 	 * In case of failure or MST no need to update connector status or notify the OS
4446 	 * since (for MST case) MST does this in its own context.
4447 	 */
4448 	guard(mutex)(&aconnector->hpd_lock);
4449 
4450 	if (adev->dm.hdcp_workqueue) {
4451 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
4452 		dm_con_state->update_hdcp = true;
4453 	}
4454 	if (aconnector->fake_enable)
4455 		aconnector->fake_enable = false;
4456 
4457 	aconnector->timing_changed = false;
4458 
4459 	if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
4460 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4461 
4462 	/*
4463 	 * Check for HDMI disconnect with debounce enabled.
4464 	 */
4465 	debounce_required = (aconnector->hdmi_hpd_debounce_delay_ms > 0 &&
4466 			      dc_is_hdmi_signal(aconnector->dc_link->connector_signal) &&
4467 			      new_connection_type == dc_connection_none &&
4468 			      aconnector->dc_link->local_sink != NULL);
4469 
4470 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
4471 		emulated_link_detect(aconnector->dc_link);
4472 
4473 		drm_modeset_lock_all(dev);
4474 		dm_restore_drm_connector_state(dev, connector);
4475 		drm_modeset_unlock_all(dev);
4476 
4477 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4478 			drm_kms_helper_connector_hotplug_event(connector);
4479 	} else if (debounce_required) {
4480 		/*
4481 		 * HDMI disconnect detected - schedule delayed work instead of
4482 		 * processing immediately. This allows us to coalesce spurious
4483 		 * HDMI signals from physical unplugs.
4484 		 */
4485 		drm_dbg_kms(dev, "HDMI HPD: Disconnect detected, scheduling debounce work (%u ms)\n",
4486 			    aconnector->hdmi_hpd_debounce_delay_ms);
4487 
4488 		/* Cache the current sink for later comparison */
4489 		if (aconnector->hdmi_prev_sink)
4490 			dc_sink_release(aconnector->hdmi_prev_sink);
4491 		aconnector->hdmi_prev_sink = aconnector->dc_link->local_sink;
4492 		if (aconnector->hdmi_prev_sink)
4493 			dc_sink_retain(aconnector->hdmi_prev_sink);
4494 
4495 		/* Schedule delayed detection. */
4496 		if (mod_delayed_work(system_percpu_wq,
4497 				 &aconnector->hdmi_hpd_debounce_work,
4498 				 msecs_to_jiffies(aconnector->hdmi_hpd_debounce_delay_ms)))
4499 			drm_dbg_kms(dev, "HDMI HPD: Re-scheduled debounce work\n");
4500 
4501 	} else {
4502 
4503 		/* If the aconnector->hdmi_hpd_debounce_work is scheduled, exit early */
4504 		if (delayed_work_pending(&aconnector->hdmi_hpd_debounce_work))
4505 			return;
4506 
4507 		scoped_guard(mutex, &adev->dm.dc_lock) {
4508 			dc_exit_ips_for_hw_access(dc);
4509 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4510 		}
4511 		if (ret) {
4512 			/* w/a delay for certain panels */
4513 			apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4514 			amdgpu_dm_update_connector_after_detect(aconnector);
4515 
4516 			drm_modeset_lock_all(dev);
4517 			dm_restore_drm_connector_state(dev, connector);
4518 			drm_modeset_unlock_all(dev);
4519 
4520 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4521 				drm_kms_helper_connector_hotplug_event(connector);
4522 		}
4523 	}
4524 }
4525 
4526 static void handle_hpd_irq(void *param)
4527 {
4528 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4529 
4530 	handle_hpd_irq_helper(aconnector);
4531 
4532 }
4533 
4534 static void schedule_hpd_rx_offload_work(struct amdgpu_device *adev, struct hpd_rx_irq_offload_work_queue *offload_wq,
4535 							union hpd_irq_data hpd_irq_data)
4536 {
4537 	struct hpd_rx_irq_offload_work *offload_work = kzalloc_obj(*offload_work);
4538 
4539 	if (!offload_work) {
4540 		drm_err(adev_to_drm(adev), "Failed to allocate hpd_rx_irq_offload_work.\n");
4541 		return;
4542 	}
4543 
4544 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
4545 	offload_work->data = hpd_irq_data;
4546 	offload_work->offload_wq = offload_wq;
4547 	offload_work->adev = adev;
4548 
4549 	queue_work(offload_wq->wq, &offload_work->work);
4550 	drm_dbg_kms(adev_to_drm(adev), "queue work to handle hpd_rx offload work");
4551 }
4552 
4553 static void handle_hpd_rx_irq(void *param)
4554 {
4555 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4556 	struct drm_connector *connector = &aconnector->base;
4557 	struct drm_device *dev = connector->dev;
4558 	struct dc_link *dc_link = aconnector->dc_link;
4559 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
4560 	bool result = false;
4561 	enum dc_connection_type new_connection_type = dc_connection_none;
4562 	struct amdgpu_device *adev = drm_to_adev(dev);
4563 	union hpd_irq_data hpd_irq_data;
4564 	bool link_loss = false;
4565 	bool has_left_work = false;
4566 	int idx = dc_link->link_index;
4567 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
4568 	struct dc *dc = aconnector->dc_link->ctx->dc;
4569 
4570 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
4571 
4572 	if (adev->dm.disable_hpd_irq)
4573 		return;
4574 
4575 	/*
4576 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
4577 	 * conflict, after implement i2c helper, this mutex should be
4578 	 * retired.
4579 	 */
4580 	mutex_lock(&aconnector->hpd_lock);
4581 
4582 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
4583 						&link_loss, true, &has_left_work);
4584 
4585 	if (!has_left_work)
4586 		goto out;
4587 
4588 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
4589 		schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4590 		goto out;
4591 	}
4592 
4593 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
4594 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
4595 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
4596 			bool skip = false;
4597 
4598 			/*
4599 			 * DOWN_REP_MSG_RDY is also handled by polling method
4600 			 * mgr->cbs->poll_hpd_irq()
4601 			 */
4602 			spin_lock(&offload_wq->offload_lock);
4603 			skip = offload_wq->is_handling_mst_msg_rdy_event;
4604 
4605 			if (!skip)
4606 				offload_wq->is_handling_mst_msg_rdy_event = true;
4607 
4608 			spin_unlock(&offload_wq->offload_lock);
4609 
4610 			if (!skip)
4611 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4612 
4613 			goto out;
4614 		}
4615 
4616 		if (link_loss) {
4617 			bool skip = false;
4618 
4619 			spin_lock(&offload_wq->offload_lock);
4620 			skip = offload_wq->is_handling_link_loss;
4621 
4622 			if (!skip)
4623 				offload_wq->is_handling_link_loss = true;
4624 
4625 			spin_unlock(&offload_wq->offload_lock);
4626 
4627 			if (!skip)
4628 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4629 
4630 			goto out;
4631 		}
4632 	}
4633 
4634 out:
4635 	if (result && !is_mst_root_connector) {
4636 		/* Downstream Port status changed. */
4637 		if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
4638 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4639 
4640 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4641 			emulated_link_detect(dc_link);
4642 
4643 			if (aconnector->fake_enable)
4644 				aconnector->fake_enable = false;
4645 
4646 			amdgpu_dm_update_connector_after_detect(aconnector);
4647 
4648 
4649 			drm_modeset_lock_all(dev);
4650 			dm_restore_drm_connector_state(dev, connector);
4651 			drm_modeset_unlock_all(dev);
4652 
4653 			drm_kms_helper_connector_hotplug_event(connector);
4654 		} else {
4655 			bool ret = false;
4656 
4657 			mutex_lock(&adev->dm.dc_lock);
4658 			dc_exit_ips_for_hw_access(dc);
4659 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
4660 			mutex_unlock(&adev->dm.dc_lock);
4661 
4662 			if (ret) {
4663 				if (aconnector->fake_enable)
4664 					aconnector->fake_enable = false;
4665 
4666 				amdgpu_dm_update_connector_after_detect(aconnector);
4667 
4668 				drm_modeset_lock_all(dev);
4669 				dm_restore_drm_connector_state(dev, connector);
4670 				drm_modeset_unlock_all(dev);
4671 
4672 				drm_kms_helper_connector_hotplug_event(connector);
4673 			}
4674 		}
4675 	}
4676 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
4677 		if (adev->dm.hdcp_workqueue)
4678 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
4679 	}
4680 
4681 	if (dc_link->type != dc_connection_mst_branch)
4682 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
4683 
4684 	mutex_unlock(&aconnector->hpd_lock);
4685 }
4686 
4687 static int register_hpd_handlers(struct amdgpu_device *adev)
4688 {
4689 	struct drm_device *dev = adev_to_drm(adev);
4690 	struct drm_connector *connector;
4691 	struct amdgpu_dm_connector *aconnector;
4692 	const struct dc_link *dc_link;
4693 	struct dc_interrupt_params int_params = {0};
4694 
4695 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4696 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4697 
4698 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
4699 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD,
4700 			dmub_hpd_callback, true)) {
4701 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4702 			return -EINVAL;
4703 		}
4704 
4705 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ,
4706 			dmub_hpd_callback, true)) {
4707 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4708 			return -EINVAL;
4709 		}
4710 
4711 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_SENSE_NOTIFY,
4712 			dmub_hpd_sense_callback, true)) {
4713 			drm_err(adev_to_drm(adev), "fail to register dmub hpd sense callback");
4714 			return -EINVAL;
4715 		}
4716 	}
4717 
4718 	list_for_each_entry(connector,
4719 			&dev->mode_config.connector_list, head)	{
4720 
4721 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
4722 			continue;
4723 
4724 		aconnector = to_amdgpu_dm_connector(connector);
4725 		dc_link = aconnector->dc_link;
4726 
4727 		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
4728 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4729 			int_params.irq_source = dc_link->irq_source_hpd;
4730 
4731 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4732 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1 ||
4733 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6) {
4734 				drm_err(adev_to_drm(adev), "Failed to register hpd irq!\n");
4735 				return -EINVAL;
4736 			}
4737 
4738 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4739 				handle_hpd_irq, (void *) aconnector))
4740 				return -ENOMEM;
4741 		}
4742 
4743 		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
4744 
4745 			/* Also register for DP short pulse (hpd_rx). */
4746 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4747 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
4748 
4749 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4750 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1RX ||
4751 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6RX) {
4752 				drm_err(adev_to_drm(adev), "Failed to register hpd rx irq!\n");
4753 				return -EINVAL;
4754 			}
4755 
4756 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4757 				handle_hpd_rx_irq, (void *) aconnector))
4758 				return -ENOMEM;
4759 		}
4760 	}
4761 	return 0;
4762 }
4763 
4764 /* Register IRQ sources and initialize IRQ callbacks */
4765 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
4766 {
4767 	struct dc *dc = adev->dm.dc;
4768 	struct common_irq_params *c_irq_params;
4769 	struct dc_interrupt_params int_params = {0};
4770 	int r;
4771 	int i;
4772 	unsigned int src_id;
4773 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4774 	/* Use different interrupts for VBLANK on DCE 6 vs. newer. */
4775 	const unsigned int vblank_d1 =
4776 		adev->dm.dc->ctx->dce_version >= DCE_VERSION_8_0
4777 		? VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0 : 1;
4778 
4779 	if (adev->family >= AMDGPU_FAMILY_AI)
4780 		client_id = SOC15_IH_CLIENTID_DCE;
4781 
4782 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4783 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4784 
4785 	/*
4786 	 * Actions of amdgpu_irq_add_id():
4787 	 * 1. Register a set() function with base driver.
4788 	 *    Base driver will call set() function to enable/disable an
4789 	 *    interrupt in DC hardware.
4790 	 * 2. Register amdgpu_dm_irq_handler().
4791 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4792 	 *    coming from DC hardware.
4793 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4794 	 *    for acknowledging and handling.
4795 	 */
4796 
4797 	/* Use VBLANK interrupt */
4798 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
4799 		src_id = vblank_d1 + i;
4800 		r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->crtc_irq);
4801 		if (r) {
4802 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4803 			return r;
4804 		}
4805 
4806 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4807 		int_params.irq_source =
4808 			dc_interrupt_to_irq_source(dc, src_id, 0);
4809 
4810 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4811 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4812 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4813 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4814 			return -EINVAL;
4815 		}
4816 
4817 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4818 
4819 		c_irq_params->adev = adev;
4820 		c_irq_params->irq_src = int_params.irq_source;
4821 
4822 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4823 			dm_crtc_high_irq, c_irq_params))
4824 			return -ENOMEM;
4825 	}
4826 
4827 	if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
4828 		/* Use VUPDATE interrupt */
4829 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
4830 			src_id = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT + i * 2;
4831 			r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->vupdate_irq);
4832 			if (r) {
4833 				drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4834 				return r;
4835 			}
4836 
4837 			int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4838 			int_params.irq_source =
4839 				dc_interrupt_to_irq_source(dc, src_id, 0);
4840 
4841 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4842 				int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4843 				int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4844 				drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4845 				return -EINVAL;
4846 			}
4847 
4848 			c_irq_params = &adev->dm.vupdate_params[
4849 				int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4850 			c_irq_params->adev = adev;
4851 			c_irq_params->irq_src = int_params.irq_source;
4852 
4853 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4854 				dm_vupdate_high_irq, c_irq_params))
4855 				return -ENOMEM;
4856 		}
4857 	}
4858 
4859 	/* Use GRPH_PFLIP interrupt */
4860 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4861 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4862 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4863 		if (r) {
4864 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4865 			return r;
4866 		}
4867 
4868 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4869 		int_params.irq_source =
4870 			dc_interrupt_to_irq_source(dc, i, 0);
4871 
4872 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4873 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4874 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4875 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4876 			return -EINVAL;
4877 		}
4878 
4879 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4880 
4881 		c_irq_params->adev = adev;
4882 		c_irq_params->irq_src = int_params.irq_source;
4883 
4884 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4885 			dm_pflip_high_irq, c_irq_params))
4886 			return -ENOMEM;
4887 	}
4888 
4889 	/* HPD */
4890 	r = amdgpu_irq_add_id(adev, client_id,
4891 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4892 	if (r) {
4893 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4894 		return r;
4895 	}
4896 
4897 	r = register_hpd_handlers(adev);
4898 
4899 	return r;
4900 }
4901 
4902 /* Register IRQ sources and initialize IRQ callbacks */
4903 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
4904 {
4905 	struct dc *dc = adev->dm.dc;
4906 	struct common_irq_params *c_irq_params;
4907 	struct dc_interrupt_params int_params = {0};
4908 	int r;
4909 	int i;
4910 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4911 	static const unsigned int vrtl_int_srcid[] = {
4912 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
4913 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
4914 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
4915 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
4916 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
4917 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
4918 	};
4919 #endif
4920 
4921 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4922 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4923 
4924 	/*
4925 	 * Actions of amdgpu_irq_add_id():
4926 	 * 1. Register a set() function with base driver.
4927 	 *    Base driver will call set() function to enable/disable an
4928 	 *    interrupt in DC hardware.
4929 	 * 2. Register amdgpu_dm_irq_handler().
4930 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4931 	 *    coming from DC hardware.
4932 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4933 	 *    for acknowledging and handling.
4934 	 */
4935 
4936 	/* Use otg vertical line interrupt */
4937 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4938 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
4939 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
4940 				vrtl_int_srcid[i], &adev->vline0_irq);
4941 
4942 		if (r) {
4943 			drm_err(adev_to_drm(adev), "Failed to add vline0 irq id!\n");
4944 			return r;
4945 		}
4946 
4947 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4948 		int_params.irq_source =
4949 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
4950 
4951 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4952 			int_params.irq_source < DC_IRQ_SOURCE_DC1_VLINE0 ||
4953 			int_params.irq_source > DC_IRQ_SOURCE_DC6_VLINE0) {
4954 			drm_err(adev_to_drm(adev), "Failed to register vline0 irq!\n");
4955 			return -EINVAL;
4956 		}
4957 
4958 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
4959 					- DC_IRQ_SOURCE_DC1_VLINE0];
4960 
4961 		c_irq_params->adev = adev;
4962 		c_irq_params->irq_src = int_params.irq_source;
4963 
4964 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4965 			dm_dcn_vertical_interrupt0_high_irq,
4966 			c_irq_params))
4967 			return -ENOMEM;
4968 	}
4969 #endif
4970 
4971 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
4972 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
4973 	 * to trigger at end of each vblank, regardless of state of the lock,
4974 	 * matching DCE behaviour.
4975 	 */
4976 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
4977 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
4978 	     i++) {
4979 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
4980 
4981 		if (r) {
4982 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4983 			return r;
4984 		}
4985 
4986 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4987 		int_params.irq_source =
4988 			dc_interrupt_to_irq_source(dc, i, 0);
4989 
4990 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4991 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4992 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4993 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4994 			return -EINVAL;
4995 		}
4996 
4997 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4998 
4999 		c_irq_params->adev = adev;
5000 		c_irq_params->irq_src = int_params.irq_source;
5001 
5002 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
5003 			dm_vupdate_high_irq, c_irq_params))
5004 			return -ENOMEM;
5005 	}
5006 
5007 	/* HPD */
5008 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
5009 			&adev->hpd_irq);
5010 	if (r) {
5011 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
5012 		return r;
5013 	}
5014 
5015 	r = register_hpd_handlers(adev);
5016 
5017 	return r;
5018 }
5019 /* Register Outbox IRQ sources and initialize IRQ callbacks */
5020 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
5021 {
5022 	struct dc *dc = adev->dm.dc;
5023 	struct common_irq_params *c_irq_params;
5024 	struct dc_interrupt_params int_params = {0};
5025 	int r, i;
5026 
5027 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
5028 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
5029 
5030 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
5031 			&adev->dmub_outbox_irq);
5032 	if (r) {
5033 		drm_err(adev_to_drm(adev), "Failed to add outbox irq id!\n");
5034 		return r;
5035 	}
5036 
5037 	if (dc->ctx->dmub_srv) {
5038 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
5039 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
5040 		int_params.irq_source =
5041 		dc_interrupt_to_irq_source(dc, i, 0);
5042 
5043 		c_irq_params = &adev->dm.dmub_outbox_params[0];
5044 
5045 		c_irq_params->adev = adev;
5046 		c_irq_params->irq_src = int_params.irq_source;
5047 
5048 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
5049 			dm_dmub_outbox1_low_irq, c_irq_params))
5050 			return -ENOMEM;
5051 	}
5052 
5053 	return 0;
5054 }
5055 
5056 /*
5057  * Acquires the lock for the atomic state object and returns
5058  * the new atomic state.
5059  *
5060  * This should only be called during atomic check.
5061  */
5062 int dm_atomic_get_state(struct drm_atomic_commit *state,
5063 			struct dm_atomic_state **dm_state)
5064 {
5065 	struct drm_device *dev = state->dev;
5066 	struct amdgpu_device *adev = drm_to_adev(dev);
5067 	struct amdgpu_display_manager *dm = &adev->dm;
5068 	struct drm_private_state *priv_state;
5069 
5070 	if (*dm_state)
5071 		return 0;
5072 
5073 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
5074 	if (IS_ERR(priv_state))
5075 		return PTR_ERR(priv_state);
5076 
5077 	*dm_state = to_dm_atomic_state(priv_state);
5078 
5079 	return 0;
5080 }
5081 
5082 static struct dm_atomic_state *
5083 dm_atomic_get_new_state(struct drm_atomic_commit *state)
5084 {
5085 	struct drm_device *dev = state->dev;
5086 	struct amdgpu_device *adev = drm_to_adev(dev);
5087 	struct amdgpu_display_manager *dm = &adev->dm;
5088 	struct drm_private_obj *obj;
5089 	struct drm_private_state *new_obj_state;
5090 	int i;
5091 
5092 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
5093 		if (obj->funcs == dm->atomic_obj.funcs)
5094 			return to_dm_atomic_state(new_obj_state);
5095 	}
5096 
5097 	return NULL;
5098 }
5099 
5100 static struct drm_private_state *
5101 dm_atomic_duplicate_state(struct drm_private_obj *obj)
5102 {
5103 	struct dm_atomic_state *old_state, *new_state;
5104 
5105 	new_state = kzalloc_obj(*new_state);
5106 	if (!new_state)
5107 		return NULL;
5108 
5109 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
5110 
5111 	old_state = to_dm_atomic_state(obj->state);
5112 
5113 	if (old_state && old_state->context)
5114 		new_state->context = dc_state_create_copy(old_state->context);
5115 
5116 	if (!new_state->context) {
5117 		kfree(new_state);
5118 		return NULL;
5119 	}
5120 
5121 	return &new_state->base;
5122 }
5123 
5124 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
5125 				    struct drm_private_state *state)
5126 {
5127 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
5128 
5129 	if (dm_state && dm_state->context)
5130 		dc_state_release(dm_state->context);
5131 
5132 	kfree(dm_state);
5133 }
5134 
5135 static struct drm_private_state *
5136 dm_atomic_create_state(struct drm_private_obj *obj)
5137 {
5138 	struct amdgpu_device *adev = drm_to_adev(obj->dev);
5139 	struct dm_atomic_state *dm_state;
5140 	struct dc_state *context;
5141 
5142 	dm_state = kzalloc_obj(*dm_state);
5143 	if (!dm_state)
5144 		return ERR_PTR(-ENOMEM);
5145 
5146 	context = dc_state_create_current_copy(adev->dm.dc);
5147 	if (!context) {
5148 		kfree(dm_state);
5149 		return ERR_PTR(-ENOMEM);
5150 	}
5151 
5152 	__drm_atomic_helper_private_obj_create_state(obj, &dm_state->base);
5153 	dm_state->context = context;
5154 
5155 	return &dm_state->base;
5156 }
5157 
5158 static struct drm_private_state_funcs dm_atomic_state_funcs = {
5159 	.atomic_create_state = dm_atomic_create_state,
5160 	.atomic_duplicate_state = dm_atomic_duplicate_state,
5161 	.atomic_destroy_state = dm_atomic_destroy_state,
5162 };
5163 
5164 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
5165 {
5166 	int r;
5167 
5168 	adev->mode_info.mode_config_initialized = true;
5169 
5170 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
5171 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
5172 
5173 	adev_to_drm(adev)->mode_config.max_width = 16384;
5174 	adev_to_drm(adev)->mode_config.max_height = 16384;
5175 
5176 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
5177 	if (adev->asic_type == CHIP_HAWAII)
5178 		/* disable prefer shadow for now due to hibernation issues */
5179 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
5180 	else
5181 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
5182 	/* indicates support for immediate flip */
5183 	adev_to_drm(adev)->mode_config.async_page_flip = true;
5184 
5185 	drm_atomic_private_obj_init(adev_to_drm(adev),
5186 				    &adev->dm.atomic_obj,
5187 				    &dm_atomic_state_funcs);
5188 
5189 	r = amdgpu_display_modeset_create_props(adev);
5190 	if (r)
5191 		return r;
5192 
5193 #ifdef AMD_PRIVATE_COLOR
5194 	if (amdgpu_dm_create_color_properties(adev))
5195 		return -ENOMEM;
5196 #endif
5197 
5198 	r = amdgpu_dm_audio_init(adev);
5199 	if (r)
5200 		return r;
5201 
5202 	return 0;
5203 }
5204 
5205 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
5206 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
5207 #define AMDGPU_DM_MIN_SPREAD ((AMDGPU_DM_DEFAULT_MAX_BACKLIGHT - AMDGPU_DM_DEFAULT_MIN_BACKLIGHT) / 2)
5208 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
5209 
5210 void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
5211 				     int bl_idx)
5212 {
5213 	struct amdgpu_dm_backlight_caps *caps = &dm->backlight_caps[bl_idx];
5214 
5215 	if (caps->caps_valid)
5216 		return;
5217 
5218 #if defined(CONFIG_ACPI)
5219 	amdgpu_acpi_get_backlight_caps(caps);
5220 
5221 	/* validate the firmware value is sane */
5222 	if (caps->caps_valid) {
5223 		int spread = caps->max_input_signal - caps->min_input_signal;
5224 
5225 		if (caps->max_input_signal > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5226 		    caps->min_input_signal < 0 ||
5227 		    spread > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5228 		    spread < AMDGPU_DM_MIN_SPREAD) {
5229 			drm_dbg_kms(adev_to_drm(dm->adev), "DM: Invalid backlight caps: min=%d, max=%d\n",
5230 				      caps->min_input_signal, caps->max_input_signal);
5231 			caps->caps_valid = false;
5232 		}
5233 	}
5234 
5235 	if (!caps->caps_valid) {
5236 		caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5237 		caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5238 		caps->caps_valid = true;
5239 	}
5240 #else
5241 	if (caps->aux_support)
5242 		return;
5243 
5244 	caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5245 	caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5246 	caps->caps_valid = true;
5247 #endif
5248 }
5249 
5250 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
5251 				unsigned int *min, unsigned int *max)
5252 {
5253 	if (!caps)
5254 		return 0;
5255 
5256 	if (caps->aux_support) {
5257 		// Firmware limits are in nits, DC API wants millinits.
5258 		*max = 1000 * caps->aux_max_input_signal;
5259 		*min = 1000 * caps->aux_min_input_signal;
5260 	} else {
5261 		// Firmware limits are 8-bit, PWM control is 16-bit.
5262 		*max = 0x101 * caps->max_input_signal;
5263 		*min = 0x101 * caps->min_input_signal;
5264 	}
5265 	return 1;
5266 }
5267 
5268 /* Rescale from [min..max] to [0..AMDGPU_MAX_BL_LEVEL] */
5269 static inline u32 scale_input_to_fw(int min, int max, u64 input)
5270 {
5271 	return DIV_ROUND_CLOSEST_ULL(input * AMDGPU_MAX_BL_LEVEL, max - min);
5272 }
5273 
5274 /* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [min..max] */
5275 static inline u32 scale_fw_to_input(int min, int max, u64 input)
5276 {
5277 	return min + DIV_ROUND_CLOSEST_ULL(input * (max - min), AMDGPU_MAX_BL_LEVEL);
5278 }
5279 
5280 static void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps,
5281 				      unsigned int min, unsigned int max,
5282 				      uint32_t *user_brightness)
5283 {
5284 	u32 brightness = scale_input_to_fw(min, max, *user_brightness);
5285 	u8 lower_signal, upper_signal, upper_lum, lower_lum, lum;
5286 	int left, right;
5287 
5288 	if (amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)
5289 		return;
5290 
5291 	if (!caps->data_points)
5292 		return;
5293 
5294 	/*
5295 	 * Handle the case where brightness is below the first data point
5296 	 * Interpolate between (0,0) and (first_signal, first_lum)
5297 	 */
5298 	if (brightness < caps->luminance_data[0].input_signal) {
5299 		lum = DIV_ROUND_CLOSEST(caps->luminance_data[0].luminance * brightness,
5300 					caps->luminance_data[0].input_signal);
5301 		goto scale;
5302 	}
5303 
5304 	left = 0;
5305 	right = caps->data_points - 1;
5306 	while (left <= right) {
5307 		int mid = left + (right - left) / 2;
5308 		u8 signal = caps->luminance_data[mid].input_signal;
5309 
5310 		/* Exact match found */
5311 		if (signal == brightness) {
5312 			lum = caps->luminance_data[mid].luminance;
5313 			goto scale;
5314 		}
5315 
5316 		if (signal < brightness)
5317 			left = mid + 1;
5318 		else
5319 			right = mid - 1;
5320 	}
5321 
5322 	/* verify bound */
5323 	if (left >= caps->data_points)
5324 		left = caps->data_points - 1;
5325 
5326 	/* At this point, left > right */
5327 	lower_signal = caps->luminance_data[right].input_signal;
5328 	upper_signal = caps->luminance_data[left].input_signal;
5329 	lower_lum = caps->luminance_data[right].luminance;
5330 	upper_lum = caps->luminance_data[left].luminance;
5331 
5332 	/* interpolate */
5333 	if (right == left || !lower_lum)
5334 		lum = upper_lum;
5335 	else
5336 		lum = lower_lum + DIV_ROUND_CLOSEST((upper_lum - lower_lum) *
5337 						    (brightness - lower_signal),
5338 						    upper_signal - lower_signal);
5339 scale:
5340 	*user_brightness = scale_fw_to_input(min, max,
5341 					     DIV_ROUND_CLOSEST(lum * brightness, 101));
5342 }
5343 
5344 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
5345 					uint32_t brightness)
5346 {
5347 	unsigned int min, max;
5348 
5349 	if (!get_brightness_range(caps, &min, &max))
5350 		return brightness;
5351 
5352 	convert_custom_brightness(caps, min, max, &brightness);
5353 
5354 	// Rescale 0..max to min..max
5355 	return min + DIV_ROUND_CLOSEST_ULL((u64)(max - min) * brightness, max);
5356 }
5357 
5358 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
5359 				      uint32_t brightness)
5360 {
5361 	unsigned int min, max;
5362 
5363 	if (!get_brightness_range(caps, &min, &max))
5364 		return brightness;
5365 
5366 	if (brightness < min)
5367 		return 0;
5368 	// Rescale min..max to 0..max
5369 	return DIV_ROUND_CLOSEST_ULL((u64)max * (brightness - min),
5370 				 max - min);
5371 }
5372 
5373 static struct dc_stream_state *dm_find_stream_with_link(
5374 	struct amdgpu_display_manager *dm,
5375 	struct dc_link *link)
5376 {
5377 	struct dc_state *cur_dc_state = dm->dc->current_state;
5378 	struct dc_stream_state *stream = NULL;
5379 	int i;
5380 
5381 	for (i = 0; i < cur_dc_state->stream_count; i++) {
5382 		stream = cur_dc_state->streams[i];
5383 		if (stream->link == link)
5384 			return stream;
5385 	}
5386 
5387 	return NULL;
5388 }
5389 
5390 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
5391 					 int bl_idx,
5392 					 u32 user_brightness)
5393 {
5394 	struct amdgpu_dm_backlight_caps *caps;
5395 	struct dc_link *link;
5396 	u32 brightness = 0;
5397 	bool rc = false, reallow_idle = false;
5398 	struct drm_connector *connector;
5399 	struct dc_stream_state *stream;
5400 	unsigned int min, max;
5401 
5402 	list_for_each_entry(connector, &dm->ddev->mode_config.connector_list, head) {
5403 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5404 
5405 		if (aconnector->bl_idx != bl_idx)
5406 			continue;
5407 
5408 		/* if connector is off, save the brightness for next time it's on */
5409 		if (!aconnector->base.encoder) {
5410 			dm->brightness[bl_idx] = user_brightness;
5411 			dm->actual_brightness[bl_idx] = 0;
5412 			return;
5413 		}
5414 	}
5415 
5416 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5417 	caps = &dm->backlight_caps[bl_idx];
5418 
5419 	dm->brightness[bl_idx] = user_brightness;
5420 	/* update scratch register */
5421 	if (bl_idx == 0)
5422 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
5423 	brightness = convert_brightness_from_user(caps, dm->brightness[bl_idx]);
5424 	link = (struct dc_link *)dm->backlight_link[bl_idx];
5425 
5426 	/* Apply brightness quirk */
5427 	if (caps->brightness_mask)
5428 		brightness |= caps->brightness_mask;
5429 
5430 	if (trace_amdgpu_dm_brightness_enabled()) {
5431 		trace_amdgpu_dm_brightness(__builtin_return_address(0),
5432 					   user_brightness,
5433 					   brightness,
5434 					   caps->aux_support,
5435 					   power_supply_is_system_supplied() > 0);
5436 	}
5437 
5438 	stream = dm_find_stream_with_link(dm, link);
5439 	if (!stream)
5440 		return;
5441 
5442 	mutex_lock(&dm->dc_lock);
5443 	if (dm->dc->caps.ips_support && dm->dc->ctx->dmub_srv->idle_allowed) {
5444 		dc_allow_idle_optimizations(dm->dc, false);
5445 		reallow_idle = true;
5446 	}
5447 
5448 	if (caps->aux_support) {
5449 		rc = mod_power_set_backlight_nits(dm->power_module, stream, brightness,
5450 			AUX_BL_DEFAULT_TRANSITION_TIME_MS, false, true);
5451 	} else {
5452 		/* power module uses millipercent */
5453 		get_brightness_range(caps, &min, &max);
5454 		brightness = DIV_ROUND_CLOSEST(brightness * 100, (max - min)) * 1000;
5455 		rc = mod_power_set_backlight_percent(dm->power_module, stream,
5456 						     brightness, 0, false);
5457 	}
5458 
5459 	/*
5460 	 * Some kms clients create a ramped backlight transition effect
5461 	 * by rapidly changing the backlight. Yet we must wait on dmcub
5462 	 * fw to exit psr/replay before programming backlight. To
5463 	 * prevent lag, keep disable psr/replay and let the next atomic
5464 	 * flip clear the event.
5465 	 *
5466 	 * ToDo: use ISM to handle rapidly backlight change
5467 	 *
5468 	 * Rapidly backlight change is similar to rapidly cursor events,
5469 	 * which is now handled by ISM. ISM can delay the event until system
5470 	 * is really idle, so we may use ISM to handle backlight change as well.
5471 	 */
5472 	amdgpu_dm_psr_set_event(dm, stream, true,
5473 		psr_event_hw_programming, true);
5474 	amdgpu_dm_replay_set_event(dm, stream, true,
5475 		replay_event_hw_programming, true);
5476 
5477 	if (dm->dc->caps.ips_support && reallow_idle)
5478 		dc_allow_idle_optimizations(dm->dc, true);
5479 
5480 	mutex_unlock(&dm->dc_lock);
5481 
5482 	if (rc)
5483 		dm->actual_brightness[bl_idx] = user_brightness;
5484 }
5485 
5486 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
5487 {
5488 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5489 	int i;
5490 
5491 	for (i = 0; i < dm->num_of_edps; i++) {
5492 		if (bd == dm->backlight_dev[i])
5493 			break;
5494 	}
5495 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5496 		i = 0;
5497 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
5498 
5499 	return 0;
5500 }
5501 
5502 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
5503 					 int bl_idx)
5504 {
5505 	int ret;
5506 	struct amdgpu_dm_backlight_caps caps;
5507 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
5508 
5509 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5510 	caps = dm->backlight_caps[bl_idx];
5511 
5512 	if (caps.aux_support) {
5513 		u32 avg, peak;
5514 
5515 		if (!dc_link_get_backlight_level_nits(link, &avg, &peak))
5516 			return dm->brightness[bl_idx];
5517 		return convert_brightness_to_user(&caps, avg);
5518 	}
5519 
5520 	ret = dc_link_get_backlight_level(link);
5521 
5522 	if (ret == DC_ERROR_UNEXPECTED)
5523 		return dm->brightness[bl_idx];
5524 
5525 	return convert_brightness_to_user(&caps, ret);
5526 }
5527 
5528 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
5529 {
5530 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5531 	int i;
5532 
5533 	for (i = 0; i < dm->num_of_edps; i++) {
5534 		if (bd == dm->backlight_dev[i])
5535 			break;
5536 	}
5537 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5538 		i = 0;
5539 	return amdgpu_dm_backlight_get_level(dm, i);
5540 }
5541 
5542 static const struct backlight_ops amdgpu_dm_backlight_ops = {
5543 	.options = BL_CORE_SUSPENDRESUME,
5544 	.get_brightness = amdgpu_dm_backlight_get_brightness,
5545 	.update_status	= amdgpu_dm_backlight_update_status,
5546 };
5547 
5548 static void
5549 amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector *aconnector)
5550 {
5551 	struct drm_device *drm = aconnector->base.dev;
5552 	struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
5553 	struct backlight_properties props = { 0 };
5554 	struct amdgpu_dm_backlight_caps *caps;
5555 	char bl_name[16];
5556 	int min, max;
5557 	int real_brightness;
5558 	int init_brightness;
5559 
5560 	if (aconnector->bl_idx == -1)
5561 		return;
5562 
5563 	if (!acpi_video_backlight_use_native()) {
5564 		drm_info(drm, "Skipping amdgpu DM backlight registration\n");
5565 		/* Try registering an ACPI video backlight device instead. */
5566 		acpi_video_register_backlight();
5567 		return;
5568 	}
5569 
5570 	caps = &dm->backlight_caps[aconnector->bl_idx];
5571 	if (get_brightness_range(caps, &min, &max)) {
5572 		if (power_supply_is_system_supplied() > 0)
5573 			props.brightness = DIV_ROUND_CLOSEST(max * caps->ac_level, 100);
5574 		else
5575 			props.brightness = DIV_ROUND_CLOSEST(max * caps->dc_level, 100);
5576 		/* min is zero, so max needs to be adjusted */
5577 		props.max_brightness = max;
5578 		drm_dbg(drm, "Backlight caps: min: %d, max: %d, ac %d, dc %d\n", min, max,
5579 			caps->ac_level, caps->dc_level);
5580 	} else
5581 		props.brightness = props.max_brightness = MAX_BACKLIGHT_LEVEL;
5582 
5583 	init_brightness = props.brightness;
5584 
5585 	if (caps->data_points && !(amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)) {
5586 		drm_info(drm, "Using custom brightness curve\n");
5587 		props.scale = BACKLIGHT_SCALE_NON_LINEAR;
5588 	} else
5589 		props.scale = BACKLIGHT_SCALE_LINEAR;
5590 	props.type = BACKLIGHT_RAW;
5591 
5592 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
5593 		 drm->primary->index + aconnector->bl_idx);
5594 
5595 	dm->backlight_dev[aconnector->bl_idx] =
5596 		backlight_device_register(bl_name, aconnector->base.kdev, dm,
5597 					  &amdgpu_dm_backlight_ops, &props);
5598 	dm->brightness[aconnector->bl_idx] = props.brightness;
5599 
5600 	if (IS_ERR(dm->backlight_dev[aconnector->bl_idx])) {
5601 		drm_err(drm, "DM: Backlight registration failed!\n");
5602 		dm->backlight_dev[aconnector->bl_idx] = NULL;
5603 	} else {
5604 		/*
5605 		 * dm->brightness[x] can be inconsistent just after startup until
5606 		 * ops.get_brightness is called.
5607 		 */
5608 		real_brightness =
5609 			amdgpu_dm_backlight_ops.get_brightness(dm->backlight_dev[aconnector->bl_idx]);
5610 
5611 		if (real_brightness != init_brightness) {
5612 			dm->actual_brightness[aconnector->bl_idx] = real_brightness;
5613 			dm->brightness[aconnector->bl_idx] = real_brightness;
5614 		}
5615 		drm_dbg_driver(drm, "DM: Registered Backlight device: %s\n", bl_name);
5616 	}
5617 }
5618 
5619 static int initialize_plane(struct amdgpu_display_manager *dm,
5620 			    struct amdgpu_mode_info *mode_info, int plane_id,
5621 			    enum drm_plane_type plane_type,
5622 			    const struct dc_plane_cap *plane_cap)
5623 {
5624 	struct drm_plane *plane;
5625 	unsigned long possible_crtcs;
5626 	int ret = 0;
5627 
5628 	plane = kzalloc_obj(struct drm_plane);
5629 	if (!plane) {
5630 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
5631 		return -ENOMEM;
5632 	}
5633 	plane->type = plane_type;
5634 
5635 	/*
5636 	 * HACK: IGT tests expect that the primary plane for a CRTC
5637 	 * can only have one possible CRTC. Only expose support for
5638 	 * any CRTC if they're not going to be used as a primary plane
5639 	 * for a CRTC - like overlay or underlay planes.
5640 	 */
5641 	possible_crtcs = 1 << plane_id;
5642 	if (plane_id >= dm->dc->caps.max_streams)
5643 		possible_crtcs = 0xff;
5644 
5645 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
5646 
5647 	if (ret) {
5648 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
5649 		kfree(plane);
5650 		return ret;
5651 	}
5652 
5653 	if (mode_info)
5654 		mode_info->planes[plane_id] = plane;
5655 
5656 	return ret;
5657 }
5658 
5659 
5660 static void setup_backlight_device(struct amdgpu_display_manager *dm,
5661 				   struct amdgpu_dm_connector *aconnector)
5662 {
5663 	struct amdgpu_dm_backlight_caps *caps;
5664 	struct dc_link *link = aconnector->dc_link;
5665 	int bl_idx = dm->num_of_edps;
5666 
5667 	if (!(link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) ||
5668 	    link->type == dc_connection_none)
5669 		return;
5670 
5671 	if (dm->num_of_edps >= AMDGPU_DM_MAX_NUM_EDP) {
5672 		drm_warn(adev_to_drm(dm->adev), "Too much eDP connections, skipping backlight setup for additional eDPs\n");
5673 		return;
5674 	}
5675 
5676 	aconnector->bl_idx = bl_idx;
5677 
5678 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5679 	dm->backlight_link[bl_idx] = link;
5680 	dm->num_of_edps++;
5681 
5682 	update_connector_ext_caps(aconnector);
5683 	caps = &dm->backlight_caps[aconnector->bl_idx];
5684 
5685 	/* Only offer ABM property when non-OLED and user didn't turn off by module parameter */
5686 	if (caps->ext_caps && !caps->ext_caps->bits.oled && amdgpu_dm_abm_level < 0)
5687 		drm_object_attach_property(&aconnector->base.base,
5688 					   dm->adev->mode_info.abm_level_property,
5689 					   ABM_SYSFS_CONTROL);
5690 }
5691 
5692 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
5693 
5694 
5695 
5696 /*
5697  * In this architecture, the association
5698  * connector -> encoder -> crtc
5699  * id not really requried. The crtc and connector will hold the
5700  * display_index as an abstraction to use with DAL component
5701  *
5702  * Returns 0 on success
5703  */
5704 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
5705 {
5706 	struct amdgpu_display_manager *dm = &adev->dm;
5707 	s32 i;
5708 	struct amdgpu_dm_connector *aconnector = NULL;
5709 	struct amdgpu_encoder *aencoder = NULL;
5710 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5711 	u32 link_cnt;
5712 	s32 primary_planes;
5713 	enum dc_connection_type new_connection_type = dc_connection_none;
5714 	const struct dc_plane_cap *plane;
5715 	bool psr_feature_enabled = false;
5716 	bool replay_feature_enabled = false;
5717 	int max_overlay = dm->dc->caps.max_slave_planes;
5718 
5719 	dm->display_indexes_num = dm->dc->caps.max_streams;
5720 	/* Update the actual used number of crtc */
5721 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
5722 
5723 	amdgpu_dm_set_irq_funcs(adev);
5724 
5725 	link_cnt = dm->dc->caps.max_links;
5726 	if (amdgpu_dm_mode_config_init(dm->adev)) {
5727 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
5728 		return -EINVAL;
5729 	}
5730 
5731 	/* There is one primary plane per CRTC */
5732 	primary_planes = dm->dc->caps.max_streams;
5733 	if (primary_planes > AMDGPU_MAX_PLANES) {
5734 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
5735 		return -EINVAL;
5736 	}
5737 
5738 	/*
5739 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
5740 	 * Order is reversed to match iteration order in atomic check.
5741 	 */
5742 	for (i = (primary_planes - 1); i >= 0; i--) {
5743 		plane = &dm->dc->caps.planes[i];
5744 
5745 		if (initialize_plane(dm, mode_info, i,
5746 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
5747 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
5748 			goto fail;
5749 		}
5750 	}
5751 
5752 	/*
5753 	 * Initialize overlay planes, index starting after primary planes.
5754 	 * These planes have a higher DRM index than the primary planes since
5755 	 * they should be considered as having a higher z-order.
5756 	 * Order is reversed to match iteration order in atomic check.
5757 	 *
5758 	 * Only support DCN for now, and only expose one so we don't encourage
5759 	 * userspace to use up all the pipes.
5760 	 */
5761 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
5762 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
5763 
5764 		/* Do not create overlay if MPO disabled */
5765 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
5766 			break;
5767 
5768 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
5769 			continue;
5770 
5771 		if (!plane->pixel_format_support.argb8888)
5772 			continue;
5773 
5774 		if (max_overlay-- == 0)
5775 			break;
5776 
5777 		if (initialize_plane(dm, NULL, primary_planes + i,
5778 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
5779 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
5780 			goto fail;
5781 		}
5782 	}
5783 
5784 	for (i = 0; i < dm->dc->caps.max_streams; i++)
5785 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
5786 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
5787 			goto fail;
5788 		}
5789 
5790 	/* Use Outbox interrupt */
5791 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5792 	case IP_VERSION(3, 0, 0):
5793 	case IP_VERSION(3, 1, 2):
5794 	case IP_VERSION(3, 1, 3):
5795 	case IP_VERSION(3, 1, 4):
5796 	case IP_VERSION(3, 1, 5):
5797 	case IP_VERSION(3, 1, 6):
5798 	case IP_VERSION(3, 2, 0):
5799 	case IP_VERSION(3, 2, 1):
5800 	case IP_VERSION(2, 1, 0):
5801 	case IP_VERSION(3, 5, 0):
5802 	case IP_VERSION(3, 5, 1):
5803 	case IP_VERSION(3, 6, 0):
5804 	case IP_VERSION(4, 0, 1):
5805 	case IP_VERSION(4, 2, 0):
5806 	case IP_VERSION(4, 2, 1):
5807 		if (register_outbox_irq_handlers(dm->adev)) {
5808 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5809 			goto fail;
5810 		}
5811 		break;
5812 	default:
5813 		drm_dbg_kms(adev_to_drm(adev), "Unsupported DCN IP version for outbox: 0x%X\n",
5814 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
5815 	}
5816 
5817 	/* Determine whether to enable PSR support by default. */
5818 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
5819 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5820 		case IP_VERSION(3, 1, 2):
5821 		case IP_VERSION(3, 1, 3):
5822 		case IP_VERSION(3, 1, 4):
5823 		case IP_VERSION(3, 1, 5):
5824 		case IP_VERSION(3, 1, 6):
5825 		case IP_VERSION(3, 2, 0):
5826 		case IP_VERSION(3, 2, 1):
5827 		case IP_VERSION(3, 5, 0):
5828 		case IP_VERSION(3, 5, 1):
5829 		case IP_VERSION(3, 6, 0):
5830 		case IP_VERSION(4, 0, 1):
5831 		case IP_VERSION(4, 2, 0):
5832 		case IP_VERSION(4, 2, 1):
5833 			psr_feature_enabled = true;
5834 			break;
5835 		default:
5836 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
5837 			break;
5838 		}
5839 	}
5840 
5841 	/* Determine whether to enable Replay support by default. */
5842 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
5843 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5844 		case IP_VERSION(3, 1, 4):
5845 		case IP_VERSION(3, 2, 0):
5846 		case IP_VERSION(3, 2, 1):
5847 		case IP_VERSION(3, 5, 0):
5848 		case IP_VERSION(3, 5, 1):
5849 		case IP_VERSION(3, 6, 0):
5850 		case IP_VERSION(4, 2, 0):
5851 		case IP_VERSION(4, 2, 1):
5852 			replay_feature_enabled = true;
5853 			break;
5854 
5855 		default:
5856 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
5857 			break;
5858 		}
5859 	}
5860 
5861 	if (link_cnt > MAX_LINKS) {
5862 		drm_err(adev_to_drm(adev),
5863 			"KMS: Cannot support more than %d display indexes\n",
5864 				MAX_LINKS);
5865 		goto fail;
5866 	}
5867 
5868 	/* loops over all connectors on the board */
5869 	for (i = 0; i < link_cnt; i++) {
5870 		struct dc_link *link = NULL;
5871 
5872 		link = dc_get_link_at_index(dm->dc, i);
5873 
5874 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
5875 			struct amdgpu_dm_wb_connector *wbcon = kzalloc_obj(*wbcon);
5876 
5877 			if (!wbcon) {
5878 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
5879 				continue;
5880 			}
5881 
5882 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
5883 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
5884 				kfree(wbcon);
5885 				continue;
5886 			}
5887 
5888 			link->psr_settings.psr_feature_enabled = false;
5889 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
5890 
5891 			continue;
5892 		}
5893 
5894 		aconnector = kzalloc_obj(*aconnector);
5895 		if (!aconnector)
5896 			goto fail;
5897 
5898 		aencoder = kzalloc_obj(*aencoder);
5899 		if (!aencoder)
5900 			goto fail;
5901 
5902 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
5903 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
5904 			goto fail;
5905 		}
5906 
5907 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
5908 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
5909 			goto fail;
5910 		}
5911 
5912 		if (dm->hpd_rx_offload_wq)
5913 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
5914 				aconnector;
5915 
5916 		if (!dc_link_detect_connection_type(link, &new_connection_type))
5917 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
5918 
5919 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
5920 			emulated_link_detect(link);
5921 			amdgpu_dm_update_connector_after_detect(aconnector);
5922 		} else {
5923 			bool ret = false;
5924 
5925 			mutex_lock(&dm->dc_lock);
5926 			dc_exit_ips_for_hw_access(dm->dc);
5927 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
5928 			mutex_unlock(&dm->dc_lock);
5929 
5930 			if (ret) {
5931 				amdgpu_dm_update_connector_after_detect(aconnector);
5932 				setup_backlight_device(dm, aconnector);
5933 
5934 				/* Disable PSR if Replay can be enabled */
5935 				if (replay_feature_enabled)
5936 					if (amdgpu_dm_set_replay_caps(link, aconnector))
5937 						psr_feature_enabled = false;
5938 
5939 				if (psr_feature_enabled) {
5940 					amdgpu_dm_set_psr_caps(link, aconnector);
5941 					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",
5942 						 aconnector->base.name,
5943 						 link->psr_settings.psr_feature_enabled,
5944 						 link->psr_settings.psr_version,
5945 						 link->dpcd_caps.psr_info.psr_version,
5946 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
5947 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
5948 				}
5949 			}
5950 		}
5951 		amdgpu_set_panel_orientation(&aconnector->base);
5952 	}
5953 
5954 	/* Debug dump: list all DC links and their associated sinks after detection
5955 	 * is complete for all connectors. This provides a comprehensive view of the
5956 	 * final state without repeating the dump for each connector.
5957 	 */
5958 	amdgpu_dm_dump_links_and_sinks(adev);
5959 
5960 	/* Software is initialized. Now we can register interrupt handlers. */
5961 	switch (adev->asic_type) {
5962 #if defined(CONFIG_DRM_AMD_DC_SI)
5963 	case CHIP_TAHITI:
5964 	case CHIP_PITCAIRN:
5965 	case CHIP_VERDE:
5966 	case CHIP_OLAND:
5967 #endif
5968 	case CHIP_BONAIRE:
5969 	case CHIP_HAWAII:
5970 	case CHIP_KAVERI:
5971 	case CHIP_KABINI:
5972 	case CHIP_MULLINS:
5973 	case CHIP_TONGA:
5974 	case CHIP_FIJI:
5975 	case CHIP_CARRIZO:
5976 	case CHIP_STONEY:
5977 	case CHIP_POLARIS11:
5978 	case CHIP_POLARIS10:
5979 	case CHIP_POLARIS12:
5980 	case CHIP_VEGAM:
5981 	case CHIP_VEGA10:
5982 	case CHIP_VEGA12:
5983 	case CHIP_VEGA20:
5984 		if (dce110_register_irq_handlers(dm->adev)) {
5985 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5986 			goto fail;
5987 		}
5988 		break;
5989 	default:
5990 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5991 		case IP_VERSION(1, 0, 0):
5992 		case IP_VERSION(1, 0, 1):
5993 		case IP_VERSION(2, 0, 2):
5994 		case IP_VERSION(2, 0, 3):
5995 		case IP_VERSION(2, 0, 0):
5996 		case IP_VERSION(2, 1, 0):
5997 		case IP_VERSION(3, 0, 0):
5998 		case IP_VERSION(3, 0, 2):
5999 		case IP_VERSION(3, 0, 3):
6000 		case IP_VERSION(3, 0, 1):
6001 		case IP_VERSION(3, 1, 2):
6002 		case IP_VERSION(3, 1, 3):
6003 		case IP_VERSION(3, 1, 4):
6004 		case IP_VERSION(3, 1, 5):
6005 		case IP_VERSION(3, 1, 6):
6006 		case IP_VERSION(3, 2, 0):
6007 		case IP_VERSION(3, 2, 1):
6008 		case IP_VERSION(3, 5, 0):
6009 		case IP_VERSION(3, 5, 1):
6010 		case IP_VERSION(3, 6, 0):
6011 		case IP_VERSION(4, 0, 1):
6012 		case IP_VERSION(4, 2, 0):
6013 		case IP_VERSION(4, 2, 1):
6014 			if (dcn10_register_irq_handlers(dm->adev)) {
6015 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
6016 				goto fail;
6017 			}
6018 			break;
6019 		default:
6020 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
6021 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6022 			goto fail;
6023 		}
6024 		break;
6025 	}
6026 
6027 	return 0;
6028 fail:
6029 	kfree(aencoder);
6030 	kfree(aconnector);
6031 
6032 	return -EINVAL;
6033 }
6034 
6035 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
6036 {
6037 	if (dm->atomic_obj.state)
6038 		drm_atomic_private_obj_fini(&dm->atomic_obj);
6039 }
6040 
6041 /******************************************************************************
6042  * amdgpu_display_funcs functions
6043  *****************************************************************************/
6044 
6045 /*
6046  * dm_bandwidth_update - program display watermarks
6047  *
6048  * @adev: amdgpu_device pointer
6049  *
6050  * Calculate and program the display watermarks and line buffer allocation.
6051  */
6052 static void dm_bandwidth_update(struct amdgpu_device *adev)
6053 {
6054 	/* TODO: implement later */
6055 }
6056 
6057 static const struct amdgpu_display_funcs dm_display_funcs = {
6058 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
6059 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
6060 	.backlight_set_level = NULL, /* never called for DC */
6061 	.backlight_get_level = NULL, /* never called for DC */
6062 	.hpd_sense = NULL,/* called unconditionally */
6063 	.hpd_set_polarity = NULL, /* called unconditionally */
6064 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
6065 	.page_flip_get_scanoutpos =
6066 		dm_crtc_get_scanoutpos,/* called unconditionally */
6067 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
6068 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
6069 };
6070 
6071 #if defined(CONFIG_DEBUG_KERNEL_DC)
6072 
6073 static ssize_t s3_debug_store(struct device *device,
6074 			      struct device_attribute *attr,
6075 			      const char *buf,
6076 			      size_t count)
6077 {
6078 	int ret;
6079 	int s3_state;
6080 	struct drm_device *drm_dev = dev_get_drvdata(device);
6081 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
6082 	struct amdgpu_ip_block *ip_block;
6083 
6084 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
6085 	if (!ip_block)
6086 		return -EINVAL;
6087 
6088 	ret = kstrtoint(buf, 0, &s3_state);
6089 
6090 	if (ret == 0) {
6091 		if (s3_state) {
6092 			dm_resume(ip_block);
6093 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
6094 		} else
6095 			dm_suspend(ip_block);
6096 	}
6097 
6098 	return ret == 0 ? count : 0;
6099 }
6100 
6101 DEVICE_ATTR_WO(s3_debug);
6102 
6103 #endif
6104 
6105 static int dm_init_microcode(struct amdgpu_device *adev)
6106 {
6107 	char *fw_name_dmub;
6108 	int r;
6109 
6110 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6111 	case IP_VERSION(2, 1, 0):
6112 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
6113 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
6114 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
6115 		break;
6116 	case IP_VERSION(3, 0, 0):
6117 		if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(10, 3, 0))
6118 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
6119 		else
6120 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
6121 		break;
6122 	case IP_VERSION(3, 0, 1):
6123 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
6124 		break;
6125 	case IP_VERSION(3, 0, 2):
6126 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
6127 		break;
6128 	case IP_VERSION(3, 0, 3):
6129 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
6130 		break;
6131 	case IP_VERSION(3, 1, 2):
6132 	case IP_VERSION(3, 1, 3):
6133 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
6134 		break;
6135 	case IP_VERSION(3, 1, 4):
6136 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
6137 		break;
6138 	case IP_VERSION(3, 1, 5):
6139 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
6140 		break;
6141 	case IP_VERSION(3, 1, 6):
6142 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
6143 		break;
6144 	case IP_VERSION(3, 2, 0):
6145 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
6146 		break;
6147 	case IP_VERSION(3, 2, 1):
6148 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
6149 		break;
6150 	case IP_VERSION(3, 5, 0):
6151 		fw_name_dmub = FIRMWARE_DCN_35_DMUB;
6152 		break;
6153 	case IP_VERSION(3, 5, 1):
6154 		fw_name_dmub = FIRMWARE_DCN_351_DMUB;
6155 		break;
6156 	case IP_VERSION(3, 6, 0):
6157 		fw_name_dmub = FIRMWARE_DCN_36_DMUB;
6158 		break;
6159 	case IP_VERSION(4, 0, 1):
6160 		fw_name_dmub = FIRMWARE_DCN_401_DMUB;
6161 		break;
6162 	case IP_VERSION(4, 2, 0):
6163 		fw_name_dmub = FIRMWARE_DCN_42_DMUB;
6164 		break;
6165 	case IP_VERSION(4, 2, 1):
6166 		fw_name_dmub = FIRMWARE_DCN_42B_DMUB;
6167 		break;
6168 	default:
6169 		/* ASIC doesn't support DMUB. */
6170 		return 0;
6171 	}
6172 	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, AMDGPU_UCODE_REQUIRED,
6173 				 "%s", fw_name_dmub);
6174 	return r;
6175 }
6176 
6177 static int dm_early_init(struct amdgpu_ip_block *ip_block)
6178 {
6179 	struct amdgpu_device *adev = ip_block->adev;
6180 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
6181 	struct atom_context *ctx = mode_info->atom_context;
6182 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
6183 	u16 data_offset;
6184 
6185 	/* if there is no object header, skip DM */
6186 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
6187 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
6188 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
6189 		return -ENOENT;
6190 	}
6191 
6192 	switch (adev->asic_type) {
6193 #if defined(CONFIG_DRM_AMD_DC_SI)
6194 	case CHIP_TAHITI:
6195 	case CHIP_PITCAIRN:
6196 	case CHIP_VERDE:
6197 		adev->mode_info.num_crtc = 6;
6198 		adev->mode_info.num_hpd = 6;
6199 		adev->mode_info.num_dig = 6;
6200 		break;
6201 	case CHIP_OLAND:
6202 		adev->mode_info.num_crtc = 2;
6203 		adev->mode_info.num_hpd = 2;
6204 		adev->mode_info.num_dig = 2;
6205 		break;
6206 #endif
6207 	case CHIP_BONAIRE:
6208 	case CHIP_HAWAII:
6209 		adev->mode_info.num_crtc = 6;
6210 		adev->mode_info.num_hpd = 6;
6211 		adev->mode_info.num_dig = 6;
6212 		break;
6213 	case CHIP_KAVERI:
6214 		adev->mode_info.num_crtc = 4;
6215 		adev->mode_info.num_hpd = 6;
6216 		adev->mode_info.num_dig = 7;
6217 		break;
6218 	case CHIP_KABINI:
6219 	case CHIP_MULLINS:
6220 		adev->mode_info.num_crtc = 2;
6221 		adev->mode_info.num_hpd = 6;
6222 		adev->mode_info.num_dig = 6;
6223 		break;
6224 	case CHIP_FIJI:
6225 	case CHIP_TONGA:
6226 		adev->mode_info.num_crtc = 6;
6227 		adev->mode_info.num_hpd = 6;
6228 		adev->mode_info.num_dig = 7;
6229 		break;
6230 	case CHIP_CARRIZO:
6231 		adev->mode_info.num_crtc = 3;
6232 		adev->mode_info.num_hpd = 6;
6233 		adev->mode_info.num_dig = 9;
6234 		break;
6235 	case CHIP_STONEY:
6236 		adev->mode_info.num_crtc = 2;
6237 		adev->mode_info.num_hpd = 6;
6238 		adev->mode_info.num_dig = 9;
6239 		break;
6240 	case CHIP_POLARIS11:
6241 	case CHIP_POLARIS12:
6242 		adev->mode_info.num_crtc = 5;
6243 		adev->mode_info.num_hpd = 5;
6244 		adev->mode_info.num_dig = 5;
6245 		break;
6246 	case CHIP_POLARIS10:
6247 	case CHIP_VEGAM:
6248 		adev->mode_info.num_crtc = 6;
6249 		adev->mode_info.num_hpd = 6;
6250 		adev->mode_info.num_dig = 6;
6251 		break;
6252 	case CHIP_VEGA10:
6253 	case CHIP_VEGA12:
6254 	case CHIP_VEGA20:
6255 		adev->mode_info.num_crtc = 6;
6256 		adev->mode_info.num_hpd = 6;
6257 		adev->mode_info.num_dig = 6;
6258 		break;
6259 	default:
6260 
6261 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6262 		case IP_VERSION(2, 0, 2):
6263 		case IP_VERSION(3, 0, 0):
6264 			adev->mode_info.num_crtc = 6;
6265 			adev->mode_info.num_hpd = 6;
6266 			adev->mode_info.num_dig = 6;
6267 			break;
6268 		case IP_VERSION(2, 0, 0):
6269 		case IP_VERSION(3, 0, 2):
6270 			adev->mode_info.num_crtc = 5;
6271 			adev->mode_info.num_hpd = 5;
6272 			adev->mode_info.num_dig = 5;
6273 			break;
6274 		case IP_VERSION(2, 0, 3):
6275 		case IP_VERSION(3, 0, 3):
6276 			adev->mode_info.num_crtc = 2;
6277 			adev->mode_info.num_hpd = 2;
6278 			adev->mode_info.num_dig = 2;
6279 			break;
6280 		case IP_VERSION(1, 0, 0):
6281 		case IP_VERSION(1, 0, 1):
6282 		case IP_VERSION(3, 0, 1):
6283 		case IP_VERSION(2, 1, 0):
6284 		case IP_VERSION(3, 1, 2):
6285 		case IP_VERSION(3, 1, 3):
6286 		case IP_VERSION(3, 1, 4):
6287 		case IP_VERSION(3, 1, 5):
6288 		case IP_VERSION(3, 1, 6):
6289 		case IP_VERSION(3, 2, 0):
6290 		case IP_VERSION(3, 2, 1):
6291 		case IP_VERSION(3, 5, 0):
6292 		case IP_VERSION(3, 5, 1):
6293 		case IP_VERSION(3, 6, 0):
6294 		case IP_VERSION(4, 0, 1):
6295 		case IP_VERSION(4, 2, 0):
6296 		case IP_VERSION(4, 2, 1):
6297 			adev->mode_info.num_crtc = 4;
6298 			adev->mode_info.num_hpd = 4;
6299 			adev->mode_info.num_dig = 4;
6300 			break;
6301 		default:
6302 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
6303 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6304 			return -EINVAL;
6305 		}
6306 		break;
6307 	}
6308 
6309 	if (adev->mode_info.funcs == NULL)
6310 		adev->mode_info.funcs = &dm_display_funcs;
6311 
6312 	/*
6313 	 * Note: Do NOT change adev->reg.audio_endpt.rreg and
6314 	 * adev->reg.audio_endpt.wreg because they are initialised in
6315 	 * amdgpu_device_init()
6316 	 */
6317 #if defined(CONFIG_DEBUG_KERNEL_DC)
6318 	device_create_file(
6319 		adev_to_drm(adev)->dev,
6320 		&dev_attr_s3_debug);
6321 #endif
6322 	adev->dc_enabled = true;
6323 
6324 	return dm_init_microcode(adev);
6325 }
6326 
6327 static bool modereset_required(struct drm_crtc_state *crtc_state)
6328 {
6329 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
6330 }
6331 
6332 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
6333 {
6334 	drm_encoder_cleanup(encoder);
6335 	kfree(encoder);
6336 }
6337 
6338 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
6339 	.destroy = amdgpu_dm_encoder_destroy,
6340 };
6341 
6342 static int
6343 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
6344 			    const enum surface_pixel_format format,
6345 			    enum dc_color_space *color_space)
6346 {
6347 	bool full_range;
6348 
6349 	*color_space = COLOR_SPACE_SRGB;
6350 
6351 	/* Ignore properties when DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE is set */
6352 	if (plane_state->state && plane_state->state->plane_color_pipeline)
6353 		return 0;
6354 
6355 	/* DRM color properties only affect non-RGB formats. */
6356 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
6357 		return 0;
6358 
6359 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
6360 
6361 	switch (plane_state->color_encoding) {
6362 	case DRM_COLOR_YCBCR_BT601:
6363 		if (full_range)
6364 			*color_space = COLOR_SPACE_YCBCR601;
6365 		else
6366 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
6367 		break;
6368 
6369 	case DRM_COLOR_YCBCR_BT709:
6370 		if (full_range)
6371 			*color_space = COLOR_SPACE_YCBCR709;
6372 		else
6373 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
6374 		break;
6375 
6376 	case DRM_COLOR_YCBCR_BT2020:
6377 		if (full_range)
6378 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
6379 		else
6380 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6381 		break;
6382 
6383 	default:
6384 		return -EINVAL;
6385 	}
6386 
6387 	return 0;
6388 }
6389 
6390 static int
6391 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
6392 			    const struct drm_plane_state *plane_state,
6393 			    const u64 tiling_flags,
6394 			    struct dc_plane_info *plane_info,
6395 			    struct dc_plane_address *address,
6396 			    bool tmz_surface)
6397 {
6398 	const struct drm_framebuffer *fb = plane_state->fb;
6399 	const struct amdgpu_framebuffer *afb =
6400 		to_amdgpu_framebuffer(plane_state->fb);
6401 	int ret;
6402 
6403 	memset(plane_info, 0, sizeof(*plane_info));
6404 
6405 	switch (fb->format->format) {
6406 	case DRM_FORMAT_C8:
6407 		plane_info->format =
6408 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
6409 		break;
6410 	case DRM_FORMAT_RGB565:
6411 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
6412 		break;
6413 	case DRM_FORMAT_XRGB8888:
6414 	case DRM_FORMAT_ARGB8888:
6415 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6416 		break;
6417 	case DRM_FORMAT_XRGB2101010:
6418 	case DRM_FORMAT_ARGB2101010:
6419 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
6420 		break;
6421 	case DRM_FORMAT_XBGR2101010:
6422 	case DRM_FORMAT_ABGR2101010:
6423 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
6424 		break;
6425 	case DRM_FORMAT_XBGR8888:
6426 	case DRM_FORMAT_ABGR8888:
6427 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
6428 		break;
6429 	case DRM_FORMAT_NV21:
6430 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
6431 		break;
6432 	case DRM_FORMAT_NV12:
6433 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
6434 		break;
6435 	case DRM_FORMAT_P010:
6436 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
6437 		break;
6438 	case DRM_FORMAT_XRGB16161616F:
6439 	case DRM_FORMAT_ARGB16161616F:
6440 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
6441 		break;
6442 	case DRM_FORMAT_XBGR16161616F:
6443 	case DRM_FORMAT_ABGR16161616F:
6444 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
6445 		break;
6446 	case DRM_FORMAT_XRGB16161616:
6447 	case DRM_FORMAT_ARGB16161616:
6448 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
6449 		break;
6450 	case DRM_FORMAT_XBGR16161616:
6451 	case DRM_FORMAT_ABGR16161616:
6452 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
6453 		break;
6454 	default:
6455 		drm_err(adev_to_drm(adev),
6456 			"Unsupported screen format %p4cc\n",
6457 			&fb->format->format);
6458 		return -EINVAL;
6459 	}
6460 
6461 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
6462 	case DRM_MODE_ROTATE_0:
6463 		plane_info->rotation = ROTATION_ANGLE_0;
6464 		break;
6465 	case DRM_MODE_ROTATE_90:
6466 		plane_info->rotation = ROTATION_ANGLE_90;
6467 		break;
6468 	case DRM_MODE_ROTATE_180:
6469 		plane_info->rotation = ROTATION_ANGLE_180;
6470 		break;
6471 	case DRM_MODE_ROTATE_270:
6472 		plane_info->rotation = ROTATION_ANGLE_270;
6473 		break;
6474 	default:
6475 		plane_info->rotation = ROTATION_ANGLE_0;
6476 		break;
6477 	}
6478 
6479 
6480 	plane_info->visible = true;
6481 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
6482 
6483 	plane_info->layer_index = plane_state->normalized_zpos;
6484 
6485 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
6486 					  &plane_info->color_space);
6487 	if (ret)
6488 		return ret;
6489 
6490 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
6491 					   plane_info->rotation, tiling_flags,
6492 					   &plane_info->tiling_info,
6493 					   &plane_info->plane_size,
6494 					   &plane_info->dcc, address,
6495 					   tmz_surface);
6496 	if (ret)
6497 		return ret;
6498 
6499 	amdgpu_dm_plane_fill_blending_from_plane_state(
6500 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
6501 		&plane_info->global_alpha, &plane_info->global_alpha_value);
6502 
6503 	return 0;
6504 }
6505 
6506 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
6507 				    struct dc_plane_state *dc_plane_state,
6508 				    struct drm_plane_state *plane_state,
6509 				    struct drm_crtc_state *crtc_state)
6510 {
6511 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6512 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
6513 	struct dc_scaling_info scaling_info;
6514 	struct dc_plane_info plane_info;
6515 	int ret;
6516 
6517 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
6518 	if (ret)
6519 		return ret;
6520 
6521 	dc_plane_state->src_rect = scaling_info.src_rect;
6522 	dc_plane_state->dst_rect = scaling_info.dst_rect;
6523 	dc_plane_state->clip_rect = scaling_info.clip_rect;
6524 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
6525 
6526 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
6527 					  afb->tiling_flags,
6528 					  &plane_info,
6529 					  &dc_plane_state->address,
6530 					  afb->tmz_surface);
6531 	if (ret)
6532 		return ret;
6533 
6534 	dc_plane_state->format = plane_info.format;
6535 	dc_plane_state->color_space = plane_info.color_space;
6536 	dc_plane_state->format = plane_info.format;
6537 	dc_plane_state->plane_size = plane_info.plane_size;
6538 	dc_plane_state->rotation = plane_info.rotation;
6539 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
6540 	dc_plane_state->stereo_format = plane_info.stereo_format;
6541 	dc_plane_state->tiling_info = plane_info.tiling_info;
6542 	dc_plane_state->visible = plane_info.visible;
6543 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
6544 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
6545 	dc_plane_state->global_alpha = plane_info.global_alpha;
6546 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
6547 	dc_plane_state->dcc = plane_info.dcc;
6548 	dc_plane_state->layer_index = plane_info.layer_index;
6549 	dc_plane_state->flip_int_enabled = true;
6550 
6551 	/*
6552 	 * Always set input transfer function, since plane state is refreshed
6553 	 * every time.
6554 	 */
6555 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
6556 						plane_state,
6557 						dc_plane_state);
6558 	if (ret)
6559 		return ret;
6560 
6561 	return 0;
6562 }
6563 
6564 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
6565 				      struct rect *dirty_rect, int32_t x,
6566 				      s32 y, s32 width, s32 height,
6567 				      int *i, bool ffu)
6568 {
6569 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
6570 
6571 	dirty_rect->x = x;
6572 	dirty_rect->y = y;
6573 	dirty_rect->width = width;
6574 	dirty_rect->height = height;
6575 
6576 	if (ffu)
6577 		drm_dbg(plane->dev,
6578 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
6579 			plane->base.id, width, height);
6580 	else
6581 		drm_dbg(plane->dev,
6582 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
6583 			plane->base.id, x, y, width, height);
6584 
6585 	(*i)++;
6586 }
6587 
6588 /**
6589  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
6590  *
6591  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
6592  *         remote fb
6593  * @old_plane_state: Old state of @plane
6594  * @new_plane_state: New state of @plane
6595  * @crtc_state: New state of CRTC connected to the @plane
6596  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
6597  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
6598  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
6599  *             that have changed will be updated. If PSR SU is not enabled,
6600  *             or if damage clips are not available, the entire screen will be updated.
6601  * @dirty_regions_changed: dirty regions changed
6602  *
6603  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
6604  * (referred to as "damage clips" in DRM nomenclature) that require updating on
6605  * the eDP remote buffer. The responsibility of specifying the dirty regions is
6606  * amdgpu_dm's.
6607  *
6608  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
6609  * plane with regions that require flushing to the eDP remote buffer. In
6610  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
6611  * implicitly provide damage clips without any client support via the plane
6612  * bounds.
6613  */
6614 static void fill_dc_dirty_rects(struct drm_plane *plane,
6615 				struct drm_plane_state *old_plane_state,
6616 				struct drm_plane_state *new_plane_state,
6617 				struct drm_crtc_state *crtc_state,
6618 				struct dc_flip_addrs *flip_addrs,
6619 				bool is_psr_su,
6620 				bool *dirty_regions_changed)
6621 {
6622 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6623 	struct rect *dirty_rects = flip_addrs->dirty_rects;
6624 	u32 num_clips = 0;
6625 	struct drm_mode_rect *clips = NULL;
6626 	bool bb_changed;
6627 	bool fb_changed;
6628 	u32 i = 0;
6629 	*dirty_regions_changed = false;
6630 
6631 	/*
6632 	 * Cursor plane has it's own dirty rect update interface. See
6633 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
6634 	 */
6635 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
6636 		return;
6637 
6638 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
6639 		goto ffu;
6640 
6641 	if (!new_plane_state->ignore_damage_clips) {
6642 		num_clips = drm_plane_get_damage_clips_count(new_plane_state);
6643 		clips = drm_plane_get_damage_clips(new_plane_state);
6644 	}
6645 
6646 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
6647 						   is_psr_su)))
6648 		goto ffu;
6649 
6650 	if (!dm_crtc_state->mpo_requested) {
6651 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
6652 			goto ffu;
6653 
6654 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
6655 			fill_dc_dirty_rect(new_plane_state->plane,
6656 					   &dirty_rects[flip_addrs->dirty_rect_count],
6657 					   clips->x1, clips->y1,
6658 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
6659 					   &flip_addrs->dirty_rect_count,
6660 					   false);
6661 		return;
6662 	}
6663 
6664 	/*
6665 	 * MPO is requested. Add entire plane bounding box to dirty rects if
6666 	 * flipped to or damaged.
6667 	 *
6668 	 * If plane is moved or resized, also add old bounding box to dirty
6669 	 * rects.
6670 	 */
6671 	fb_changed = old_plane_state->fb->base.id !=
6672 		     new_plane_state->fb->base.id;
6673 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
6674 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
6675 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
6676 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
6677 
6678 	drm_dbg(plane->dev,
6679 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
6680 		new_plane_state->plane->base.id,
6681 		bb_changed, fb_changed, num_clips);
6682 
6683 	*dirty_regions_changed = bb_changed;
6684 
6685 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
6686 		goto ffu;
6687 
6688 	if (bb_changed) {
6689 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6690 				   new_plane_state->crtc_x,
6691 				   new_plane_state->crtc_y,
6692 				   new_plane_state->crtc_w,
6693 				   new_plane_state->crtc_h, &i, false);
6694 
6695 		/* Add old plane bounding-box if plane is moved or resized */
6696 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6697 				   old_plane_state->crtc_x,
6698 				   old_plane_state->crtc_y,
6699 				   old_plane_state->crtc_w,
6700 				   old_plane_state->crtc_h, &i, false);
6701 	}
6702 
6703 	if (num_clips) {
6704 		for (; i < num_clips; clips++)
6705 			fill_dc_dirty_rect(new_plane_state->plane,
6706 					   &dirty_rects[i], clips->x1,
6707 					   clips->y1, clips->x2 - clips->x1,
6708 					   clips->y2 - clips->y1, &i, false);
6709 	} else if (fb_changed && !bb_changed) {
6710 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6711 				   new_plane_state->crtc_x,
6712 				   new_plane_state->crtc_y,
6713 				   new_plane_state->crtc_w,
6714 				   new_plane_state->crtc_h, &i, false);
6715 	}
6716 
6717 	flip_addrs->dirty_rect_count = i;
6718 	return;
6719 
6720 ffu:
6721 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
6722 			   dm_crtc_state->base.mode.crtc_hdisplay,
6723 			   dm_crtc_state->base.mode.crtc_vdisplay,
6724 			   &flip_addrs->dirty_rect_count, true);
6725 }
6726 
6727 static void update_stream_scaling_settings(struct drm_device *dev,
6728 					   const struct drm_display_mode *mode,
6729 					   const struct dm_connector_state *dm_state,
6730 					   struct dc_stream_state *stream)
6731 {
6732 	enum amdgpu_rmx_type rmx_type;
6733 
6734 	struct rect src = { 0 }; /* viewport in composition space*/
6735 	struct rect dst = { 0 }; /* stream addressable area */
6736 
6737 	/* no mode. nothing to be done */
6738 	if (!mode)
6739 		return;
6740 
6741 	/* Full screen scaling by default */
6742 	src.width = mode->hdisplay;
6743 	src.height = mode->vdisplay;
6744 	dst.width = stream->timing.h_addressable;
6745 	dst.height = stream->timing.v_addressable;
6746 
6747 	if (dm_state) {
6748 		rmx_type = dm_state->scaling;
6749 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
6750 			if (src.width * dst.height <
6751 					src.height * dst.width) {
6752 				/* height needs less upscaling/more downscaling */
6753 				dst.width = src.width *
6754 						dst.height / src.height;
6755 			} else {
6756 				/* width needs less upscaling/more downscaling */
6757 				dst.height = src.height *
6758 						dst.width / src.width;
6759 			}
6760 		} else if (rmx_type == RMX_CENTER) {
6761 			dst = src;
6762 		}
6763 
6764 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
6765 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
6766 
6767 		if (dm_state->underscan_enable) {
6768 			dst.x += dm_state->underscan_hborder / 2;
6769 			dst.y += dm_state->underscan_vborder / 2;
6770 			dst.width -= dm_state->underscan_hborder;
6771 			dst.height -= dm_state->underscan_vborder;
6772 		}
6773 	}
6774 
6775 	stream->src = src;
6776 	stream->dst = dst;
6777 
6778 	drm_dbg_kms(dev, "Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
6779 		    dst.x, dst.y, dst.width, dst.height);
6780 
6781 }
6782 
6783 static enum dc_color_depth
6784 convert_color_depth_from_display_info(const struct drm_connector *connector,
6785 				      bool is_y420, int requested_bpc)
6786 {
6787 	u8 bpc;
6788 
6789 	if (is_y420) {
6790 		bpc = 8;
6791 
6792 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
6793 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
6794 			bpc = 16;
6795 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
6796 			bpc = 12;
6797 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
6798 			bpc = 10;
6799 	} else {
6800 		bpc = (uint8_t)connector->display_info.bpc;
6801 		/* Assume 8 bpc by default if no bpc is specified. */
6802 		bpc = bpc ? bpc : 8;
6803 	}
6804 
6805 	if (requested_bpc > 0) {
6806 		/*
6807 		 * Cap display bpc based on the user requested value.
6808 		 *
6809 		 * The value for state->max_bpc may not correctly updated
6810 		 * depending on when the connector gets added to the state
6811 		 * or if this was called outside of atomic check, so it
6812 		 * can't be used directly.
6813 		 */
6814 		bpc = min_t(u8, bpc, requested_bpc);
6815 
6816 		/* Round down to the nearest even number. */
6817 		bpc = bpc - (bpc & 1);
6818 	}
6819 
6820 	switch (bpc) {
6821 	case 0:
6822 		/*
6823 		 * Temporary Work around, DRM doesn't parse color depth for
6824 		 * EDID revision before 1.4
6825 		 * TODO: Fix edid parsing
6826 		 */
6827 		return COLOR_DEPTH_888;
6828 	case 6:
6829 		return COLOR_DEPTH_666;
6830 	case 8:
6831 		return COLOR_DEPTH_888;
6832 	case 10:
6833 		return COLOR_DEPTH_101010;
6834 	case 12:
6835 		return COLOR_DEPTH_121212;
6836 	case 14:
6837 		return COLOR_DEPTH_141414;
6838 	case 16:
6839 		return COLOR_DEPTH_161616;
6840 	default:
6841 		return COLOR_DEPTH_UNDEFINED;
6842 	}
6843 }
6844 
6845 static enum dc_aspect_ratio
6846 get_aspect_ratio(const struct drm_display_mode *mode_in)
6847 {
6848 	/* 1-1 mapping, since both enums follow the HDMI spec. */
6849 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
6850 }
6851 
6852 static enum dc_color_space
6853 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
6854 		       const struct drm_connector_state *connector_state)
6855 {
6856 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
6857 
6858 	switch (connector_state->colorspace) {
6859 	case DRM_MODE_COLORIMETRY_BT601_YCC:
6860 		if (dc_crtc_timing->flags.Y_ONLY)
6861 			color_space = COLOR_SPACE_YCBCR601_LIMITED;
6862 		else
6863 			color_space = COLOR_SPACE_YCBCR601;
6864 		break;
6865 	case DRM_MODE_COLORIMETRY_BT709_YCC:
6866 		if (dc_crtc_timing->flags.Y_ONLY)
6867 			color_space = COLOR_SPACE_YCBCR709_LIMITED;
6868 		else
6869 			color_space = COLOR_SPACE_YCBCR709;
6870 		break;
6871 	case DRM_MODE_COLORIMETRY_OPRGB:
6872 		color_space = COLOR_SPACE_ADOBERGB;
6873 		break;
6874 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
6875 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
6876 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
6877 			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
6878 		else
6879 			color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6880 		break;
6881 	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
6882 	default:
6883 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
6884 			color_space = COLOR_SPACE_SRGB;
6885 			if (connector_state->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_LIMITED)
6886 				color_space = COLOR_SPACE_SRGB_LIMITED;
6887 		/*
6888 		 * 27030khz is the separation point between HDTV and SDTV
6889 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
6890 		 * respectively
6891 		 */
6892 		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
6893 			if (dc_crtc_timing->flags.Y_ONLY)
6894 				color_space =
6895 					COLOR_SPACE_YCBCR709_LIMITED;
6896 			else
6897 				color_space = COLOR_SPACE_YCBCR709;
6898 		} else {
6899 			if (dc_crtc_timing->flags.Y_ONLY)
6900 				color_space =
6901 					COLOR_SPACE_YCBCR601_LIMITED;
6902 			else
6903 				color_space = COLOR_SPACE_YCBCR601;
6904 		}
6905 		break;
6906 	}
6907 
6908 	return color_space;
6909 }
6910 
6911 static enum display_content_type
6912 get_output_content_type(const struct drm_connector_state *connector_state)
6913 {
6914 	switch (connector_state->content_type) {
6915 	default:
6916 	case DRM_MODE_CONTENT_TYPE_NO_DATA:
6917 		return DISPLAY_CONTENT_TYPE_NO_DATA;
6918 	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
6919 		return DISPLAY_CONTENT_TYPE_GRAPHICS;
6920 	case DRM_MODE_CONTENT_TYPE_PHOTO:
6921 		return DISPLAY_CONTENT_TYPE_PHOTO;
6922 	case DRM_MODE_CONTENT_TYPE_CINEMA:
6923 		return DISPLAY_CONTENT_TYPE_CINEMA;
6924 	case DRM_MODE_CONTENT_TYPE_GAME:
6925 		return DISPLAY_CONTENT_TYPE_GAME;
6926 	}
6927 }
6928 
6929 static bool adjust_colour_depth_from_display_info(
6930 	struct dc_crtc_timing *timing_out,
6931 	const struct drm_display_info *info)
6932 {
6933 	enum dc_color_depth depth = timing_out->display_color_depth;
6934 	int normalized_clk;
6935 
6936 	do {
6937 		normalized_clk = timing_out->pix_clk_100hz / 10;
6938 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
6939 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
6940 			normalized_clk /= 2;
6941 		/* Adjusting pix clock following on HDMI spec based on colour depth */
6942 		switch (depth) {
6943 		case COLOR_DEPTH_888:
6944 			break;
6945 		case COLOR_DEPTH_101010:
6946 			normalized_clk = (normalized_clk * 30) / 24;
6947 			break;
6948 		case COLOR_DEPTH_121212:
6949 			normalized_clk = (normalized_clk * 36) / 24;
6950 			break;
6951 		case COLOR_DEPTH_161616:
6952 			normalized_clk = (normalized_clk * 48) / 24;
6953 			break;
6954 		default:
6955 			/* The above depths are the only ones valid for HDMI. */
6956 			return false;
6957 		}
6958 		if (normalized_clk <= info->max_tmds_clock) {
6959 			timing_out->display_color_depth = depth;
6960 			return true;
6961 		}
6962 	} while (--depth > COLOR_DEPTH_666);
6963 	return false;
6964 }
6965 
6966 static void fill_stream_properties_from_drm_display_mode(
6967 	struct dc_stream_state *stream,
6968 	const struct drm_display_mode *mode_in,
6969 	const struct drm_connector *connector,
6970 	const struct drm_connector_state *connector_state,
6971 	const struct dc_stream_state *old_stream,
6972 	int requested_bpc)
6973 {
6974 	struct dc_crtc_timing *timing_out = &stream->timing;
6975 	const struct drm_display_info *info = &connector->display_info;
6976 	struct amdgpu_dm_connector *aconnector = NULL;
6977 	struct hdmi_vendor_infoframe hv_frame;
6978 	struct hdmi_avi_infoframe avi_frame;
6979 	ssize_t err;
6980 
6981 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
6982 		aconnector = to_amdgpu_dm_connector(connector);
6983 
6984 	memset(&hv_frame, 0, sizeof(hv_frame));
6985 	memset(&avi_frame, 0, sizeof(avi_frame));
6986 
6987 	timing_out->h_border_left = 0;
6988 	timing_out->h_border_right = 0;
6989 	timing_out->v_border_top = 0;
6990 	timing_out->v_border_bottom = 0;
6991 	/* TODO: un-hardcode */
6992 	if (drm_mode_is_420_only(info, mode_in)
6993 			&& (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
6994 			    stream->signal == SIGNAL_TYPE_HDMI_FRL)
6995 			&& aconnector
6996 			&& aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR420)
6997 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6998 	else if (drm_mode_is_420_also(info, mode_in)
6999 			&& aconnector
7000 			&& (aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR420
7001 			|| aconnector->force_yuv420_output))
7002 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
7003 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR422))
7004 			&& aconnector
7005 			&& (aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR422
7006 			|| aconnector->force_yuv422_output))
7007 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR422;
7008 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR444))
7009 			&& (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7010 			    stream->signal == SIGNAL_TYPE_HDMI_FRL)
7011 			&& aconnector
7012 			&& aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR444)
7013 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
7014 	else
7015 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
7016 
7017 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
7018 	timing_out->display_color_depth = convert_color_depth_from_display_info(
7019 		connector,
7020 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
7021 		requested_bpc);
7022 	timing_out->scan_type = SCANNING_TYPE_NODATA;
7023 	timing_out->hdmi_vic = 0;
7024 
7025 	if (old_stream) {
7026 		timing_out->vic = old_stream->timing.vic;
7027 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
7028 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
7029 	} else {
7030 		timing_out->vic = drm_match_cea_mode(mode_in);
7031 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
7032 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
7033 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
7034 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
7035 	}
7036 
7037 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7038 		stream->signal == SIGNAL_TYPE_HDMI_FRL) {
7039 		err = drm_hdmi_avi_infoframe_from_display_mode(&avi_frame,
7040 							       (struct drm_connector *)connector,
7041 							       mode_in);
7042 		if (err < 0)
7043 			drm_warn_once(connector->dev, "Failed to setup avi infoframe on connector %s: %zd\n",
7044 				      connector->name, err);
7045 		timing_out->vic = avi_frame.video_code;
7046 		err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame,
7047 								  (struct drm_connector *)connector,
7048 								  mode_in);
7049 		if (err < 0)
7050 			drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n",
7051 				      connector->name, err);
7052 		timing_out->hdmi_vic = hv_frame.vic;
7053 	}
7054 
7055 	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
7056 		timing_out->h_addressable = mode_in->hdisplay;
7057 		timing_out->h_total = mode_in->htotal;
7058 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
7059 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
7060 		timing_out->v_total = mode_in->vtotal;
7061 		timing_out->v_addressable = mode_in->vdisplay;
7062 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
7063 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
7064 		timing_out->pix_clk_100hz = mode_in->clock * 10;
7065 	} else {
7066 		timing_out->h_addressable = mode_in->crtc_hdisplay;
7067 		timing_out->h_total = mode_in->crtc_htotal;
7068 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
7069 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
7070 		timing_out->v_total = mode_in->crtc_vtotal;
7071 		timing_out->v_addressable = mode_in->crtc_vdisplay;
7072 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
7073 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
7074 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
7075 	}
7076 
7077 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
7078 
7079 	stream->out_transfer_func.type = TF_TYPE_PREDEFINED;
7080 	stream->out_transfer_func.tf = TRANSFER_FUNCTION_SRGB;
7081 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
7082 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
7083 		    drm_mode_is_420_also(info, mode_in) &&
7084 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
7085 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
7086 			adjust_colour_depth_from_display_info(timing_out, info);
7087 		}
7088 	}
7089 
7090 	stream->output_color_space = get_output_color_space(timing_out, connector_state);
7091 	stream->content_type = get_output_content_type(connector_state);
7092 }
7093 
7094 static void fill_audio_info(struct audio_info *audio_info,
7095 			    const struct drm_connector *drm_connector,
7096 			    const struct dc_sink *dc_sink)
7097 {
7098 	int i = 0;
7099 	int cea_revision = 0;
7100 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
7101 
7102 	audio_info->manufacture_id = edid_caps->manufacturer_id;
7103 	audio_info->product_id = edid_caps->product_id;
7104 
7105 	cea_revision = drm_connector->display_info.cea_rev;
7106 
7107 	strscpy(audio_info->display_name,
7108 		edid_caps->display_name,
7109 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
7110 
7111 	if (cea_revision >= 3) {
7112 		audio_info->mode_count = edid_caps->audio_mode_count;
7113 
7114 		for (i = 0; i < audio_info->mode_count; ++i) {
7115 			audio_info->modes[i].format_code =
7116 					(enum audio_format_code)
7117 					(edid_caps->audio_modes[i].format_code);
7118 			audio_info->modes[i].channel_count =
7119 					edid_caps->audio_modes[i].channel_count;
7120 			audio_info->modes[i].sample_rates.all =
7121 					edid_caps->audio_modes[i].sample_rate;
7122 			audio_info->modes[i].sample_size =
7123 					edid_caps->audio_modes[i].sample_size;
7124 		}
7125 	}
7126 
7127 	audio_info->flags.all = edid_caps->speaker_flags;
7128 
7129 	/* TODO: We only check for the progressive mode, check for interlace mode too */
7130 	if (drm_connector->latency_present[0]) {
7131 		audio_info->video_latency = drm_connector->video_latency[0];
7132 		audio_info->audio_latency = drm_connector->audio_latency[0];
7133 	}
7134 
7135 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
7136 
7137 }
7138 
7139 static void
7140 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
7141 				      struct drm_display_mode *dst_mode)
7142 {
7143 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
7144 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
7145 	dst_mode->crtc_clock = src_mode->crtc_clock;
7146 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
7147 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
7148 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
7149 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
7150 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
7151 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
7152 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
7153 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
7154 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
7155 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
7156 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
7157 }
7158 
7159 static void
7160 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
7161 					const struct drm_display_mode *native_mode,
7162 					bool scale_enabled)
7163 {
7164 	if (scale_enabled || (
7165 	    native_mode->clock == drm_mode->clock &&
7166 	    native_mode->htotal == drm_mode->htotal &&
7167 	    native_mode->vtotal == drm_mode->vtotal)) {
7168 		if (native_mode->crtc_clock)
7169 			copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
7170 	} else {
7171 		/* no scaling nor amdgpu inserted, no need to patch */
7172 	}
7173 }
7174 
7175 static struct dc_sink *
7176 create_fake_sink(struct drm_device *dev, struct dc_link *link)
7177 {
7178 	struct dc_sink_init_data sink_init_data = { 0 };
7179 	struct dc_sink *sink = NULL;
7180 
7181 	sink_init_data.link = link;
7182 	sink_init_data.sink_signal = link->connector_signal;
7183 
7184 	sink = dc_sink_create(&sink_init_data);
7185 	if (!sink) {
7186 		drm_err(dev, "Failed to create sink!\n");
7187 		return NULL;
7188 	}
7189 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
7190 
7191 	return sink;
7192 }
7193 
7194 static void set_multisync_trigger_params(
7195 		struct dc_stream_state *stream)
7196 {
7197 	struct dc_stream_state *master = NULL;
7198 
7199 	if (stream->triggered_crtc_reset.enabled) {
7200 		master = stream->triggered_crtc_reset.event_source;
7201 		stream->triggered_crtc_reset.event =
7202 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
7203 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
7204 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
7205 	}
7206 }
7207 
7208 static void set_master_stream(struct dc_stream_state *stream_set[],
7209 			      int stream_count)
7210 {
7211 	int j, highest_rfr = 0, master_stream = 0;
7212 
7213 	for (j = 0;  j < stream_count; j++) {
7214 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
7215 			int refresh_rate = 0;
7216 
7217 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
7218 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
7219 			if (refresh_rate > highest_rfr) {
7220 				highest_rfr = refresh_rate;
7221 				master_stream = j;
7222 			}
7223 		}
7224 	}
7225 	for (j = 0;  j < stream_count; j++) {
7226 		if (stream_set[j])
7227 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
7228 	}
7229 }
7230 
7231 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
7232 {
7233 	int i = 0;
7234 	struct dc_stream_state *stream;
7235 
7236 	if (context->stream_count < 2)
7237 		return;
7238 	for (i = 0; i < context->stream_count ; i++) {
7239 		if (!context->streams[i])
7240 			continue;
7241 		/*
7242 		 * TODO: add a function to read AMD VSDB bits and set
7243 		 * crtc_sync_master.multi_sync_enabled flag
7244 		 * For now it's set to false
7245 		 */
7246 	}
7247 
7248 	set_master_stream(context->streams, context->stream_count);
7249 
7250 	for (i = 0; i < context->stream_count ; i++) {
7251 		stream = context->streams[i];
7252 
7253 		if (!stream)
7254 			continue;
7255 
7256 		set_multisync_trigger_params(stream);
7257 	}
7258 }
7259 
7260 /**
7261  * DOC: FreeSync Video
7262  *
7263  * When a userspace application wants to play a video, the content follows a
7264  * standard format definition that usually specifies the FPS for that format.
7265  * The below list illustrates some video format and the expected FPS,
7266  * respectively:
7267  *
7268  * - TV/NTSC (23.976 FPS)
7269  * - Cinema (24 FPS)
7270  * - TV/PAL (25 FPS)
7271  * - TV/NTSC (29.97 FPS)
7272  * - TV/NTSC (30 FPS)
7273  * - Cinema HFR (48 FPS)
7274  * - TV/PAL (50 FPS)
7275  * - Commonly used (60 FPS)
7276  * - Multiples of 24 (48,72,96 FPS)
7277  *
7278  * The list of standards video format is not huge and can be added to the
7279  * connector modeset list beforehand. With that, userspace can leverage
7280  * FreeSync to extends the front porch in order to attain the target refresh
7281  * rate. Such a switch will happen seamlessly, without screen blanking or
7282  * reprogramming of the output in any other way. If the userspace requests a
7283  * modesetting change compatible with FreeSync modes that only differ in the
7284  * refresh rate, DC will skip the full update and avoid blink during the
7285  * transition. For example, the video player can change the modesetting from
7286  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
7287  * causing any display blink. This same concept can be applied to a mode
7288  * setting change.
7289  */
7290 static struct drm_display_mode *
7291 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
7292 		bool use_probed_modes)
7293 {
7294 	struct drm_display_mode *m, *m_pref = NULL;
7295 	u16 current_refresh, highest_refresh;
7296 	struct list_head *list_head = use_probed_modes ?
7297 		&aconnector->base.probed_modes :
7298 		&aconnector->base.modes;
7299 
7300 	if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
7301 		return NULL;
7302 
7303 	if (aconnector->freesync_vid_base.clock != 0)
7304 		return &aconnector->freesync_vid_base;
7305 
7306 	/* Find the preferred mode */
7307 	list_for_each_entry(m, list_head, head) {
7308 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
7309 			m_pref = m;
7310 			break;
7311 		}
7312 	}
7313 
7314 	if (!m_pref) {
7315 		/* Probably an EDID with no preferred mode. Fallback to first entry */
7316 		m_pref = list_first_entry_or_null(
7317 				&aconnector->base.modes, struct drm_display_mode, head);
7318 		if (!m_pref) {
7319 			drm_dbg_driver(aconnector->base.dev, "No preferred mode found in EDID\n");
7320 			return NULL;
7321 		}
7322 	}
7323 
7324 	highest_refresh = drm_mode_vrefresh(m_pref);
7325 
7326 	/*
7327 	 * Find the mode with highest refresh rate with same resolution.
7328 	 * For some monitors, preferred mode is not the mode with highest
7329 	 * supported refresh rate.
7330 	 */
7331 	list_for_each_entry(m, list_head, head) {
7332 		current_refresh  = drm_mode_vrefresh(m);
7333 
7334 		if (m->hdisplay == m_pref->hdisplay &&
7335 		    m->vdisplay == m_pref->vdisplay &&
7336 		    highest_refresh < current_refresh) {
7337 			highest_refresh = current_refresh;
7338 			m_pref = m;
7339 		}
7340 	}
7341 
7342 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
7343 	return m_pref;
7344 }
7345 
7346 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
7347 		struct amdgpu_dm_connector *aconnector)
7348 {
7349 	struct drm_display_mode *high_mode;
7350 	int timing_diff;
7351 
7352 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
7353 	if (!high_mode || !mode)
7354 		return false;
7355 
7356 	timing_diff = high_mode->vtotal - mode->vtotal;
7357 
7358 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
7359 	    high_mode->hdisplay != mode->hdisplay ||
7360 	    high_mode->vdisplay != mode->vdisplay ||
7361 	    high_mode->hsync_start != mode->hsync_start ||
7362 	    high_mode->hsync_end != mode->hsync_end ||
7363 	    high_mode->htotal != mode->htotal ||
7364 	    high_mode->hskew != mode->hskew ||
7365 	    high_mode->vscan != mode->vscan ||
7366 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
7367 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
7368 		return false;
7369 	else
7370 		return true;
7371 }
7372 
7373 #if defined(CONFIG_DRM_AMD_DC_FP)
7374 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
7375 			    struct dc_sink *sink, struct dc_stream_state *stream,
7376 			    struct dsc_dec_dpcd_caps *dsc_caps)
7377 {
7378 	stream->timing.flags.DSC = 0;
7379 	dsc_caps->is_dsc_supported = false;
7380 
7381 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
7382 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
7383 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE)
7384 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7385 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7386 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7387 				dsc_caps);
7388 		else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7389 			if (aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.fields.dsc_support.DSC_PASSTHROUGH_SUPPORT &&
7390 					!aconnector->dsc_settings.dsc_force_disable_passthrough &&
7391 					aconnector->dc_link->dpcd_caps.dongle_caps.dp_hdmi_frl_max_link_bw_in_kbps > 0 &&
7392 					sink->edid_caps.frl_dsc_support &&
7393 					sink->edid_caps.max_frl_rate > 0 &&
7394 					sink->edid_caps.frl_dsc_max_frl_rate > 0)
7395 				dc_dsc_parse_dsc_edid(aconnector->dc_link->ctx->dc, &sink->edid_caps, dsc_caps);
7396 			else
7397 				dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7398 				      aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7399 				      aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7400 				      dsc_caps);
7401 		}
7402 	} else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_HDMI_FRL) {
7403 		if (sink->edid_caps.frl_dsc_support &&
7404 				sink->edid_caps.max_frl_rate > 0 &&
7405 				sink->edid_caps.frl_dsc_max_frl_rate > 0)
7406 			dc_dsc_parse_dsc_edid(aconnector->dc_link->ctx->dc, &sink->edid_caps, dsc_caps);
7407 	}
7408 }
7409 
7410 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
7411 				    struct dc_sink *sink, struct dc_stream_state *stream,
7412 				    struct dsc_dec_dpcd_caps *dsc_caps,
7413 				    uint32_t max_dsc_target_bpp_limit_override)
7414 {
7415 	const struct dc_link_settings *verified_link_cap = NULL;
7416 	u32 link_bw_in_kbps;
7417 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
7418 	struct dc *dc = sink->ctx->dc;
7419 	struct dc_dsc_bw_range bw_range = {0};
7420 	struct dc_dsc_config dsc_cfg = {0};
7421 	struct dc_dsc_config_options dsc_options = {0};
7422 
7423 	dc_dsc_get_default_config_option(dc, &dsc_options);
7424 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7425 
7426 	verified_link_cap = dc_link_get_link_cap(stream->link);
7427 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
7428 	edp_min_bpp_x16 = 8 * 16;
7429 	edp_max_bpp_x16 = 8 * 16;
7430 
7431 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
7432 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
7433 
7434 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
7435 		edp_min_bpp_x16 = edp_max_bpp_x16;
7436 
7437 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
7438 				dc->debug.dsc_min_slice_height_override,
7439 				edp_min_bpp_x16, edp_max_bpp_x16,
7440 				dsc_caps,
7441 				&stream->timing,
7442 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7443 				&bw_range)) {
7444 
7445 		if (bw_range.max_kbps < link_bw_in_kbps) {
7446 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7447 					dsc_caps,
7448 					&dsc_options,
7449 					0,
7450 					&stream->timing,
7451 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7452 					&dsc_cfg)) {
7453 				stream->timing.dsc_cfg = dsc_cfg;
7454 				stream->timing.flags.DSC = 1;
7455 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
7456 			}
7457 			return;
7458 		}
7459 	}
7460 
7461 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7462 				dsc_caps,
7463 				&dsc_options,
7464 				link_bw_in_kbps,
7465 				&stream->timing,
7466 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7467 				&dsc_cfg)) {
7468 		stream->timing.dsc_cfg = dsc_cfg;
7469 		stream->timing.flags.DSC = 1;
7470 	}
7471 }
7472 
7473 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
7474 					struct dc_sink *sink, struct dc_stream_state *stream,
7475 					struct dsc_dec_dpcd_caps *dsc_caps)
7476 {
7477 	struct drm_connector *drm_connector = &aconnector->base;
7478 	u32 link_bandwidth_kbps;
7479 	struct dc *dc = sink->ctx->dc;
7480 	const struct dc_hdmi_frl_link_settings *frl_verified_link_cap = NULL;
7481 	u32 converter_bw_in_kbps;
7482 	u32 sink_bw_in_kbps;
7483 	u32 dsc_sink_bw_in_kbps;
7484 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
7485 	u32 dsc_max_supported_bw_in_kbps;
7486 	u32 max_dsc_target_bpp_limit_override =
7487 		drm_connector->display_info.max_dsc_bpp;
7488 	struct dc_dsc_config_options dsc_options = {0};
7489 
7490 	dc_dsc_get_default_config_option(dc, &dsc_options);
7491 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7492 
7493 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
7494 							dc_link_get_link_cap(aconnector->dc_link));
7495 
7496 	/* Set DSC policy according to dsc_clock_en */
7497 	dc_dsc_policy_set_enable_dsc_when_not_needed(
7498 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
7499 
7500 	if (sink->sink_signal == SIGNAL_TYPE_EDP &&
7501 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
7502 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
7503 
7504 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
7505 
7506 	} else if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
7507 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
7508 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7509 						dsc_caps,
7510 						&dsc_options,
7511 						link_bandwidth_kbps,
7512 						&stream->timing,
7513 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7514 						&stream->timing.dsc_cfg)) {
7515 				stream->timing.flags.DSC = 1;
7516 				drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from SST RX\n",
7517 							__func__, drm_connector->name);
7518 			}
7519 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7520 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
7521 					dc_link_get_highest_encoding_format(aconnector->dc_link));
7522 			converter_bw_in_kbps = aconnector->dc_link->dpcd_caps.dongle_caps.dp_hdmi_frl_max_link_bw_in_kbps;
7523 			sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.max_frl_rate);
7524 			dsc_sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.frl_dsc_max_frl_rate);
7525 
7526 			if (dsc_caps->is_frl) {
7527 				max_supported_bw_in_kbps = min(link_bandwidth_kbps, converter_bw_in_kbps);
7528 				max_supported_bw_in_kbps = min(max_supported_bw_in_kbps, sink_bw_in_kbps);
7529 				dsc_max_supported_bw_in_kbps = min(max_supported_bw_in_kbps, dsc_sink_bw_in_kbps);
7530 			} else {
7531 				max_supported_bw_in_kbps = link_bandwidth_kbps;
7532 				dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
7533 			}
7534 
7535 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
7536 					max_supported_bw_in_kbps > 0 &&
7537 					dsc_max_supported_bw_in_kbps > 0)
7538 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7539 						dsc_caps,
7540 						&dsc_options,
7541 						dsc_max_supported_bw_in_kbps,
7542 						&stream->timing,
7543 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7544 						&stream->timing.dsc_cfg)) {
7545 					stream->timing.flags.DSC = 1;
7546 					drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from %s\n",
7547 							__func__, drm_connector->name,
7548 							(dsc_caps->is_frl == 1) ? "HDMI FRL RX" : "DP-HDMI PCON");
7549 				}
7550 		}
7551 	}
7552 	else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_HDMI_FRL) {
7553 		struct dc_dsc_policy dsc_policy = {0};
7554 
7555 		frl_verified_link_cap = dc_link_get_frl_link_cap(stream->link);
7556 		if (frl_verified_link_cap->frl_link_rate != HDMI_FRL_LINK_RATE_DISABLE &&
7557 			aconnector->dc_link->frl_flags.force_frl_dsc) {
7558 			dc_dsc_policy_set_enable_dsc_when_not_needed(true);
7559 			dc_dsc_get_policy_for_timing(&stream->timing, 0, &dsc_policy, dc_link_get_highest_encoding_format(stream->link));
7560 		}
7561 
7562 		timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing, DC_LINK_ENCODING_HDMI_FRL);
7563 		link_bandwidth_kbps = dc_link_frl_bandwidth_kbps(stream->link, frl_verified_link_cap->frl_link_rate);
7564 		dsc_sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.frl_dsc_max_frl_rate);
7565 
7566 		if ((timing_bw_in_kbps > link_bandwidth_kbps && dsc_sink_bw_in_kbps > 0) ||
7567 		    (dsc_policy.enable_dsc_when_not_needed || dsc_options.force_dsc_when_not_needed)) {
7568 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7569 					dsc_caps,
7570 					&dsc_options,
7571 					dsc_sink_bw_in_kbps,
7572 					&stream->timing,
7573 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7574 					&stream->timing.dsc_cfg)) {
7575 				stream->timing.flags.DSC = 1;
7576 				drm_dbg_driver(drm_connector->dev, "%s: HDMI_FRL_DSC [%s] DSC is selected from HDMI FRL RX\n",
7577 						__func__, drm_connector->name);
7578 			}
7579 		}
7580 	}
7581 
7582 	/* Overwrite the stream flag if DSC is enabled through debugfs */
7583 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
7584 		stream->timing.flags.DSC = 1;
7585 
7586 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
7587 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
7588 
7589 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
7590 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
7591 
7592 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
7593 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
7594 }
7595 #endif
7596 
7597 static struct dc_stream_state *
7598 create_stream_for_sink(struct drm_connector *connector,
7599 		       const struct drm_display_mode *drm_mode,
7600 		       const struct dm_connector_state *dm_state,
7601 		       const struct dc_stream_state *old_stream,
7602 		       int requested_bpc)
7603 {
7604 	struct drm_device *dev = connector->dev;
7605 	struct amdgpu_dm_connector *aconnector = NULL;
7606 	struct drm_display_mode *preferred_mode = NULL;
7607 	const struct drm_connector_state *con_state = &dm_state->base;
7608 	struct dc_stream_state *stream = NULL;
7609 	struct drm_display_mode mode;
7610 	struct drm_display_mode saved_mode;
7611 	struct drm_display_mode *freesync_mode = NULL;
7612 	bool native_mode_found = false;
7613 	bool recalculate_timing = false;
7614 	bool scale = dm_state->scaling != RMX_OFF;
7615 	int mode_refresh;
7616 	int preferred_refresh = 0;
7617 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
7618 #if defined(CONFIG_DRM_AMD_DC_FP)
7619 	struct dsc_dec_dpcd_caps dsc_caps = {0};
7620 #endif
7621 	struct dc_link *link = NULL;
7622 	struct dc_sink *sink = NULL;
7623 
7624 	drm_mode_init(&mode, drm_mode);
7625 	memset(&saved_mode, 0, sizeof(saved_mode));
7626 
7627 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK) {
7628 		aconnector = NULL;
7629 		aconnector = to_amdgpu_dm_connector(connector);
7630 		link = aconnector->dc_link;
7631 	} else {
7632 		struct drm_writeback_connector *wbcon = NULL;
7633 		struct amdgpu_dm_wb_connector *dm_wbcon = NULL;
7634 
7635 		wbcon = drm_connector_to_writeback(connector);
7636 		dm_wbcon = to_amdgpu_dm_wb_connector(wbcon);
7637 		link = dm_wbcon->link;
7638 	}
7639 
7640 	if (!aconnector || !aconnector->dc_sink) {
7641 		sink = create_fake_sink(dev, link);
7642 		if (!sink)
7643 			return stream;
7644 
7645 	} else {
7646 		sink = aconnector->dc_sink;
7647 		dc_sink_retain(sink);
7648 	}
7649 
7650 	stream = dc_create_stream_for_sink(sink);
7651 
7652 	if (stream == NULL) {
7653 		drm_err(dev, "Failed to create stream for sink!\n");
7654 		goto finish;
7655 	}
7656 
7657 	/* We leave this NULL for writeback connectors */
7658 	stream->dm_stream_context = aconnector;
7659 
7660 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
7661 		connector->display_info.hdmi.scdc.scrambling.low_rates;
7662 
7663 	list_for_each_entry(preferred_mode, &connector->modes, head) {
7664 		/* Search for preferred mode */
7665 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
7666 			native_mode_found = true;
7667 			break;
7668 		}
7669 	}
7670 	if (!native_mode_found)
7671 		preferred_mode = list_first_entry_or_null(
7672 				&connector->modes,
7673 				struct drm_display_mode,
7674 				head);
7675 
7676 	mode_refresh = drm_mode_vrefresh(&mode);
7677 
7678 	if (preferred_mode == NULL) {
7679 		/*
7680 		 * This may not be an error, the use case is when we have no
7681 		 * usermode calls to reset and set mode upon hotplug. In this
7682 		 * case, we call set mode ourselves to restore the previous mode
7683 		 * and the modelist may not be filled in time.
7684 		 */
7685 		drm_dbg_driver(dev, "No preferred mode found\n");
7686 	} else if (aconnector) {
7687 		recalculate_timing = amdgpu_freesync_vid_mode &&
7688 				 is_freesync_video_mode(&mode, aconnector);
7689 		if (recalculate_timing) {
7690 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
7691 			drm_mode_copy(&saved_mode, &mode);
7692 			saved_mode.picture_aspect_ratio = mode.picture_aspect_ratio;
7693 			drm_mode_copy(&mode, freesync_mode);
7694 			mode.picture_aspect_ratio = saved_mode.picture_aspect_ratio;
7695 		} else {
7696 			decide_crtc_timing_for_drm_display_mode(
7697 					&mode, preferred_mode, scale);
7698 
7699 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
7700 		}
7701 	}
7702 
7703 	if (recalculate_timing)
7704 		drm_mode_set_crtcinfo(&saved_mode, 0);
7705 
7706 	/*
7707 	 * If scaling is enabled and refresh rate didn't change
7708 	 * we copy the vic and polarities of the old timings
7709 	 */
7710 	if (!scale || mode_refresh != preferred_refresh)
7711 		fill_stream_properties_from_drm_display_mode(
7712 			stream, &mode, connector, con_state, NULL,
7713 			requested_bpc);
7714 	else
7715 		fill_stream_properties_from_drm_display_mode(
7716 			stream, &mode, connector, con_state, old_stream,
7717 			requested_bpc);
7718 
7719 	/* The rest isn't needed for writeback connectors */
7720 	if (!aconnector)
7721 		goto finish;
7722 
7723 	if (aconnector->timing_changed) {
7724 		drm_dbg(aconnector->base.dev,
7725 			"overriding timing for automated test, bpc %d, changing to %d\n",
7726 			stream->timing.display_color_depth,
7727 			aconnector->timing_requested->display_color_depth);
7728 		stream->timing = *aconnector->timing_requested;
7729 	}
7730 
7731 #if defined(CONFIG_DRM_AMD_DC_FP)
7732 	/* SST DSC determination policy */
7733 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
7734 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
7735 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
7736 #endif
7737 
7738 	update_stream_scaling_settings(dev, &mode, dm_state, stream);
7739 
7740 	fill_audio_info(
7741 		&stream->audio_info,
7742 		connector,
7743 		sink);
7744 
7745 	update_stream_signal(stream, sink);
7746 
7747 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7748 	    stream->signal == SIGNAL_TYPE_HDMI_FRL)
7749 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket, false, false);
7750 
7751 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT ||
7752 	    stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
7753 	    stream->signal == SIGNAL_TYPE_EDP) {
7754 		const struct dc_edid_caps *edid_caps;
7755 		unsigned int disable_colorimetry = 0;
7756 
7757 		if (aconnector->dc_sink) {
7758 			edid_caps = &aconnector->dc_sink->edid_caps;
7759 			disable_colorimetry = edid_caps->panel_patch.disable_colorimetry;
7760 		}
7761 
7762 		//
7763 		// should decide stream support vsc sdp colorimetry capability
7764 		// before building vsc info packet
7765 		//
7766 		stream->use_vsc_sdp_for_colorimetry = stream->link->dpcd_caps.dpcd_rev.raw >= 0x14 &&
7767 						      stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED &&
7768 						      !disable_colorimetry;
7769 
7770 		if (stream->out_transfer_func.tf == TRANSFER_FUNCTION_GAMMA22)
7771 			tf = TRANSFER_FUNC_GAMMA_22;
7772 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
7773 		aconnector->sr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
7774 
7775 	}
7776 finish:
7777 	dc_sink_release(sink);
7778 
7779 	return stream;
7780 }
7781 
7782 /**
7783  * amdgpu_dm_connector_poll - Poll a connector to see if it's connected to a display
7784  * @aconnector: DM connector to poll (owns @base drm_connector and @dc_link)
7785  * @force: if true, force polling even when DAC load detection was used
7786  *
7787  * Used for connectors that don't support HPD (hotplug detection) to
7788  * periodically check whether the connector is connected to a display.
7789  *
7790  * When connection was determined via DAC load detection, we avoid
7791  * re-running it on normal polls to prevent visible glitches, unless
7792  * @force is set.
7793  *
7794  * Return: The probed connector status (connected/disconnected/unknown).
7795  */
7796 static enum drm_connector_status
7797 amdgpu_dm_connector_poll(struct amdgpu_dm_connector *aconnector, bool force)
7798 {
7799 	struct drm_connector *connector = &aconnector->base;
7800 	struct drm_device *dev = connector->dev;
7801 	struct amdgpu_device *adev = drm_to_adev(dev);
7802 	struct dc_link *link = aconnector->dc_link;
7803 	enum dc_connection_type conn_type = dc_connection_none;
7804 	enum drm_connector_status status = connector_status_disconnected;
7805 
7806 	/* When we determined the connection using DAC load detection,
7807 	 * do NOT poll the connector do detect disconnect because
7808 	 * that would run DAC load detection again which can cause
7809 	 * visible visual glitches.
7810 	 *
7811 	 * Only allow to poll such a connector again when forcing.
7812 	 */
7813 	if (!force && link->local_sink && link->type == dc_connection_analog_load)
7814 		return connector->status;
7815 
7816 	mutex_lock(&aconnector->hpd_lock);
7817 
7818 	if (dc_link_detect_connection_type(aconnector->dc_link, &conn_type) &&
7819 	    conn_type != dc_connection_none) {
7820 		mutex_lock(&adev->dm.dc_lock);
7821 
7822 		/* Only call full link detection when a sink isn't created yet,
7823 		 * ie. just when the display is plugged in, otherwise we risk flickering.
7824 		 */
7825 		if (link->local_sink ||
7826 			dc_link_detect(link, DETECT_REASON_HPD))
7827 			status = connector_status_connected;
7828 
7829 		mutex_unlock(&adev->dm.dc_lock);
7830 	}
7831 
7832 	if (connector->status != status) {
7833 		if (status == connector_status_disconnected) {
7834 			if (link->local_sink)
7835 				dc_sink_release(link->local_sink);
7836 
7837 			link->local_sink = NULL;
7838 			link->dpcd_sink_count = 0;
7839 			link->type = dc_connection_none;
7840 		}
7841 
7842 		amdgpu_dm_update_connector_after_detect(aconnector);
7843 	}
7844 
7845 	mutex_unlock(&aconnector->hpd_lock);
7846 	return status;
7847 }
7848 
7849 /**
7850  * amdgpu_dm_connector_detect() - Detect whether a DRM connector is connected to a display
7851  *
7852  * A connector is considered connected when it has a sink that is not NULL.
7853  * For connectors that support HPD (hotplug detection), the connection is
7854  * handled in the HPD interrupt.
7855  * For connectors that may not support HPD, such as analog connectors,
7856  * DRM will call this function repeatedly to poll them.
7857  *
7858  * Notes:
7859  * 1. This interface is NOT called in context of HPD irq.
7860  * 2. This interface *is called* in context of user-mode ioctl. Which
7861  *    makes it a bad place for *any* MST-related activity.
7862  *
7863  * @connector: The DRM connector we are checking. We convert it to
7864  *             amdgpu_dm_connector so we can read the DC link and state.
7865  * @force:     If true, do a full detect again. This is used even when
7866  *             a lighter check would normally be used to avoid flicker.
7867  *
7868  * Return: The connector status (connected, disconnected, or unknown).
7869  *
7870  */
7871 static enum drm_connector_status
7872 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
7873 {
7874 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7875 
7876 	update_subconnector_property(aconnector);
7877 
7878 	if (aconnector->base.force == DRM_FORCE_ON ||
7879 		aconnector->base.force == DRM_FORCE_ON_DIGITAL)
7880 		return connector_status_connected;
7881 	else if (aconnector->base.force == DRM_FORCE_OFF)
7882 		return connector_status_disconnected;
7883 
7884 	/* Poll analog connectors and only when either
7885 	 * disconnected or connected to an analog display.
7886 	 */
7887 	if (drm_kms_helper_is_poll_worker() &&
7888 		dc_connector_supports_analog(aconnector->dc_link->link_id.id) &&
7889 		(!aconnector->dc_sink || aconnector->dc_sink->edid_caps.analog))
7890 		return amdgpu_dm_connector_poll(aconnector, force);
7891 
7892 	return (aconnector->dc_sink ? connector_status_connected :
7893 			connector_status_disconnected);
7894 }
7895 
7896 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
7897 					    struct drm_connector_state *connector_state,
7898 					    struct drm_property *property,
7899 					    uint64_t val)
7900 {
7901 	struct drm_device *dev = connector->dev;
7902 	struct amdgpu_device *adev = drm_to_adev(dev);
7903 	struct dm_connector_state *dm_old_state =
7904 		to_dm_connector_state(connector->state);
7905 	struct dm_connector_state *dm_new_state =
7906 		to_dm_connector_state(connector_state);
7907 
7908 	int ret = -EINVAL;
7909 
7910 	if (property == dev->mode_config.scaling_mode_property) {
7911 		enum amdgpu_rmx_type rmx_type;
7912 
7913 		switch (val) {
7914 		case DRM_MODE_SCALE_CENTER:
7915 			rmx_type = RMX_CENTER;
7916 			break;
7917 		case DRM_MODE_SCALE_ASPECT:
7918 			rmx_type = RMX_ASPECT;
7919 			break;
7920 		case DRM_MODE_SCALE_FULLSCREEN:
7921 			rmx_type = RMX_FULL;
7922 			break;
7923 		case DRM_MODE_SCALE_NONE:
7924 		default:
7925 			rmx_type = RMX_OFF;
7926 			break;
7927 		}
7928 
7929 		if (dm_old_state->scaling == rmx_type)
7930 			return 0;
7931 
7932 		dm_new_state->scaling = rmx_type;
7933 		ret = 0;
7934 	} else if (property == adev->mode_info.underscan_hborder_property) {
7935 		dm_new_state->underscan_hborder = val;
7936 		ret = 0;
7937 	} else if (property == adev->mode_info.underscan_vborder_property) {
7938 		dm_new_state->underscan_vborder = val;
7939 		ret = 0;
7940 	} else if (property == adev->mode_info.underscan_property) {
7941 		dm_new_state->underscan_enable = val;
7942 		ret = 0;
7943 	} else if (property == adev->mode_info.abm_level_property) {
7944 		switch (val) {
7945 		case ABM_SYSFS_CONTROL:
7946 			dm_new_state->abm_sysfs_forbidden = false;
7947 			break;
7948 		case ABM_LEVEL_OFF:
7949 			dm_new_state->abm_sysfs_forbidden = true;
7950 			dm_new_state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7951 			break;
7952 		default:
7953 			dm_new_state->abm_sysfs_forbidden = true;
7954 			dm_new_state->abm_level = val;
7955 		}
7956 		ret = 0;
7957 	}
7958 
7959 	return ret;
7960 }
7961 
7962 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
7963 					    const struct drm_connector_state *state,
7964 					    struct drm_property *property,
7965 					    uint64_t *val)
7966 {
7967 	struct drm_device *dev = connector->dev;
7968 	struct amdgpu_device *adev = drm_to_adev(dev);
7969 	struct dm_connector_state *dm_state =
7970 		to_dm_connector_state(state);
7971 	int ret = -EINVAL;
7972 
7973 	if (property == dev->mode_config.scaling_mode_property) {
7974 		switch (dm_state->scaling) {
7975 		case RMX_CENTER:
7976 			*val = DRM_MODE_SCALE_CENTER;
7977 			break;
7978 		case RMX_ASPECT:
7979 			*val = DRM_MODE_SCALE_ASPECT;
7980 			break;
7981 		case RMX_FULL:
7982 			*val = DRM_MODE_SCALE_FULLSCREEN;
7983 			break;
7984 		case RMX_OFF:
7985 		default:
7986 			*val = DRM_MODE_SCALE_NONE;
7987 			break;
7988 		}
7989 		ret = 0;
7990 	} else if (property == adev->mode_info.underscan_hborder_property) {
7991 		*val = dm_state->underscan_hborder;
7992 		ret = 0;
7993 	} else if (property == adev->mode_info.underscan_vborder_property) {
7994 		*val = dm_state->underscan_vborder;
7995 		ret = 0;
7996 	} else if (property == adev->mode_info.underscan_property) {
7997 		*val = dm_state->underscan_enable;
7998 		ret = 0;
7999 	} else if (property == adev->mode_info.abm_level_property) {
8000 		if (!dm_state->abm_sysfs_forbidden)
8001 			*val = ABM_SYSFS_CONTROL;
8002 		else
8003 			*val = (dm_state->abm_level != ABM_LEVEL_IMMEDIATE_DISABLE) ?
8004 				dm_state->abm_level : 0;
8005 		ret = 0;
8006 	}
8007 
8008 	return ret;
8009 }
8010 
8011 /**
8012  * DOC: panel power savings
8013  *
8014  * The display manager allows you to set your desired **panel power savings**
8015  * level (between 0-4, with 0 representing off), e.g. using the following::
8016  *
8017  *   # echo 3 > /sys/class/drm/card0-eDP-1/amdgpu/panel_power_savings
8018  *
8019  * Modifying this value can have implications on color accuracy, so tread
8020  * carefully.
8021  */
8022 
8023 static ssize_t panel_power_savings_show(struct device *device,
8024 					struct device_attribute *attr,
8025 					char *buf)
8026 {
8027 	struct drm_connector *connector = dev_get_drvdata(device);
8028 	struct drm_device *dev = connector->dev;
8029 	u8 val;
8030 
8031 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
8032 	val = to_dm_connector_state(connector->state)->abm_level ==
8033 		ABM_LEVEL_IMMEDIATE_DISABLE ? 0 :
8034 		to_dm_connector_state(connector->state)->abm_level;
8035 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
8036 
8037 	return sysfs_emit(buf, "%u\n", val);
8038 }
8039 
8040 static ssize_t panel_power_savings_store(struct device *device,
8041 					 struct device_attribute *attr,
8042 					 const char *buf, size_t count)
8043 {
8044 	struct drm_connector *connector = dev_get_drvdata(device);
8045 	struct drm_device *dev = connector->dev;
8046 	long val;
8047 	int ret;
8048 
8049 	ret = kstrtol(buf, 0, &val);
8050 
8051 	if (ret)
8052 		return ret;
8053 
8054 	if (val < 0 || val > 4)
8055 		return -EINVAL;
8056 
8057 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
8058 	if (to_dm_connector_state(connector->state)->abm_sysfs_forbidden)
8059 		ret = -EBUSY;
8060 	else
8061 		to_dm_connector_state(connector->state)->abm_level = val ?:
8062 			ABM_LEVEL_IMMEDIATE_DISABLE;
8063 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
8064 
8065 	if (ret)
8066 		return ret;
8067 
8068 	drm_kms_helper_hotplug_event(dev);
8069 
8070 	return count;
8071 }
8072 
8073 static DEVICE_ATTR_RW(panel_power_savings);
8074 
8075 static struct attribute *amdgpu_attrs[] = {
8076 	&dev_attr_panel_power_savings.attr,
8077 	NULL
8078 };
8079 
8080 static const struct attribute_group amdgpu_group = {
8081 	.name = "amdgpu",
8082 	.attrs = amdgpu_attrs
8083 };
8084 
8085 static bool
8086 amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector *amdgpu_dm_connector)
8087 {
8088 	if (amdgpu_dm_abm_level >= 0)
8089 		return false;
8090 
8091 	if (amdgpu_dm_connector->base.connector_type != DRM_MODE_CONNECTOR_eDP)
8092 		return false;
8093 
8094 	/* check for OLED panels */
8095 	if (amdgpu_dm_connector->bl_idx >= 0) {
8096 		struct drm_device *drm = amdgpu_dm_connector->base.dev;
8097 		struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
8098 		struct amdgpu_dm_backlight_caps *caps;
8099 
8100 		caps = &dm->backlight_caps[amdgpu_dm_connector->bl_idx];
8101 		if (caps->aux_support)
8102 			return false;
8103 	}
8104 
8105 	return true;
8106 }
8107 
8108 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
8109 {
8110 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
8111 
8112 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector))
8113 		sysfs_remove_group(&connector->kdev->kobj, &amdgpu_group);
8114 
8115 	cec_notifier_conn_unregister(amdgpu_dm_connector->notifier);
8116 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
8117 }
8118 
8119 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
8120 {
8121 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8122 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8123 	struct amdgpu_display_manager *dm = &adev->dm;
8124 
8125 	/*
8126 	 * Call only if mst_mgr was initialized before since it's not done
8127 	 * for all connector types.
8128 	 */
8129 	if (aconnector->mst_mgr.dev)
8130 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
8131 
8132 	/* Cancel and flush any pending HDMI HPD debounce work */
8133 	if (aconnector->hdmi_hpd_debounce_delay_ms) {
8134 		cancel_delayed_work_sync(&aconnector->hdmi_hpd_debounce_work);
8135 		if (aconnector->hdmi_prev_sink) {
8136 			dc_sink_release(aconnector->hdmi_prev_sink);
8137 			aconnector->hdmi_prev_sink = NULL;
8138 		}
8139 	}
8140 
8141 	if (aconnector->bl_idx != -1) {
8142 		backlight_device_unregister(dm->backlight_dev[aconnector->bl_idx]);
8143 		dm->backlight_dev[aconnector->bl_idx] = NULL;
8144 	}
8145 
8146 	if (aconnector->dc_em_sink)
8147 		dc_sink_release(aconnector->dc_em_sink);
8148 	aconnector->dc_em_sink = NULL;
8149 	if (aconnector->dc_sink)
8150 		dc_sink_release(aconnector->dc_sink);
8151 	aconnector->dc_sink = NULL;
8152 
8153 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
8154 	drm_connector_unregister(connector);
8155 	drm_connector_cleanup(connector);
8156 	kfree(aconnector->dm_dp_aux.aux.name);
8157 
8158 	kfree(connector);
8159 }
8160 
8161 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
8162 {
8163 	struct dm_connector_state *state =
8164 		to_dm_connector_state(connector->state);
8165 
8166 	if (connector->state)
8167 		__drm_atomic_helper_connector_destroy_state(connector->state);
8168 
8169 	kfree(state);
8170 
8171 	state = kzalloc_obj(*state);
8172 
8173 	if (state) {
8174 		state->scaling = RMX_OFF;
8175 		state->underscan_enable = false;
8176 		state->underscan_hborder = 0;
8177 		state->underscan_vborder = 0;
8178 		state->base.max_requested_bpc = 8;
8179 		state->vcpi_slots = 0;
8180 		state->pbn = 0;
8181 
8182 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) {
8183 			if (amdgpu_dm_abm_level <= 0)
8184 				state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
8185 			else
8186 				state->abm_level = amdgpu_dm_abm_level;
8187 		}
8188 
8189 		__drm_atomic_helper_connector_reset(connector, &state->base);
8190 	}
8191 }
8192 
8193 struct drm_connector_state *
8194 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
8195 {
8196 	struct dm_connector_state *state =
8197 		to_dm_connector_state(connector->state);
8198 
8199 	struct dm_connector_state *new_state =
8200 			kmemdup(state, sizeof(*state), GFP_KERNEL);
8201 
8202 	if (!new_state)
8203 		return NULL;
8204 
8205 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
8206 
8207 	new_state->freesync_capable = state->freesync_capable;
8208 	new_state->abm_level = state->abm_level;
8209 	new_state->scaling = state->scaling;
8210 	new_state->underscan_enable = state->underscan_enable;
8211 	new_state->underscan_hborder = state->underscan_hborder;
8212 	new_state->underscan_vborder = state->underscan_vborder;
8213 	new_state->vcpi_slots = state->vcpi_slots;
8214 	new_state->pbn = state->pbn;
8215 	return &new_state->base;
8216 }
8217 
8218 static int
8219 amdgpu_dm_connector_late_register(struct drm_connector *connector)
8220 {
8221 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8222 		to_amdgpu_dm_connector(connector);
8223 	int r;
8224 
8225 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector)) {
8226 		r = sysfs_create_group(&connector->kdev->kobj,
8227 				       &amdgpu_group);
8228 		if (r)
8229 			return r;
8230 	}
8231 
8232 	amdgpu_dm_register_backlight_device(amdgpu_dm_connector);
8233 
8234 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
8235 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
8236 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
8237 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
8238 		if (r)
8239 			return r;
8240 	}
8241 
8242 #if defined(CONFIG_DEBUG_FS)
8243 	connector_debugfs_init(amdgpu_dm_connector);
8244 #endif
8245 
8246 	return 0;
8247 }
8248 
8249 static void amdgpu_dm_connector_funcs_force(struct drm_connector *connector)
8250 {
8251 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8252 	struct dc_link *dc_link = aconnector->dc_link;
8253 	struct dc_sink *dc_em_sink = aconnector->dc_em_sink;
8254 	const struct drm_edid *drm_edid;
8255 	struct i2c_adapter *ddc;
8256 	struct drm_device *dev = connector->dev;
8257 
8258 	if (dc_link && dc_link->aux_mode)
8259 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8260 	else
8261 		ddc = &aconnector->i2c->base;
8262 
8263 	drm_edid = drm_edid_read_ddc(connector, ddc);
8264 	drm_edid_connector_update(connector, drm_edid);
8265 	if (!drm_edid) {
8266 		drm_err(dev, "No EDID found on connector: %s.\n", connector->name);
8267 		return;
8268 	}
8269 
8270 	aconnector->drm_edid = drm_edid;
8271 	/* Update emulated (virtual) sink's EDID */
8272 	if (dc_em_sink && dc_link) {
8273 		// FIXME: Get rid of drm_edid_raw()
8274 		const struct edid *edid = drm_edid_raw(drm_edid);
8275 
8276 		memset(&dc_em_sink->edid_caps, 0, sizeof(struct dc_edid_caps));
8277 		memmove(dc_em_sink->dc_edid.raw_edid, edid,
8278 			(edid->extensions + 1) * EDID_LENGTH);
8279 		dm_helpers_parse_edid_caps(
8280 			dc_link,
8281 			&dc_em_sink->dc_edid,
8282 			&dc_em_sink->edid_caps);
8283 	}
8284 }
8285 
8286 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
8287 	.reset = amdgpu_dm_connector_funcs_reset,
8288 	.detect = amdgpu_dm_connector_detect,
8289 	.fill_modes = drm_helper_probe_single_connector_modes,
8290 	.destroy = amdgpu_dm_connector_destroy,
8291 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
8292 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
8293 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
8294 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
8295 	.late_register = amdgpu_dm_connector_late_register,
8296 	.early_unregister = amdgpu_dm_connector_unregister,
8297 	.force = amdgpu_dm_connector_funcs_force
8298 };
8299 
8300 static int get_modes(struct drm_connector *connector)
8301 {
8302 	return amdgpu_dm_connector_get_modes(connector);
8303 }
8304 
8305 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
8306 {
8307 	struct drm_connector *connector = &aconnector->base;
8308 	struct dc_link *dc_link = aconnector->dc_link;
8309 	struct dc_sink_init_data init_params = {
8310 			.link = aconnector->dc_link,
8311 			.sink_signal = SIGNAL_TYPE_VIRTUAL
8312 	};
8313 	const struct drm_edid *drm_edid;
8314 	const struct edid *edid;
8315 	struct i2c_adapter *ddc;
8316 
8317 	if (dc_link && dc_link->aux_mode)
8318 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8319 	else
8320 		ddc = &aconnector->i2c->base;
8321 
8322 	drm_edid = drm_edid_read_ddc(connector, ddc);
8323 	drm_edid_connector_update(connector, drm_edid);
8324 	if (!drm_edid) {
8325 		drm_err(connector->dev, "No EDID found on connector: %s.\n", connector->name);
8326 		return;
8327 	}
8328 
8329 	if (connector->display_info.is_hdmi)
8330 		init_params.sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
8331 
8332 	aconnector->drm_edid = drm_edid;
8333 
8334 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
8335 	aconnector->dc_em_sink = dc_link_add_remote_sink(
8336 		aconnector->dc_link,
8337 		(uint8_t *)edid,
8338 		(edid->extensions + 1) * EDID_LENGTH,
8339 		&init_params);
8340 
8341 	if (aconnector->base.force == DRM_FORCE_ON) {
8342 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
8343 		aconnector->dc_link->local_sink :
8344 		aconnector->dc_em_sink;
8345 		if (aconnector->dc_sink)
8346 			dc_sink_retain(aconnector->dc_sink);
8347 	}
8348 }
8349 
8350 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
8351 {
8352 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
8353 
8354 	/*
8355 	 * In case of headless boot with force on for DP managed connector
8356 	 * Those settings have to be != 0 to get initial modeset
8357 	 */
8358 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
8359 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
8360 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
8361 	}
8362 
8363 	create_eml_sink(aconnector);
8364 }
8365 
8366 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
8367 						struct dc_stream_state *stream)
8368 {
8369 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
8370 	struct dc_plane_state *dc_plane_state = NULL;
8371 	struct dc_state *dc_state = NULL;
8372 
8373 	if (!stream)
8374 		goto cleanup;
8375 
8376 	dc_plane_state = dc_create_plane_state(dc);
8377 	if (!dc_plane_state)
8378 		goto cleanup;
8379 
8380 	dc_state = dc_state_create(dc, NULL);
8381 	if (!dc_state)
8382 		goto cleanup;
8383 
8384 	/* populate stream to plane */
8385 	dc_plane_state->src_rect.height  = stream->src.height;
8386 	dc_plane_state->src_rect.width   = stream->src.width;
8387 	dc_plane_state->dst_rect.height  = stream->src.height;
8388 	dc_plane_state->dst_rect.width   = stream->src.width;
8389 	dc_plane_state->clip_rect.height = stream->src.height;
8390 	dc_plane_state->clip_rect.width  = stream->src.width;
8391 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
8392 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
8393 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
8394 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
8395 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
8396 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
8397 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
8398 	dc_plane_state->rotation = ROTATION_ANGLE_0;
8399 	dc_plane_state->is_tiling_rotated = false;
8400 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
8401 
8402 	dc_result = dc_validate_stream(dc, stream);
8403 	if (dc_result == DC_OK)
8404 		dc_result = dc_validate_plane(dc, dc_plane_state);
8405 
8406 	if (dc_result == DC_OK)
8407 		dc_result = dc_state_add_stream(dc, dc_state, stream);
8408 
8409 	if (dc_result == DC_OK && !dc_state_add_plane(
8410 						dc,
8411 						stream,
8412 						dc_plane_state,
8413 						dc_state))
8414 		dc_result = DC_FAIL_ATTACH_SURFACES;
8415 
8416 	if (dc_result == DC_OK)
8417 		dc_result = dc_validate_global_state(dc, dc_state, DC_VALIDATE_MODE_ONLY);
8418 
8419 cleanup:
8420 	if (dc_state)
8421 		dc_state_release(dc_state);
8422 
8423 	if (dc_plane_state)
8424 		dc_plane_state_release(dc_plane_state);
8425 
8426 	return dc_result;
8427 }
8428 
8429 struct dc_stream_state *
8430 create_validate_stream_for_sink(struct drm_connector *connector,
8431 				const struct drm_display_mode *drm_mode,
8432 				const struct dm_connector_state *dm_state,
8433 				const struct dc_stream_state *old_stream)
8434 {
8435 	struct amdgpu_dm_connector *aconnector = NULL;
8436 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8437 	struct dc_stream_state *stream;
8438 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
8439 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
8440 	enum dc_status dc_result = DC_OK;
8441 	uint8_t bpc_limit = 6;
8442 
8443 	if (!dm_state)
8444 		return NULL;
8445 
8446 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
8447 		aconnector = to_amdgpu_dm_connector(connector);
8448 
8449 	if (aconnector &&
8450 	    (aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
8451 	     aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_FRL ||
8452 	     aconnector->dc_link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER))
8453 		bpc_limit = 8;
8454 
8455 	do {
8456 		drm_dbg_kms(connector->dev, "Trying with %d bpc\n", requested_bpc);
8457 		stream = create_stream_for_sink(connector, drm_mode,
8458 						dm_state, old_stream,
8459 						requested_bpc);
8460 		if (stream == NULL) {
8461 			drm_err(adev_to_drm(adev), "Failed to create stream for sink!\n");
8462 			break;
8463 		}
8464 
8465 		dc_result = dc_validate_stream(adev->dm.dc, stream);
8466 
8467 		if (!aconnector) /* writeback connector */
8468 			return stream;
8469 
8470 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
8471 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
8472 
8473 		if (dc_result == DC_OK)
8474 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
8475 
8476 		if (dc_result != DC_OK) {
8477 			drm_dbg_kms(connector->dev, "Pruned mode %d x %d (clk %d) %s %s -- %s\n",
8478 				      drm_mode->hdisplay,
8479 				      drm_mode->vdisplay,
8480 				      drm_mode->clock,
8481 				      dc_pixel_encoding_to_str(stream->timing.pixel_encoding),
8482 				      dc_color_depth_to_str(stream->timing.display_color_depth),
8483 				      dc_status_to_str(dc_result));
8484 
8485 			dc_stream_release(stream);
8486 			stream = NULL;
8487 			requested_bpc -= 2; /* lower bpc to retry validation */
8488 		}
8489 
8490 	} while (stream == NULL && requested_bpc >= bpc_limit);
8491 
8492 	switch (dc_result) {
8493 	/*
8494 	 * If we failed to validate DP bandwidth stream with the requested RGB color depth,
8495 	 * we try to fallback and configure in order:
8496 	 * YUV422 (8bpc, 6bpc)
8497 	 * YUV420 (8bpc, 6bpc)
8498 	 */
8499 	case DC_FAIL_ENC_VALIDATE:
8500 	case DC_EXCEED_DONGLE_CAP:
8501 	case DC_NO_DP_LINK_BANDWIDTH:
8502 		/* recursively entered twice and already tried both YUV422 and YUV420 */
8503 		if (aconnector->force_yuv422_output && aconnector->force_yuv420_output)
8504 			break;
8505 		/* first failure; try YUV422 */
8506 		if (!aconnector->force_yuv422_output) {
8507 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV422\n",
8508 				    __func__, __LINE__, dc_result);
8509 			aconnector->force_yuv422_output = true;
8510 		/* recursively entered and YUV422 failed, try YUV420 */
8511 		} else if (!aconnector->force_yuv420_output) {
8512 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV420\n",
8513 				    __func__, __LINE__, dc_result);
8514 			aconnector->force_yuv420_output = true;
8515 		}
8516 		stream = create_validate_stream_for_sink(connector, drm_mode,
8517 							 dm_state, old_stream);
8518 		aconnector->force_yuv422_output = false;
8519 		aconnector->force_yuv420_output = false;
8520 		break;
8521 	case DC_OK:
8522 		break;
8523 	default:
8524 		drm_dbg_kms(connector->dev, "%s:%d Unhandled validation failure %d\n",
8525 			    __func__, __LINE__, dc_result);
8526 		break;
8527 	}
8528 
8529 	return stream;
8530 }
8531 
8532 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
8533 				   const struct drm_display_mode *mode)
8534 {
8535 	int result = MODE_ERROR;
8536 	struct dc_sink *dc_sink;
8537 	struct drm_display_mode *test_mode;
8538 	/* TODO: Unhardcode stream count */
8539 	struct dc_stream_state *stream;
8540 	/* we always have an amdgpu_dm_connector here since we got
8541 	 * here via the amdgpu_dm_connector_helper_funcs
8542 	 */
8543 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8544 
8545 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
8546 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
8547 		return result;
8548 
8549 	/*
8550 	 * Only run this the first time mode_valid is called to initilialize
8551 	 * EDID mgmt
8552 	 */
8553 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
8554 		!aconnector->dc_em_sink)
8555 		handle_edid_mgmt(aconnector);
8556 
8557 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
8558 
8559 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
8560 				aconnector->base.force != DRM_FORCE_ON) {
8561 		drm_err(connector->dev, "dc_sink is NULL!\n");
8562 		goto fail;
8563 	}
8564 
8565 	test_mode = drm_mode_duplicate(connector->dev, mode);
8566 	if (!test_mode)
8567 		goto fail;
8568 
8569 	drm_mode_set_crtcinfo(test_mode, 0);
8570 
8571 	stream = create_validate_stream_for_sink(connector, test_mode,
8572 						 to_dm_connector_state(connector->state),
8573 						 NULL);
8574 	drm_mode_destroy(connector->dev, test_mode);
8575 	if (stream) {
8576 		dc_stream_release(stream);
8577 		result = MODE_OK;
8578 	}
8579 
8580 fail:
8581 	/* TODO: error handling*/
8582 	return result;
8583 }
8584 
8585 static int fill_hdr_info_packet(const struct drm_connector_state *state,
8586 				struct dc_info_packet *out)
8587 {
8588 	struct hdmi_drm_infoframe frame;
8589 	unsigned char buf[30]; /* 26 + 4 */
8590 	ssize_t len;
8591 	int ret, i;
8592 
8593 	memset(out, 0, sizeof(*out));
8594 
8595 	if (!state->hdr_output_metadata)
8596 		return 0;
8597 
8598 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
8599 	if (ret)
8600 		return ret;
8601 
8602 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
8603 	if (len < 0)
8604 		return (int)len;
8605 
8606 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
8607 	if (len != 30)
8608 		return -EINVAL;
8609 
8610 	/* Prepare the infopacket for DC. */
8611 	switch (state->connector->connector_type) {
8612 	case DRM_MODE_CONNECTOR_HDMIA:
8613 		out->hb0 = 0x87; /* type */
8614 		out->hb1 = 0x01; /* version */
8615 		out->hb2 = 0x1A; /* length */
8616 		out->sb[0] = buf[3]; /* checksum */
8617 		i = 1;
8618 		break;
8619 
8620 	case DRM_MODE_CONNECTOR_DisplayPort:
8621 	case DRM_MODE_CONNECTOR_eDP:
8622 		out->hb0 = 0x00; /* sdp id, zero */
8623 		out->hb1 = 0x87; /* type */
8624 		out->hb2 = 0x1D; /* payload len - 1 */
8625 		out->hb3 = (0x13 << 2); /* sdp version */
8626 		out->sb[0] = 0x01; /* version */
8627 		out->sb[1] = 0x1A; /* length */
8628 		i = 2;
8629 		break;
8630 
8631 	default:
8632 		return -EINVAL;
8633 	}
8634 
8635 	memcpy(&out->sb[i], &buf[4], 26);
8636 	out->valid = true;
8637 
8638 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
8639 		       sizeof(out->sb), false);
8640 
8641 	return 0;
8642 }
8643 
8644 static int
8645 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
8646 				 struct drm_atomic_commit *state)
8647 {
8648 	struct drm_connector_state *new_con_state =
8649 		drm_atomic_get_new_connector_state(state, conn);
8650 	struct drm_connector_state *old_con_state =
8651 		drm_atomic_get_old_connector_state(state, conn);
8652 	struct drm_crtc *crtc = new_con_state->crtc;
8653 	struct drm_crtc_state *new_crtc_state;
8654 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
8655 	int ret;
8656 
8657 	if (WARN_ON(unlikely(!old_con_state || !new_con_state)))
8658 		return -EINVAL;
8659 
8660 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
8661 
8662 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
8663 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
8664 		if (ret < 0)
8665 			return ret;
8666 	}
8667 
8668 	if (!crtc)
8669 		return 0;
8670 
8671 	if (new_con_state->privacy_screen_sw_state != old_con_state->privacy_screen_sw_state) {
8672 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8673 		if (IS_ERR(new_crtc_state))
8674 			return PTR_ERR(new_crtc_state);
8675 
8676 		new_crtc_state->mode_changed = true;
8677 	}
8678 
8679 	if (new_con_state->colorspace != old_con_state->colorspace) {
8680 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8681 		if (IS_ERR(new_crtc_state))
8682 			return PTR_ERR(new_crtc_state);
8683 
8684 		new_crtc_state->mode_changed = true;
8685 	}
8686 
8687 	if (new_con_state->content_type != old_con_state->content_type) {
8688 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8689 		if (IS_ERR(new_crtc_state))
8690 			return PTR_ERR(new_crtc_state);
8691 
8692 		new_crtc_state->mode_changed = true;
8693 	}
8694 
8695 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
8696 		struct dc_info_packet hdr_infopacket;
8697 
8698 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
8699 		if (ret)
8700 			return ret;
8701 
8702 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8703 		if (IS_ERR(new_crtc_state))
8704 			return PTR_ERR(new_crtc_state);
8705 
8706 		/*
8707 		 * DC considers the stream backends changed if the
8708 		 * static metadata changes. Forcing the modeset also
8709 		 * gives a simple way for userspace to switch from
8710 		 * 8bpc to 10bpc when setting the metadata to enter
8711 		 * or exit HDR.
8712 		 *
8713 		 * Changing the static metadata after it's been
8714 		 * set is permissible, however. So only force a
8715 		 * modeset if we're entering or exiting HDR.
8716 		 */
8717 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
8718 			!old_con_state->hdr_output_metadata ||
8719 			!new_con_state->hdr_output_metadata;
8720 	}
8721 
8722 	return 0;
8723 }
8724 
8725 static const struct drm_connector_helper_funcs
8726 amdgpu_dm_connector_helper_funcs = {
8727 	/*
8728 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
8729 	 * modes will be filtered by drm_mode_validate_size(), and those modes
8730 	 * are missing after user start lightdm. So we need to renew modes list.
8731 	 * in get_modes call back, not just return the modes count
8732 	 */
8733 	.get_modes = get_modes,
8734 	.mode_valid = amdgpu_dm_connector_mode_valid,
8735 	.atomic_check = amdgpu_dm_connector_atomic_check,
8736 };
8737 
8738 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
8739 {
8740 
8741 }
8742 
8743 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
8744 {
8745 	switch (display_color_depth) {
8746 	case COLOR_DEPTH_666:
8747 		return 6;
8748 	case COLOR_DEPTH_888:
8749 		return 8;
8750 	case COLOR_DEPTH_101010:
8751 		return 10;
8752 	case COLOR_DEPTH_121212:
8753 		return 12;
8754 	case COLOR_DEPTH_141414:
8755 		return 14;
8756 	case COLOR_DEPTH_161616:
8757 		return 16;
8758 	default:
8759 		break;
8760 	}
8761 	return 0;
8762 }
8763 
8764 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
8765 					  struct drm_crtc_state *crtc_state,
8766 					  struct drm_connector_state *conn_state)
8767 {
8768 	struct drm_atomic_commit *state = crtc_state->state;
8769 	struct drm_connector *connector = conn_state->connector;
8770 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8771 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
8772 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
8773 	struct drm_dp_mst_topology_mgr *mst_mgr;
8774 	struct drm_dp_mst_port *mst_port;
8775 	struct drm_dp_mst_topology_state *mst_state;
8776 	enum dc_color_depth color_depth;
8777 	int clock, bpp = 0;
8778 	bool is_y420 = false;
8779 
8780 	if ((connector->connector_type == DRM_MODE_CONNECTOR_eDP) ||
8781 	    (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)) {
8782 		struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8783 		struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8784 		enum drm_mode_status result;
8785 
8786 		result = drm_crtc_helper_mode_valid_fixed(encoder->crtc, adjusted_mode, native_mode);
8787 		if (result != MODE_OK && dm_new_connector_state->scaling == RMX_OFF) {
8788 			drm_dbg_driver(encoder->dev,
8789 				       "mode %dx%d@%dHz is not native, enabling scaling\n",
8790 				       adjusted_mode->hdisplay, adjusted_mode->vdisplay,
8791 				       drm_mode_vrefresh(adjusted_mode));
8792 			dm_new_connector_state->scaling = RMX_ASPECT;
8793 		}
8794 		return 0;
8795 	}
8796 
8797 	if (!aconnector->mst_output_port)
8798 		return 0;
8799 
8800 	mst_port = aconnector->mst_output_port;
8801 	mst_mgr = &aconnector->mst_root->mst_mgr;
8802 
8803 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
8804 		return 0;
8805 
8806 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
8807 	if (IS_ERR(mst_state))
8808 		return PTR_ERR(mst_state);
8809 
8810 	mst_state->pbn_div.full = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
8811 
8812 	if (!state->duplicated) {
8813 		int max_bpc = conn_state->max_requested_bpc;
8814 
8815 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
8816 			  aconnector->force_yuv420_output;
8817 		color_depth = convert_color_depth_from_display_info(connector,
8818 								    is_y420,
8819 								    max_bpc);
8820 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
8821 		clock = adjusted_mode->clock;
8822 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
8823 	}
8824 
8825 	dm_new_connector_state->vcpi_slots =
8826 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
8827 					      dm_new_connector_state->pbn);
8828 	if (dm_new_connector_state->vcpi_slots < 0) {
8829 		drm_dbg_atomic(connector->dev, "failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
8830 		return dm_new_connector_state->vcpi_slots;
8831 	}
8832 	return 0;
8833 }
8834 
8835 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
8836 	.disable = dm_encoder_helper_disable,
8837 	.atomic_check = dm_encoder_helper_atomic_check
8838 };
8839 
8840 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_commit *state,
8841 					    struct dc_state *dc_state,
8842 					    struct dsc_mst_fairness_vars *vars)
8843 {
8844 	struct dc_stream_state *stream = NULL;
8845 	struct drm_connector *connector;
8846 	struct drm_connector_state *new_con_state;
8847 	struct amdgpu_dm_connector *aconnector;
8848 	struct dm_connector_state *dm_conn_state;
8849 	int i, j, ret;
8850 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
8851 
8852 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8853 
8854 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
8855 			continue;
8856 
8857 		aconnector = to_amdgpu_dm_connector(connector);
8858 
8859 		if (!aconnector->mst_output_port)
8860 			continue;
8861 
8862 		if (!new_con_state || !new_con_state->crtc)
8863 			continue;
8864 
8865 		dm_conn_state = to_dm_connector_state(new_con_state);
8866 
8867 		for (j = 0; j < dc_state->stream_count; j++) {
8868 			stream = dc_state->streams[j];
8869 			if (!stream)
8870 				continue;
8871 
8872 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
8873 				break;
8874 
8875 			stream = NULL;
8876 		}
8877 
8878 		if (!stream)
8879 			continue;
8880 
8881 		pbn_div = dm_mst_get_pbn_divider(stream->link);
8882 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
8883 		for (j = 0; j < dc_state->stream_count; j++) {
8884 			if (vars[j].aconnector == aconnector) {
8885 				pbn = vars[j].pbn;
8886 				break;
8887 			}
8888 		}
8889 
8890 		if (j == dc_state->stream_count || pbn_div == 0)
8891 			continue;
8892 
8893 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
8894 
8895 		if (stream->timing.flags.DSC != 1) {
8896 			dm_conn_state->pbn = pbn;
8897 			dm_conn_state->vcpi_slots = slot_num;
8898 
8899 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
8900 							   dm_conn_state->pbn, false);
8901 			if (ret < 0)
8902 				return ret;
8903 
8904 			continue;
8905 		}
8906 
8907 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
8908 		if (vcpi < 0)
8909 			return vcpi;
8910 
8911 		dm_conn_state->pbn = pbn;
8912 		dm_conn_state->vcpi_slots = vcpi;
8913 	}
8914 	return 0;
8915 }
8916 
8917 static int to_drm_connector_type(enum signal_type st, uint32_t connector_id)
8918 {
8919 	switch (st) {
8920 	case SIGNAL_TYPE_HDMI_TYPE_A:
8921 		return DRM_MODE_CONNECTOR_HDMIA;
8922 	case SIGNAL_TYPE_EDP:
8923 		return DRM_MODE_CONNECTOR_eDP;
8924 	case SIGNAL_TYPE_LVDS:
8925 		return DRM_MODE_CONNECTOR_LVDS;
8926 	case SIGNAL_TYPE_RGB:
8927 		return DRM_MODE_CONNECTOR_VGA;
8928 	case SIGNAL_TYPE_DISPLAY_PORT:
8929 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
8930 		/* External DP bridges have a different connector type. */
8931 		if (connector_id == CONNECTOR_ID_VGA)
8932 			return DRM_MODE_CONNECTOR_VGA;
8933 		else if (connector_id == CONNECTOR_ID_LVDS)
8934 			return DRM_MODE_CONNECTOR_LVDS;
8935 
8936 		return DRM_MODE_CONNECTOR_DisplayPort;
8937 	case SIGNAL_TYPE_DVI_DUAL_LINK:
8938 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
8939 		if (connector_id == CONNECTOR_ID_SINGLE_LINK_DVII ||
8940 			connector_id == CONNECTOR_ID_DUAL_LINK_DVII)
8941 			return DRM_MODE_CONNECTOR_DVII;
8942 
8943 		return DRM_MODE_CONNECTOR_DVID;
8944 	case SIGNAL_TYPE_VIRTUAL:
8945 		return DRM_MODE_CONNECTOR_VIRTUAL;
8946 
8947 	default:
8948 		return DRM_MODE_CONNECTOR_Unknown;
8949 	}
8950 }
8951 
8952 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
8953 {
8954 	struct drm_encoder *encoder;
8955 
8956 	/* There is only one encoder per connector */
8957 	drm_connector_for_each_possible_encoder(connector, encoder)
8958 		return encoder;
8959 
8960 	return NULL;
8961 }
8962 
8963 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
8964 {
8965 	struct drm_encoder *encoder;
8966 	struct amdgpu_encoder *amdgpu_encoder;
8967 
8968 	encoder = amdgpu_dm_connector_to_encoder(connector);
8969 
8970 	if (encoder == NULL)
8971 		return;
8972 
8973 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8974 
8975 	amdgpu_encoder->native_mode.clock = 0;
8976 
8977 	if (!list_empty(&connector->probed_modes)) {
8978 		struct drm_display_mode *preferred_mode = NULL;
8979 
8980 		list_for_each_entry(preferred_mode,
8981 				    &connector->probed_modes,
8982 				    head) {
8983 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
8984 				amdgpu_encoder->native_mode = *preferred_mode;
8985 
8986 			break;
8987 		}
8988 
8989 	}
8990 }
8991 
8992 static struct drm_display_mode *
8993 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
8994 			     const char *name,
8995 			     int hdisplay, int vdisplay)
8996 {
8997 	struct drm_device *dev = encoder->dev;
8998 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8999 	struct drm_display_mode *mode = NULL;
9000 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
9001 
9002 	mode = drm_mode_duplicate(dev, native_mode);
9003 
9004 	if (mode == NULL)
9005 		return NULL;
9006 
9007 	mode->hdisplay = hdisplay;
9008 	mode->vdisplay = vdisplay;
9009 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
9010 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
9011 
9012 	return mode;
9013 
9014 }
9015 
9016 static const struct amdgpu_dm_mode_size {
9017 	char name[DRM_DISPLAY_MODE_LEN];
9018 	int w;
9019 	int h;
9020 } common_modes[] = {
9021 	{  "640x480",  640,  480},
9022 	{  "800x600",  800,  600},
9023 	{ "1024x768", 1024,  768},
9024 	{ "1280x720", 1280,  720},
9025 	{ "1280x800", 1280,  800},
9026 	{"1280x1024", 1280, 1024},
9027 	{ "1440x900", 1440,  900},
9028 	{"1680x1050", 1680, 1050},
9029 	{"1600x1200", 1600, 1200},
9030 	{"1920x1080", 1920, 1080},
9031 	{"1920x1200", 1920, 1200}
9032 };
9033 
9034 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
9035 						 struct drm_connector *connector)
9036 {
9037 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
9038 	struct drm_display_mode *mode = NULL;
9039 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
9040 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9041 				to_amdgpu_dm_connector(connector);
9042 	int i;
9043 	int n;
9044 
9045 	if ((connector->connector_type != DRM_MODE_CONNECTOR_eDP) &&
9046 	    (connector->connector_type != DRM_MODE_CONNECTOR_LVDS))
9047 		return;
9048 
9049 	n = ARRAY_SIZE(common_modes);
9050 
9051 	for (i = 0; i < n; i++) {
9052 		struct drm_display_mode *curmode = NULL;
9053 		bool mode_existed = false;
9054 
9055 		if (common_modes[i].w > native_mode->hdisplay ||
9056 		    common_modes[i].h > native_mode->vdisplay ||
9057 		   (common_modes[i].w == native_mode->hdisplay &&
9058 		    common_modes[i].h == native_mode->vdisplay))
9059 			continue;
9060 
9061 		list_for_each_entry(curmode, &connector->probed_modes, head) {
9062 			if (common_modes[i].w == curmode->hdisplay &&
9063 			    common_modes[i].h == curmode->vdisplay) {
9064 				mode_existed = true;
9065 				break;
9066 			}
9067 		}
9068 
9069 		if (mode_existed)
9070 			continue;
9071 
9072 		mode = amdgpu_dm_create_common_mode(encoder,
9073 				common_modes[i].name, common_modes[i].w,
9074 				common_modes[i].h);
9075 		if (!mode)
9076 			continue;
9077 
9078 		drm_mode_probed_add(connector, mode);
9079 		amdgpu_dm_connector->num_modes++;
9080 	}
9081 }
9082 
9083 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
9084 {
9085 	struct drm_encoder *encoder;
9086 	struct amdgpu_encoder *amdgpu_encoder;
9087 	const struct drm_display_mode *native_mode;
9088 
9089 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
9090 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
9091 		return;
9092 
9093 	mutex_lock(&connector->dev->mode_config.mutex);
9094 	amdgpu_dm_connector_get_modes(connector);
9095 	mutex_unlock(&connector->dev->mode_config.mutex);
9096 
9097 	encoder = amdgpu_dm_connector_to_encoder(connector);
9098 	if (!encoder)
9099 		return;
9100 
9101 	amdgpu_encoder = to_amdgpu_encoder(encoder);
9102 
9103 	native_mode = &amdgpu_encoder->native_mode;
9104 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
9105 		return;
9106 
9107 	drm_connector_set_panel_orientation_with_quirk(connector,
9108 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
9109 						       native_mode->hdisplay,
9110 						       native_mode->vdisplay);
9111 }
9112 
9113 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
9114 					      const struct drm_edid *drm_edid)
9115 {
9116 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9117 			to_amdgpu_dm_connector(connector);
9118 
9119 	if (drm_edid) {
9120 		/* empty probed_modes */
9121 		INIT_LIST_HEAD(&connector->probed_modes);
9122 		amdgpu_dm_connector->num_modes =
9123 				drm_edid_connector_add_modes(connector);
9124 
9125 		/* sorting the probed modes before calling function
9126 		 * amdgpu_dm_get_native_mode() since EDID can have
9127 		 * more than one preferred mode. The modes that are
9128 		 * later in the probed mode list could be of higher
9129 		 * and preferred resolution. For example, 3840x2160
9130 		 * resolution in base EDID preferred timing and 4096x2160
9131 		 * preferred resolution in DID extension block later.
9132 		 */
9133 		drm_mode_sort(&connector->probed_modes);
9134 		amdgpu_dm_get_native_mode(connector);
9135 
9136 		/* Freesync capabilities are reset by calling
9137 		 * drm_edid_connector_add_modes() and need to be
9138 		 * restored here.
9139 		 */
9140 		amdgpu_dm_update_freesync_caps(connector, drm_edid, false);
9141 	} else {
9142 		amdgpu_dm_connector->num_modes = 0;
9143 	}
9144 }
9145 
9146 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
9147 			      struct drm_display_mode *mode)
9148 {
9149 	struct drm_display_mode *m;
9150 
9151 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
9152 		if (drm_mode_equal(m, mode))
9153 			return true;
9154 	}
9155 
9156 	return false;
9157 }
9158 
9159 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
9160 {
9161 	const struct drm_display_mode *m;
9162 	struct drm_display_mode *new_mode;
9163 	uint i;
9164 	u32 new_modes_count = 0;
9165 
9166 	/* Standard FPS values
9167 	 *
9168 	 * 23.976       - TV/NTSC
9169 	 * 24           - Cinema
9170 	 * 25           - TV/PAL
9171 	 * 29.97        - TV/NTSC
9172 	 * 30           - TV/NTSC
9173 	 * 48           - Cinema HFR
9174 	 * 50           - TV/PAL
9175 	 * 60           - Commonly used
9176 	 * 48,72,96,120 - Multiples of 24
9177 	 */
9178 	static const u32 common_rates[] = {
9179 		23976, 24000, 25000, 29970, 30000,
9180 		48000, 50000, 60000, 72000, 96000, 120000
9181 	};
9182 
9183 	/*
9184 	 * Find mode with highest refresh rate with the same resolution
9185 	 * as the preferred mode. Some monitors report a preferred mode
9186 	 * with lower resolution than the highest refresh rate supported.
9187 	 */
9188 
9189 	m = get_highest_refresh_rate_mode(aconnector, true);
9190 	if (!m)
9191 		return 0;
9192 
9193 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
9194 		u64 target_vtotal, target_vtotal_diff;
9195 		u64 num, den;
9196 
9197 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
9198 			continue;
9199 
9200 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
9201 		    common_rates[i] > aconnector->max_vfreq * 1000)
9202 			continue;
9203 
9204 		num = (unsigned long long)m->clock * 1000 * 1000;
9205 		den = common_rates[i] * (unsigned long long)m->htotal;
9206 		target_vtotal = div_u64(num, den);
9207 		target_vtotal_diff = target_vtotal - m->vtotal;
9208 
9209 		/* Check for illegal modes */
9210 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
9211 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
9212 		    m->vtotal + target_vtotal_diff < m->vsync_end)
9213 			continue;
9214 
9215 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
9216 		if (!new_mode)
9217 			goto out;
9218 
9219 		new_mode->vtotal += (u16)target_vtotal_diff;
9220 		new_mode->vsync_start += (u16)target_vtotal_diff;
9221 		new_mode->vsync_end += (u16)target_vtotal_diff;
9222 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
9223 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
9224 
9225 		if (!is_duplicate_mode(aconnector, new_mode)) {
9226 			drm_mode_probed_add(&aconnector->base, new_mode);
9227 			new_modes_count += 1;
9228 		} else
9229 			drm_mode_destroy(aconnector->base.dev, new_mode);
9230 	}
9231  out:
9232 	return new_modes_count;
9233 }
9234 
9235 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
9236 						   const struct drm_edid *drm_edid)
9237 {
9238 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9239 		to_amdgpu_dm_connector(connector);
9240 
9241 	if (!(amdgpu_freesync_vid_mode && drm_edid))
9242 		return;
9243 
9244 	if (!amdgpu_dm_connector->dc_sink || !amdgpu_dm_connector->dc_link)
9245 		return;
9246 
9247 	if (!dc_supports_vrr(amdgpu_dm_connector->dc_sink->ctx->dce_version))
9248 		return;
9249 
9250 	if (dc_connector_supports_analog(amdgpu_dm_connector->dc_link->link_id.id) &&
9251 	    amdgpu_dm_connector->dc_sink->edid_caps.analog)
9252 		return;
9253 
9254 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
9255 		amdgpu_dm_connector->num_modes +=
9256 			add_fs_modes(amdgpu_dm_connector);
9257 }
9258 
9259 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
9260 {
9261 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9262 			to_amdgpu_dm_connector(connector);
9263 	struct dc_link *dc_link = amdgpu_dm_connector->dc_link;
9264 	struct drm_encoder *encoder;
9265 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
9266 	struct dc_link_settings *verified_link_cap = &dc_link->verified_link_cap;
9267 	const struct dc *dc = dc_link->dc;
9268 
9269 	encoder = amdgpu_dm_connector_to_encoder(connector);
9270 
9271 	if (!drm_edid) {
9272 		amdgpu_dm_connector->num_modes =
9273 				drm_add_modes_noedid(connector, 640, 480);
9274 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
9275 			amdgpu_dm_connector->num_modes +=
9276 				drm_add_modes_noedid(connector, 1920, 1080);
9277 
9278 		if (amdgpu_dm_connector->dc_sink &&
9279 		    amdgpu_dm_connector->dc_sink->edid_caps.analog &&
9280 		    dc_connector_supports_analog(dc_link->link_id.id)) {
9281 			/* Analog monitor connected by DAC load detection.
9282 			 * Add common modes. It will be up to the user to select one that works.
9283 			 */
9284 			for (int i = 0; i < ARRAY_SIZE(common_modes); i++)
9285 				amdgpu_dm_connector->num_modes += drm_add_modes_noedid(
9286 					connector, common_modes[i].w, common_modes[i].h);
9287 		}
9288 	} else {
9289 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
9290 		if (encoder)
9291 			amdgpu_dm_connector_add_common_modes(encoder, connector);
9292 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
9293 	}
9294 	amdgpu_dm_fbc_init(connector);
9295 
9296 	return amdgpu_dm_connector->num_modes;
9297 }
9298 
9299 static const u32 supported_colorspaces =
9300 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
9301 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
9302 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
9303 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
9304 
9305 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
9306 				     struct amdgpu_dm_connector *aconnector,
9307 				     int connector_type,
9308 				     struct dc_link *link,
9309 				     int link_index)
9310 {
9311 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
9312 
9313 	/*
9314 	 * Some of the properties below require access to state, like bpc.
9315 	 * Allocate some default initial connector state with our reset helper.
9316 	 */
9317 	if (aconnector->base.funcs->reset)
9318 		aconnector->base.funcs->reset(&aconnector->base);
9319 
9320 	aconnector->connector_id = link_index;
9321 	aconnector->bl_idx = -1;
9322 	aconnector->dc_link = link;
9323 	aconnector->base.interlace_allowed = false;
9324 	aconnector->base.doublescan_allowed = false;
9325 	aconnector->base.stereo_allowed = false;
9326 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
9327 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
9328 	aconnector->audio_inst = -1;
9329 	aconnector->pack_sdp_v1_3 = false;
9330 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
9331 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
9332 	mutex_init(&aconnector->hpd_lock);
9333 	mutex_init(&aconnector->handle_mst_msg_ready);
9334 
9335 	/*
9336 	 * If HDMI HPD debounce delay is set, use the minimum between selected
9337 	 * value and AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS
9338 	 */
9339 	if (amdgpu_hdmi_hpd_debounce_delay_ms) {
9340 		aconnector->hdmi_hpd_debounce_delay_ms = min(amdgpu_hdmi_hpd_debounce_delay_ms,
9341 							     AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS);
9342 		INIT_DELAYED_WORK(&aconnector->hdmi_hpd_debounce_work, hdmi_hpd_debounce_work);
9343 		aconnector->hdmi_prev_sink = NULL;
9344 	} else {
9345 		aconnector->hdmi_hpd_debounce_delay_ms = 0;
9346 	}
9347 
9348 	/*
9349 	 * configure support HPD hot plug connector_>polled default value is 0
9350 	 * which means HPD hot plug not supported
9351 	 */
9352 	switch (connector_type) {
9353 	case DRM_MODE_CONNECTOR_HDMIA:
9354 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9355 		aconnector->base.ycbcr_420_allowed =
9356 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
9357 		break;
9358 	case DRM_MODE_CONNECTOR_DisplayPort:
9359 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9360 		link->link_enc = link_enc_cfg_get_link_enc(link);
9361 		ASSERT(link->link_enc);
9362 		if (link->link_enc)
9363 			aconnector->base.ycbcr_420_allowed =
9364 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
9365 		break;
9366 	case DRM_MODE_CONNECTOR_DVID:
9367 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9368 		break;
9369 	case DRM_MODE_CONNECTOR_DVII:
9370 	case DRM_MODE_CONNECTOR_VGA:
9371 		aconnector->base.polled =
9372 			DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT;
9373 		break;
9374 	default:
9375 		break;
9376 	}
9377 
9378 	drm_object_attach_property(&aconnector->base.base,
9379 				dm->ddev->mode_config.scaling_mode_property,
9380 				DRM_MODE_SCALE_NONE);
9381 
9382 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA
9383 		|| (connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root))
9384 		drm_connector_attach_broadcast_rgb_property(&aconnector->base);
9385 
9386 	drm_object_attach_property(&aconnector->base.base,
9387 				adev->mode_info.underscan_property,
9388 				UNDERSCAN_OFF);
9389 	drm_object_attach_property(&aconnector->base.base,
9390 				adev->mode_info.underscan_hborder_property,
9391 				0);
9392 	drm_object_attach_property(&aconnector->base.base,
9393 				adev->mode_info.underscan_vborder_property,
9394 				0);
9395 
9396 	if (!aconnector->mst_root)
9397 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
9398 
9399 	aconnector->base.state->max_bpc = 16;
9400 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
9401 
9402 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9403 		/* Content Type is currently only implemented for HDMI. */
9404 		drm_connector_attach_content_type_property(&aconnector->base);
9405 	}
9406 
9407 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9408 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
9409 			drm_connector_attach_colorspace_property(&aconnector->base);
9410 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
9411 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
9412 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
9413 			drm_connector_attach_colorspace_property(&aconnector->base);
9414 	}
9415 
9416 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9417 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
9418 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
9419 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
9420 
9421 		if (!aconnector->mst_root)
9422 			drm_connector_attach_vrr_capable_property(&aconnector->base);
9423 
9424 		if (adev->dm.hdcp_workqueue)
9425 			drm_connector_attach_content_protection_property(&aconnector->base, true);
9426 	}
9427 
9428 	if (connector_type == DRM_MODE_CONNECTOR_eDP) {
9429 		struct drm_privacy_screen *privacy_screen;
9430 
9431 		drm_connector_attach_panel_type_property(&aconnector->base);
9432 
9433 		privacy_screen = drm_privacy_screen_get(adev_to_drm(adev)->dev, NULL);
9434 		if (!IS_ERR(privacy_screen)) {
9435 			drm_connector_attach_privacy_screen_provider(&aconnector->base,
9436 								     privacy_screen);
9437 		} else if (PTR_ERR(privacy_screen) != -ENODEV) {
9438 			drm_warn(adev_to_drm(adev), "Error getting privacy-screen\n");
9439 		}
9440 	}
9441 }
9442 
9443 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
9444 			      struct i2c_msg *msgs, int num)
9445 {
9446 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
9447 	struct ddc_service *ddc_service = i2c->ddc_service;
9448 	struct i2c_command cmd;
9449 	int i;
9450 	int result = -EIO;
9451 
9452 	if (!ddc_service->ddc_pin)
9453 		return result;
9454 
9455 	cmd.payloads = kzalloc_objs(struct i2c_payload, num);
9456 
9457 	if (!cmd.payloads)
9458 		return result;
9459 
9460 	cmd.number_of_payloads = num;
9461 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
9462 	cmd.speed = 100;
9463 
9464 	for (i = 0; i < num; i++) {
9465 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
9466 		cmd.payloads[i].address = msgs[i].addr;
9467 		cmd.payloads[i].length = msgs[i].len;
9468 		cmd.payloads[i].data = msgs[i].buf;
9469 	}
9470 
9471 	if (i2c->oem) {
9472 		if (dc_submit_i2c_oem(
9473 			    ddc_service->ctx->dc,
9474 			    &cmd))
9475 			result = num;
9476 	} else {
9477 		if (dc_submit_i2c(
9478 			    ddc_service->ctx->dc,
9479 			    ddc_service->link->link_index,
9480 			    &cmd))
9481 			result = num;
9482 	}
9483 
9484 	kfree(cmd.payloads);
9485 	return result;
9486 }
9487 
9488 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
9489 {
9490 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
9491 }
9492 
9493 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
9494 	.master_xfer = amdgpu_dm_i2c_xfer,
9495 	.functionality = amdgpu_dm_i2c_func,
9496 };
9497 
9498 static struct amdgpu_i2c_adapter *
9499 create_i2c(struct ddc_service *ddc_service, bool oem)
9500 {
9501 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
9502 	struct amdgpu_i2c_adapter *i2c;
9503 
9504 	i2c = kzalloc_obj(struct amdgpu_i2c_adapter);
9505 	if (!i2c)
9506 		return NULL;
9507 	i2c->base.owner = THIS_MODULE;
9508 	i2c->base.dev.parent = &adev->pdev->dev;
9509 	i2c->base.algo = &amdgpu_dm_i2c_algo;
9510 	if (oem)
9511 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c OEM bus");
9512 	else
9513 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d",
9514 			 ddc_service->link->link_index);
9515 	i2c_set_adapdata(&i2c->base, i2c);
9516 	i2c->ddc_service = ddc_service;
9517 	i2c->oem = oem;
9518 
9519 	return i2c;
9520 }
9521 
9522 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
9523 {
9524 	struct cec_connector_info conn_info;
9525 	struct drm_device *ddev = aconnector->base.dev;
9526 	struct device *hdmi_dev = ddev->dev;
9527 
9528 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
9529 		drm_info(ddev, "HDMI-CEC feature masked\n");
9530 		return -EINVAL;
9531 	}
9532 
9533 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
9534 	aconnector->notifier =
9535 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
9536 	if (!aconnector->notifier) {
9537 		drm_err(ddev, "Failed to create cec notifier\n");
9538 		return -ENOMEM;
9539 	}
9540 
9541 	return 0;
9542 }
9543 
9544 /*
9545  * Note: this function assumes that dc_link_detect() was called for the
9546  * dc_link which will be represented by this aconnector.
9547  */
9548 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
9549 				    struct amdgpu_dm_connector *aconnector,
9550 				    u32 link_index,
9551 				    struct amdgpu_encoder *aencoder)
9552 {
9553 	int res = 0;
9554 	int connector_type;
9555 	struct dc *dc = dm->dc;
9556 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
9557 	struct amdgpu_i2c_adapter *i2c;
9558 
9559 	/* Not needed for writeback connector */
9560 	link->priv = aconnector;
9561 
9562 
9563 	i2c = create_i2c(link->ddc, false);
9564 	if (!i2c) {
9565 		drm_err(adev_to_drm(dm->adev), "Failed to create i2c adapter data\n");
9566 		return -ENOMEM;
9567 	}
9568 
9569 	aconnector->i2c = i2c;
9570 	res = devm_i2c_add_adapter(dm->adev->dev, &i2c->base);
9571 
9572 	if (res) {
9573 		drm_err(adev_to_drm(dm->adev), "Failed to register hw i2c %d\n", link->link_index);
9574 		goto out_free;
9575 	}
9576 
9577 	connector_type = to_drm_connector_type(link->connector_signal, link->link_id.id);
9578 
9579 	res = drm_connector_init_with_ddc(
9580 			dm->ddev,
9581 			&aconnector->base,
9582 			&amdgpu_dm_connector_funcs,
9583 			connector_type,
9584 			&i2c->base);
9585 
9586 	if (res) {
9587 		drm_err(adev_to_drm(dm->adev), "connector_init failed\n");
9588 		aconnector->connector_id = -1;
9589 		goto out_free;
9590 	}
9591 
9592 	drm_connector_helper_add(
9593 			&aconnector->base,
9594 			&amdgpu_dm_connector_helper_funcs);
9595 
9596 	amdgpu_dm_connector_init_helper(
9597 		dm,
9598 		aconnector,
9599 		connector_type,
9600 		link,
9601 		link_index);
9602 
9603 	drm_connector_attach_encoder(
9604 		&aconnector->base, &aencoder->base);
9605 
9606 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9607 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
9608 		amdgpu_dm_initialize_hdmi_connector(aconnector);
9609 
9610 	if (dc_is_dp_signal(link->connector_signal))
9611 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
9612 
9613 out_free:
9614 	if (res) {
9615 		kfree(i2c);
9616 		aconnector->i2c = NULL;
9617 	}
9618 	return res;
9619 }
9620 
9621 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
9622 {
9623 	switch (adev->mode_info.num_crtc) {
9624 	case 1:
9625 		return 0x1;
9626 	case 2:
9627 		return 0x3;
9628 	case 3:
9629 		return 0x7;
9630 	case 4:
9631 		return 0xf;
9632 	case 5:
9633 		return 0x1f;
9634 	case 6:
9635 	default:
9636 		return 0x3f;
9637 	}
9638 }
9639 
9640 static int amdgpu_dm_encoder_init(struct drm_device *dev,
9641 				  struct amdgpu_encoder *aencoder,
9642 				  uint32_t link_index)
9643 {
9644 	struct amdgpu_device *adev = drm_to_adev(dev);
9645 
9646 	int res = drm_encoder_init(dev,
9647 				   &aencoder->base,
9648 				   &amdgpu_dm_encoder_funcs,
9649 				   DRM_MODE_ENCODER_TMDS,
9650 				   NULL);
9651 
9652 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
9653 
9654 	if (!res)
9655 		aencoder->encoder_id = link_index;
9656 	else
9657 		aencoder->encoder_id = -1;
9658 
9659 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
9660 
9661 	return res;
9662 }
9663 
9664 static void manage_dm_interrupts(struct amdgpu_device *adev,
9665 				 struct amdgpu_crtc *acrtc,
9666 				 struct dm_crtc_state *acrtc_state)
9667 {	/*
9668 	 * We cannot be sure that the frontend index maps to the same
9669 	 * backend index - some even map to more than one.
9670 	 * So we have to go through the CRTC to find the right IRQ.
9671 	 */
9672 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
9673 			adev,
9674 			acrtc->crtc_id);
9675 	struct drm_device *dev = adev_to_drm(adev);
9676 
9677 	struct drm_vblank_crtc_config config = {0};
9678 	struct dc_crtc_timing *timing;
9679 	int offdelay;
9680 
9681 	if (acrtc_state) {
9682 		timing = &acrtc_state->stream->timing;
9683 
9684 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
9685 			   IP_VERSION(3, 5, 0) ||
9686 			   !(adev->flags & AMD_IS_APU)) {
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 		/*
9706 		 * Since pflip_high_irq is no longer registered for DCN, grab an
9707 		 * extra reference to vupdate irq instead to workaround this
9708 		 * issue:
9709 		 * https://gitlab.freedesktop.org/drm/amd/-/work_items/3936
9710 		 *
9711 		 * The callbacks to drm_vblank_on/off should really take care of
9712 		 * this though.
9713 		 */
9714 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9715 		case IP_VERSION(3, 0, 0):
9716 		case IP_VERSION(3, 0, 2):
9717 		case IP_VERSION(3, 0, 3):
9718 		case IP_VERSION(3, 2, 0):
9719 			if (amdgpu_irq_get(adev, &adev->vupdate_irq, irq_type))
9720 				drm_err(dev, "DM_IRQ: Cannot get vupdate irq!\n");
9721 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9722 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
9723 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
9724 #endif
9725 		}
9726 
9727 	} else {
9728 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
9729 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9730 		case IP_VERSION(3, 0, 0):
9731 		case IP_VERSION(3, 0, 2):
9732 		case IP_VERSION(3, 0, 3):
9733 		case IP_VERSION(3, 2, 0):
9734 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9735 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
9736 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
9737 #endif
9738 			if (amdgpu_irq_put(adev, &adev->vupdate_irq, irq_type))
9739 				drm_err(dev, "DM_IRQ: Cannot put vupdate irq!\n");
9740 		}
9741 
9742 		drm_crtc_vblank_off(&acrtc->base);
9743 	}
9744 }
9745 
9746 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
9747 				      struct amdgpu_crtc *acrtc)
9748 {
9749 	int irq_type =
9750 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
9751 
9752 	/* GRPH_PFLIP is not used on DCN; nothing to reapply. */
9753 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) != 0)
9754 		return;
9755 
9756 	/**
9757 	 * This reads the current state for the IRQ and force reapplies
9758 	 * the setting to hardware.
9759 	 */
9760 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
9761 }
9762 
9763 static bool
9764 is_scaling_state_different(const struct dm_connector_state *dm_state,
9765 			   const struct dm_connector_state *old_dm_state)
9766 {
9767 	if (dm_state->scaling != old_dm_state->scaling)
9768 		return true;
9769 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
9770 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
9771 			return true;
9772 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
9773 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
9774 			return true;
9775 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
9776 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
9777 		return true;
9778 	return false;
9779 }
9780 
9781 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
9782 					    struct drm_crtc_state *old_crtc_state,
9783 					    struct drm_connector_state *new_conn_state,
9784 					    struct drm_connector_state *old_conn_state,
9785 					    const struct drm_connector *connector,
9786 					    struct hdcp_workqueue *hdcp_w)
9787 {
9788 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
9789 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
9790 
9791 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
9792 		connector->index, connector->status, connector->dpms);
9793 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
9794 		old_conn_state->content_protection, new_conn_state->content_protection);
9795 
9796 	if (old_crtc_state)
9797 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9798 		old_crtc_state->enable,
9799 		old_crtc_state->active,
9800 		old_crtc_state->mode_changed,
9801 		old_crtc_state->active_changed,
9802 		old_crtc_state->connectors_changed);
9803 
9804 	if (new_crtc_state)
9805 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9806 		new_crtc_state->enable,
9807 		new_crtc_state->active,
9808 		new_crtc_state->mode_changed,
9809 		new_crtc_state->active_changed,
9810 		new_crtc_state->connectors_changed);
9811 
9812 	/* hdcp content type change */
9813 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
9814 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
9815 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9816 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
9817 		return true;
9818 	}
9819 
9820 	/* CP is being re enabled, ignore this */
9821 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
9822 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9823 		if (new_crtc_state && new_crtc_state->mode_changed) {
9824 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9825 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
9826 			return true;
9827 		}
9828 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
9829 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
9830 		return false;
9831 	}
9832 
9833 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
9834 	 *
9835 	 * Handles:	UNDESIRED -> ENABLED
9836 	 */
9837 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
9838 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
9839 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9840 
9841 	/* Stream removed and re-enabled
9842 	 *
9843 	 * Can sometimes overlap with the HPD case,
9844 	 * thus set update_hdcp to false to avoid
9845 	 * setting HDCP multiple times.
9846 	 *
9847 	 * Handles:	DESIRED -> DESIRED (Special case)
9848 	 */
9849 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
9850 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
9851 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9852 		dm_con_state->update_hdcp = false;
9853 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
9854 			__func__);
9855 		return true;
9856 	}
9857 
9858 	/* Hot-plug, headless s3, dpms
9859 	 *
9860 	 * Only start HDCP if the display is connected/enabled.
9861 	 * update_hdcp flag will be set to false until the next
9862 	 * HPD comes in.
9863 	 *
9864 	 * Handles:	DESIRED -> DESIRED (Special case)
9865 	 */
9866 	if (dm_con_state->update_hdcp &&
9867 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
9868 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
9869 		dm_con_state->update_hdcp = false;
9870 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
9871 			__func__);
9872 		return true;
9873 	}
9874 
9875 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
9876 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9877 			if (new_crtc_state && new_crtc_state->mode_changed) {
9878 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
9879 					__func__);
9880 				return true;
9881 			}
9882 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
9883 				__func__);
9884 			return false;
9885 		}
9886 
9887 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
9888 		return false;
9889 	}
9890 
9891 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9892 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
9893 			__func__);
9894 		return true;
9895 	}
9896 
9897 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
9898 	return false;
9899 }
9900 
9901 static void remove_stream(struct amdgpu_device *adev,
9902 			  struct amdgpu_crtc *acrtc,
9903 			  struct dc_stream_state *stream)
9904 {
9905 	/* this is the update mode case */
9906 
9907 	acrtc->otg_inst = -1;
9908 	acrtc->enabled = false;
9909 }
9910 
9911 static void update_freesync_state_on_stream(
9912 	struct amdgpu_display_manager *dm,
9913 	struct dm_crtc_state *new_crtc_state,
9914 	struct dc_stream_state *new_stream,
9915 	struct dc_plane_state *surface,
9916 	u32 flip_timestamp_in_us)
9917 {
9918 	struct mod_vrr_params vrr_params;
9919 	struct dc_info_packet vrr_infopacket = {0};
9920 	struct amdgpu_device *adev = dm->adev;
9921 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9922 	unsigned long flags;
9923 	bool pack_sdp_v1_3 = false;
9924 	struct amdgpu_dm_connector *aconn;
9925 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
9926 
9927 	if (!new_stream)
9928 		return;
9929 
9930 	/*
9931 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9932 	 * For now it's sufficient to just guard against these conditions.
9933 	 */
9934 
9935 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9936 		return;
9937 
9938 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9939 	vrr_params = acrtc->dm_irq_params.vrr_params;
9940 
9941 	if (surface) {
9942 		mod_freesync_handle_preflip(
9943 			dm->freesync_module,
9944 			surface,
9945 			new_stream,
9946 			flip_timestamp_in_us,
9947 			&vrr_params);
9948 
9949 		if (adev->family < AMDGPU_FAMILY_AI &&
9950 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
9951 			mod_freesync_handle_v_update(dm->freesync_module,
9952 						     new_stream, &vrr_params);
9953 
9954 			/* Need to call this before the frame ends. */
9955 			dc_stream_adjust_vmin_vmax(dm->dc,
9956 						   new_crtc_state->stream,
9957 						   &vrr_params.adjust);
9958 		}
9959 	}
9960 
9961 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
9962 
9963 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
9964 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
9965 
9966 		if (aconn->vsdb_info.amd_vsdb_version == 1)
9967 			packet_type = PACKET_TYPE_FS_V1;
9968 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
9969 			packet_type = PACKET_TYPE_FS_V2;
9970 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
9971 			packet_type = PACKET_TYPE_FS_V3;
9972 
9973 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
9974 					&new_stream->adaptive_sync_infopacket);
9975 	}
9976 
9977 	mod_freesync_build_vrr_infopacket(
9978 		dm->freesync_module,
9979 		new_stream,
9980 		&vrr_params,
9981 		packet_type,
9982 		TRANSFER_FUNC_UNKNOWN,
9983 		&vrr_infopacket,
9984 		pack_sdp_v1_3);
9985 
9986 	new_crtc_state->freesync_vrr_info_changed |=
9987 		(memcmp(&new_crtc_state->vrr_infopacket,
9988 			&vrr_infopacket,
9989 			sizeof(vrr_infopacket)) != 0);
9990 
9991 	acrtc->dm_irq_params.vrr_params = vrr_params;
9992 	new_crtc_state->vrr_infopacket = vrr_infopacket;
9993 
9994 	new_stream->vrr_infopacket = vrr_infopacket;
9995 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
9996 
9997 	if (new_crtc_state->freesync_vrr_info_changed)
9998 		drm_dbg_kms(adev_to_drm(adev), "VRR packet update: crtc=%u enabled=%d state=%d",
9999 			      new_crtc_state->base.crtc->base.id,
10000 			      (int)new_crtc_state->base.vrr_enabled,
10001 			      (int)vrr_params.state);
10002 
10003 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10004 }
10005 
10006 static void update_stream_irq_parameters(
10007 	struct amdgpu_display_manager *dm,
10008 	struct dm_crtc_state *new_crtc_state)
10009 {
10010 	struct dc_stream_state *new_stream = new_crtc_state->stream;
10011 	struct mod_vrr_params vrr_params;
10012 	struct mod_freesync_config config = new_crtc_state->freesync_config;
10013 	struct amdgpu_device *adev = dm->adev;
10014 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
10015 	unsigned long flags;
10016 
10017 	if (!new_stream)
10018 		return;
10019 
10020 	/*
10021 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
10022 	 * For now it's sufficient to just guard against these conditions.
10023 	 */
10024 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
10025 		return;
10026 
10027 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
10028 	vrr_params = acrtc->dm_irq_params.vrr_params;
10029 
10030 	if (new_crtc_state->vrr_supported &&
10031 	    config.min_refresh_in_uhz &&
10032 	    config.max_refresh_in_uhz) {
10033 		/*
10034 		 * if freesync compatible mode was set, config.state will be set
10035 		 * in atomic check
10036 		 */
10037 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
10038 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
10039 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
10040 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
10041 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
10042 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
10043 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
10044 		} else {
10045 			config.state = new_crtc_state->base.vrr_enabled ?
10046 						     VRR_STATE_ACTIVE_VARIABLE :
10047 						     VRR_STATE_INACTIVE;
10048 		}
10049 	} else {
10050 		config.state = VRR_STATE_UNSUPPORTED;
10051 	}
10052 
10053 	mod_freesync_build_vrr_params(dm->freesync_module,
10054 				      new_stream,
10055 				      &config, &vrr_params);
10056 
10057 	new_crtc_state->freesync_config = config;
10058 	/* Copy state for access from DM IRQ handler */
10059 	acrtc->dm_irq_params.freesync_config = config;
10060 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
10061 	acrtc->dm_irq_params.vrr_params = vrr_params;
10062 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10063 }
10064 
10065 static void amdgpu_dm_handle_vrr_transition(struct amdgpu_display_manager *dm,
10066 					    struct dm_crtc_state *old_state,
10067 					    struct dm_crtc_state *new_state)
10068 {
10069 	struct amdgpu_device *adev = drm_to_adev(new_state->base.crtc->dev);
10070 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
10071 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
10072 
10073 	/* Only DCE gates vupdate on VRR, keep it enabled for DCN */
10074 	bool vrr_gates_vupdate = amdgpu_ip_version(adev, DCE_HWIP, 0) == 0;
10075 
10076 	if (!old_vrr_active && new_vrr_active) {
10077 		/* Transition VRR inactive -> active:
10078 		 * While VRR is active, we must not disable vblank irq, as a
10079 		 * reenable after disable would compute bogus vblank/pflip
10080 		 * timestamps if it likely happened inside display front-porch.
10081 		 *
10082 		 * We also need vupdate irq for the actual core vblank handling
10083 		 * at end of vblank.
10084 		 */
10085 		if (vrr_gates_vupdate)
10086 			WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
10087 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
10088 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR off->on: Get vblank ref\n",
10089 				 __func__, new_state->base.crtc->base.id);
10090 
10091 		scoped_guard(mutex, &dm->dc_lock) {
10092 			dc_exit_ips_for_hw_access(dm->dc);
10093 			amdgpu_dm_psr_set_event(dm, new_state->stream, true,
10094 				psr_event_vrr_transition, true);
10095 			amdgpu_dm_replay_set_event(dm, new_state->stream, true,
10096 				replay_event_vrr, true);
10097 		}
10098 	} else if (old_vrr_active && !new_vrr_active) {
10099 		/* Transition VRR active -> inactive:
10100 		 * Allow vblank irq disable again for fixed refresh rate.
10101 		 */
10102 		if (vrr_gates_vupdate)
10103 			WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
10104 		drm_crtc_vblank_put(new_state->base.crtc);
10105 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR on->off: Drop vblank ref\n",
10106 				 __func__, new_state->base.crtc->base.id);
10107 
10108 		scoped_guard(mutex, &dm->dc_lock) {
10109 			dc_exit_ips_for_hw_access(dm->dc);
10110 			amdgpu_dm_psr_set_event(dm, new_state->stream, false,
10111 				psr_event_vrr_transition, false);
10112 			amdgpu_dm_replay_set_event(dm, new_state->stream, false,
10113 				replay_event_vrr, false);
10114 		}
10115 	}
10116 }
10117 
10118 static void amdgpu_dm_commit_cursors(struct drm_atomic_commit *state)
10119 {
10120 	struct drm_plane *plane;
10121 	struct drm_plane_state *old_plane_state;
10122 	int i;
10123 
10124 	/*
10125 	 * TODO: Make this per-stream so we don't issue redundant updates for
10126 	 * commits with multiple streams.
10127 	 */
10128 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
10129 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
10130 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
10131 }
10132 
10133 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
10134 {
10135 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
10136 
10137 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
10138 }
10139 
10140 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
10141 				    struct drm_plane_state *old_plane_state,
10142 				    struct dc_stream_update *update)
10143 {
10144 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
10145 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
10146 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
10147 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
10148 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
10149 	uint64_t address = afb ? afb->address : 0;
10150 	struct dc_cursor_position position = {0};
10151 	struct dc_cursor_attributes attributes;
10152 	int ret;
10153 
10154 	if (!plane->state->fb && !old_plane_state->fb)
10155 		return;
10156 
10157 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
10158 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
10159 		       plane->state->crtc_h);
10160 
10161 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
10162 	if (ret)
10163 		return;
10164 
10165 	if (!position.enable) {
10166 		/* turn off cursor */
10167 		if (crtc_state && crtc_state->stream) {
10168 			dc_stream_set_cursor_position(crtc_state->stream,
10169 						      &position);
10170 			update->cursor_position = &crtc_state->stream->cursor_position;
10171 		}
10172 		return;
10173 	}
10174 
10175 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
10176 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
10177 
10178 	memset(&attributes, 0, sizeof(attributes));
10179 	attributes.address.high_part = upper_32_bits(address);
10180 	attributes.address.low_part  = lower_32_bits(address);
10181 	attributes.width             = plane->state->crtc_w;
10182 	attributes.height            = plane->state->crtc_h;
10183 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
10184 	attributes.rotation_angle    = 0;
10185 	attributes.attribute_flags.value = 0;
10186 
10187 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
10188 	 * legacy gamma setup.
10189 	 */
10190 	if (crtc_state->cm_is_degamma_srgb &&
10191 	    adev->dm.dc->caps.color.dpp.gamma_corr)
10192 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
10193 
10194 	if (afb)
10195 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
10196 
10197 	if (crtc_state->stream) {
10198 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
10199 						     &attributes))
10200 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
10201 
10202 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
10203 
10204 		if (!dc_stream_set_cursor_position(crtc_state->stream,
10205 						   &position))
10206 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
10207 
10208 		update->cursor_position = &crtc_state->stream->cursor_position;
10209 	}
10210 }
10211 
10212 static void amdgpu_dm_enable_self_refresh(struct amdgpu_display_manager *dm,
10213 					  struct amdgpu_crtc *acrtc_attach,
10214 					  const struct dm_crtc_state *acrtc_state,
10215 					  const u64 current_ts)
10216 {
10217 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
10218 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
10219 	struct amdgpu_dm_connector *aconn =
10220 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
10221 
10222 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
10223 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
10224 	    (psr->psr_feature_enabled || pr->replay_feature_enabled)) {
10225 		if (aconn->sr_skip_count > 0)
10226 			aconn->sr_skip_count--;
10227 
10228 		/* Allow SR when skip count is 0. */
10229 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
10230 
10231 		/*
10232 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
10233 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
10234 		 * can be enabled immediately once OS demonstrates an
10235 		 * adequate number of fast atomic commits to notify KMD
10236 		 * of update events.
10237 		 * See `amdgpu_dm_crtc_vblank_control_worker()`.
10238 		 */
10239 		if (acrtc_attach->dm_irq_params.allow_sr_entry &&
10240 			(current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
10241 			amdgpu_dm_psr_set_event(dm, acrtc_state->stream, false,
10242 				psr_event_hw_programming, false);
10243 
10244 			amdgpu_dm_replay_set_event(dm, acrtc_state->stream, false,
10245 				replay_event_hw_programming, false);
10246 		}
10247 	} else {
10248 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
10249 	}
10250 }
10251 
10252 static void dm_arm_vblank_event(struct amdgpu_crtc *acrtc,
10253 				struct dm_crtc_state *acrtc_state,
10254 				bool pflip_update,
10255 				bool cursor_update)
10256 {
10257 	assert_spin_locked(&acrtc->base.dev->event_lock);
10258 
10259 	if (!acrtc->base.state->event || acrtc_state->active_planes == 0)
10260 		return;
10261 
10262 	if (pflip_update) {
10263 		WARN_ON(acrtc->pflip_status != AMDGPU_FLIP_NONE);
10264 		WARN_ON(acrtc->event);
10265 
10266 		acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
10267 		acrtc->event = acrtc->base.state->event;
10268 		acrtc->base.state->event = NULL;
10269 
10270 		drm_dbg_state(acrtc->base.dev,
10271 			      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
10272 			      acrtc->crtc_id);
10273 	} else if (cursor_update) {
10274 		acrtc->event = acrtc->base.state->event;
10275 		acrtc->base.state->event = NULL;
10276 	}
10277 }
10278 
10279 /**
10280  * dm_arm_vblank_event_pre_programming - Prepare for programming
10281  * @acrtc: The amdgpu CRTC to prepare
10282  * @acrtc_state: The new CRTC state
10283  * @pflip_update: Whether a page flip is being programmed
10284  * @cursor_update: Whether a cursor update is being programmed
10285  *
10286  * Grab a reference on the vblank counter if a page flip or cursor update is to
10287  * be programmed. Do this before programming so the HW is not in any
10288  * idle-optimized state (such as PSR).
10289  */
10290 static void dm_arm_vblank_event_pre_programming(struct amdgpu_crtc *acrtc,
10291 						struct dm_crtc_state *acrtc_state,
10292 						bool pflip_update,
10293 						bool cursor_update)
10294 {
10295 	assert_spin_locked(&acrtc->base.dev->event_lock);
10296 
10297 	if (!acrtc->base.state->event || acrtc_state->active_planes == 0)
10298 		return;
10299 
10300 	if (pflip_update || cursor_update)
10301 		drm_crtc_vblank_get(&acrtc->base);
10302 }
10303 
10304 static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state,
10305 				    struct drm_device *dev,
10306 				    struct amdgpu_display_manager *dm,
10307 				    struct drm_crtc *pcrtc,
10308 				    bool wait_for_vblank)
10309 {
10310 	u32 i;
10311 	u64 timestamp_ns = ktime_get_ns();
10312 	struct drm_plane *plane;
10313 	struct drm_plane_state *old_plane_state, *new_plane_state;
10314 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
10315 	struct drm_crtc_state *new_pcrtc_state =
10316 			drm_atomic_get_new_crtc_state(state, pcrtc);
10317 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
10318 	struct dm_crtc_state *dm_old_crtc_state =
10319 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
10320 	int planes_count = 0, vpos, hpos;
10321 	unsigned long flags;
10322 	u32 target_vblank, last_flip_vblank;
10323 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
10324 	bool cursor_update = false;
10325 	bool pflip_present = false;
10326 	bool immediate_flip = false;
10327 	bool flip_latched_during_prog = false;
10328 	bool dirty_rects_changed = false;
10329 	bool updated_planes_and_streams = false;
10330 	struct {
10331 		struct dc_surface_update surface_updates[MAX_SURFACES];
10332 		struct dc_plane_info plane_infos[MAX_SURFACES];
10333 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
10334 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
10335 		struct dc_stream_update stream_update;
10336 	} *bundle;
10337 
10338 	bundle = kzalloc_obj(*bundle);
10339 
10340 	if (!bundle) {
10341 		drm_err(dev, "Failed to allocate update bundle\n");
10342 		goto cleanup;
10343 	}
10344 
10345 	/*
10346 	 * Disable the cursor first if we're disabling all the planes.
10347 	 * It'll remain on the screen after the planes are re-enabled
10348 	 * if we don't.
10349 	 *
10350 	 * If the cursor is transitioning from native to overlay mode, the
10351 	 * native cursor needs to be disabled first.
10352 	 */
10353 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
10354 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10355 		struct dc_cursor_position cursor_position = {0};
10356 
10357 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
10358 						   &cursor_position))
10359 			drm_err(dev, "DC failed to disable native cursor\n");
10360 
10361 		bundle->stream_update.cursor_position =
10362 				&acrtc_state->stream->cursor_position;
10363 	}
10364 
10365 	if (acrtc_state->active_planes == 0 &&
10366 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10367 		amdgpu_dm_commit_cursors(state);
10368 
10369 	/* update planes when needed */
10370 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
10371 		struct drm_crtc *crtc = new_plane_state->crtc;
10372 		struct drm_crtc_state *new_crtc_state;
10373 		struct drm_framebuffer *fb = new_plane_state->fb;
10374 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
10375 		bool plane_needs_flip;
10376 		struct dc_plane_state *dc_plane;
10377 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
10378 
10379 		/* Cursor plane is handled after stream updates */
10380 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
10381 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10382 			if ((fb && crtc == pcrtc) ||
10383 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
10384 				cursor_update = true;
10385 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
10386 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
10387 			}
10388 
10389 			continue;
10390 		}
10391 
10392 		if (!fb || !crtc || pcrtc != crtc)
10393 			continue;
10394 
10395 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
10396 		if (!new_crtc_state->active)
10397 			continue;
10398 
10399 		dc_plane = dm_new_plane_state->dc_state;
10400 		if (!dc_plane)
10401 			continue;
10402 
10403 		bundle->surface_updates[planes_count].surface = dc_plane;
10404 		if (new_pcrtc_state->color_mgmt_changed || new_plane_state->color_mgmt_changed) {
10405 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
10406 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
10407 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
10408 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
10409 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
10410 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
10411 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
10412 		}
10413 
10414 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
10415 				     &bundle->scaling_infos[planes_count]);
10416 
10417 		bundle->surface_updates[planes_count].scaling_info =
10418 			&bundle->scaling_infos[planes_count];
10419 
10420 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
10421 
10422 		pflip_present = pflip_present || plane_needs_flip;
10423 
10424 		if (!plane_needs_flip) {
10425 			planes_count += 1;
10426 			continue;
10427 		}
10428 
10429 		fill_dc_plane_info_and_addr(
10430 			dm->adev, new_plane_state,
10431 			afb->tiling_flags,
10432 			&bundle->plane_infos[planes_count],
10433 			&bundle->flip_addrs[planes_count].address,
10434 			afb->tmz_surface);
10435 
10436 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
10437 				 new_plane_state->plane->index,
10438 				 bundle->plane_infos[planes_count].dcc.enable);
10439 
10440 		bundle->surface_updates[planes_count].plane_info =
10441 			&bundle->plane_infos[planes_count];
10442 
10443 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
10444 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
10445 			fill_dc_dirty_rects(plane, old_plane_state,
10446 					    new_plane_state, new_crtc_state,
10447 					    &bundle->flip_addrs[planes_count],
10448 					    acrtc_state->stream->link->psr_settings.psr_version ==
10449 					    DC_PSR_VERSION_SU_1,
10450 					    &dirty_rects_changed);
10451 
10452 			/*
10453 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
10454 			 * and enabled it again after dirty regions are stable to avoid video glitch.
10455 			 * PSR-SU will be enabled in
10456 			 * amdgpu_dm_crtc_vblank_control_worker() if user
10457 			 * pause the video during the PSR-SU was disabled.
10458 			 */
10459 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
10460 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
10461 			    dirty_rects_changed) {
10462 				mutex_lock(&dm->dc_lock);
10463 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
10464 				timestamp_ns;
10465 				dc_exit_ips_for_hw_access(dm->dc);
10466 				amdgpu_dm_psr_set_event(dm, acrtc_state->stream, true,
10467 					psr_event_hw_programming, true);
10468 				mutex_unlock(&dm->dc_lock);
10469 			}
10470 		}
10471 
10472 		/*
10473 		 * Only allow immediate flips for fast updates that don't
10474 		 * change memory domain, FB pitch, DCC state, rotation or
10475 		 * mirroring.
10476 		 *
10477 		 * dm_crtc_helper_atomic_check() only accepts async flips with
10478 		 * fast updates.
10479 		 */
10480 		if (crtc->state->async_flip &&
10481 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
10482 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
10483 			drm_warn_once(state->dev,
10484 				      "[PLANE:%d:%s] async flip with non-fast update\n",
10485 				      plane->base.id, plane->name);
10486 
10487 		bundle->flip_addrs[planes_count].flip_immediate =
10488 			crtc->state->async_flip &&
10489 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
10490 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
10491 
10492 		immediate_flip |= bundle->flip_addrs[planes_count].flip_immediate;
10493 
10494 		timestamp_ns = ktime_get_ns();
10495 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
10496 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
10497 		bundle->surface_updates[planes_count].surface = dc_plane;
10498 
10499 		if (!bundle->surface_updates[planes_count].surface) {
10500 			drm_err(dev, "No surface for CRTC: id=%d\n",
10501 					acrtc_attach->crtc_id);
10502 			continue;
10503 		}
10504 
10505 		if (plane == pcrtc->primary)
10506 			update_freesync_state_on_stream(
10507 				dm,
10508 				acrtc_state,
10509 				acrtc_state->stream,
10510 				dc_plane,
10511 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
10512 
10513 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
10514 				 __func__,
10515 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
10516 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
10517 
10518 		planes_count += 1;
10519 
10520 	}
10521 
10522 	if (pflip_present) {
10523 		if (!vrr_active) {
10524 			/* Use old throttling in non-vrr fixed refresh rate mode
10525 			 * to keep flip scheduling based on target vblank counts
10526 			 * working in a backwards compatible way, e.g., for
10527 			 * clients using the GLX_OML_sync_control extension or
10528 			 * DRI3/Present extension with defined target_msc.
10529 			 */
10530 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
10531 		} else {
10532 			/* For variable refresh rate mode only:
10533 			 * Get vblank of last completed flip to avoid > 1 vrr
10534 			 * flips per video frame by use of throttling, but allow
10535 			 * flip programming anywhere in the possibly large
10536 			 * variable vrr vblank interval for fine-grained flip
10537 			 * timing control and more opportunity to avoid stutter
10538 			 * on late submission of flips.
10539 			 */
10540 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10541 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
10542 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10543 		}
10544 
10545 		target_vblank = last_flip_vblank + wait_for_vblank;
10546 
10547 		/*
10548 		 * Wait until we're out of the vertical blank period before the one
10549 		 * targeted by the flip
10550 		 */
10551 		while ((acrtc_attach->enabled &&
10552 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
10553 							    0, &vpos, &hpos, NULL,
10554 							    NULL, &pcrtc->hwmode)
10555 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
10556 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
10557 			(int)(target_vblank -
10558 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
10559 			usleep_range(1000, 1100);
10560 		}
10561 
10562 		if (acrtc_state->stream) {
10563 			if (acrtc_state->freesync_vrr_info_changed)
10564 				bundle->stream_update.vrr_infopacket =
10565 					&acrtc_state->stream->vrr_infopacket;
10566 		}
10567 	}
10568 
10569 	scoped_guard(spinlock_irqsave, &pcrtc->dev->event_lock) {
10570 		dm_arm_vblank_event_pre_programming(acrtc_attach, acrtc_state,
10571 						    pflip_present,
10572 						    cursor_update);
10573 		/*
10574 		 * DCE depends on a combination of GRPH_FLIP, VLINE0, and
10575 		 * VUPDATE for event delivery. Only GRPH_FLIP handler can send
10576 		 * pflip events, and it only fires if HW latched to the flip.
10577 		 * Maintain legacy behavior by arming event before programming.
10578 		 */
10579 		if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) {
10580 			dm_arm_vblank_event(acrtc_attach, acrtc_state,
10581 					    pflip_present, cursor_update);
10582 		}
10583 	}
10584 
10585 	/* Update the planes if changed or disable if we don't have any. */
10586 	if ((planes_count || acrtc_state->active_planes == 0) &&
10587 		acrtc_state->stream) {
10588 		/*
10589 		 * If PSR or idle optimizations are enabled then flush out
10590 		 * any pending work before hardware programming.
10591 		 */
10592 		if (dm->vblank_control_workqueue)
10593 			flush_workqueue(dm->vblank_control_workqueue);
10594 
10595 		bundle->stream_update.stream = acrtc_state->stream;
10596 		if (new_pcrtc_state->mode_changed) {
10597 			bundle->stream_update.src = acrtc_state->stream->src;
10598 			bundle->stream_update.dst = acrtc_state->stream->dst;
10599 		}
10600 
10601 		if (new_pcrtc_state->color_mgmt_changed) {
10602 			/*
10603 			 * TODO: This isn't fully correct since we've actually
10604 			 * already modified the stream in place.
10605 			 */
10606 			bundle->stream_update.gamut_remap =
10607 				&acrtc_state->stream->gamut_remap_matrix;
10608 			bundle->stream_update.output_csc_transform =
10609 				&acrtc_state->stream->csc_color_matrix;
10610 			bundle->stream_update.out_transfer_func =
10611 				&acrtc_state->stream->out_transfer_func;
10612 			bundle->stream_update.lut3d_func =
10613 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
10614 			bundle->stream_update.func_shaper =
10615 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
10616 		}
10617 
10618 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
10619 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
10620 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
10621 
10622 		/*
10623 		 * If FreeSync state on the stream has changed then we need to
10624 		 * re-adjust the min/max bounds now that DC doesn't handle this
10625 		 * as part of commit.
10626 		 */
10627 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
10628 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10629 			dc_stream_adjust_vmin_vmax(
10630 				dm->dc, acrtc_state->stream,
10631 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
10632 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10633 		}
10634 		mutex_lock(&dm->dc_lock);
10635 		update_planes_and_stream_adapter(dm->dc,
10636 					 acrtc_state->update_type,
10637 					 planes_count,
10638 					 acrtc_state->stream,
10639 					 &bundle->stream_update,
10640 					 bundle->surface_updates);
10641 		updated_planes_and_streams = true;
10642 
10643 		/**
10644 		 * Enable or disable the interrupts on the backend.
10645 		 *
10646 		 * Most pipes are put into power gating when unused.
10647 		 *
10648 		 * When power gating is enabled on a pipe we lose the
10649 		 * interrupt enablement state when power gating is disabled.
10650 		 *
10651 		 * So we need to update the IRQ control state in hardware
10652 		 * whenever the pipe turns on (since it could be previously
10653 		 * power gated) or off (since some pipes can't be power gated
10654 		 * on some ASICs).
10655 		 */
10656 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
10657 			dm_update_pflip_irq_state(drm_to_adev(dev),
10658 						  acrtc_attach);
10659 		amdgpu_dm_enable_self_refresh(dm, acrtc_attach, acrtc_state,
10660 					      timestamp_ns);
10661 		mutex_unlock(&dm->dc_lock);
10662 	}
10663 
10664 	/*
10665 	 * Update cursor state *after* programming all the planes.
10666 	 * This avoids redundant programming in the case where we're going
10667 	 * to be disabling a single plane - those pipes are being disabled.
10668 	 */
10669 	if (acrtc_state->active_planes &&
10670 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
10671 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10672 		amdgpu_dm_commit_cursors(state);
10673 
10674 	/*
10675 	 * DCN specific vblank handling
10676 	 * ============================
10677 	 *
10678 	 * With the event_lock held, arm the vblank event, and determine whether
10679 	 * deliver it immediately, or in VUPDATE_NO_LOCK IRQ (i.e. HW latch
10680 	 * point) handler. Do this *after* programming so that the IRQ handler
10681 	 * will not deliver the event before HW laches onto the programmed
10682 	 * values:
10683 	 *
10684 	 *     Commit thread      IRQ handler                       HW
10685 	 *     -----------------------------------------------------------------
10686 	 *     arm_vblank_event()
10687 	 *                                                          vupdate()
10688 	 *                        vupdate_handler()
10689 	 *                          cook_timestamp()
10690 	 *                          # prev flip already latched,
10691 	 *                          # so flip_latched == true.
10692 	 *                          if event_armed && flip_latched:
10693 	 *                            send_vblank_event()
10694 	 *                            # sent before latch, **BAD!**
10695 	 *     hw_program()
10696 	 *                                                          vupdate()
10697 	 *                                                          **latch**
10698 	 *
10699 	 * There's a consequence of arming after: it's possible for HW to latch
10700 	 * between start of HW programming and acrtc->event/pflip_status arming.
10701 	 * When this happens, the IRQ handler will send the event on the next
10702 	 * immediate latch point, even though HW has already latched. This is
10703 	 * handled by optimistically checking for HW latch after programming,
10704 	 * and if latched, send the event immediately:
10705 	 *
10706 	 *     Commit thread             IRQ handler                HW
10707 	 *     -----------------------------------------------------------------
10708 	 *     hw_program()
10709 	 *                                                          vupdate()
10710 	 *                                                          **latch**
10711 	 *                               vupdate_handler()
10712 	 *                                 cook_timestamp()
10713 	 *                                 # event_armed == false
10714 	 *                                 # **no event sent!**
10715 	 *     arm_vblank_event()
10716 	 *     if flip_latched:
10717 	 *       **send_vblank_event()**
10718 	 *       disarm_vblank_event()
10719 	 *
10720 	 * The IRQ handler is expected to cook the timestamp, but we need to
10721 	 * cook the timestamp before optimistic sending as well. That's because
10722 	 * the following sequence is possible:
10723 	 *
10724 	 *     Commit thread              IRQ handler              HW
10725 	 *     -----------------------------------------------------------------
10726 	 *     hw_program()
10727 	 *     arm_vblank_event()
10728 	 *                                                         vupdate()
10729 	 *                                                         **latch**
10730 	 *     if flip_latched:
10731 	 *       # Need cook before send!
10732 	 *       **cook_timestamp()**
10733 	 *       send_vblank_event()
10734 	 *       disarm_vblank_event()
10735 	 *                                vupdate_handler()
10736 	 *                                  cook_timestamp()
10737 	 *                                  # event_armed == false
10738 	 *                                  # no event sent!
10739 	 *
10740 	 * Cooking twice is OK, since DRM scanout accurate timestamps report A)
10741 	 * the previous vactive start if currently in vactive, or B) the next
10742 	 * vactive start if currently in vblank (see &get_vblank_counter). 'A)'
10743 	 * is what we want for the optimistic send, and for 'B)', we'll cook a
10744 	 * timestamp no later than the next IRQ handler run.
10745 	 *
10746 	 * The more correct fix is to wrap programming and arming with the
10747 	 * event_lock and thus serializing it with the IRQ handler. However,
10748 	 * there are various sleep-waits within
10749 	 * update_planes_and_stream_adapter() that makes spin locking illegal.
10750 	 * And on full updates, it can take 1-2 frame-times to return (see
10751 	 * commit_planes_for_stream).
10752 	 *
10753 	 * On DCE, GRPH_PFLIP IRQ is used and takes care of this.
10754 	 */
10755 	if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0) {
10756 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10757 
10758 		if (updated_planes_and_streams) {
10759 			flip_latched_during_prog =
10760 				!dc_get_flip_pending_on_otg(dm->dc, acrtc_attach->otg_inst);
10761 		}
10762 
10763 		dm_arm_vblank_event(acrtc_attach, acrtc_state,
10764 				    pflip_present, cursor_update);
10765 
10766 		/*
10767 		 * Deliver the event immediately on immediate flip, or on a
10768 		 * update that has already latched.
10769 		 */
10770 		if ((immediate_flip || flip_latched_during_prog) &&
10771 		    acrtc_attach->pflip_status == AMDGPU_FLIP_SUBMITTED &&
10772 		    acrtc_attach->event) {
10773 			drm_crtc_accurate_vblank_count(&acrtc_attach->base);
10774 			drm_crtc_send_vblank_event(&acrtc_attach->base,
10775 						   acrtc_attach->event);
10776 			acrtc_attach->event = NULL;
10777 			drm_crtc_vblank_put(&acrtc_attach->base);
10778 			acrtc_attach->pflip_status = AMDGPU_FLIP_NONE;
10779 		}
10780 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10781 	}
10782 
10783 cleanup:
10784 	kfree(bundle);
10785 }
10786 
10787 static void amdgpu_dm_commit_audio(struct drm_device *dev,
10788 				   struct drm_atomic_commit *state)
10789 {
10790 	struct amdgpu_device *adev = drm_to_adev(dev);
10791 	struct amdgpu_dm_connector *aconnector;
10792 	struct drm_connector *connector;
10793 	struct drm_connector_state *old_con_state, *new_con_state;
10794 	struct drm_crtc_state *new_crtc_state;
10795 	struct dm_crtc_state *new_dm_crtc_state;
10796 	const struct dc_stream_status *status;
10797 	int i, inst;
10798 
10799 	/* Notify device removals. */
10800 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10801 		if (old_con_state->crtc != new_con_state->crtc) {
10802 			/* CRTC changes require notification. */
10803 			goto notify;
10804 		}
10805 
10806 		if (!new_con_state->crtc)
10807 			continue;
10808 
10809 		new_crtc_state = drm_atomic_get_new_crtc_state(
10810 			state, new_con_state->crtc);
10811 
10812 		if (!new_crtc_state)
10813 			continue;
10814 
10815 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10816 			continue;
10817 
10818 notify:
10819 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10820 			continue;
10821 
10822 		aconnector = to_amdgpu_dm_connector(connector);
10823 
10824 		mutex_lock(&adev->dm.audio_lock);
10825 		inst = aconnector->audio_inst;
10826 		aconnector->audio_inst = -1;
10827 		mutex_unlock(&adev->dm.audio_lock);
10828 
10829 		amdgpu_dm_audio_eld_notify(adev, inst);
10830 	}
10831 
10832 	/* Notify audio device additions. */
10833 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10834 		if (!new_con_state->crtc)
10835 			continue;
10836 
10837 		new_crtc_state = drm_atomic_get_new_crtc_state(
10838 			state, new_con_state->crtc);
10839 
10840 		if (!new_crtc_state)
10841 			continue;
10842 
10843 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10844 			continue;
10845 
10846 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
10847 		if (!new_dm_crtc_state->stream)
10848 			continue;
10849 
10850 		status = dc_stream_get_status(new_dm_crtc_state->stream);
10851 		if (!status)
10852 			continue;
10853 
10854 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10855 			continue;
10856 
10857 		aconnector = to_amdgpu_dm_connector(connector);
10858 
10859 		mutex_lock(&adev->dm.audio_lock);
10860 		inst = status->audio_inst;
10861 		aconnector->audio_inst = inst;
10862 		mutex_unlock(&adev->dm.audio_lock);
10863 
10864 		amdgpu_dm_audio_eld_notify(adev, inst);
10865 	}
10866 }
10867 
10868 /*
10869  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
10870  * @crtc_state: the DRM CRTC state
10871  * @stream_state: the DC stream state.
10872  *
10873  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
10874  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
10875  */
10876 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
10877 						struct dc_stream_state *stream_state)
10878 {
10879 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
10880 }
10881 
10882 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
10883 			      struct dm_crtc_state *crtc_state)
10884 {
10885 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
10886 }
10887 
10888 /**
10889  * amdgpu_dm_mod_power_update_streams - update mod_power stream state on modeset
10890  * @state: the drm atomic state
10891  * @dm: the display manager to update mod_power on
10892  *
10893  * Notify mod_power of stream changes on modeset events, and disable PSR/Replay
10894  * in preparation for hardware programming. See also
10895  * amdgpu_dm_mod_power_setup_streams() for post-modeset mod_power setup.
10896  */
10897 static void amdgpu_dm_mod_power_update_streams(struct drm_atomic_commit *state,
10898 					       struct amdgpu_display_manager *dm)
10899 {
10900 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10901 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10902 	struct amdgpu_dm_connector *aconnector;
10903 	struct drm_crtc *crtc;
10904 	int i = 0;
10905 
10906 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10907 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10908 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10909 
10910 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10911 			continue;
10912 
10913 		/*
10914 		 * Update mod_power on modeset event in preparation for hw
10915 		 * programming. Always use the old stream, since it would have
10916 		 * been previously added to mod_power. If old stream is null (on
10917 		 * crtc enable, for example), mod_power will no-op, which is the
10918 		 * desried behavior.
10919 		 */
10920 		if (old_crtc_state->active) {
10921 			scoped_guard(mutex, &dm->dc_lock) {
10922 				dc_exit_ips_for_hw_access(dm->dc);
10923 				amdgpu_dm_psr_set_event(dm, dm_old_crtc_state->stream, true,
10924 					psr_event_hw_programming, true);
10925 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, true,
10926 					replay_event_hw_programming, true);
10927 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, false,
10928 					replay_event_general_ui, false);
10929 			}
10930 		}
10931 
10932 		if (new_crtc_state->active) {
10933 			aconnector = (struct amdgpu_dm_connector *)
10934 				dm_new_crtc_state->stream->dm_stream_context;
10935 			if (old_crtc_state->active) {
10936 				mod_power_replace_stream(dm->power_module,
10937 					dm_old_crtc_state->stream,
10938 					dm_new_crtc_state->stream,
10939 					&aconnector->psr_caps);
10940 			} else {
10941 				mod_power_add_stream(dm->power_module,
10942 					dm_new_crtc_state->stream,
10943 					&aconnector->psr_caps);
10944 			}
10945 		} else if (old_crtc_state->active) {
10946 			mod_power_remove_stream(dm->power_module,
10947 				dm_old_crtc_state->stream);
10948 		}
10949 	}
10950 }
10951 
10952 /**
10953  * amdgpu_dm_mod_power_setup_streams - setup mod_power stream state post modeset
10954  * @state: the drm atomic state
10955  * @dm: the display manager to update mod_power on
10956  *
10957  * Notify mod_power of mode_change. This needs to be done after dc_stream
10958  * updates have been committed, and VRR parameters have been updated.
10959  */
10960 static void amdgpu_dm_mod_power_setup_streams(struct drm_atomic_commit *state,
10961 					      struct amdgpu_display_manager *dm)
10962 {
10963 	struct dm_crtc_state *dm_new_crtc_state;
10964 	struct drm_crtc_state *new_crtc_state;
10965 	struct amdgpu_crtc *acrtc;
10966 	struct drm_crtc *crtc;
10967 	int i = 0;
10968 
10969 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10970 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10971 		acrtc = to_amdgpu_crtc(crtc);
10972 
10973 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10974 			continue;
10975 
10976 		if (new_crtc_state->active) {
10977 			amdgpu_dm_link_setup_replay(dm_new_crtc_state->stream,
10978 					&acrtc->dm_irq_params.vrr_params);
10979 			mod_power_notify_mode_change(dm->power_module,
10980 						dm_new_crtc_state->stream,
10981 						false);
10982 
10983 			/*
10984 			 * Block PSR / Replay on the new stream until display settles post-modeset.
10985 			 * These events will be cleared by amdgpu_dm_enable_self_refresh() once
10986 			 * allow_sr_entry becomes true.
10987 			 */
10988 			amdgpu_dm_psr_set_event(dm, dm_new_crtc_state->stream, true,
10989 				psr_event_hw_programming, true);
10990 
10991 			amdgpu_dm_replay_set_event(dm, dm_new_crtc_state->stream, true,
10992 				replay_event_hw_programming | replay_event_general_ui,
10993 				true);
10994 		}
10995 	}
10996 
10997 }
10998 
10999 static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state,
11000 					struct dc_state *dc_state)
11001 {
11002 	struct drm_device *dev = state->dev;
11003 	struct amdgpu_device *adev = drm_to_adev(dev);
11004 	struct amdgpu_display_manager *dm = &adev->dm;
11005 	struct drm_crtc *crtc;
11006 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11007 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11008 	struct drm_connector_state *old_con_state;
11009 	struct drm_connector *connector;
11010 	bool mode_set_reset_required = false;
11011 	u32 i;
11012 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
11013 	bool set_backlight_level = false;
11014 
11015 	/* Disable writeback */
11016 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
11017 		struct dm_connector_state *dm_old_con_state;
11018 		struct amdgpu_crtc *acrtc;
11019 
11020 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11021 			continue;
11022 
11023 		old_crtc_state = NULL;
11024 
11025 		dm_old_con_state = to_dm_connector_state(old_con_state);
11026 		if (!dm_old_con_state->base.crtc)
11027 			continue;
11028 
11029 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
11030 		if (acrtc)
11031 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11032 
11033 		if (!acrtc || !acrtc->wb_enabled)
11034 			continue;
11035 
11036 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11037 
11038 		dm_clear_writeback(dm, dm_old_crtc_state);
11039 		acrtc->wb_enabled = false;
11040 	}
11041 
11042 	amdgpu_dm_mod_power_update_streams(state, dm);
11043 
11044 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
11045 				      new_crtc_state, i) {
11046 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11047 
11048 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11049 
11050 		if (old_crtc_state->active &&
11051 		    (!new_crtc_state->active ||
11052 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11053 			manage_dm_interrupts(adev, acrtc, NULL);
11054 			dc_stream_release(dm_old_crtc_state->stream);
11055 		}
11056 	}
11057 
11058 	drm_atomic_helper_calc_timestamping_constants(state);
11059 
11060 	/* update changed items */
11061 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11062 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11063 
11064 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11065 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11066 
11067 		drm_dbg_state(state->dev,
11068 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
11069 			acrtc->crtc_id,
11070 			new_crtc_state->enable,
11071 			new_crtc_state->active,
11072 			new_crtc_state->planes_changed,
11073 			new_crtc_state->mode_changed,
11074 			new_crtc_state->active_changed,
11075 			new_crtc_state->connectors_changed);
11076 
11077 		/* Disable cursor if disabling crtc */
11078 		if (old_crtc_state->active && !new_crtc_state->active) {
11079 			struct dc_cursor_position position;
11080 
11081 			memset(&position, 0, sizeof(position));
11082 			mutex_lock(&dm->dc_lock);
11083 			dc_exit_ips_for_hw_access(dm->dc);
11084 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
11085 			mutex_unlock(&dm->dc_lock);
11086 		}
11087 
11088 		/* Copy all transient state flags into dc state */
11089 		if (dm_new_crtc_state->stream) {
11090 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
11091 							    dm_new_crtc_state->stream);
11092 		}
11093 
11094 		/* handles headless hotplug case, updating new_state and
11095 		 * aconnector as needed
11096 		 */
11097 
11098 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
11099 
11100 			drm_dbg_atomic(dev,
11101 				       "Atomic commit: SET crtc id %d: [%p]\n",
11102 				       acrtc->crtc_id, acrtc);
11103 
11104 			if (!dm_new_crtc_state->stream) {
11105 				/*
11106 				 * this could happen because of issues with
11107 				 * userspace notifications delivery.
11108 				 * In this case userspace tries to set mode on
11109 				 * display which is disconnected in fact.
11110 				 * dc_sink is NULL in this case on aconnector.
11111 				 * We expect reset mode will come soon.
11112 				 *
11113 				 * This can also happen when unplug is done
11114 				 * during resume sequence ended
11115 				 *
11116 				 * In this case, we want to pretend we still
11117 				 * have a sink to keep the pipe running so that
11118 				 * hw state is consistent with the sw state
11119 				 */
11120 				drm_dbg_atomic(dev,
11121 					       "Failed to create new stream for crtc %d\n",
11122 						acrtc->base.base.id);
11123 				continue;
11124 			}
11125 
11126 			if (dm_old_crtc_state->stream)
11127 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
11128 
11129 			pm_runtime_get_noresume(dev->dev);
11130 
11131 			acrtc->enabled = true;
11132 			acrtc->hw_mode = new_crtc_state->mode;
11133 			crtc->hwmode = new_crtc_state->mode;
11134 			mode_set_reset_required = true;
11135 			set_backlight_level = true;
11136 		} else if (modereset_required(new_crtc_state)) {
11137 			drm_dbg_atomic(dev,
11138 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
11139 				       acrtc->crtc_id, acrtc);
11140 			/* i.e. reset mode */
11141 			if (dm_old_crtc_state->stream)
11142 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
11143 
11144 			mode_set_reset_required = true;
11145 		}
11146 	} /* for_each_crtc_in_state() */
11147 
11148 	/* if there mode set or reset, flush vblank work queue */
11149 	if (mode_set_reset_required) {
11150 		if (dm->vblank_control_workqueue)
11151 			flush_workqueue(dm->vblank_control_workqueue);
11152 	}
11153 
11154 	dm_enable_per_frame_crtc_master_sync(dc_state);
11155 	mutex_lock(&dm->dc_lock);
11156 	dc_exit_ips_for_hw_access(dm->dc);
11157 	WARN_ON(!dc_commit_streams(dm->dc, &params));
11158 
11159 	bool frl_stream_found = false;
11160 
11161 	for (i = 0; i < params.stream_count; i++) {
11162 		struct dc_stream_state *stream = params.streams[i];
11163 
11164 		if (stream->signal == SIGNAL_TYPE_HDMI_FRL) {
11165 			frl_stream_found = true;
11166 			break;
11167 		}
11168 	}
11169 	if (frl_stream_found) {
11170 		if (queue_delayed_work(dm->hdmi_frl_status_polling_wq,
11171 				       &dm->hdmi_frl_status_polling_work,
11172 				       msecs_to_jiffies(dm->hdmi_frl_status_polling_delay_ms)))
11173 			drm_dbg_kms(dev, "200ms frl status polling starts ...\n");
11174 	} else {
11175 		if (cancel_delayed_work_sync(&dm->hdmi_frl_status_polling_work))
11176 			drm_dbg_kms(dev, "200ms frl status polling stops ...\n");
11177 	}
11178 	/* Allow idle optimization when vblank count is 0 for display off */
11179 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
11180 		dc_allow_idle_optimizations(dm->dc, true);
11181 	mutex_unlock(&dm->dc_lock);
11182 
11183 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11184 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11185 
11186 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11187 
11188 		if (dm_new_crtc_state->stream != NULL) {
11189 			const struct dc_stream_status *status =
11190 					dc_stream_get_status(dm_new_crtc_state->stream);
11191 
11192 			if (!status)
11193 				status = dc_state_get_stream_status(dc_state,
11194 									 dm_new_crtc_state->stream);
11195 			if (!status)
11196 				drm_err(dev,
11197 					"got no status for stream %p on acrtc%p\n",
11198 					dm_new_crtc_state->stream, acrtc);
11199 			else
11200 				acrtc->otg_inst = status->primary_otg_inst;
11201 		}
11202 	}
11203 
11204 	/* During boot up and resume the DC layer will reset the panel brightness
11205 	 * to fix a flicker issue.
11206 	 * It will cause the dm->actual_brightness is not the current panel brightness
11207 	 * level. (the dm->brightness is the correct panel level)
11208 	 * So we set the backlight level with dm->brightness value after set mode
11209 	 */
11210 	if (set_backlight_level) {
11211 		for (i = 0; i < dm->num_of_edps; i++) {
11212 			if (dm->backlight_dev[i])
11213 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11214 		}
11215 	}
11216 }
11217 
11218 static void dm_set_writeback(struct amdgpu_display_manager *dm,
11219 			      struct dm_crtc_state *crtc_state,
11220 			      struct drm_connector *connector,
11221 			      struct drm_connector_state *new_con_state)
11222 {
11223 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
11224 	struct amdgpu_device *adev = dm->adev;
11225 	struct amdgpu_crtc *acrtc;
11226 	struct dc_writeback_info *wb_info;
11227 	struct pipe_ctx *pipe = NULL;
11228 	struct amdgpu_framebuffer *afb;
11229 	int i = 0;
11230 
11231 	wb_info = kzalloc_obj(*wb_info);
11232 	if (!wb_info) {
11233 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
11234 		return;
11235 	}
11236 
11237 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
11238 	if (!acrtc) {
11239 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
11240 		kfree(wb_info);
11241 		return;
11242 	}
11243 
11244 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
11245 	if (!afb) {
11246 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
11247 		kfree(wb_info);
11248 		return;
11249 	}
11250 
11251 	for (i = 0; i < MAX_PIPES; i++) {
11252 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
11253 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
11254 			break;
11255 		}
11256 	}
11257 
11258 	/* fill in wb_info */
11259 	wb_info->wb_enabled = true;
11260 
11261 	wb_info->dwb_pipe_inst = 0;
11262 	wb_info->dwb_params.dwbscl_black_color = 0;
11263 	wb_info->dwb_params.hdr_mult = 0x1F000;
11264 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
11265 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
11266 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
11267 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
11268 
11269 	/* width & height from crtc */
11270 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
11271 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
11272 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
11273 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
11274 
11275 	wb_info->dwb_params.cnv_params.crop_en = false;
11276 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
11277 
11278 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
11279 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
11280 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
11281 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
11282 
11283 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
11284 
11285 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
11286 
11287 	wb_info->dwb_params.scaler_taps.h_taps = 1;
11288 	wb_info->dwb_params.scaler_taps.v_taps = 1;
11289 	wb_info->dwb_params.scaler_taps.h_taps_c = 1;
11290 	wb_info->dwb_params.scaler_taps.v_taps_c = 1;
11291 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
11292 
11293 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
11294 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
11295 
11296 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
11297 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
11298 		wb_info->mcif_buf_params.chroma_address[i] = 0;
11299 	}
11300 
11301 	wb_info->mcif_buf_params.p_vmid = 1;
11302 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
11303 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
11304 		wb_info->mcif_warmup_params.region_size =
11305 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
11306 	}
11307 	wb_info->mcif_warmup_params.p_vmid = 1;
11308 	wb_info->writeback_source_plane = pipe->plane_state;
11309 
11310 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
11311 
11312 	acrtc->wb_pending = true;
11313 	acrtc->wb_conn = wb_conn;
11314 	drm_writeback_queue_job(wb_conn, new_con_state);
11315 }
11316 
11317 static void amdgpu_dm_update_hdcp(struct drm_atomic_commit *state)
11318 {
11319 	struct drm_connector_state *old_con_state, *new_con_state;
11320 	struct drm_device *dev = state->dev;
11321 	struct drm_connector *connector;
11322 	struct amdgpu_device *adev = drm_to_adev(dev);
11323 	int i;
11324 
11325 	if (!adev->dm.hdcp_workqueue)
11326 		return;
11327 
11328 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11329 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11330 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11331 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11332 		struct dm_crtc_state *dm_new_crtc_state;
11333 		struct amdgpu_dm_connector *aconnector;
11334 
11335 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11336 			continue;
11337 
11338 		aconnector = to_amdgpu_dm_connector(connector);
11339 
11340 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
11341 
11342 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
11343 			connector->index, connector->status, connector->dpms);
11344 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
11345 			old_con_state->content_protection, new_con_state->content_protection);
11346 
11347 		if (aconnector->dc_sink) {
11348 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
11349 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
11350 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
11351 				aconnector->dc_sink->edid_caps.display_name);
11352 			}
11353 		}
11354 
11355 		new_crtc_state = NULL;
11356 		old_crtc_state = NULL;
11357 
11358 		if (acrtc) {
11359 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11360 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11361 		}
11362 
11363 		if (old_crtc_state)
11364 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11365 			old_crtc_state->enable,
11366 			old_crtc_state->active,
11367 			old_crtc_state->mode_changed,
11368 			old_crtc_state->active_changed,
11369 			old_crtc_state->connectors_changed);
11370 
11371 		if (new_crtc_state)
11372 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11373 			new_crtc_state->enable,
11374 			new_crtc_state->active,
11375 			new_crtc_state->mode_changed,
11376 			new_crtc_state->active_changed,
11377 			new_crtc_state->connectors_changed);
11378 
11379 
11380 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11381 
11382 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
11383 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
11384 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
11385 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
11386 			dm_new_con_state->update_hdcp = true;
11387 			continue;
11388 		}
11389 
11390 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
11391 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
11392 			/* when display is unplugged from mst hub, connctor will
11393 			 * be destroyed within dm_dp_mst_connector_destroy. connector
11394 			 * hdcp perperties, like type, undesired, desired, enabled,
11395 			 * will be lost. So, save hdcp properties into hdcp_work within
11396 			 * amdgpu_dm_atomic_commit_tail. if the same display is
11397 			 * plugged back with same display index, its hdcp properties
11398 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
11399 			 */
11400 
11401 			bool enable_encryption = false;
11402 
11403 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
11404 				enable_encryption = true;
11405 
11406 			if (aconnector->dc_link && aconnector->dc_sink &&
11407 				aconnector->dc_link->type == dc_connection_mst_branch) {
11408 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
11409 				struct hdcp_workqueue *hdcp_w =
11410 					&hdcp_work[aconnector->dc_link->link_index];
11411 
11412 				hdcp_w->hdcp_content_type[connector->index] =
11413 					new_con_state->hdcp_content_type;
11414 				hdcp_w->content_protection[connector->index] =
11415 					new_con_state->content_protection;
11416 			}
11417 
11418 			if (new_crtc_state && new_crtc_state->mode_changed &&
11419 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
11420 				enable_encryption = true;
11421 
11422 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
11423 
11424 			if (aconnector->dc_link)
11425 				hdcp_update_display(
11426 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
11427 					new_con_state->hdcp_content_type, enable_encryption);
11428 		}
11429 	}
11430 }
11431 
11432 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state)
11433 {
11434 	struct drm_crtc *crtc;
11435 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11436 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11437 	int i, ret;
11438 
11439 	ret = drm_dp_mst_atomic_setup_commit(state);
11440 	if (ret)
11441 		return ret;
11442 
11443 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11444 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11445 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11446 		/*
11447 		 * Color management settings. We also update color properties
11448 		 * when a modeset is needed, to ensure it gets reprogrammed.
11449 		 */
11450 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
11451 		    (dm_new_crtc_state->base.color_mgmt_changed ||
11452 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11453 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11454 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
11455 			if (ret) {
11456 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
11457 				return ret;
11458 			}
11459 		}
11460 	}
11461 
11462 	return 0;
11463 }
11464 
11465 /**
11466  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
11467  * @state: The atomic state to commit
11468  *
11469  * This will tell DC to commit the constructed DC state from atomic_check,
11470  * programming the hardware. Any failures here implies a hardware failure, since
11471  * atomic check should have filtered anything non-kosher.
11472  */
11473 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state)
11474 {
11475 	struct drm_device *dev = state->dev;
11476 	struct amdgpu_device *adev = drm_to_adev(dev);
11477 	struct amdgpu_display_manager *dm = &adev->dm;
11478 	struct dm_atomic_state *dm_state;
11479 	struct dc_state *dc_state = NULL;
11480 	u32 i, j;
11481 	struct drm_crtc *crtc;
11482 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11483 	unsigned long flags;
11484 	bool wait_for_vblank = true;
11485 	struct drm_connector *connector;
11486 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
11487 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11488 	int crtc_disable_count = 0;
11489 
11490 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
11491 
11492 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
11493 	drm_dp_mst_atomic_wait_for_dependencies(state);
11494 
11495 	dm_state = dm_atomic_get_new_state(state);
11496 	if (dm_state && dm_state->context) {
11497 		dc_state = dm_state->context;
11498 		amdgpu_dm_commit_streams(state, dc_state);
11499 	}
11500 
11501 	amdgpu_dm_update_hdcp(state);
11502 
11503 	/* Handle connector state changes */
11504 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11505 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11506 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
11507 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11508 		struct dc_surface_update *dummy_updates;
11509 		struct dc_stream_update stream_update;
11510 		struct dc_info_packet hdr_packet;
11511 		struct dc_stream_status *status = NULL;
11512 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
11513 
11514 		memset(&stream_update, 0, sizeof(stream_update));
11515 
11516 		if (acrtc) {
11517 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11518 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11519 		}
11520 
11521 		/* Skip any modesets/resets */
11522 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
11523 			continue;
11524 
11525 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11526 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11527 
11528 		scaling_changed = is_scaling_state_different(dm_new_con_state,
11529 							     dm_old_con_state);
11530 
11531 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
11532 			(dm_old_crtc_state->stream->output_color_space !=
11533 				get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
11534 			output_color_space_changed = true;
11535 
11536 		abm_changed = dm_new_crtc_state->abm_level !=
11537 			      dm_old_crtc_state->abm_level;
11538 
11539 		hdr_changed =
11540 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
11541 
11542 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
11543 			continue;
11544 
11545 		stream_update.stream = dm_new_crtc_state->stream;
11546 		if (scaling_changed) {
11547 			update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
11548 					dm_new_con_state, dm_new_crtc_state->stream);
11549 
11550 			stream_update.src = dm_new_crtc_state->stream->src;
11551 			stream_update.dst = dm_new_crtc_state->stream->dst;
11552 		}
11553 
11554 		if (output_color_space_changed) {
11555 			dm_new_crtc_state->stream->output_color_space
11556 				= get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
11557 
11558 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
11559 		}
11560 
11561 		if (abm_changed) {
11562 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
11563 
11564 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
11565 		}
11566 
11567 		if (hdr_changed) {
11568 			fill_hdr_info_packet(new_con_state, &hdr_packet);
11569 			stream_update.hdr_static_metadata = &hdr_packet;
11570 		}
11571 
11572 		status = dc_stream_get_status(dm_new_crtc_state->stream);
11573 
11574 		if (WARN_ON(!status))
11575 			continue;
11576 
11577 		WARN_ON(!status->plane_count);
11578 
11579 		/*
11580 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
11581 		 * Here we create an empty update on each plane.
11582 		 * To fix this, DC should permit updating only stream properties.
11583 		 */
11584 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
11585 		if (!dummy_updates) {
11586 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
11587 			continue;
11588 		}
11589 		for (j = 0; j < status->plane_count; j++)
11590 			dummy_updates[j].surface = status->plane_states[j];
11591 
11592 		sort(dummy_updates, status->plane_count,
11593 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
11594 
11595 		mutex_lock(&dm->dc_lock);
11596 		dc_exit_ips_for_hw_access(dm->dc);
11597 		dc_update_planes_and_stream(dm->dc,
11598 					    dummy_updates,
11599 					    status->plane_count,
11600 					    dm_new_crtc_state->stream,
11601 					    &stream_update);
11602 		mutex_unlock(&dm->dc_lock);
11603 		kfree(dummy_updates);
11604 
11605 		drm_connector_update_privacy_screen(new_con_state);
11606 	}
11607 
11608 	/**
11609 	 * Enable interrupts for CRTCs that are newly enabled or went through
11610 	 * a modeset. It was intentionally deferred until after the front end
11611 	 * state was modified to wait until the OTG was on and so the IRQ
11612 	 * handlers didn't access stale or invalid state.
11613 	 */
11614 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11615 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11616 #ifdef CONFIG_DEBUG_FS
11617 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
11618 #endif
11619 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
11620 		if (old_crtc_state->active && !new_crtc_state->active)
11621 			crtc_disable_count++;
11622 
11623 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11624 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11625 
11626 		/* For freesync config update on crtc state and params for irq */
11627 		update_stream_irq_parameters(dm, dm_new_crtc_state);
11628 
11629 #ifdef CONFIG_DEBUG_FS
11630 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11631 		cur_crc_src = acrtc->dm_irq_params.crc_src;
11632 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11633 #endif
11634 
11635 		if (new_crtc_state->active &&
11636 		    (!old_crtc_state->active ||
11637 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11638 			dc_stream_retain(dm_new_crtc_state->stream);
11639 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
11640 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
11641 		}
11642 		/* Handle vrr on->off / off->on transitions */
11643 		amdgpu_dm_handle_vrr_transition(dm, dm_old_crtc_state, dm_new_crtc_state);
11644 
11645 #ifdef CONFIG_DEBUG_FS
11646 		if (new_crtc_state->active &&
11647 		    (!old_crtc_state->active ||
11648 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11649 			/**
11650 			 * Frontend may have changed so reapply the CRC capture
11651 			 * settings for the stream.
11652 			 */
11653 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
11654 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
11655 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
11656 					uint8_t cnt;
11657 
11658 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11659 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
11660 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
11661 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
11662 
11663 							/**
11664 							 * It takes 2 frames for HW to stably generate CRC when
11665 							 * resuming from suspend, so we set skip_frame_cnt 2.
11666 							 */
11667 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
11668 						}
11669 					}
11670 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11671 				}
11672 #endif
11673 				if (amdgpu_dm_crtc_configure_crc_source(
11674 					crtc, dm_new_crtc_state, cur_crc_src))
11675 					drm_dbg_atomic(dev, "Failed to configure crc source");
11676 			}
11677 		}
11678 #endif
11679 	}
11680 
11681 	amdgpu_dm_mod_power_setup_streams(state, dm);
11682 
11683 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
11684 		if (new_crtc_state->async_flip)
11685 			wait_for_vblank = false;
11686 
11687 	/* update planes when needed per crtc*/
11688 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
11689 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11690 
11691 		if (dm_new_crtc_state->stream)
11692 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
11693 	}
11694 
11695 	/* Enable writeback */
11696 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11697 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11698 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11699 
11700 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11701 			continue;
11702 
11703 		if (!new_con_state->writeback_job)
11704 			continue;
11705 
11706 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11707 
11708 		if (!new_crtc_state)
11709 			continue;
11710 
11711 		if (acrtc->wb_enabled)
11712 			continue;
11713 
11714 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11715 
11716 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
11717 		acrtc->wb_enabled = true;
11718 	}
11719 
11720 	/* Update audio instances for each connector. */
11721 	amdgpu_dm_commit_audio(dev, state);
11722 
11723 	/* restore the backlight level */
11724 	for (i = 0; i < dm->num_of_edps; i++) {
11725 		if (dm->backlight_dev[i] &&
11726 		    (dm->actual_brightness[i] != dm->brightness[i]))
11727 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11728 	}
11729 
11730 	/*
11731 	 * send vblank event on all events not handled in flip and
11732 	 * mark consumed event for drm_atomic_helper_commit_hw_done
11733 	 */
11734 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11735 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11736 
11737 		if (new_crtc_state->event)
11738 			drm_send_event_locked(dev, &new_crtc_state->event->base);
11739 
11740 		new_crtc_state->event = NULL;
11741 	}
11742 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11743 
11744 	/* Signal HW programming completion */
11745 	drm_atomic_helper_commit_hw_done(state);
11746 
11747 	if (wait_for_vblank)
11748 		drm_atomic_helper_wait_for_flip_done(dev, state);
11749 
11750 	drm_atomic_helper_cleanup_planes(dev, state);
11751 
11752 	/* Don't free the memory if we are hitting this as part of suspend.
11753 	 * This way we don't free any memory during suspend; see
11754 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
11755 	 * non-suspend modeset or when the driver is torn down.
11756 	 */
11757 	if (!adev->in_suspend) {
11758 		/* return the stolen vga memory back to VRAM */
11759 		if (!adev->mman.keep_stolen_vga_memory)
11760 			amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_VGA);
11761 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_EXTENDED);
11762 	}
11763 
11764 	/*
11765 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
11766 	 * so we can put the GPU into runtime suspend if we're not driving any
11767 	 * displays anymore
11768 	 */
11769 	for (i = 0; i < crtc_disable_count; i++)
11770 		pm_runtime_put_autosuspend(dev->dev);
11771 	pm_runtime_mark_last_busy(dev->dev);
11772 
11773 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
11774 }
11775 
11776 static int dm_force_atomic_commit(struct drm_connector *connector)
11777 {
11778 	int ret = 0;
11779 	struct drm_device *ddev = connector->dev;
11780 	struct drm_atomic_commit *state = drm_atomic_commit_alloc(ddev);
11781 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11782 	struct drm_plane *plane = disconnected_acrtc->base.primary;
11783 	struct drm_connector_state *conn_state;
11784 	struct drm_crtc_state *crtc_state;
11785 	struct drm_plane_state *plane_state;
11786 
11787 	if (!state)
11788 		return -ENOMEM;
11789 
11790 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
11791 
11792 	/* Construct an atomic state to restore previous display setting */
11793 
11794 	/*
11795 	 * Attach connectors to drm_atomic_commit
11796 	 */
11797 	conn_state = drm_atomic_get_connector_state(state, connector);
11798 
11799 	/* Check for error in getting connector state */
11800 	if (IS_ERR(conn_state)) {
11801 		ret = PTR_ERR(conn_state);
11802 		goto out;
11803 	}
11804 
11805 	/* Attach crtc to drm_atomic_commit*/
11806 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
11807 
11808 	/* Check for error in getting crtc state */
11809 	if (IS_ERR(crtc_state)) {
11810 		ret = PTR_ERR(crtc_state);
11811 		goto out;
11812 	}
11813 
11814 	/* force a restore */
11815 	crtc_state->mode_changed = true;
11816 
11817 	/* Attach plane to drm_atomic_commit */
11818 	plane_state = drm_atomic_get_plane_state(state, plane);
11819 
11820 	/* Check for error in getting plane state */
11821 	if (IS_ERR(plane_state)) {
11822 		ret = PTR_ERR(plane_state);
11823 		goto out;
11824 	}
11825 
11826 	/* Call commit internally with the state we just constructed */
11827 	ret = drm_atomic_commit(state);
11828 
11829 out:
11830 	drm_atomic_commit_put(state);
11831 	if (ret)
11832 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
11833 
11834 	return ret;
11835 }
11836 
11837 /*
11838  * This function handles all cases when set mode does not come upon hotplug.
11839  * This includes when a display is unplugged then plugged back into the
11840  * same port and when running without usermode desktop manager supprot
11841  */
11842 void dm_restore_drm_connector_state(struct drm_device *dev,
11843 				    struct drm_connector *connector)
11844 {
11845 	struct amdgpu_dm_connector *aconnector;
11846 	struct amdgpu_crtc *disconnected_acrtc;
11847 	struct dm_crtc_state *acrtc_state;
11848 
11849 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11850 		return;
11851 
11852 	aconnector = to_amdgpu_dm_connector(connector);
11853 
11854 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
11855 		return;
11856 
11857 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11858 	if (!disconnected_acrtc)
11859 		return;
11860 
11861 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
11862 	if (!acrtc_state->stream)
11863 		return;
11864 
11865 	/*
11866 	 * If the previous sink is not released and different from the current,
11867 	 * we deduce we are in a state where we can not rely on usermode call
11868 	 * to turn on the display, so we do it here
11869 	 */
11870 	if (acrtc_state->stream->sink != aconnector->dc_sink)
11871 		dm_force_atomic_commit(&aconnector->base);
11872 }
11873 
11874 /*
11875  * Grabs all modesetting locks to serialize against any blocking commits,
11876  * Waits for completion of all non blocking commits.
11877  */
11878 static int do_aquire_global_lock(struct drm_device *dev,
11879 				 struct drm_atomic_commit *state)
11880 {
11881 	struct drm_crtc *crtc;
11882 	struct drm_crtc_commit *commit;
11883 	long ret;
11884 
11885 	/*
11886 	 * Adding all modeset locks to aquire_ctx will
11887 	 * ensure that when the framework release it the
11888 	 * extra locks we are locking here will get released to
11889 	 */
11890 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
11891 	if (ret)
11892 		return ret;
11893 
11894 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
11895 		spin_lock(&crtc->commit_lock);
11896 		commit = list_first_entry_or_null(&crtc->commit_list,
11897 				struct drm_crtc_commit, commit_entry);
11898 		if (commit)
11899 			drm_crtc_commit_get(commit);
11900 		spin_unlock(&crtc->commit_lock);
11901 
11902 		if (!commit)
11903 			continue;
11904 
11905 		/*
11906 		 * Make sure all pending HW programming completed and
11907 		 * page flips done
11908 		 */
11909 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
11910 
11911 		if (ret > 0)
11912 			ret = wait_for_completion_interruptible_timeout(
11913 					&commit->flip_done, 10*HZ);
11914 
11915 		if (ret == 0)
11916 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
11917 				  crtc->base.id, crtc->name);
11918 
11919 		drm_crtc_commit_put(commit);
11920 	}
11921 
11922 	return ret < 0 ? ret : 0;
11923 }
11924 
11925 static void get_freesync_config_for_crtc(
11926 	struct dm_crtc_state *new_crtc_state,
11927 	struct dm_connector_state *new_con_state)
11928 {
11929 	struct mod_freesync_config config = {0};
11930 	struct amdgpu_dm_connector *aconnector;
11931 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
11932 	int vrefresh = drm_mode_vrefresh(mode);
11933 	bool fs_vid_mode = false;
11934 
11935 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11936 		return;
11937 
11938 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
11939 
11940 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
11941 					vrefresh >= aconnector->min_vfreq &&
11942 					vrefresh <= aconnector->max_vfreq;
11943 
11944 	if (new_crtc_state->vrr_supported) {
11945 		new_crtc_state->stream->ignore_msa_timing_param = true;
11946 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
11947 
11948 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
11949 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
11950 		config.vsif_supported = true;
11951 		config.btr = true;
11952 
11953 		if (fs_vid_mode) {
11954 			config.state = VRR_STATE_ACTIVE_FIXED;
11955 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
11956 			goto out;
11957 		} else if (new_crtc_state->base.vrr_enabled) {
11958 			config.state = VRR_STATE_ACTIVE_VARIABLE;
11959 		} else {
11960 			config.state = VRR_STATE_INACTIVE;
11961 		}
11962 	} else {
11963 		config.state = VRR_STATE_UNSUPPORTED;
11964 	}
11965 out:
11966 	new_crtc_state->freesync_config = config;
11967 }
11968 
11969 static void reset_freesync_config_for_crtc(
11970 	struct dm_crtc_state *new_crtc_state)
11971 {
11972 	new_crtc_state->vrr_supported = false;
11973 
11974 	memset(&new_crtc_state->vrr_infopacket, 0,
11975 	       sizeof(new_crtc_state->vrr_infopacket));
11976 }
11977 
11978 static bool
11979 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
11980 				 struct drm_crtc_state *new_crtc_state)
11981 {
11982 	const struct drm_display_mode *old_mode, *new_mode;
11983 
11984 	if (!old_crtc_state || !new_crtc_state)
11985 		return false;
11986 
11987 	old_mode = &old_crtc_state->mode;
11988 	new_mode = &new_crtc_state->mode;
11989 
11990 	if (old_mode->clock       == new_mode->clock &&
11991 	    old_mode->hdisplay    == new_mode->hdisplay &&
11992 	    old_mode->vdisplay    == new_mode->vdisplay &&
11993 	    old_mode->htotal      == new_mode->htotal &&
11994 	    old_mode->vtotal      != new_mode->vtotal &&
11995 	    old_mode->hsync_start == new_mode->hsync_start &&
11996 	    old_mode->vsync_start != new_mode->vsync_start &&
11997 	    old_mode->hsync_end   == new_mode->hsync_end &&
11998 	    old_mode->vsync_end   != new_mode->vsync_end &&
11999 	    old_mode->hskew       == new_mode->hskew &&
12000 	    old_mode->vscan       == new_mode->vscan &&
12001 	    (old_mode->vsync_end - old_mode->vsync_start) ==
12002 	    (new_mode->vsync_end - new_mode->vsync_start))
12003 		return true;
12004 
12005 	return false;
12006 }
12007 
12008 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
12009 {
12010 	u64 num, den, res;
12011 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
12012 
12013 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
12014 
12015 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
12016 	den = (unsigned long long)new_crtc_state->mode.htotal *
12017 	      (unsigned long long)new_crtc_state->mode.vtotal;
12018 
12019 	res = div_u64(num, den);
12020 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
12021 }
12022 
12023 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
12024 			 struct drm_atomic_commit *state,
12025 			 struct drm_crtc *crtc,
12026 			 struct drm_crtc_state *old_crtc_state,
12027 			 struct drm_crtc_state *new_crtc_state,
12028 			 bool enable,
12029 			 bool *lock_and_validation_needed)
12030 {
12031 	struct dm_atomic_state *dm_state = NULL;
12032 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12033 	struct dc_stream_state *new_stream;
12034 	struct amdgpu_device *adev = dm->adev;
12035 	int ret = 0;
12036 
12037 	/*
12038 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
12039 	 * update changed items
12040 	 */
12041 	struct amdgpu_crtc *acrtc = NULL;
12042 	struct drm_connector *connector = NULL;
12043 	struct amdgpu_dm_connector *aconnector = NULL;
12044 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
12045 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
12046 
12047 	new_stream = NULL;
12048 
12049 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12050 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12051 	acrtc = to_amdgpu_crtc(crtc);
12052 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
12053 	if (connector)
12054 		aconnector = to_amdgpu_dm_connector(connector);
12055 
12056 	/* TODO This hack should go away */
12057 	if (connector && enable) {
12058 		/* Make sure fake sink is created in plug-in scenario */
12059 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
12060 									connector);
12061 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
12062 									connector);
12063 
12064 		if (WARN_ON(!drm_new_conn_state)) {
12065 			ret = -EINVAL;
12066 			goto fail;
12067 		}
12068 
12069 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
12070 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
12071 
12072 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
12073 			goto skip_modeset;
12074 
12075 		new_stream = create_validate_stream_for_sink(connector,
12076 							     &new_crtc_state->mode,
12077 							     dm_new_conn_state,
12078 							     dm_old_crtc_state->stream);
12079 
12080 		/*
12081 		 * we can have no stream on ACTION_SET if a display
12082 		 * was disconnected during S3, in this case it is not an
12083 		 * error, the OS will be updated after detection, and
12084 		 * will do the right thing on next atomic commit
12085 		 */
12086 
12087 		if (!new_stream) {
12088 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
12089 					__func__, acrtc->base.base.id);
12090 			ret = -ENOMEM;
12091 			goto fail;
12092 		}
12093 
12094 		/*
12095 		 * TODO: Check VSDB bits to decide whether this should
12096 		 * be enabled or not.
12097 		 */
12098 		new_stream->triggered_crtc_reset.enabled =
12099 			dm->force_timing_sync;
12100 
12101 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
12102 
12103 		ret = fill_hdr_info_packet(drm_new_conn_state,
12104 					   &new_stream->hdr_static_metadata);
12105 		if (ret)
12106 			goto fail;
12107 
12108 		/*
12109 		 * If we already removed the old stream from the context
12110 		 * (and set the new stream to NULL) then we can't reuse
12111 		 * the old stream even if the stream and scaling are unchanged.
12112 		 * We'll hit the BUG_ON and black screen.
12113 		 *
12114 		 * TODO: Refactor this function to allow this check to work
12115 		 * in all conditions.
12116 		 */
12117 		if (amdgpu_freesync_vid_mode &&
12118 		    dm_new_crtc_state->stream &&
12119 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
12120 			goto skip_modeset;
12121 
12122 		if (dm_new_crtc_state->stream &&
12123 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
12124 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
12125 			new_crtc_state->mode_changed = false;
12126 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
12127 					 new_crtc_state->mode_changed);
12128 		}
12129 	}
12130 
12131 	/* mode_changed flag may get updated above, need to check again */
12132 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
12133 		goto skip_modeset;
12134 
12135 	drm_dbg_state(state->dev,
12136 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
12137 		acrtc->crtc_id,
12138 		new_crtc_state->enable,
12139 		new_crtc_state->active,
12140 		new_crtc_state->planes_changed,
12141 		new_crtc_state->mode_changed,
12142 		new_crtc_state->active_changed,
12143 		new_crtc_state->connectors_changed);
12144 
12145 	/* Remove stream for any changed/disabled CRTC */
12146 	if (!enable) {
12147 
12148 		if (!dm_old_crtc_state->stream)
12149 			goto skip_modeset;
12150 
12151 		/* Unset freesync video if it was active before */
12152 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
12153 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
12154 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
12155 		}
12156 
12157 		/* Now check if we should set freesync video mode */
12158 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
12159 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
12160 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
12161 		    is_timing_unchanged_for_freesync(new_crtc_state,
12162 						     old_crtc_state)) {
12163 			new_crtc_state->mode_changed = false;
12164 			drm_dbg_driver(adev_to_drm(adev),
12165 				"Mode change not required for front porch change, setting mode_changed to %d",
12166 				new_crtc_state->mode_changed);
12167 
12168 			set_freesync_fixed_config(dm_new_crtc_state);
12169 
12170 			goto skip_modeset;
12171 		} else if (amdgpu_freesync_vid_mode && aconnector &&
12172 			   is_freesync_video_mode(&new_crtc_state->mode,
12173 						  aconnector)) {
12174 			struct drm_display_mode *high_mode;
12175 
12176 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
12177 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
12178 				set_freesync_fixed_config(dm_new_crtc_state);
12179 		}
12180 
12181 		ret = dm_atomic_get_state(state, &dm_state);
12182 		if (ret)
12183 			goto fail;
12184 
12185 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
12186 				crtc->base.id);
12187 
12188 		/* i.e. reset mode */
12189 		if (dc_state_remove_stream(
12190 				dm->dc,
12191 				dm_state->context,
12192 				dm_old_crtc_state->stream) != DC_OK) {
12193 			ret = -EINVAL;
12194 			goto fail;
12195 		}
12196 
12197 		dc_stream_release(dm_old_crtc_state->stream);
12198 		dm_new_crtc_state->stream = NULL;
12199 
12200 		reset_freesync_config_for_crtc(dm_new_crtc_state);
12201 
12202 		*lock_and_validation_needed = true;
12203 
12204 	} else {/* Add stream for any updated/enabled CRTC */
12205 		/*
12206 		 * Quick fix to prevent NULL pointer on new_stream when
12207 		 * added MST connectors not found in existing crtc_state in the chained mode
12208 		 * TODO: need to dig out the root cause of that
12209 		 */
12210 		if (!connector)
12211 			goto skip_modeset;
12212 
12213 		if (modereset_required(new_crtc_state))
12214 			goto skip_modeset;
12215 
12216 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
12217 				     dm_old_crtc_state->stream)) {
12218 
12219 			WARN_ON(dm_new_crtc_state->stream);
12220 
12221 			ret = dm_atomic_get_state(state, &dm_state);
12222 			if (ret)
12223 				goto fail;
12224 
12225 			dm_new_crtc_state->stream = new_stream;
12226 
12227 			dc_stream_retain(new_stream);
12228 
12229 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
12230 					 crtc->base.id);
12231 
12232 			if (dc_state_add_stream(
12233 					dm->dc,
12234 					dm_state->context,
12235 					dm_new_crtc_state->stream) != DC_OK) {
12236 				ret = -EINVAL;
12237 				goto fail;
12238 			}
12239 
12240 			*lock_and_validation_needed = true;
12241 		}
12242 	}
12243 
12244 skip_modeset:
12245 	/* Release extra reference */
12246 	if (new_stream)
12247 		dc_stream_release(new_stream);
12248 	new_stream = NULL;
12249 
12250 	/*
12251 	 * We want to do dc stream updates that do not require a
12252 	 * full modeset below.
12253 	 */
12254 	if (!(enable && connector && new_crtc_state->active))
12255 		return 0;
12256 	/*
12257 	 * Given above conditions, the dc state cannot be NULL because:
12258 	 * 1. We're in the process of enabling CRTCs (just been added
12259 	 *    to the dc context, or already is on the context)
12260 	 * 2. Has a valid connector attached, and
12261 	 * 3. Is currently active and enabled.
12262 	 * => The dc stream state currently exists.
12263 	 */
12264 	BUG_ON(dm_new_crtc_state->stream == NULL);
12265 
12266 	/* Scaling or underscan settings */
12267 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
12268 				drm_atomic_crtc_needs_modeset(new_crtc_state))
12269 		update_stream_scaling_settings(adev_to_drm(adev),
12270 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
12271 
12272 	/* ABM settings */
12273 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
12274 
12275 	/*
12276 	 * Color management settings. We also update color properties
12277 	 * when a modeset is needed, to ensure it gets reprogrammed.
12278 	 */
12279 	if (dm_new_crtc_state->base.color_mgmt_changed ||
12280 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
12281 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
12282 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
12283 		if (ret)
12284 			goto fail;
12285 	}
12286 
12287 	/* Update Freesync settings. */
12288 	get_freesync_config_for_crtc(dm_new_crtc_state,
12289 				     dm_new_conn_state);
12290 
12291 	return ret;
12292 
12293 fail:
12294 	if (new_stream)
12295 		dc_stream_release(new_stream);
12296 	return ret;
12297 }
12298 
12299 static bool should_reset_plane(struct drm_atomic_commit *state,
12300 			       struct drm_plane *plane,
12301 			       struct drm_plane_state *old_plane_state,
12302 			       struct drm_plane_state *new_plane_state)
12303 {
12304 	struct drm_plane *other;
12305 	struct drm_plane_state *old_other_state, *new_other_state;
12306 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12307 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
12308 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
12309 	struct drm_connector_state *new_con_state;
12310 	struct drm_connector *connector;
12311 	int i;
12312 
12313 	/*
12314 	 * TODO: Remove this hack for all asics once it proves that the
12315 	 * fast updates works fine on DCN3.2+.
12316 	 */
12317 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
12318 	    state->allow_modeset)
12319 		return true;
12320 
12321 	/* Check for writeback commit */
12322 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
12323 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
12324 			continue;
12325 
12326 		if (new_con_state->writeback_job)
12327 			return true;
12328 	}
12329 
12330 	if (amdgpu_in_reset(adev) && state->allow_modeset)
12331 		return true;
12332 
12333 	/* Exit early if we know that we're adding or removing the plane. */
12334 	if (old_plane_state->crtc != new_plane_state->crtc)
12335 		return true;
12336 
12337 	/* old crtc == new_crtc == NULL, plane not in context. */
12338 	if (!new_plane_state->crtc)
12339 		return false;
12340 
12341 	new_crtc_state =
12342 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
12343 	old_crtc_state =
12344 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
12345 
12346 	if (!new_crtc_state)
12347 		return true;
12348 
12349 	/*
12350 	 * A change in cursor mode means a new dc pipe needs to be acquired or
12351 	 * released from the state
12352 	 */
12353 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
12354 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
12355 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
12356 	    old_dm_crtc_state != NULL &&
12357 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
12358 		return true;
12359 	}
12360 
12361 	/* CRTC Degamma changes currently require us to recreate planes. */
12362 	if (new_crtc_state->color_mgmt_changed)
12363 		return true;
12364 
12365 	/* Plane color pipeline or its colorop changes. */
12366 	if (new_plane_state->color_mgmt_changed)
12367 		return true;
12368 
12369 	/*
12370 	 * On zpos change, planes need to be reordered by removing and re-adding
12371 	 * them one by one to the dc state, in order of descending zpos.
12372 	 *
12373 	 * TODO: We can likely skip bandwidth validation if the only thing that
12374 	 * changed about the plane was it'z z-ordering.
12375 	 */
12376 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
12377 		return true;
12378 
12379 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
12380 		return true;
12381 
12382 	/*
12383 	 * If there are any new primary or overlay planes being added or
12384 	 * removed then the z-order can potentially change. To ensure
12385 	 * correct z-order and pipe acquisition the current DC architecture
12386 	 * requires us to remove and recreate all existing planes.
12387 	 *
12388 	 * TODO: Come up with a more elegant solution for this.
12389 	 */
12390 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
12391 		struct amdgpu_framebuffer *old_afb, *new_afb;
12392 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
12393 
12394 		dm_new_other_state = to_dm_plane_state(new_other_state);
12395 		dm_old_other_state = to_dm_plane_state(old_other_state);
12396 
12397 		if (other->type == DRM_PLANE_TYPE_CURSOR)
12398 			continue;
12399 
12400 		if (old_other_state->crtc != new_plane_state->crtc &&
12401 		    new_other_state->crtc != new_plane_state->crtc)
12402 			continue;
12403 
12404 		if (old_other_state->crtc != new_other_state->crtc)
12405 			return true;
12406 
12407 		/* Src/dst size and scaling updates. */
12408 		if (old_other_state->src_w != new_other_state->src_w ||
12409 		    old_other_state->src_h != new_other_state->src_h ||
12410 		    old_other_state->crtc_w != new_other_state->crtc_w ||
12411 		    old_other_state->crtc_h != new_other_state->crtc_h)
12412 			return true;
12413 
12414 		/* Rotation / mirroring updates. */
12415 		if (old_other_state->rotation != new_other_state->rotation)
12416 			return true;
12417 
12418 		/* Blending updates. */
12419 		if (old_other_state->pixel_blend_mode !=
12420 		    new_other_state->pixel_blend_mode)
12421 			return true;
12422 
12423 		/* Alpha updates. */
12424 		if (old_other_state->alpha != new_other_state->alpha)
12425 			return true;
12426 
12427 		/* Colorspace changes. */
12428 		if (old_other_state->color_range != new_other_state->color_range ||
12429 		    old_other_state->color_encoding != new_other_state->color_encoding)
12430 			return true;
12431 
12432 		/* HDR/Transfer Function changes. */
12433 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
12434 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
12435 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
12436 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
12437 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
12438 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
12439 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
12440 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
12441 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
12442 			return true;
12443 
12444 		/* Framebuffer checks fall at the end. */
12445 		if (!old_other_state->fb || !new_other_state->fb)
12446 			continue;
12447 
12448 		/* Pixel format changes can require bandwidth updates. */
12449 		if (old_other_state->fb->format != new_other_state->fb->format)
12450 			return true;
12451 
12452 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
12453 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
12454 
12455 		/* Tiling and DCC changes also require bandwidth updates. */
12456 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
12457 		    old_afb->base.modifier != new_afb->base.modifier)
12458 			return true;
12459 	}
12460 
12461 	return false;
12462 }
12463 
12464 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
12465 			      struct drm_plane_state *new_plane_state,
12466 			      struct drm_framebuffer *fb)
12467 {
12468 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
12469 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
12470 	unsigned int pitch;
12471 	bool linear;
12472 
12473 	if (fb->width > new_acrtc->max_cursor_width ||
12474 	    fb->height > new_acrtc->max_cursor_height) {
12475 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB size %dx%d\n",
12476 				 new_plane_state->fb->width,
12477 				 new_plane_state->fb->height);
12478 		return -EINVAL;
12479 	}
12480 	if (new_plane_state->src_w != fb->width << 16 ||
12481 	    new_plane_state->src_h != fb->height << 16) {
12482 		drm_dbg_atomic(adev_to_drm(adev), "Cropping not supported for cursor plane\n");
12483 		return -EINVAL;
12484 	}
12485 
12486 	/* Pitch in pixels */
12487 	pitch = fb->pitches[0] / fb->format->cpp[0];
12488 
12489 	if (fb->width != pitch) {
12490 		drm_dbg_atomic(adev_to_drm(adev), "Cursor FB width %d doesn't match pitch %d",
12491 				 fb->width, pitch);
12492 		return -EINVAL;
12493 	}
12494 
12495 	switch (pitch) {
12496 	case 64:
12497 	case 128:
12498 	case 256:
12499 		/* FB pitch is supported by cursor plane */
12500 		break;
12501 	default:
12502 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB pitch %d px\n", pitch);
12503 		return -EINVAL;
12504 	}
12505 
12506 	/* Core DRM takes care of checking FB modifiers, so we only need to
12507 	 * check tiling flags when the FB doesn't have a modifier.
12508 	 */
12509 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
12510 		if (adev->family == AMDGPU_FAMILY_GC_12_0_0) {
12511 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
12512 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
12513 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
12514 		} else {
12515 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
12516 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
12517 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
12518 		}
12519 		if (!linear) {
12520 			drm_dbg_atomic(adev_to_drm(adev), "Cursor FB not linear");
12521 			return -EINVAL;
12522 		}
12523 	}
12524 
12525 	return 0;
12526 }
12527 
12528 /*
12529  * Helper function for checking the cursor in native mode
12530  */
12531 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
12532 					struct drm_plane *plane,
12533 					struct drm_plane_state *new_plane_state,
12534 					bool enable)
12535 {
12536 
12537 	struct amdgpu_crtc *new_acrtc;
12538 	int ret;
12539 
12540 	if (!enable || !new_plane_crtc ||
12541 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
12542 		return 0;
12543 
12544 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
12545 
12546 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
12547 		drm_dbg_atomic(new_plane_crtc->dev, "Cropping not supported for cursor plane\n");
12548 		return -EINVAL;
12549 	}
12550 
12551 	if (new_plane_state->fb) {
12552 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
12553 						new_plane_state->fb);
12554 		if (ret)
12555 			return ret;
12556 	}
12557 
12558 	return 0;
12559 }
12560 
12561 static bool dm_should_update_native_cursor(struct drm_atomic_commit *state,
12562 					   struct drm_crtc *old_plane_crtc,
12563 					   struct drm_crtc *new_plane_crtc,
12564 					   bool enable)
12565 {
12566 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12567 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12568 
12569 	if (!enable) {
12570 		if (old_plane_crtc == NULL)
12571 			return true;
12572 
12573 		old_crtc_state = drm_atomic_get_old_crtc_state(
12574 			state, old_plane_crtc);
12575 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12576 
12577 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12578 	} else {
12579 		if (new_plane_crtc == NULL)
12580 			return true;
12581 
12582 		new_crtc_state = drm_atomic_get_new_crtc_state(
12583 			state, new_plane_crtc);
12584 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12585 
12586 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12587 	}
12588 }
12589 
12590 static int dm_update_plane_state(struct dc *dc,
12591 				 struct drm_atomic_commit *state,
12592 				 struct drm_plane *plane,
12593 				 struct drm_plane_state *old_plane_state,
12594 				 struct drm_plane_state *new_plane_state,
12595 				 bool enable,
12596 				 bool *lock_and_validation_needed,
12597 				 bool *is_top_most_overlay)
12598 {
12599 
12600 	struct dm_atomic_state *dm_state = NULL;
12601 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
12602 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12603 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
12604 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
12605 	bool needs_reset, update_native_cursor;
12606 	int ret = 0;
12607 
12608 
12609 	new_plane_crtc = new_plane_state->crtc;
12610 	old_plane_crtc = old_plane_state->crtc;
12611 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
12612 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
12613 
12614 	update_native_cursor = dm_should_update_native_cursor(state,
12615 							      old_plane_crtc,
12616 							      new_plane_crtc,
12617 							      enable);
12618 
12619 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
12620 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12621 						    new_plane_state, enable);
12622 		if (ret)
12623 			return ret;
12624 
12625 		return 0;
12626 	}
12627 
12628 	needs_reset = should_reset_plane(state, plane, old_plane_state,
12629 					 new_plane_state);
12630 
12631 	/* Remove any changed/removed planes */
12632 	if (!enable) {
12633 		if (!needs_reset)
12634 			return 0;
12635 
12636 		if (!old_plane_crtc)
12637 			return 0;
12638 
12639 		old_crtc_state = drm_atomic_get_old_crtc_state(
12640 				state, old_plane_crtc);
12641 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12642 
12643 		if (!dm_old_crtc_state->stream)
12644 			return 0;
12645 
12646 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
12647 				plane->base.id, old_plane_crtc->base.id);
12648 
12649 		ret = dm_atomic_get_state(state, &dm_state);
12650 		if (ret)
12651 			return ret;
12652 
12653 		if (!dc_state_remove_plane(
12654 				dc,
12655 				dm_old_crtc_state->stream,
12656 				dm_old_plane_state->dc_state,
12657 				dm_state->context)) {
12658 
12659 			return -EINVAL;
12660 		}
12661 
12662 		if (dm_old_plane_state->dc_state)
12663 			dc_plane_state_release(dm_old_plane_state->dc_state);
12664 
12665 		dm_new_plane_state->dc_state = NULL;
12666 
12667 		*lock_and_validation_needed = true;
12668 
12669 	} else { /* Add new planes */
12670 		struct dc_plane_state *dc_new_plane_state;
12671 
12672 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
12673 			return 0;
12674 
12675 		if (!new_plane_crtc)
12676 			return 0;
12677 
12678 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
12679 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12680 
12681 		if (!dm_new_crtc_state->stream)
12682 			return 0;
12683 
12684 		if (!needs_reset)
12685 			return 0;
12686 
12687 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
12688 		if (ret)
12689 			goto out;
12690 
12691 		WARN_ON(dm_new_plane_state->dc_state);
12692 
12693 		dc_new_plane_state = dc_create_plane_state(dc);
12694 		if (!dc_new_plane_state) {
12695 			ret = -ENOMEM;
12696 			goto out;
12697 		}
12698 
12699 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
12700 				 plane->base.id, new_plane_crtc->base.id);
12701 
12702 		ret = fill_dc_plane_attributes(
12703 			drm_to_adev(new_plane_crtc->dev),
12704 			dc_new_plane_state,
12705 			new_plane_state,
12706 			new_crtc_state);
12707 		if (ret) {
12708 			dc_plane_state_release(dc_new_plane_state);
12709 			goto out;
12710 		}
12711 
12712 		ret = dm_atomic_get_state(state, &dm_state);
12713 		if (ret) {
12714 			dc_plane_state_release(dc_new_plane_state);
12715 			goto out;
12716 		}
12717 
12718 		/*
12719 		 * Any atomic check errors that occur after this will
12720 		 * not need a release. The plane state will be attached
12721 		 * to the stream, and therefore part of the atomic
12722 		 * state. It'll be released when the atomic state is
12723 		 * cleaned.
12724 		 */
12725 		if (!dc_state_add_plane(
12726 				dc,
12727 				dm_new_crtc_state->stream,
12728 				dc_new_plane_state,
12729 				dm_state->context)) {
12730 
12731 			dc_plane_state_release(dc_new_plane_state);
12732 			ret = -EINVAL;
12733 			goto out;
12734 		}
12735 
12736 		dm_new_plane_state->dc_state = dc_new_plane_state;
12737 
12738 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
12739 
12740 		/* Tell DC to do a full surface update every time there
12741 		 * is a plane change. Inefficient, but works for now.
12742 		 */
12743 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
12744 
12745 		*lock_and_validation_needed = true;
12746 	}
12747 
12748 out:
12749 	/* If enabling cursor overlay failed, attempt fallback to native mode */
12750 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
12751 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12752 						    new_plane_state, enable);
12753 		if (ret)
12754 			return ret;
12755 
12756 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
12757 	}
12758 
12759 	return ret;
12760 }
12761 
12762 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
12763 				       int *src_w, int *src_h)
12764 {
12765 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
12766 	case DRM_MODE_ROTATE_90:
12767 	case DRM_MODE_ROTATE_270:
12768 		*src_w = plane_state->src_h >> 16;
12769 		*src_h = plane_state->src_w >> 16;
12770 		break;
12771 	case DRM_MODE_ROTATE_0:
12772 	case DRM_MODE_ROTATE_180:
12773 	default:
12774 		*src_w = plane_state->src_w >> 16;
12775 		*src_h = plane_state->src_h >> 16;
12776 		break;
12777 	}
12778 }
12779 
12780 static void
12781 dm_get_plane_scale(struct drm_plane_state *plane_state,
12782 		   int *out_plane_scale_w, int *out_plane_scale_h)
12783 {
12784 	int plane_src_w, plane_src_h;
12785 
12786 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
12787 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
12788 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
12789 }
12790 
12791 /*
12792  * The normalized_zpos value cannot be used by this iterator directly. It's only
12793  * calculated for enabled planes, potentially causing normalized_zpos collisions
12794  * between enabled/disabled planes in the atomic state. We need a unique value
12795  * so that the iterator will not generate the same object twice, or loop
12796  * indefinitely.
12797  */
12798 static inline struct __drm_planes_state *__get_next_zpos(
12799 	struct drm_atomic_commit *state,
12800 	struct __drm_planes_state *prev)
12801 {
12802 	unsigned int highest_zpos = 0, prev_zpos = 256;
12803 	uint32_t highest_id = 0, prev_id = UINT_MAX;
12804 	struct drm_plane_state *new_plane_state;
12805 	struct drm_plane *plane;
12806 	int i, highest_i = -1;
12807 
12808 	if (prev != NULL) {
12809 		prev_zpos = prev->new_state->zpos;
12810 		prev_id = prev->ptr->base.id;
12811 	}
12812 
12813 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
12814 		/* Skip planes with higher zpos than the previously returned */
12815 		if (new_plane_state->zpos > prev_zpos ||
12816 		    (new_plane_state->zpos == prev_zpos &&
12817 		     plane->base.id >= prev_id))
12818 			continue;
12819 
12820 		/* Save the index of the plane with highest zpos */
12821 		if (new_plane_state->zpos > highest_zpos ||
12822 		    (new_plane_state->zpos == highest_zpos &&
12823 		     plane->base.id > highest_id)) {
12824 			highest_zpos = new_plane_state->zpos;
12825 			highest_id = plane->base.id;
12826 			highest_i = i;
12827 		}
12828 	}
12829 
12830 	if (highest_i < 0)
12831 		return NULL;
12832 
12833 	return &state->planes[highest_i];
12834 }
12835 
12836 /*
12837  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
12838  * by descending zpos, as read from the new plane state. This is the same
12839  * ordering as defined by drm_atomic_normalize_zpos().
12840  */
12841 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
12842 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
12843 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
12844 		for_each_if(((plane) = __i->ptr,				\
12845 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
12846 			     (old_plane_state) = __i->old_state,		\
12847 			     (new_plane_state) = __i->new_state, 1))
12848 
12849 static int add_affected_mst_dsc_crtcs(struct drm_atomic_commit *state, struct drm_crtc *crtc)
12850 {
12851 	struct drm_connector *connector;
12852 	struct drm_connector_state *conn_state, *old_conn_state;
12853 	struct amdgpu_dm_connector *aconnector = NULL;
12854 	int i;
12855 
12856 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
12857 		if (!conn_state->crtc)
12858 			conn_state = old_conn_state;
12859 
12860 		if (conn_state->crtc != crtc)
12861 			continue;
12862 
12863 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
12864 			continue;
12865 
12866 		aconnector = to_amdgpu_dm_connector(connector);
12867 		if (!aconnector->mst_output_port || !aconnector->mst_root)
12868 			aconnector = NULL;
12869 		else
12870 			break;
12871 	}
12872 
12873 	if (!aconnector)
12874 		return 0;
12875 
12876 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
12877 }
12878 
12879 /**
12880  * DOC: Cursor Modes - Native vs Overlay
12881  *
12882  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
12883  * plane. It does not require a dedicated hw plane to enable, but it is
12884  * subjected to the same z-order and scaling as the hw plane. It also has format
12885  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
12886  * hw plane.
12887  *
12888  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
12889  * own scaling and z-pos. It also has no blending restrictions. It lends to a
12890  * cursor behavior more akin to a DRM client's expectations. However, it does
12891  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
12892  * available.
12893  */
12894 
12895 /**
12896  * dm_plane_color_pipeline_active() - Check if a plane's color pipeline active.
12897  * @state: DRM atomic state
12898  * @plane: DRM plane to check
12899  * @use_old: if true, inspect the old colorop states; otherwise the new ones
12900  *
12901  * A color pipeline may be selected (color_pipeline != NULL) but still is
12902  * inactive if every colorop in the chain is bypassed.  Only return
12903  * true when at least one colorop has bypass == false, meaning the cursor
12904  * would be subjected to the transformation in native mode.
12905  *
12906  * Return: true if the pipeline modifies pixels, false otherwise.
12907  */
12908 static bool dm_plane_color_pipeline_active(struct drm_atomic_commit *state,
12909 					   struct drm_plane *plane,
12910 					   bool use_old)
12911 {
12912 	struct drm_colorop *colorop;
12913 	struct drm_colorop_state *old_colorop_state, *new_colorop_state;
12914 	int i;
12915 
12916 	for_each_oldnew_colorop_in_state(state, colorop, old_colorop_state, new_colorop_state, i) {
12917 		struct drm_colorop_state *cstate = use_old ? old_colorop_state : new_colorop_state;
12918 
12919 		if (cstate->colorop->plane != plane)
12920 			continue;
12921 		if (!cstate->bypass)
12922 			return true;
12923 	}
12924 	return false;
12925 }
12926 
12927 /**
12928  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
12929  * @adev: amdgpu device
12930  * @state: DRM atomic state
12931  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
12932  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
12933  *
12934  * Get whether the cursor should be enabled in native mode, or overlay mode, on
12935  * the dm_crtc_state.
12936  *
12937  * The cursor should be enabled in overlay mode if there exists an underlying
12938  * plane - on which the cursor may be blended - that is either YUV formatted,
12939  * scaled differently from the cursor, or has a color pipeline active.
12940  *
12941  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
12942  * calling this function.
12943  *
12944  * Return: 0 on success, or an error code if getting the cursor plane state
12945  * failed.
12946  */
12947 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
12948 				   struct drm_atomic_commit *state,
12949 				   struct dm_crtc_state *dm_crtc_state,
12950 				   enum amdgpu_dm_cursor_mode *cursor_mode)
12951 {
12952 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
12953 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
12954 	struct drm_plane *plane;
12955 	bool consider_mode_change = false;
12956 	bool entire_crtc_covered = false;
12957 	bool cursor_changed = false;
12958 	int underlying_scale_w, underlying_scale_h;
12959 	int cursor_scale_w, cursor_scale_h;
12960 	int i;
12961 
12962 	/* Overlay cursor not supported on HW before DCN
12963 	 * DCN401/420 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
12964 	 * as previous DCN generations, so enable native mode on DCN401/420
12965 	 *
12966 	 * Always set native cursor mode when the CRTC is disabled,
12967 	 * to make sure it doesn't cause atomic commits to fail when
12968 	 * they are trying to disable the CRTC.
12969 	 */
12970 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1) ||
12971 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
12972 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 1) ||
12973 	    !dm_crtc_state->base.enable) {
12974 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12975 		return 0;
12976 	}
12977 
12978 	/* Init cursor_mode to be the same as current */
12979 	*cursor_mode = dm_crtc_state->cursor_mode;
12980 
12981 	/*
12982 	 * Cursor mode can change if a plane's format changes, scale changes, is
12983 	 * enabled/disabled, z-order changes, or color management properties change.
12984 	 */
12985 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
12986 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
12987 
12988 		/* Only care about planes on this CRTC */
12989 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
12990 			continue;
12991 
12992 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
12993 			cursor_changed = true;
12994 
12995 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
12996 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
12997 		    old_plane_state->fb->format != plane_state->fb->format) {
12998 			consider_mode_change = true;
12999 			break;
13000 		}
13001 
13002 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
13003 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
13004 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
13005 			consider_mode_change = true;
13006 			break;
13007 		}
13008 
13009 		if (dm_plane_color_pipeline_active(state, plane, true) !=
13010 		    dm_plane_color_pipeline_active(state, plane, false)) {
13011 			consider_mode_change = true;
13012 			break;
13013 		}
13014 	}
13015 
13016 	if (!consider_mode_change && !crtc_state->zpos_changed)
13017 		return 0;
13018 
13019 	/*
13020 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
13021 	 * no need to set cursor mode. This avoids needlessly locking the cursor
13022 	 * state.
13023 	 */
13024 	if (!cursor_changed &&
13025 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
13026 		return 0;
13027 	}
13028 
13029 	cursor_state = drm_atomic_get_plane_state(state,
13030 						  crtc_state->crtc->cursor);
13031 	if (IS_ERR(cursor_state))
13032 		return PTR_ERR(cursor_state);
13033 
13034 	/* Cursor is disabled */
13035 	if (!cursor_state->fb)
13036 		return 0;
13037 
13038 	/* For all planes in descending z-order (all of which are below cursor
13039 	 * as per zpos definitions), check their scaling and format
13040 	 */
13041 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
13042 
13043 		/* Only care about non-cursor planes on this CRTC */
13044 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
13045 		    plane->type == DRM_PLANE_TYPE_CURSOR)
13046 			continue;
13047 
13048 		/* Underlying plane is YUV format - use overlay cursor */
13049 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
13050 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
13051 			return 0;
13052 		}
13053 
13054 		/* Underlying plane has an active color pipeline - cursor would be transformed */
13055 		if (dm_plane_color_pipeline_active(state, plane, false)) {
13056 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
13057 			return 0;
13058 		}
13059 
13060 		dm_get_plane_scale(plane_state,
13061 				   &underlying_scale_w, &underlying_scale_h);
13062 		dm_get_plane_scale(cursor_state,
13063 				   &cursor_scale_w, &cursor_scale_h);
13064 
13065 		/* Underlying plane has different scale - use overlay cursor */
13066 		if (cursor_scale_w != underlying_scale_w &&
13067 		    cursor_scale_h != underlying_scale_h) {
13068 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
13069 			return 0;
13070 		}
13071 
13072 		/* If this plane covers the whole CRTC, no need to check planes underneath */
13073 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
13074 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
13075 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
13076 			entire_crtc_covered = true;
13077 			break;
13078 		}
13079 	}
13080 
13081 	/* If planes do not cover the entire CRTC, use overlay mode to enable
13082 	 * cursor over holes
13083 	 */
13084 	if (entire_crtc_covered)
13085 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
13086 	else
13087 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
13088 
13089 	return 0;
13090 }
13091 
13092 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
13093 					    struct drm_atomic_commit *state,
13094 					    struct drm_crtc_state *crtc_state)
13095 {
13096 	struct drm_plane *plane;
13097 	struct drm_plane_state *new_plane_state, *old_plane_state;
13098 
13099 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
13100 		new_plane_state = drm_atomic_get_new_plane_state(state, plane);
13101 		old_plane_state = drm_atomic_get_old_plane_state(state, plane);
13102 
13103 		if (!old_plane_state || !new_plane_state)
13104 			continue;
13105 
13106 		if (old_plane_state->fb && new_plane_state->fb &&
13107 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
13108 			return true;
13109 	}
13110 
13111 	return false;
13112 }
13113 
13114 /**
13115  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
13116  *
13117  * @dev: The DRM device
13118  * @state: The atomic state to commit
13119  *
13120  * Validate that the given atomic state is programmable by DC into hardware.
13121  * This involves constructing a &struct dc_state reflecting the new hardware
13122  * state we wish to commit, then querying DC to see if it is programmable. It's
13123  * important not to modify the existing DC state. Otherwise, atomic_check
13124  * may unexpectedly commit hardware changes.
13125  *
13126  * When validating the DC state, it's important that the right locks are
13127  * acquired. For full updates case which removes/adds/updates streams on one
13128  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
13129  * that any such full update commit will wait for completion of any outstanding
13130  * flip using DRMs synchronization events.
13131  *
13132  * Note that DM adds the affected connectors for all CRTCs in state, when that
13133  * might not seem necessary. This is because DC stream creation requires the
13134  * DC sink, which is tied to the DRM connector state. Cleaning this up should
13135  * be possible but non-trivial - a possible TODO item.
13136  *
13137  * Return: -Error code if validation failed.
13138  */
13139 static int amdgpu_dm_atomic_check(struct drm_device *dev,
13140 				  struct drm_atomic_commit *state)
13141 {
13142 	struct amdgpu_device *adev = drm_to_adev(dev);
13143 	struct dm_atomic_state *dm_state = NULL;
13144 	struct dc *dc = adev->dm.dc;
13145 	struct drm_connector *connector;
13146 	struct drm_connector_state *old_con_state, *new_con_state;
13147 	struct drm_crtc *crtc;
13148 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13149 	struct drm_plane *plane;
13150 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
13151 	enum dc_status status;
13152 	int ret, i;
13153 	bool lock_and_validation_needed = false;
13154 	bool is_top_most_overlay = true;
13155 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
13156 	struct drm_dp_mst_topology_mgr *mgr;
13157 	struct drm_dp_mst_topology_state *mst_state;
13158 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
13159 
13160 	trace_amdgpu_dm_atomic_check_begin(state);
13161 
13162 	ret = drm_atomic_helper_check_modeset(dev, state);
13163 	if (ret) {
13164 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
13165 		goto fail;
13166 	}
13167 
13168 	/* Check connector changes */
13169 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
13170 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
13171 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
13172 
13173 		/* Skip connectors that are disabled or part of modeset already. */
13174 		if (!new_con_state->crtc)
13175 			continue;
13176 
13177 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
13178 		if (IS_ERR(new_crtc_state)) {
13179 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
13180 			ret = PTR_ERR(new_crtc_state);
13181 			goto fail;
13182 		}
13183 
13184 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
13185 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
13186 			new_crtc_state->connectors_changed = true;
13187 	}
13188 
13189 	if (dc_resource_is_dsc_encoding_supported(dc)) {
13190 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13191 			dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13192 			dm_new_crtc_state->mode_changed_independent_from_dsc = new_crtc_state->mode_changed;
13193 		}
13194 
13195 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13196 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
13197 				ret = add_affected_mst_dsc_crtcs(state, crtc);
13198 				if (ret) {
13199 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
13200 					goto fail;
13201 				}
13202 			}
13203 		}
13204 	}
13205 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13206 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
13207 
13208 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
13209 		    !new_crtc_state->color_mgmt_changed &&
13210 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
13211 			dm_old_crtc_state->dsc_force_changed == false)
13212 			continue;
13213 
13214 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
13215 		if (ret) {
13216 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
13217 			goto fail;
13218 		}
13219 
13220 		if (!new_crtc_state->enable)
13221 			continue;
13222 
13223 		ret = drm_atomic_add_affected_connectors(state, crtc);
13224 		if (ret) {
13225 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
13226 			goto fail;
13227 		}
13228 
13229 		ret = drm_atomic_add_affected_planes(state, crtc);
13230 		if (ret) {
13231 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
13232 			goto fail;
13233 		}
13234 
13235 		if (dm_old_crtc_state->dsc_force_changed)
13236 			new_crtc_state->mode_changed = true;
13237 	}
13238 
13239 	/*
13240 	 * Add all primary and overlay planes on the CRTC to the state
13241 	 * whenever a plane is enabled to maintain correct z-ordering
13242 	 * and to enable fast surface updates.
13243 	 */
13244 	drm_for_each_crtc(crtc, dev) {
13245 		bool modified = false;
13246 
13247 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
13248 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
13249 				continue;
13250 
13251 			if (new_plane_state->crtc == crtc ||
13252 			    old_plane_state->crtc == crtc) {
13253 				modified = true;
13254 				break;
13255 			}
13256 		}
13257 
13258 		if (!modified)
13259 			continue;
13260 
13261 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
13262 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
13263 				continue;
13264 
13265 			new_plane_state =
13266 				drm_atomic_get_plane_state(state, plane);
13267 
13268 			if (IS_ERR(new_plane_state)) {
13269 				ret = PTR_ERR(new_plane_state);
13270 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
13271 				goto fail;
13272 			}
13273 		}
13274 	}
13275 
13276 	/*
13277 	 * DC consults the zpos (layer_index in DC terminology) to determine the
13278 	 * hw plane on which to enable the hw cursor (see
13279 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
13280 	 * atomic state, so call drm helper to normalize zpos.
13281 	 */
13282 	ret = drm_atomic_normalize_zpos(dev, state);
13283 	if (ret) {
13284 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
13285 		goto fail;
13286 	}
13287 
13288 	/*
13289 	 * Determine whether cursors on each CRTC should be enabled in native or
13290 	 * overlay mode.
13291 	 */
13292 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13293 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13294 
13295 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
13296 					      &dm_new_crtc_state->cursor_mode);
13297 		if (ret) {
13298 			drm_dbg(dev, "Failed to determine cursor mode\n");
13299 			goto fail;
13300 		}
13301 
13302 		/*
13303 		 * If overlay cursor is needed, DC cannot go through the
13304 		 * native cursor update path. All enabled planes on the CRTC
13305 		 * need to be added for DC to not disable a plane by mistake
13306 		 */
13307 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
13308 			if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
13309 				drm_dbg(dev, "Overlay cursor not supported on DCE\n");
13310 				ret = -EINVAL;
13311 				goto fail;
13312 			}
13313 
13314 			ret = drm_atomic_add_affected_planes(state, crtc);
13315 			if (ret)
13316 				goto fail;
13317 		}
13318 	}
13319 
13320 	/* Remove exiting planes if they are modified */
13321 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13322 
13323 		ret = dm_update_plane_state(dc, state, plane,
13324 					    old_plane_state,
13325 					    new_plane_state,
13326 					    false,
13327 					    &lock_and_validation_needed,
13328 					    &is_top_most_overlay);
13329 		if (ret) {
13330 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13331 			goto fail;
13332 		}
13333 	}
13334 
13335 	/* Disable all crtcs which require disable */
13336 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13337 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
13338 					   old_crtc_state,
13339 					   new_crtc_state,
13340 					   false,
13341 					   &lock_and_validation_needed);
13342 		if (ret) {
13343 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
13344 			goto fail;
13345 		}
13346 	}
13347 
13348 	/* Enable all crtcs which require enable */
13349 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13350 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
13351 					   old_crtc_state,
13352 					   new_crtc_state,
13353 					   true,
13354 					   &lock_and_validation_needed);
13355 		if (ret) {
13356 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
13357 			goto fail;
13358 		}
13359 	}
13360 
13361 	/* Add new/modified planes */
13362 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13363 		ret = dm_update_plane_state(dc, state, plane,
13364 					    old_plane_state,
13365 					    new_plane_state,
13366 					    true,
13367 					    &lock_and_validation_needed,
13368 					    &is_top_most_overlay);
13369 		if (ret) {
13370 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13371 			goto fail;
13372 		}
13373 	}
13374 
13375 #if defined(CONFIG_DRM_AMD_DC_FP)
13376 	if (dc_resource_is_dsc_encoding_supported(dc)) {
13377 		ret = pre_validate_dsc(state, &dm_state, vars);
13378 		if (ret != 0)
13379 			goto fail;
13380 	}
13381 #endif
13382 
13383 	/* Run this here since we want to validate the streams we created */
13384 	ret = drm_atomic_helper_check_planes(dev, state);
13385 	if (ret) {
13386 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
13387 		goto fail;
13388 	}
13389 
13390 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13391 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13392 		if (dm_new_crtc_state->mpo_requested)
13393 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
13394 	}
13395 
13396 	/* Check cursor restrictions */
13397 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13398 		enum amdgpu_dm_cursor_mode required_cursor_mode;
13399 		int is_rotated, is_scaled;
13400 
13401 		/* Overlay cusor not subject to native cursor restrictions */
13402 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13403 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
13404 			continue;
13405 
13406 		/* Check if rotation or scaling is enabled on DCN401 */
13407 		if ((drm_plane_mask(crtc->cursor) &
13408 		     new_crtc_state->plane_mask) &&
13409 		    (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 1) ||
13410 		     amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
13411 		     amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1))) {
13412 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
13413 
13414 			is_rotated = new_cursor_state &&
13415 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
13416 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
13417 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
13418 
13419 			if (is_rotated || is_scaled) {
13420 				drm_dbg_driver(
13421 					crtc->dev,
13422 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
13423 					crtc->base.id, crtc->name);
13424 				ret = -EINVAL;
13425 				goto fail;
13426 			}
13427 		}
13428 
13429 		/* If HW can only do native cursor, check restrictions again */
13430 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
13431 					      &required_cursor_mode);
13432 		if (ret) {
13433 			drm_dbg_driver(crtc->dev,
13434 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
13435 				       crtc->base.id, crtc->name);
13436 			goto fail;
13437 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
13438 			drm_dbg_driver(crtc->dev,
13439 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling, YUV, or color pipeline restrictions\n",
13440 				       crtc->base.id, crtc->name);
13441 			ret = -EINVAL;
13442 			goto fail;
13443 		}
13444 	}
13445 
13446 	if (state->legacy_cursor_update) {
13447 		/*
13448 		 * This is a fast cursor update coming from the plane update
13449 		 * helper, check if it can be done asynchronously for better
13450 		 * performance.
13451 		 */
13452 		state->async_update =
13453 			!drm_atomic_helper_async_check(dev, state);
13454 
13455 		/*
13456 		 * Skip the remaining global validation if this is an async
13457 		 * update. Cursor updates can be done without affecting
13458 		 * state or bandwidth calcs and this avoids the performance
13459 		 * penalty of locking the private state object and
13460 		 * allocating a new dc_state.
13461 		 */
13462 		if (state->async_update)
13463 			return 0;
13464 	}
13465 
13466 	/* Check scaling and underscan changes*/
13467 	/* TODO Removed scaling changes validation due to inability to commit
13468 	 * new stream into context w\o causing full reset. Need to
13469 	 * decide how to handle.
13470 	 */
13471 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
13472 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
13473 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
13474 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
13475 
13476 		/* Skip any modesets/resets */
13477 		if (!acrtc || drm_atomic_crtc_needs_modeset(
13478 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
13479 			continue;
13480 
13481 		/* Skip any thing not scale or underscan changes */
13482 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
13483 			continue;
13484 
13485 		lock_and_validation_needed = true;
13486 	}
13487 
13488 	/* set the slot info for each mst_state based on the link encoding format */
13489 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
13490 		struct amdgpu_dm_connector *aconnector;
13491 		struct drm_connector *connector;
13492 		struct drm_connector_list_iter iter;
13493 		u8 link_coding_cap;
13494 
13495 		drm_connector_list_iter_begin(dev, &iter);
13496 		drm_for_each_connector_iter(connector, &iter) {
13497 			if (connector->index == mst_state->mgr->conn_base_id) {
13498 				aconnector = to_amdgpu_dm_connector(connector);
13499 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
13500 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
13501 
13502 				break;
13503 			}
13504 		}
13505 		drm_connector_list_iter_end(&iter);
13506 	}
13507 
13508 	/**
13509 	 * Streams and planes are reset when there are changes that affect
13510 	 * bandwidth. Anything that affects bandwidth needs to go through
13511 	 * DC global validation to ensure that the configuration can be applied
13512 	 * to hardware.
13513 	 *
13514 	 * We have to currently stall out here in atomic_check for outstanding
13515 	 * commits to finish in this case because our IRQ handlers reference
13516 	 * DRM state directly - we can end up disabling interrupts too early
13517 	 * if we don't.
13518 	 *
13519 	 * TODO: Remove this stall and drop DM state private objects.
13520 	 */
13521 	if (lock_and_validation_needed) {
13522 		ret = dm_atomic_get_state(state, &dm_state);
13523 		if (ret) {
13524 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
13525 			goto fail;
13526 		}
13527 
13528 		ret = do_aquire_global_lock(dev, state);
13529 		if (ret) {
13530 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
13531 			goto fail;
13532 		}
13533 
13534 #if defined(CONFIG_DRM_AMD_DC_FP)
13535 		if (dc_resource_is_dsc_encoding_supported(dc)) {
13536 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
13537 			if (ret) {
13538 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
13539 				ret = -EINVAL;
13540 				goto fail;
13541 			}
13542 		}
13543 #endif
13544 
13545 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
13546 		if (ret) {
13547 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
13548 			goto fail;
13549 		}
13550 
13551 		/*
13552 		 * Perform validation of MST topology in the state:
13553 		 * We need to perform MST atomic check before calling
13554 		 * dc_validate_global_state(), or there is a chance
13555 		 * to get stuck in an infinite loop and hang eventually.
13556 		 */
13557 		ret = drm_dp_mst_atomic_check(state);
13558 		if (ret) {
13559 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
13560 			goto fail;
13561 		}
13562 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
13563 		if (status != DC_OK) {
13564 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
13565 				       dc_status_to_str(status), status);
13566 			ret = -EINVAL;
13567 			goto fail;
13568 		}
13569 	} else {
13570 		/*
13571 		 * The commit is a fast update. Fast updates shouldn't change
13572 		 * the DC context, affect global validation, and can have their
13573 		 * commit work done in parallel with other commits not touching
13574 		 * the same resource. If we have a new DC context as part of
13575 		 * the DM atomic state from validation we need to free it and
13576 		 * retain the existing one instead.
13577 		 *
13578 		 * Furthermore, since the DM atomic state only contains the DC
13579 		 * context and can safely be annulled, we can free the state
13580 		 * and clear the associated private object now to free
13581 		 * some memory and avoid a possible use-after-free later.
13582 		 */
13583 
13584 		for (i = 0; i < state->num_private_objs; i++) {
13585 			struct drm_private_obj *obj = state->private_objs[i].ptr;
13586 
13587 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
13588 				int j = state->num_private_objs-1;
13589 
13590 				dm_atomic_destroy_state(obj,
13591 						state->private_objs[i].state_to_destroy);
13592 
13593 				/* If i is not at the end of the array then the
13594 				 * last element needs to be moved to where i was
13595 				 * before the array can safely be truncated.
13596 				 */
13597 				if (i != j)
13598 					state->private_objs[i] =
13599 						state->private_objs[j];
13600 
13601 				state->private_objs[j].ptr = NULL;
13602 				state->private_objs[j].state_to_destroy = NULL;
13603 				state->private_objs[j].old_state = NULL;
13604 				state->private_objs[j].new_state = NULL;
13605 
13606 				state->num_private_objs = j;
13607 				break;
13608 			}
13609 		}
13610 	}
13611 
13612 	/* Store the overall update type for use later in atomic check. */
13613 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13614 		struct dm_crtc_state *dm_new_crtc_state =
13615 			to_dm_crtc_state(new_crtc_state);
13616 
13617 		/*
13618 		 * Only allow async flips for fast updates that don't change
13619 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
13620 		 */
13621 		if (new_crtc_state->async_flip &&
13622 		    (lock_and_validation_needed ||
13623 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
13624 			drm_dbg_atomic(crtc->dev,
13625 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
13626 				       crtc->base.id, crtc->name);
13627 			ret = -EINVAL;
13628 			goto fail;
13629 		}
13630 
13631 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
13632 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
13633 	}
13634 
13635 	/* Must be success */
13636 	WARN_ON(ret);
13637 
13638 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13639 
13640 	return ret;
13641 
13642 fail:
13643 	if (ret == -EDEADLK)
13644 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
13645 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
13646 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
13647 	else
13648 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
13649 
13650 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13651 
13652 	return ret;
13653 }
13654 
13655 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
13656 		unsigned int offset,
13657 		unsigned int total_length,
13658 		u8 *data,
13659 		unsigned int length,
13660 		struct amdgpu_hdmi_vsdb_info *vsdb)
13661 {
13662 	bool res;
13663 	union dmub_rb_cmd cmd;
13664 	struct dmub_cmd_send_edid_cea *input;
13665 	struct dmub_cmd_edid_cea_output *output;
13666 
13667 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
13668 		return false;
13669 
13670 	memset(&cmd, 0, sizeof(cmd));
13671 
13672 	input = &cmd.edid_cea.data.input;
13673 
13674 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
13675 	cmd.edid_cea.header.sub_type = 0;
13676 	cmd.edid_cea.header.payload_bytes =
13677 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
13678 	input->offset = offset;
13679 	input->length = length;
13680 	input->cea_total_length = total_length;
13681 	memcpy(input->payload, data, length);
13682 
13683 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
13684 	if (!res) {
13685 		drm_err(adev_to_drm(dm->adev), "EDID CEA parser failed\n");
13686 		return false;
13687 	}
13688 
13689 	output = &cmd.edid_cea.data.output;
13690 
13691 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
13692 		if (!output->ack.success) {
13693 			drm_err(adev_to_drm(dm->adev), "EDID CEA ack failed at offset %d\n",
13694 					output->ack.offset);
13695 		}
13696 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
13697 		if (!output->amd_vsdb.vsdb_found)
13698 			return false;
13699 
13700 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
13701 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
13702 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
13703 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
13704 		vsdb->freesync_mccs_vcp_code = output->amd_vsdb.freesync_mccs_vcp_code;
13705 	} else {
13706 		drm_warn(adev_to_drm(dm->adev), "Unknown EDID CEA parser results\n");
13707 		return false;
13708 	}
13709 
13710 	return true;
13711 }
13712 
13713 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
13714 		u8 *edid_ext, int len,
13715 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13716 {
13717 	int i;
13718 
13719 	/* send extension block to DMCU for parsing */
13720 	for (i = 0; i < len; i += 8) {
13721 		bool res;
13722 		int offset;
13723 
13724 		/* send 8 bytes a time */
13725 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
13726 			return false;
13727 
13728 		if (i+8 == len) {
13729 			/* EDID block sent completed, expect result */
13730 			int version, min_rate, max_rate;
13731 
13732 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
13733 			if (res) {
13734 				/* amd vsdb found */
13735 				vsdb_info->freesync_supported = 1;
13736 				vsdb_info->amd_vsdb_version = version;
13737 				vsdb_info->min_refresh_rate_hz = min_rate;
13738 				vsdb_info->max_refresh_rate_hz = max_rate;
13739 				/* Not enabled on DMCU*/
13740 				vsdb_info->freesync_mccs_vcp_code = 0;
13741 				return true;
13742 			}
13743 			/* not amd vsdb */
13744 			return false;
13745 		}
13746 
13747 		/* check for ack*/
13748 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
13749 		if (!res)
13750 			return false;
13751 	}
13752 
13753 	return false;
13754 }
13755 
13756 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
13757 		u8 *edid_ext, int len,
13758 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13759 {
13760 	int i;
13761 
13762 	/* send extension block to DMCU for parsing */
13763 	for (i = 0; i < len; i += 8) {
13764 		/* send 8 bytes a time */
13765 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
13766 			return false;
13767 	}
13768 
13769 	return vsdb_info->freesync_supported;
13770 }
13771 
13772 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
13773 		u8 *edid_ext, int len,
13774 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13775 {
13776 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
13777 	bool ret;
13778 
13779 	mutex_lock(&adev->dm.dc_lock);
13780 	if (adev->dm.dmub_srv)
13781 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
13782 	else
13783 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
13784 	mutex_unlock(&adev->dm.dc_lock);
13785 	return ret;
13786 }
13787 
13788 static void parse_edid_displayid_vrr(struct drm_connector *connector,
13789 				     const struct edid *edid)
13790 {
13791 	u8 *edid_ext = NULL;
13792 	int i;
13793 	int j = 0;
13794 	u16 min_vfreq;
13795 	u16 max_vfreq;
13796 
13797 	if (!edid || !edid->extensions)
13798 		return;
13799 
13800 	/* Find DisplayID extension */
13801 	for (i = 0; i < edid->extensions; i++) {
13802 		edid_ext = (void *)(edid + (i + 1));
13803 		if (edid_ext[0] == DISPLAYID_EXT)
13804 			break;
13805 	}
13806 
13807 	if (i == edid->extensions)
13808 		return;
13809 
13810 	while (j < EDID_LENGTH) {
13811 		/* Get dynamic video timing range from DisplayID if available */
13812 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
13813 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
13814 			min_vfreq = edid_ext[j+9];
13815 			if (edid_ext[j+1] & 7)
13816 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
13817 			else
13818 				max_vfreq = edid_ext[j+10];
13819 
13820 			if (max_vfreq && min_vfreq) {
13821 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
13822 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
13823 
13824 				return;
13825 			}
13826 		}
13827 		j++;
13828 	}
13829 }
13830 
13831 static int get_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13832 			struct amdgpu_hdmi_vsdb_info *vsdb_info)
13833 {
13834 	struct drm_connector *connector = &aconnector->base;
13835 
13836 	vsdb_info->replay_mode = connector->display_info.amd_vsdb.replay_mode;
13837 	vsdb_info->amd_vsdb_version = connector->display_info.amd_vsdb.version;
13838 
13839 	return connector->display_info.amd_vsdb.version != 0;
13840 }
13841 
13842 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13843 			       const struct edid *edid,
13844 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
13845 {
13846 	u8 *edid_ext = NULL;
13847 	int i;
13848 	bool valid_vsdb_found = false;
13849 
13850 	/*----- drm_find_cea_extension() -----*/
13851 	/* No EDID or EDID extensions */
13852 	if (edid == NULL || edid->extensions == 0)
13853 		return -ENODEV;
13854 
13855 	/* Find CEA extension */
13856 	for (i = 0; i < edid->extensions; i++) {
13857 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
13858 		if (edid_ext[0] == CEA_EXT)
13859 			break;
13860 	}
13861 
13862 	if (i == edid->extensions)
13863 		return -ENODEV;
13864 
13865 	/*----- cea_db_offsets() -----*/
13866 	if (edid_ext[0] != CEA_EXT)
13867 		return -ENODEV;
13868 
13869 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
13870 
13871 	return valid_vsdb_found ? i : -ENODEV;
13872 }
13873 
13874 /**
13875  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
13876  *
13877  * @connector: Connector to query.
13878  * @drm_edid: DRM EDID from monitor
13879  * @do_mccs: Controls whether MCCS (Monitor Control Command Set) over
13880  *	      DDC (Display Data Channel) transactions are performed. When true,
13881  *	      the driver queries the monitor to get or update additional FreeSync
13882  *	      capability information. When false, these transactions are skipped.
13883  *
13884  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
13885  * track of some of the display information in the internal data struct used by
13886  * amdgpu_dm. This function checks which type of connector we need to set the
13887  * FreeSync parameters.
13888  */
13889 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
13890 				    const struct drm_edid *drm_edid, bool do_mccs)
13891 {
13892 	int i = 0;
13893 	struct amdgpu_dm_connector *amdgpu_dm_connector =
13894 			to_amdgpu_dm_connector(connector);
13895 	struct dm_connector_state *dm_con_state = NULL;
13896 	struct dc_sink *sink;
13897 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
13898 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
13899 	const struct edid *edid;
13900 	bool freesync_capable = false;
13901 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
13902 
13903 	if (!connector->state) {
13904 		drm_err(adev_to_drm(adev), "%s - Connector has no state", __func__);
13905 		goto update;
13906 	}
13907 
13908 	sink = amdgpu_dm_connector->dc_sink ?
13909 		amdgpu_dm_connector->dc_sink :
13910 		amdgpu_dm_connector->dc_em_sink;
13911 
13912 	drm_edid_connector_update(connector, drm_edid);
13913 
13914 	if (!drm_edid || !sink) {
13915 		dm_con_state = to_dm_connector_state(connector->state);
13916 
13917 		amdgpu_dm_connector->min_vfreq = 0;
13918 		amdgpu_dm_connector->max_vfreq = 0;
13919 		freesync_capable = false;
13920 
13921 		goto update;
13922 	}
13923 
13924 	dm_con_state = to_dm_connector_state(connector->state);
13925 
13926 	if (!adev->dm.freesync_module || !dc_supports_vrr(sink->ctx->dce_version))
13927 		goto update;
13928 
13929 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
13930 
13931 	/* Some eDP panels only have the refresh rate range info in DisplayID */
13932 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
13933 	     connector->display_info.monitor_range.max_vfreq == 0))
13934 		parse_edid_displayid_vrr(connector, edid);
13935 
13936 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
13937 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
13938 		if (amdgpu_dm_connector->dc_link &&
13939 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
13940 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
13941 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
13942 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13943 				freesync_capable = true;
13944 		}
13945 
13946 		get_amd_vsdb(amdgpu_dm_connector, &vsdb_info);
13947 
13948 		if (vsdb_info.replay_mode) {
13949 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
13950 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
13951 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
13952 		}
13953 
13954 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
13955 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13956 		if (i >= 0) {
13957 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13958 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13959 
13960 			if (vsdb_info.freesync_supported) {
13961 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13962 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13963 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13964 					freesync_capable = true;
13965 
13966 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13967 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13968 			}
13969 		}
13970 	}
13971 
13972 	if (amdgpu_dm_connector->dc_link)
13973 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
13974 
13975 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
13976 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13977 		if (i >= 0) {
13978 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13979 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13980 
13981 			if (vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
13982 				amdgpu_dm_connector->pack_sdp_v1_3 = true;
13983 				amdgpu_dm_connector->as_type = as_type;
13984 
13985 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13986 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13987 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13988 					freesync_capable = true;
13989 
13990 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13991 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13992 			}
13993 		}
13994 	}
13995 
13996 	/* Handle MCCS */
13997 	if (do_mccs) {
13998 		dm_helpers_read_mccs_caps(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13999 
14000 		if (sink->edid_caps.freesync_vcp_code && !sink->mccs_caps.freesync_supported)
14001 			freesync_capable = false;
14002 
14003 		if (sink->mccs_caps.freesync_supported && freesync_capable)
14004 			dm_helpers_mccs_vcp_set(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
14005 	}
14006 
14007 update:
14008 	if (dm_con_state)
14009 		dm_con_state->freesync_capable = freesync_capable;
14010 
14011 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
14012 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
14013 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
14014 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
14015 	}
14016 
14017 	if (connector->vrr_capable_property)
14018 		drm_connector_set_vrr_capable_property(connector,
14019 						       freesync_capable);
14020 }
14021 
14022 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
14023 {
14024 	struct amdgpu_device *adev = drm_to_adev(dev);
14025 	struct dc *dc = adev->dm.dc;
14026 	int i;
14027 
14028 	mutex_lock(&adev->dm.dc_lock);
14029 	if (dc->current_state) {
14030 		for (i = 0; i < dc->current_state->stream_count; ++i)
14031 			dc->current_state->streams[i]
14032 				->triggered_crtc_reset.enabled =
14033 				adev->dm.force_timing_sync;
14034 
14035 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
14036 		dc_trigger_sync(dc, dc->current_state);
14037 	}
14038 	mutex_unlock(&adev->dm.dc_lock);
14039 }
14040 
14041 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
14042 {
14043 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
14044 		dc_exit_ips_for_hw_access(dc);
14045 }
14046 
14047 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
14048 		       u32 value, const char *func_name)
14049 {
14050 #ifdef DM_CHECK_ADDR_0
14051 	if (address == 0) {
14052 		drm_err(adev_to_drm(ctx->driver_context),
14053 			"invalid register write. address = 0");
14054 		return;
14055 	}
14056 #endif
14057 
14058 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
14059 	cgs_write_register(ctx->cgs_device, address, value);
14060 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
14061 }
14062 
14063 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
14064 			  const char *func_name)
14065 {
14066 	u32 value;
14067 #ifdef DM_CHECK_ADDR_0
14068 	if (address == 0) {
14069 		drm_err(adev_to_drm(ctx->driver_context),
14070 			"invalid register read; address = 0\n");
14071 		return 0;
14072 	}
14073 #endif
14074 
14075 	if (ctx->dmub_srv &&
14076 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
14077 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
14078 		ASSERT(false);
14079 		return 0;
14080 	}
14081 
14082 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
14083 
14084 	value = cgs_read_register(ctx->cgs_device, address);
14085 
14086 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
14087 
14088 	return value;
14089 }
14090 
14091 int amdgpu_dm_process_dmub_aux_transfer_sync(
14092 		struct dc_context *ctx,
14093 		unsigned int link_index,
14094 		struct aux_payload *payload,
14095 		enum aux_return_code_type *operation_result)
14096 {
14097 	struct amdgpu_device *adev = ctx->driver_context;
14098 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
14099 	int ret = -1;
14100 
14101 	mutex_lock(&adev->dm.dpia_aux_lock);
14102 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
14103 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
14104 		goto out;
14105 	}
14106 
14107 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
14108 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
14109 		*operation_result = AUX_RET_ERROR_TIMEOUT;
14110 		goto out;
14111 	}
14112 
14113 	if (p_notify->result != AUX_RET_SUCCESS) {
14114 		/*
14115 		 * Transient states before tunneling is enabled could
14116 		 * lead to this error. We can ignore this for now.
14117 		 */
14118 		if (p_notify->result == AUX_RET_ERROR_PROTOCOL_ERROR) {
14119 			drm_warn(adev_to_drm(adev), "DPIA AUX failed on 0x%x(%d), error %d\n",
14120 					payload->address, payload->length,
14121 					p_notify->result);
14122 		}
14123 		*operation_result = p_notify->result;
14124 		goto out;
14125 	}
14126 
14127 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command & 0xF;
14128 	if (adev->dm.dmub_notify->aux_reply.command & 0xF0)
14129 		/* The reply is stored in the top nibble of the command. */
14130 		payload->reply[0] = (adev->dm.dmub_notify->aux_reply.command >> 4) & 0xF;
14131 
14132 	/*write req may receive a byte indicating partially written number as well*/
14133 	if (p_notify->aux_reply.length)
14134 		memcpy(payload->data, p_notify->aux_reply.data,
14135 				p_notify->aux_reply.length);
14136 
14137 	/* success */
14138 	ret = p_notify->aux_reply.length;
14139 	*operation_result = p_notify->result;
14140 out:
14141 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
14142 	mutex_unlock(&adev->dm.dpia_aux_lock);
14143 	return ret;
14144 }
14145 
14146 static void abort_fused_io(
14147 		struct dc_context *ctx,
14148 		const struct dmub_cmd_fused_request *request
14149 )
14150 {
14151 	union dmub_rb_cmd command = { 0 };
14152 	struct dmub_rb_cmd_fused_io *io = &command.fused_io;
14153 
14154 	io->header.type = DMUB_CMD__FUSED_IO;
14155 	io->header.sub_type = DMUB_CMD__FUSED_IO_ABORT;
14156 	io->header.payload_bytes = sizeof(*io) - sizeof(io->header);
14157 	io->request = *request;
14158 	dm_execute_dmub_cmd(ctx, &command, DM_DMUB_WAIT_TYPE_NO_WAIT);
14159 }
14160 
14161 static bool execute_fused_io(
14162 		struct amdgpu_device *dev,
14163 		struct dc_context *ctx,
14164 		union dmub_rb_cmd *commands,
14165 		uint8_t count,
14166 		uint32_t timeout_us
14167 )
14168 {
14169 	const uint8_t ddc_line = commands[0].fused_io.request.u.aux.ddc_line;
14170 
14171 	if (ddc_line >= ARRAY_SIZE(dev->dm.fused_io))
14172 		return false;
14173 
14174 	struct fused_io_sync *sync = &dev->dm.fused_io[ddc_line];
14175 	struct dmub_rb_cmd_fused_io *first = &commands[0].fused_io;
14176 	const bool result = dm_execute_dmub_cmd_list(ctx, count, commands, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY)
14177 			&& first->header.ret_status
14178 			&& first->request.status == FUSED_REQUEST_STATUS_SUCCESS;
14179 
14180 	if (!result)
14181 		return false;
14182 
14183 	while (wait_for_completion_timeout(&sync->replied, usecs_to_jiffies(timeout_us))) {
14184 		reinit_completion(&sync->replied);
14185 
14186 		struct dmub_cmd_fused_request *reply = (struct dmub_cmd_fused_request *) sync->reply_data;
14187 
14188 		static_assert(sizeof(*reply) <= sizeof(sync->reply_data), "Size mismatch");
14189 
14190 		if (reply->identifier == first->request.identifier) {
14191 			first->request = *reply;
14192 			return true;
14193 		}
14194 	}
14195 
14196 	reinit_completion(&sync->replied);
14197 	first->request.status = FUSED_REQUEST_STATUS_TIMEOUT;
14198 	abort_fused_io(ctx, &first->request);
14199 	return false;
14200 }
14201 
14202 bool amdgpu_dm_execute_fused_io(
14203 		struct amdgpu_device *dev,
14204 		struct dc_link *link,
14205 		union dmub_rb_cmd *commands,
14206 		uint8_t count,
14207 		uint32_t timeout_us)
14208 {
14209 	struct amdgpu_display_manager *dm = &dev->dm;
14210 
14211 	mutex_lock(&dm->dpia_aux_lock);
14212 
14213 	const bool result = execute_fused_io(dev, link->ctx, commands, count, timeout_us);
14214 
14215 	mutex_unlock(&dm->dpia_aux_lock);
14216 	return result;
14217 }
14218 
14219 int amdgpu_dm_process_dmub_set_config_sync(
14220 		struct dc_context *ctx,
14221 		unsigned int link_index,
14222 		struct set_config_cmd_payload *payload,
14223 		enum set_config_status *operation_result)
14224 {
14225 	struct amdgpu_device *adev = ctx->driver_context;
14226 	bool is_cmd_complete;
14227 	int ret;
14228 
14229 	mutex_lock(&adev->dm.dpia_aux_lock);
14230 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
14231 			link_index, payload, adev->dm.dmub_notify);
14232 
14233 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
14234 		ret = 0;
14235 		*operation_result = adev->dm.dmub_notify->sc_status;
14236 	} else {
14237 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
14238 		ret = -1;
14239 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
14240 	}
14241 
14242 	if (!is_cmd_complete)
14243 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
14244 	mutex_unlock(&adev->dm.dpia_aux_lock);
14245 	return ret;
14246 }
14247 
14248 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
14249 {
14250 	struct amdgpu_device *adev = ctx->driver_context;
14251 
14252 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
14253 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
14254 }
14255 
14256 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)
14257 {
14258 	struct amdgpu_device *adev = ctx->driver_context;
14259 
14260 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
14261 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
14262 }
14263 
14264 void dm_acpi_process_phy_transition_interlock(
14265 	const struct dc_context *ctx,
14266 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
14267 {
14268 	// Not yet implemented
14269 }
14270