xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision 9e6869be49064915edb6c8776b27c376cfdb0df5)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright 2015-2026 Advanced Micro Devices, Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  * Authors: AMD
24  *
25  */
26 
27 /* The caprices of the preprocessor require that this be declared right here */
28 #define CREATE_TRACE_POINTS
29 
30 #include "dm_services_types.h"
31 #include "dc.h"
32 #include "link_enc_cfg.h"
33 #include "dc/inc/core_types.h"
34 #include "dal_asic_id.h"
35 #include "dmub/dmub_srv.h"
36 #include "dc/inc/hw/dmcu.h"
37 #include "dc/inc/hw/abm.h"
38 #include "dc/dc_dmub_srv.h"
39 #include "dc/dc_edid_parser.h"
40 #include "dc/dc_stat.h"
41 #include "dc/dc_state.h"
42 #include "amdgpu_dm_trace.h"
43 #include "link/protocols/link_dpcd.h"
44 #include "link_service_types.h"
45 #include "link/protocols/link_dp_capability.h"
46 #include "link/protocols/link_ddc.h"
47 
48 #include "amdgpu.h"
49 #include "amdgpu_display.h"
50 #include "amdgpu_ucode.h"
51 #include "atom.h"
52 #include "amdgpu_dm.h"
53 #include "amdgpu_dm_plane.h"
54 #include "amdgpu_dm_crtc.h"
55 #include "amdgpu_dm_hdcp.h"
56 #include <drm/display/drm_hdcp_helper.h>
57 #include "amdgpu_dm_wb.h"
58 #include "amdgpu_atombios.h"
59 
60 #include "amd_shared.h"
61 #include "amdgpu_dm_irq.h"
62 #include "dm_helpers.h"
63 #include "amdgpu_dm_mst_types.h"
64 #if defined(CONFIG_DEBUG_FS)
65 #include "amdgpu_dm_debugfs.h"
66 #endif
67 #include "amdgpu_dm_psr.h"
68 #include "amdgpu_dm_replay.h"
69 
70 #include "ivsrcid/ivsrcid_vislands30.h"
71 
72 #include <linux/backlight.h>
73 #include <linux/module.h>
74 #include <linux/moduleparam.h>
75 #include <linux/types.h>
76 #include <linux/pm_runtime.h>
77 #include <linux/pci.h>
78 #include <linux/power_supply.h>
79 #include <linux/firmware.h>
80 #include <linux/component.h>
81 #include <linux/sort.h>
82 
83 #include <drm/drm_privacy_screen_consumer.h>
84 #include <drm/display/drm_dp_mst_helper.h>
85 #include <drm/display/drm_hdmi_helper.h>
86 #include <drm/drm_atomic.h>
87 #include <drm/drm_atomic_uapi.h>
88 #include <drm/drm_atomic_helper.h>
89 #include <drm/drm_blend.h>
90 #include <drm/drm_fixed.h>
91 #include <drm/drm_fourcc.h>
92 #include <drm/drm_edid.h>
93 #include <drm/drm_eld.h>
94 #include <drm/drm_mode.h>
95 #include <drm/drm_utils.h>
96 #include <drm/drm_vblank.h>
97 #include <drm/drm_audio_component.h>
98 #include <drm/drm_colorop.h>
99 #include <drm/drm_gem_atomic_helper.h>
100 
101 #include <media/cec-notifier.h>
102 #include <acpi/video.h>
103 
104 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
105 
106 #include "modules/inc/mod_freesync.h"
107 #include "modules/inc/mod_power.h"
108 #include "modules/power/power_helpers.h"
109 
110 static_assert(AMDGPU_DMUB_NOTIFICATION_MAX == DMUB_NOTIFICATION_MAX, "AMDGPU_DMUB_NOTIFICATION_MAX mismatch");
111 
112 #define FIRMWARE_RENOIR_DMUB "amdgpu/renoir_dmcub.bin"
113 MODULE_FIRMWARE(FIRMWARE_RENOIR_DMUB);
114 #define FIRMWARE_SIENNA_CICHLID_DMUB "amdgpu/sienna_cichlid_dmcub.bin"
115 MODULE_FIRMWARE(FIRMWARE_SIENNA_CICHLID_DMUB);
116 #define FIRMWARE_NAVY_FLOUNDER_DMUB "amdgpu/navy_flounder_dmcub.bin"
117 MODULE_FIRMWARE(FIRMWARE_NAVY_FLOUNDER_DMUB);
118 #define FIRMWARE_GREEN_SARDINE_DMUB "amdgpu/green_sardine_dmcub.bin"
119 MODULE_FIRMWARE(FIRMWARE_GREEN_SARDINE_DMUB);
120 #define FIRMWARE_VANGOGH_DMUB "amdgpu/vangogh_dmcub.bin"
121 MODULE_FIRMWARE(FIRMWARE_VANGOGH_DMUB);
122 #define FIRMWARE_DIMGREY_CAVEFISH_DMUB "amdgpu/dimgrey_cavefish_dmcub.bin"
123 MODULE_FIRMWARE(FIRMWARE_DIMGREY_CAVEFISH_DMUB);
124 #define FIRMWARE_BEIGE_GOBY_DMUB "amdgpu/beige_goby_dmcub.bin"
125 MODULE_FIRMWARE(FIRMWARE_BEIGE_GOBY_DMUB);
126 #define FIRMWARE_YELLOW_CARP_DMUB "amdgpu/yellow_carp_dmcub.bin"
127 MODULE_FIRMWARE(FIRMWARE_YELLOW_CARP_DMUB);
128 #define FIRMWARE_DCN_314_DMUB "amdgpu/dcn_3_1_4_dmcub.bin"
129 MODULE_FIRMWARE(FIRMWARE_DCN_314_DMUB);
130 #define FIRMWARE_DCN_315_DMUB "amdgpu/dcn_3_1_5_dmcub.bin"
131 MODULE_FIRMWARE(FIRMWARE_DCN_315_DMUB);
132 #define FIRMWARE_DCN316_DMUB "amdgpu/dcn_3_1_6_dmcub.bin"
133 MODULE_FIRMWARE(FIRMWARE_DCN316_DMUB);
134 
135 #define FIRMWARE_DCN_V3_2_0_DMCUB "amdgpu/dcn_3_2_0_dmcub.bin"
136 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_0_DMCUB);
137 #define FIRMWARE_DCN_V3_2_1_DMCUB "amdgpu/dcn_3_2_1_dmcub.bin"
138 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_1_DMCUB);
139 
140 #define FIRMWARE_RAVEN_DMCU		"amdgpu/raven_dmcu.bin"
141 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
142 
143 #define FIRMWARE_NAVI12_DMCU            "amdgpu/navi12_dmcu.bin"
144 MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
145 
146 #define FIRMWARE_DCN_35_DMUB "amdgpu/dcn_3_5_dmcub.bin"
147 MODULE_FIRMWARE(FIRMWARE_DCN_35_DMUB);
148 
149 #define FIRMWARE_DCN_351_DMUB "amdgpu/dcn_3_5_1_dmcub.bin"
150 MODULE_FIRMWARE(FIRMWARE_DCN_351_DMUB);
151 
152 #define FIRMWARE_DCN_36_DMUB "amdgpu/dcn_3_6_dmcub.bin"
153 MODULE_FIRMWARE(FIRMWARE_DCN_36_DMUB);
154 
155 #define FIRMWARE_DCN_401_DMUB "amdgpu/dcn_4_0_1_dmcub.bin"
156 MODULE_FIRMWARE(FIRMWARE_DCN_401_DMUB);
157 
158 #define FIRMWARE_DCN_42_DMUB "amdgpu/dcn_4_2_dmcub.bin"
159 MODULE_FIRMWARE(FIRMWARE_DCN_42_DMUB);
160 
161 #define FIRMWARE_DCN_42B_DMUB "amdgpu/dcn_4_2_1_dmcub.bin"
162 MODULE_FIRMWARE(FIRMWARE_DCN_42B_DMUB);
163 
164 /**
165  * DOC: overview
166  *
167  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
168  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
169  * requests into DC requests, and DC responses into DRM responses.
170  *
171  * The root control structure is &struct amdgpu_display_manager.
172  */
173 
174 /* basic init/fini API */
175 static int amdgpu_dm_init(struct amdgpu_device *adev);
176 static void amdgpu_dm_fini(struct amdgpu_device *adev);
177 static bool is_freesync_video_mode(const struct drm_display_mode *mode, struct amdgpu_dm_connector *aconnector);
178 static void reset_freesync_config_for_crtc(struct dm_crtc_state *new_crtc_state);
179 static struct amdgpu_i2c_adapter *
180 create_i2c(struct ddc_service *ddc_service, bool oem);
181 
182 static enum drm_mode_subconnector get_subconnector_type(struct dc_link *link)
183 {
184 	switch (link->dpcd_caps.dongle_type) {
185 	case DISPLAY_DONGLE_NONE:
186 		return DRM_MODE_SUBCONNECTOR_Native;
187 	case DISPLAY_DONGLE_DP_VGA_CONVERTER:
188 		return DRM_MODE_SUBCONNECTOR_VGA;
189 	case DISPLAY_DONGLE_DP_DVI_CONVERTER:
190 	case DISPLAY_DONGLE_DP_DVI_DONGLE:
191 		return DRM_MODE_SUBCONNECTOR_DVID;
192 	case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
193 	case DISPLAY_DONGLE_DP_HDMI_DONGLE:
194 		return DRM_MODE_SUBCONNECTOR_HDMIA;
195 	case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
196 	default:
197 		return DRM_MODE_SUBCONNECTOR_Unknown;
198 	}
199 }
200 
201 static void update_subconnector_property(struct amdgpu_dm_connector *aconnector)
202 {
203 	struct dc_link *link = aconnector->dc_link;
204 	struct drm_connector *connector = &aconnector->base;
205 	enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
206 
207 	if (connector->connector_type != DRM_MODE_CONNECTOR_DisplayPort)
208 		return;
209 
210 	if (aconnector->dc_sink)
211 		subconnector = get_subconnector_type(link);
212 
213 	drm_object_property_set_value(&connector->base,
214 			connector->dev->mode_config.dp_subconnector_property,
215 			subconnector);
216 }
217 
218 /*
219  * initializes drm_device display related structures, based on the information
220  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
221  * drm_encoder, drm_mode_config
222  *
223  * Returns 0 on success
224  */
225 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
226 /* removes and deallocates the drm structures, created by the above function */
227 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
228 
229 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
230 				    struct amdgpu_dm_connector *amdgpu_dm_connector,
231 				    u32 link_index,
232 				    struct amdgpu_encoder *amdgpu_encoder);
233 static int amdgpu_dm_encoder_init(struct drm_device *dev,
234 				  struct amdgpu_encoder *aencoder,
235 				  uint32_t link_index);
236 
237 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
238 
239 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state);
240 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state);
241 
242 static int amdgpu_dm_atomic_check(struct drm_device *dev,
243 				  struct drm_atomic_commit *state);
244 
245 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector);
246 static void handle_hpd_rx_irq(void *param);
247 
248 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
249 					 int bl_idx,
250 					 u32 user_brightness);
251 
252 static bool
253 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
254 				 struct drm_crtc_state *new_crtc_state);
255 /*
256  * dm_vblank_get_counter
257  *
258  * @brief
259  * Get counter for number of vertical blanks
260  *
261  * @param
262  * struct amdgpu_device *adev - [in] desired amdgpu device
263  * int disp_idx - [in] which CRTC to get the counter from
264  *
265  * @return
266  * Counter for vertical blanks
267  */
268 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
269 {
270 	struct amdgpu_crtc *acrtc = NULL;
271 
272 	if (crtc >= adev->mode_info.num_crtc)
273 		return 0;
274 
275 	acrtc = adev->mode_info.crtcs[crtc];
276 
277 	if (!acrtc->dm_irq_params.stream) {
278 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
279 			  crtc);
280 		return 0;
281 	}
282 
283 	return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
284 }
285 
286 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
287 				  u32 *vbl, u32 *position)
288 {
289 	u32 v_blank_start = 0, v_blank_end = 0, h_position = 0, v_position = 0;
290 	struct amdgpu_crtc *acrtc = NULL;
291 	struct dc *dc = adev->dm.dc;
292 
293 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
294 		return -EINVAL;
295 
296 	acrtc = adev->mode_info.crtcs[crtc];
297 
298 	if (!acrtc->dm_irq_params.stream) {
299 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
300 			  crtc);
301 		return 0;
302 	}
303 
304 	if (dc && dc->caps.ips_support && dc->idle_optimizations_allowed)
305 		dc_allow_idle_optimizations(dc, false);
306 
307 	/*
308 	 * TODO rework base driver to use values directly.
309 	 * for now parse it back into reg-format
310 	 */
311 	dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
312 				 &v_blank_start,
313 				 &v_blank_end,
314 				 &h_position,
315 				 &v_position);
316 
317 	*position = v_position | (h_position << 16);
318 	*vbl = v_blank_start | (v_blank_end << 16);
319 
320 	return 0;
321 }
322 
323 static bool dm_is_idle(struct amdgpu_ip_block *ip_block)
324 {
325 	/* XXX todo */
326 	return true;
327 }
328 
329 static int dm_wait_for_idle(struct amdgpu_ip_block *ip_block)
330 {
331 	/* XXX todo */
332 	return 0;
333 }
334 
335 static bool dm_check_soft_reset(struct amdgpu_ip_block *ip_block)
336 {
337 	return false;
338 }
339 
340 static int dm_soft_reset(struct amdgpu_ip_block *ip_block)
341 {
342 	/* XXX todo */
343 	return 0;
344 }
345 
346 static struct amdgpu_crtc *
347 get_crtc_by_otg_inst(struct amdgpu_device *adev,
348 		     int otg_inst)
349 {
350 	struct drm_device *dev = adev_to_drm(adev);
351 	struct drm_crtc *crtc;
352 	struct amdgpu_crtc *amdgpu_crtc;
353 
354 	if (WARN_ON(otg_inst == -1))
355 		return adev->mode_info.crtcs[0];
356 
357 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
358 		amdgpu_crtc = to_amdgpu_crtc(crtc);
359 
360 		if (amdgpu_crtc->otg_inst == otg_inst)
361 			return amdgpu_crtc;
362 	}
363 
364 	return NULL;
365 }
366 
367 static inline bool is_dc_timing_adjust_needed(struct dm_crtc_state *old_state,
368 					      struct dm_crtc_state *new_state)
369 {
370 	if (new_state->stream->adjust.timing_adjust_pending)
371 		return true;
372 	if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
373 		return true;
374 	else if (amdgpu_dm_crtc_vrr_active(old_state) != amdgpu_dm_crtc_vrr_active(new_state))
375 		return true;
376 	else
377 		return false;
378 }
379 
380 /*
381  * DC will program planes with their z-order determined by their ordering
382  * in the dc_surface_updates array. This comparator is used to sort them
383  * by descending zpos.
384  */
385 static int dm_plane_layer_index_cmp(const void *a, const void *b)
386 {
387 	const struct dc_surface_update *sa = (struct dc_surface_update *)a;
388 	const struct dc_surface_update *sb = (struct dc_surface_update *)b;
389 
390 	/* Sort by descending dc_plane layer_index (i.e. normalized_zpos) */
391 	return sb->surface->layer_index - sa->surface->layer_index;
392 }
393 
394 /**
395  * update_planes_and_stream_adapter() - Send planes to be updated in DC
396  *
397  * DC has a generic way to update planes and stream via
398  * dc_update_planes_and_stream function; however, DM might need some
399  * adjustments and preparation before calling it. This function is a wrapper
400  * for the dc_update_planes_and_stream that does any required configuration
401  * before passing control to DC.
402  *
403  * @dc: Display Core control structure
404  * @update_type: specify whether it is FULL/MEDIUM/FAST update
405  * @planes_count: planes count to update
406  * @stream: stream state
407  * @stream_update: stream update
408  * @array_of_surface_update: dc surface update pointer
409  *
410  */
411 static inline bool update_planes_and_stream_adapter(struct dc *dc,
412 						    int update_type,
413 						    int planes_count,
414 						    struct dc_stream_state *stream,
415 						    struct dc_stream_update *stream_update,
416 						    struct dc_surface_update *array_of_surface_update)
417 {
418 	sort(array_of_surface_update, planes_count,
419 	     sizeof(*array_of_surface_update), dm_plane_layer_index_cmp, NULL);
420 
421 	/*
422 	 * Previous frame finished and HW is ready for optimization.
423 	 */
424 	dc_post_update_surfaces_to_stream(dc);
425 
426 	return dc_update_planes_and_stream(dc,
427 					   array_of_surface_update,
428 					   planes_count,
429 					   stream,
430 					   stream_update);
431 }
432 
433 /**
434  * dm_pflip_high_irq() - Handle pageflip interrupt
435  * @interrupt_params: ignored
436  *
437  * Handles the pageflip interrupt by notifying all interested parties
438  * that the pageflip has been completed.
439  */
440 static void dm_pflip_high_irq(void *interrupt_params)
441 {
442 	struct amdgpu_crtc *amdgpu_crtc;
443 	struct common_irq_params *irq_params = interrupt_params;
444 	struct amdgpu_device *adev = irq_params->adev;
445 	struct drm_device *dev = adev_to_drm(adev);
446 	unsigned long flags;
447 	struct drm_pending_vblank_event *e;
448 	u32 vpos, hpos, v_blank_start, v_blank_end;
449 	bool vrr_active;
450 
451 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
452 
453 	/* IRQ could occur when in initial stage */
454 	/* TODO work and BO cleanup */
455 	if (amdgpu_crtc == NULL) {
456 		drm_dbg_state(dev, "CRTC is null, returning.\n");
457 		return;
458 	}
459 
460 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
461 
462 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED) {
463 		drm_dbg_state(dev,
464 			      "amdgpu_crtc->pflip_status = %d != AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p]\n",
465 			      amdgpu_crtc->pflip_status, AMDGPU_FLIP_SUBMITTED,
466 			      amdgpu_crtc->crtc_id, amdgpu_crtc);
467 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
468 		return;
469 	}
470 
471 	/* page flip completed. */
472 	e = amdgpu_crtc->event;
473 	amdgpu_crtc->event = NULL;
474 
475 	WARN_ON(!e);
476 
477 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(amdgpu_crtc);
478 
479 	/* Fixed refresh rate, or VRR scanout position outside front-porch? */
480 	if (!vrr_active ||
481 	    !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
482 				      &v_blank_end, &hpos, &vpos) ||
483 	    (vpos < v_blank_start)) {
484 		/* Update to correct count and vblank timestamp if racing with
485 		 * vblank irq. This also updates to the correct vblank timestamp
486 		 * even in VRR mode, as scanout is past the front-porch atm.
487 		 */
488 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
489 
490 		/* Wake up userspace by sending the pageflip event with proper
491 		 * count and timestamp of vblank of flip completion.
492 		 */
493 		if (e) {
494 			drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
495 
496 			/* Event sent, so done with vblank for this flip */
497 			drm_crtc_vblank_put(&amdgpu_crtc->base);
498 		}
499 	} else if (e) {
500 		/* VRR active and inside front-porch: vblank count and
501 		 * timestamp for pageflip event will only be up to date after
502 		 * drm_crtc_handle_vblank() has been executed from late vblank
503 		 * irq handler after start of back-porch (vline 0). We queue the
504 		 * pageflip event for send-out by drm_crtc_handle_vblank() with
505 		 * updated timestamp and count, once it runs after us.
506 		 *
507 		 * We need to open-code this instead of using the helper
508 		 * drm_crtc_arm_vblank_event(), as that helper would
509 		 * call drm_crtc_accurate_vblank_count(), which we must
510 		 * not call in VRR mode while we are in front-porch!
511 		 */
512 
513 		/* sequence will be replaced by real count during send-out. */
514 		e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
515 		e->pipe = amdgpu_crtc->crtc_id;
516 
517 		list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
518 		e = NULL;
519 	}
520 
521 	/* Keep track of vblank of this flip for flip throttling. We use the
522 	 * cooked hw counter, as that one incremented at start of this vblank
523 	 * of pageflip completion, so last_flip_vblank is the forbidden count
524 	 * for queueing new pageflips if vsync + VRR is enabled.
525 	 */
526 	amdgpu_crtc->dm_irq_params.last_flip_vblank =
527 		amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
528 
529 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
530 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
531 
532 	drm_dbg_state(dev,
533 		      "crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
534 		      amdgpu_crtc->crtc_id, amdgpu_crtc, vrr_active, (int)!e);
535 }
536 
537 static void dm_handle_vmin_vmax_update(struct work_struct *offload_work)
538 {
539 	struct vupdate_offload_work *work = container_of(offload_work, struct vupdate_offload_work, work);
540 	struct amdgpu_device *adev = work->adev;
541 	struct dc_stream_state *stream = work->stream;
542 	struct dc_crtc_timing_adjust *adjust = work->adjust;
543 
544 	mutex_lock(&adev->dm.dc_lock);
545 	dc_stream_adjust_vmin_vmax(adev->dm.dc, stream, adjust);
546 	mutex_unlock(&adev->dm.dc_lock);
547 
548 	dc_stream_release(stream);
549 	kfree(work->adjust);
550 	kfree(work);
551 }
552 
553 static void schedule_dc_vmin_vmax(struct amdgpu_device *adev,
554 	struct dc_stream_state *stream,
555 	struct dc_crtc_timing_adjust *adjust)
556 {
557 	struct vupdate_offload_work *offload_work = kzalloc_obj(*offload_work,
558 								GFP_NOWAIT);
559 	if (!offload_work) {
560 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate vupdate_offload_work\n");
561 		return;
562 	}
563 
564 	struct dc_crtc_timing_adjust *adjust_copy = kzalloc_obj(*adjust_copy,
565 								GFP_NOWAIT);
566 	if (!adjust_copy) {
567 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate adjust_copy\n");
568 		kfree(offload_work);
569 		return;
570 	}
571 
572 	dc_stream_retain(stream);
573 	memcpy(adjust_copy, adjust, sizeof(*adjust_copy));
574 
575 	INIT_WORK(&offload_work->work, dm_handle_vmin_vmax_update);
576 	offload_work->adev = adev;
577 	offload_work->stream = stream;
578 	offload_work->adjust = adjust_copy;
579 
580 	queue_work(system_percpu_wq, &offload_work->work);
581 }
582 
583 /**
584  * dm_crtc_high_irq_handler() - Common OTG vblank/flip event handling
585  * @adev: amdgpu device
586  * @acrtc: the CRTC to service
587  *
588  * Performs writeback completion, vblank event handling, CRC processing, VRR BTR
589  * updates and pageflip completion delivery.
590  *
591  * On DCN this is driven by VUPDATE_NO_LOCK (the register latch point) from
592  * dm_vupdate_high_irq(); on DCE it is driven by VLINE0 at the start of vblank
593  * from dm_crtc_high_irq().
594  */
595 static void dm_crtc_high_irq_handler(struct amdgpu_device *adev,
596 				     struct amdgpu_crtc *acrtc)
597 {
598 	struct drm_writeback_job *job;
599 	unsigned long flags;
600 	int vrr_active;
601 	bool is_dcn = amdgpu_ip_version(adev, DCE_HWIP, 0) != 0;
602 
603 	if (acrtc->wb_conn) {
604 		spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
605 
606 		if (acrtc->wb_pending) {
607 			job = list_first_entry_or_null(&acrtc->wb_conn->job_queue,
608 						       struct drm_writeback_job,
609 						       list_entry);
610 			acrtc->wb_pending = false;
611 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
612 
613 			if (job) {
614 				unsigned int v_total, refresh_hz;
615 				struct dc_stream_state *stream = acrtc->dm_irq_params.stream;
616 
617 				v_total = stream->adjust.v_total_max ?
618 					  stream->adjust.v_total_max : stream->timing.v_total;
619 				refresh_hz = div_u64((uint64_t) stream->timing.pix_clk_100hz *
620 					     100LL, (v_total * stream->timing.h_total));
621 				mdelay(1000 / refresh_hz);
622 
623 				drm_writeback_signal_completion(acrtc->wb_conn, 0);
624 				dc_stream_fc_disable_writeback(adev->dm.dc,
625 							       acrtc->dm_irq_params.stream, 0);
626 			}
627 		} else
628 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
629 	}
630 
631 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
632 
633 	drm_dbg_vbl(adev_to_drm(adev),
634 		    "crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
635 		    vrr_active, acrtc->dm_irq_params.active_planes);
636 
637 	/**
638 	 * Core vblank handling.
639 	 *
640 	 * On DCN this handler runs at VUPDATE_NO_LOCK, the register latch
641 	 * point, which is the correct place to timestamp both VRR and non-VRR
642 	 * vblanks.
643 	 *
644 	 * On DCE this handler runs at the start of front-porch, where only
645 	 * non-VRR timestamping is valid; VRR vblank is deferred to
646 	 * dm_vupdate_high_irq() after end of front-porch.
647 	 */
648 	if (is_dcn || !vrr_active)
649 		amdgpu_dm_crtc_handle_vblank(acrtc);
650 
651 	/**
652 	 * Following stuff must happen at start of vblank, for crc
653 	 * computation and below-the-range btr support in vrr mode.
654 	 */
655 	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
656 
657 	/* BTR updates need to happen before VUPDATE on Vega and above. */
658 	if (adev->family < AMDGPU_FAMILY_AI)
659 		return;
660 
661 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
662 
663 	if (acrtc->dm_irq_params.stream &&
664 		acrtc->dm_irq_params.vrr_params.supported) {
665 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
666 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
667 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state == VRR_STATE_ACTIVE_VARIABLE;
668 
669 		mod_freesync_handle_v_update(adev->dm.freesync_module,
670 					     acrtc->dm_irq_params.stream,
671 					     &acrtc->dm_irq_params.vrr_params);
672 
673 		/* update vmin_vmax only if freesync is enabled, or only if PSR and REPLAY are disabled */
674 		if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
675 			schedule_dc_vmin_vmax(adev, acrtc->dm_irq_params.stream,
676 					&acrtc->dm_irq_params.vrr_params.adjust);
677 		}
678 	}
679 
680 	/*
681 	 * Deliver pageflip completion events (DCN only).
682 	 *
683 	 * Since GRPH_PFLIP is not used, VUPDATE_NO_LOCK is the flip latch
684 	 * point. Deliver any pending pageflip completion event from here,
685 	 * once HW has consumed the new address (the OTG no longer reports a
686 	 * pending flip).
687 	 *
688 	 * Also handle the case here where there aren't any active planes and
689 	 * DCN HUBP may be clock-gated, so the flip-pending status may be
690 	 * undefined.
691 	 */
692 	if (is_dcn && acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
693 	    acrtc->event) {
694 
695 		if (!dc_get_flip_pending_on_otg(adev->dm.dc, acrtc->otg_inst)) {
696 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
697 			acrtc->event = NULL;
698 			drm_crtc_vblank_put(&acrtc->base);
699 			acrtc->pflip_status = AMDGPU_FLIP_NONE;
700 		}
701 		/*
702 		 * If the flip is still pending, leave it armed and
703 		 * retry on the next vupdate.
704 		 */
705 	} else if (is_dcn && acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
706 		   acrtc->dm_irq_params.active_planes == 0) {
707 
708 		if (acrtc->event) {
709 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
710 			acrtc->event = NULL;
711 			drm_crtc_vblank_put(&acrtc->base);
712 		}
713 		acrtc->pflip_status = AMDGPU_FLIP_NONE;
714 	}
715 
716 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
717 }
718 
719 static void dm_vupdate_high_irq(void *interrupt_params)
720 {
721 	struct common_irq_params *irq_params = interrupt_params;
722 	struct amdgpu_device *adev = irq_params->adev;
723 	struct amdgpu_crtc *acrtc;
724 	struct drm_device *drm_dev;
725 	struct drm_vblank_crtc *vblank;
726 	ktime_t frame_duration_ns, previous_timestamp;
727 	unsigned long flags;
728 	int vrr_active;
729 
730 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
731 	if (!acrtc)
732 		return;
733 
734 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
735 	drm_dev = acrtc->base.dev;
736 	vblank = drm_crtc_vblank_crtc(&acrtc->base);
737 	previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
738 	frame_duration_ns = vblank->time - previous_timestamp;
739 
740 	if (frame_duration_ns > 0) {
741 		trace_amdgpu_refresh_rate_track(acrtc->base.index,
742 					frame_duration_ns,
743 					ktime_divns(NSEC_PER_SEC, frame_duration_ns));
744 		atomic64_set(&irq_params->previous_timestamp, vblank->time);
745 	}
746 
747 	drm_dbg_vbl(drm_dev,
748 		    "crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
749 		    vrr_active);
750 
751 	/*
752 	 * On DCN, VUPDATE_NO_LOCK is the single OTG interrupt used to deliver
753 	 * vblank and pageflip completion events; VSTARTUP and GRPH_PFLIP are
754 	 * not used. Run the full handler here.
755 	 */
756 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) != 0) {
757 		dm_crtc_high_irq_handler(adev, acrtc);
758 		return;
759 	}
760 
761 	/* DCE only below. */
762 
763 	/* Core vblank handling is done here after end of front-porch in
764 	 * vrr mode, as vblank timestamping will give valid results
765 	 * while now done after front-porch. This will also deliver
766 	 * page-flip completion events that have been queued to us
767 	 * if a pageflip happened inside front-porch.
768 	 */
769 	if (vrr_active && acrtc->dm_irq_params.stream) {
770 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
771 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
772 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state
773 			== VRR_STATE_ACTIVE_VARIABLE;
774 
775 		amdgpu_dm_crtc_handle_vblank(acrtc);
776 
777 		/* BTR processing for pre-DCE12 ASICs */
778 		if (adev->family < AMDGPU_FAMILY_AI) {
779 			spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
780 			mod_freesync_handle_v_update(
781 				adev->dm.freesync_module,
782 				acrtc->dm_irq_params.stream,
783 				&acrtc->dm_irq_params.vrr_params);
784 
785 			if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
786 				schedule_dc_vmin_vmax(adev,
787 					acrtc->dm_irq_params.stream,
788 					&acrtc->dm_irq_params.vrr_params.adjust);
789 			}
790 			spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
791 		}
792 	}
793 }
794 
795 /**
796  * dm_crtc_high_irq() - Handles CRTC interrupt
797  * @interrupt_params: used for determining the CRTC instance
798  *
799  * Handles the CRTC/VSYNC interrupt by notifying DRM's VBLANK event handler.
800  *
801  * Used on DCE (VLINE0, set to vblank start). On DCN the equivalent handling is
802  * driven by VUPDATE_NO_LOCK in dm_vupdate_high_irq().
803  */
804 static void dm_crtc_high_irq(void *interrupt_params)
805 {
806 	struct common_irq_params *irq_params = interrupt_params;
807 	struct amdgpu_device *adev = irq_params->adev;
808 	struct amdgpu_crtc *acrtc;
809 
810 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
811 	if (!acrtc)
812 		return;
813 
814 	dm_crtc_high_irq_handler(adev, acrtc);
815 }
816 
817 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
818 /**
819  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
820  * DCN generation ASICs
821  * @interrupt_params: interrupt parameters
822  *
823  * Used to set crc window/read out crc value at vertical line 0 position
824  */
825 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
826 {
827 	struct common_irq_params *irq_params = interrupt_params;
828 	struct amdgpu_device *adev = irq_params->adev;
829 	struct amdgpu_crtc *acrtc;
830 
831 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
832 
833 	if (!acrtc)
834 		return;
835 
836 	amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
837 }
838 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
839 
840 /**
841  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
842  * @adev: amdgpu_device pointer
843  * @notify: dmub notification structure
844  *
845  * Dmub AUX or SET_CONFIG command completion processing callback
846  * Copies dmub notification to DM which is to be read by AUX command.
847  * issuing thread and also signals the event to wake up the thread.
848  */
849 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
850 					struct dmub_notification *notify)
851 {
852 	if (adev->dm.dmub_notify)
853 		memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
854 	if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
855 		complete(&adev->dm.dmub_aux_transfer_done);
856 }
857 
858 static void dmub_aux_fused_io_callback(struct amdgpu_device *adev,
859 					struct dmub_notification *notify)
860 {
861 	if (!adev || !notify) {
862 		ASSERT(false);
863 		return;
864 	}
865 
866 	const struct dmub_cmd_fused_request *req = &notify->fused_request;
867 	const uint8_t ddc_line = req->u.aux.ddc_line;
868 
869 	if (ddc_line >= ARRAY_SIZE(adev->dm.fused_io)) {
870 		ASSERT(false);
871 		return;
872 	}
873 
874 	struct fused_io_sync *sync = &adev->dm.fused_io[ddc_line];
875 
876 	static_assert(sizeof(*req) <= sizeof(sync->reply_data), "Size mismatch");
877 	memcpy(sync->reply_data, req, sizeof(*req));
878 	complete(&sync->replied);
879 }
880 
881 /**
882  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
883  * @adev: amdgpu_device pointer
884  * @notify: dmub notification structure
885  *
886  * Dmub Hpd interrupt processing callback. Gets displayindex through the
887  * ink index and calls helper to do the processing.
888  */
889 static void dmub_hpd_callback(struct amdgpu_device *adev,
890 			      struct dmub_notification *notify)
891 {
892 	struct amdgpu_dm_connector *aconnector;
893 	struct amdgpu_dm_connector *hpd_aconnector = NULL;
894 	struct drm_connector *connector;
895 	struct drm_connector_list_iter iter;
896 	struct dc_link *link;
897 	u8 link_index = 0;
898 	struct drm_device *dev;
899 
900 	if (adev == NULL)
901 		return;
902 
903 	if (notify == NULL) {
904 		drm_err(adev_to_drm(adev), "DMUB HPD callback notification was NULL");
905 		return;
906 	}
907 
908 	if (notify->link_index > adev->dm.dc->link_count) {
909 		drm_err(adev_to_drm(adev), "DMUB HPD index (%u)is abnormal", notify->link_index);
910 		return;
911 	}
912 
913 	/* Skip DMUB HPD IRQ in suspend/resume. We will probe them later. */
914 	if (notify->type == DMUB_NOTIFICATION_HPD && adev->in_suspend) {
915 		drm_info(adev_to_drm(adev), "Skip DMUB HPD IRQ callback in suspend/resume\n");
916 		return;
917 	}
918 
919 	link_index = notify->link_index;
920 	link = adev->dm.dc->links[link_index];
921 	dev = adev->dm.ddev;
922 
923 	drm_connector_list_iter_begin(dev, &iter);
924 	drm_for_each_connector_iter(connector, &iter) {
925 
926 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
927 			continue;
928 
929 		aconnector = to_amdgpu_dm_connector(connector);
930 		if (link && aconnector->dc_link == link) {
931 			if (notify->type == DMUB_NOTIFICATION_HPD)
932 				drm_info(adev_to_drm(adev), "DMUB HPD IRQ callback: link_index=%u\n", link_index);
933 			else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
934 				drm_info(adev_to_drm(adev), "DMUB HPD RX IRQ callback: link_index=%u\n", link_index);
935 			else
936 				drm_warn(adev_to_drm(adev), "DMUB Unknown HPD callback type %d, link_index=%u\n",
937 						notify->type, link_index);
938 
939 			hpd_aconnector = aconnector;
940 			break;
941 		}
942 	}
943 	drm_connector_list_iter_end(&iter);
944 
945 	if (hpd_aconnector) {
946 		if (notify->type == DMUB_NOTIFICATION_HPD) {
947 			if (hpd_aconnector->dc_link->hpd_status == (notify->hpd_status == DP_HPD_PLUG))
948 				drm_warn(adev_to_drm(adev), "DMUB reported hpd status unchanged. link_index=%u\n", link_index);
949 			handle_hpd_irq_helper(hpd_aconnector);
950 		} else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ) {
951 			handle_hpd_rx_irq(hpd_aconnector);
952 		}
953 	}
954 }
955 
956 /**
957  * dmub_hpd_sense_callback - DMUB HPD sense processing callback.
958  * @adev: amdgpu_device pointer
959  * @notify: dmub notification structure
960  *
961  * HPD sense changes can occur during low power states and need to be
962  * notified from firmware to driver.
963  */
964 static void dmub_hpd_sense_callback(struct amdgpu_device *adev,
965 			      struct dmub_notification *notify)
966 {
967 	drm_dbg_driver(adev_to_drm(adev), "DMUB HPD SENSE callback.\n");
968 }
969 
970 /**
971  * register_dmub_notify_callback - Sets callback for DMUB notify
972  * @adev: amdgpu_device pointer
973  * @type: Type of dmub notification
974  * @callback: Dmub interrupt callback function
975  * @dmub_int_thread_offload: offload indicator
976  *
977  * API to register a dmub callback handler for a dmub notification
978  * Also sets indicator whether callback processing to be offloaded.
979  * to dmub interrupt handling thread
980  * Return: true if successfully registered, false if there is existing registration
981  */
982 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
983 					  enum dmub_notification_type type,
984 					  dmub_notify_interrupt_callback_t callback,
985 					  bool dmub_int_thread_offload)
986 {
987 	if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
988 		adev->dm.dmub_callback[type] = callback;
989 		adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
990 	} else
991 		return false;
992 
993 	return true;
994 }
995 
996 static void dm_handle_hpd_work(struct work_struct *work)
997 {
998 	struct dmub_hpd_work *dmub_hpd_wrk;
999 
1000 	dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
1001 
1002 	if (!dmub_hpd_wrk->dmub_notify) {
1003 		drm_err(adev_to_drm(dmub_hpd_wrk->adev), "dmub_hpd_wrk dmub_notify is NULL");
1004 		return;
1005 	}
1006 
1007 	if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
1008 		dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
1009 		dmub_hpd_wrk->dmub_notify);
1010 	}
1011 
1012 	kfree(dmub_hpd_wrk->dmub_notify);
1013 	kfree(dmub_hpd_wrk);
1014 
1015 }
1016 
1017 static const char *dmub_notification_type_str(enum dmub_notification_type e)
1018 {
1019 	switch (e) {
1020 	case DMUB_NOTIFICATION_NO_DATA:
1021 		return "NO_DATA";
1022 	case DMUB_NOTIFICATION_AUX_REPLY:
1023 		return "AUX_REPLY";
1024 	case DMUB_NOTIFICATION_HPD:
1025 		return "HPD";
1026 	case DMUB_NOTIFICATION_HPD_IRQ:
1027 		return "HPD_IRQ";
1028 	case DMUB_NOTIFICATION_SET_CONFIG_REPLY:
1029 		return "SET_CONFIG_REPLY";
1030 	case DMUB_NOTIFICATION_DPIA_NOTIFICATION:
1031 		return "DPIA_NOTIFICATION";
1032 	case DMUB_NOTIFICATION_HPD_SENSE_NOTIFY:
1033 		return "HPD_SENSE_NOTIFY";
1034 	case DMUB_NOTIFICATION_FUSED_IO:
1035 		return "FUSED_IO";
1036 	default:
1037 		return "<unknown>";
1038 	}
1039 }
1040 
1041 #define DMUB_TRACE_MAX_READ 64
1042 /**
1043  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
1044  * @interrupt_params: used for determining the Outbox instance
1045  *
1046  * Handles the Outbox Interrupt
1047  * event handler.
1048  */
1049 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
1050 {
1051 	struct dmub_notification notify = {0};
1052 	struct common_irq_params *irq_params = interrupt_params;
1053 	struct amdgpu_device *adev = irq_params->adev;
1054 	struct amdgpu_display_manager *dm = &adev->dm;
1055 	struct dmcub_trace_buf_entry entry = { 0 };
1056 	u32 count = 0;
1057 	struct dmub_hpd_work *dmub_hpd_wrk;
1058 
1059 	do {
1060 		if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
1061 			trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
1062 							entry.param0, entry.param1);
1063 
1064 			drm_dbg_driver(adev_to_drm(adev), "trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
1065 				 entry.trace_code, entry.tick_count, entry.param0, entry.param1);
1066 		} else
1067 			break;
1068 
1069 		count++;
1070 
1071 	} while (count <= DMUB_TRACE_MAX_READ);
1072 
1073 	if (count > DMUB_TRACE_MAX_READ)
1074 		drm_dbg_driver(adev_to_drm(adev), "Warning : count > DMUB_TRACE_MAX_READ");
1075 
1076 	if (dc_enable_dmub_notifications(adev->dm.dc) &&
1077 		irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
1078 
1079 		do {
1080 			dc_stat_get_dmub_notification(adev->dm.dc, &notify);
1081 			if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
1082 				drm_err(adev_to_drm(adev), "DM: notify type %d invalid!", notify.type);
1083 				continue;
1084 			}
1085 			if (!dm->dmub_callback[notify.type]) {
1086 				drm_warn(adev_to_drm(adev), "DMUB notification skipped due to no handler: type=%s\n",
1087 					dmub_notification_type_str(notify.type));
1088 				continue;
1089 			}
1090 			if (dm->dmub_thread_offload[notify.type] == true) {
1091 				dmub_hpd_wrk = kzalloc_obj(*dmub_hpd_wrk,
1092 							   GFP_ATOMIC);
1093 				if (!dmub_hpd_wrk) {
1094 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk");
1095 					return;
1096 				}
1097 				dmub_hpd_wrk->dmub_notify = kmemdup(&notify, sizeof(struct dmub_notification),
1098 								    GFP_ATOMIC);
1099 				if (!dmub_hpd_wrk->dmub_notify) {
1100 					kfree(dmub_hpd_wrk);
1101 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk->dmub_notify");
1102 					return;
1103 				}
1104 				INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
1105 				dmub_hpd_wrk->adev = adev;
1106 				queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
1107 			} else {
1108 				dm->dmub_callback[notify.type](adev, &notify);
1109 			}
1110 		} while (notify.pending_notification);
1111 	}
1112 }
1113 
1114 static int dm_set_clockgating_state(struct amdgpu_ip_block *ip_block,
1115 		  enum amd_clockgating_state state)
1116 {
1117 	return 0;
1118 }
1119 
1120 static int dm_set_powergating_state(struct amdgpu_ip_block *ip_block,
1121 		  enum amd_powergating_state state)
1122 {
1123 	return 0;
1124 }
1125 
1126 /* Prototypes of private functions */
1127 static int dm_early_init(struct amdgpu_ip_block *ip_block);
1128 
1129 /* Allocate memory for FBC compressed data  */
1130 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
1131 {
1132 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
1133 	struct dm_compressor_info *compressor = &adev->dm.compressor;
1134 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
1135 	struct drm_display_mode *mode;
1136 	unsigned long max_size = 0;
1137 
1138 	if (adev->dm.dc->fbc_compressor == NULL)
1139 		return;
1140 
1141 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
1142 		return;
1143 
1144 	if (compressor->bo_ptr)
1145 		return;
1146 
1147 
1148 	list_for_each_entry(mode, &connector->modes, head) {
1149 		if (max_size < (unsigned long) mode->htotal * mode->vtotal)
1150 			max_size = (unsigned long) mode->htotal * mode->vtotal;
1151 	}
1152 
1153 	if (max_size) {
1154 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
1155 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
1156 			    &compressor->gpu_addr, &compressor->cpu_addr);
1157 
1158 		if (r)
1159 			drm_err(adev_to_drm(adev), "DM: Failed to initialize FBC\n");
1160 		else {
1161 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
1162 			drm_info(adev_to_drm(adev), "DM: FBC alloc %lu\n", max_size*4);
1163 		}
1164 
1165 	}
1166 
1167 }
1168 
1169 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
1170 					  int pipe, bool *enabled,
1171 					  unsigned char *buf, int max_bytes)
1172 {
1173 	struct drm_device *dev = dev_get_drvdata(kdev);
1174 	struct amdgpu_device *adev = drm_to_adev(dev);
1175 	struct drm_connector *connector;
1176 	struct drm_connector_list_iter conn_iter;
1177 	struct amdgpu_dm_connector *aconnector;
1178 	int ret = 0;
1179 
1180 	*enabled = false;
1181 
1182 	mutex_lock(&adev->dm.audio_lock);
1183 
1184 	drm_connector_list_iter_begin(dev, &conn_iter);
1185 	drm_for_each_connector_iter(connector, &conn_iter) {
1186 
1187 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1188 			continue;
1189 
1190 		aconnector = to_amdgpu_dm_connector(connector);
1191 		if (aconnector->audio_inst != port)
1192 			continue;
1193 
1194 		*enabled = true;
1195 		mutex_lock(&connector->eld_mutex);
1196 		ret = drm_eld_size(connector->eld);
1197 		memcpy(buf, connector->eld, min(max_bytes, ret));
1198 		mutex_unlock(&connector->eld_mutex);
1199 
1200 		break;
1201 	}
1202 	drm_connector_list_iter_end(&conn_iter);
1203 
1204 	mutex_unlock(&adev->dm.audio_lock);
1205 
1206 	drm_dbg_kms(adev_to_drm(adev), "Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
1207 
1208 	return ret;
1209 }
1210 
1211 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
1212 	.get_eld = amdgpu_dm_audio_component_get_eld,
1213 };
1214 
1215 static int amdgpu_dm_audio_component_bind(struct device *kdev,
1216 				       struct device *hda_kdev, void *data)
1217 {
1218 	struct drm_device *dev = dev_get_drvdata(kdev);
1219 	struct amdgpu_device *adev = drm_to_adev(dev);
1220 	struct drm_audio_component *acomp = data;
1221 
1222 	acomp->ops = &amdgpu_dm_audio_component_ops;
1223 	acomp->dev = kdev;
1224 	adev->dm.audio_component = acomp;
1225 
1226 	return 0;
1227 }
1228 
1229 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
1230 					  struct device *hda_kdev, void *data)
1231 {
1232 	struct amdgpu_device *adev = drm_to_adev(dev_get_drvdata(kdev));
1233 	struct drm_audio_component *acomp = data;
1234 
1235 	acomp->ops = NULL;
1236 	acomp->dev = NULL;
1237 	adev->dm.audio_component = NULL;
1238 }
1239 
1240 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
1241 	.bind	= amdgpu_dm_audio_component_bind,
1242 	.unbind	= amdgpu_dm_audio_component_unbind,
1243 };
1244 
1245 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
1246 {
1247 	int i, ret;
1248 
1249 	if (!amdgpu_audio)
1250 		return 0;
1251 
1252 	adev->mode_info.audio.enabled = true;
1253 
1254 	adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
1255 
1256 	for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
1257 		adev->mode_info.audio.pin[i].channels = -1;
1258 		adev->mode_info.audio.pin[i].rate = -1;
1259 		adev->mode_info.audio.pin[i].bits_per_sample = -1;
1260 		adev->mode_info.audio.pin[i].status_bits = 0;
1261 		adev->mode_info.audio.pin[i].category_code = 0;
1262 		adev->mode_info.audio.pin[i].connected = false;
1263 		adev->mode_info.audio.pin[i].id =
1264 			adev->dm.dc->res_pool->audios[i]->inst;
1265 		adev->mode_info.audio.pin[i].offset = 0;
1266 	}
1267 
1268 	ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1269 	if (ret < 0)
1270 		return ret;
1271 
1272 	adev->dm.audio_registered = true;
1273 
1274 	return 0;
1275 }
1276 
1277 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
1278 {
1279 	if (!amdgpu_audio)
1280 		return;
1281 
1282 	if (!adev->mode_info.audio.enabled)
1283 		return;
1284 
1285 	if (adev->dm.audio_registered) {
1286 		component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1287 		adev->dm.audio_registered = false;
1288 	}
1289 
1290 	/* TODO: Disable audio? */
1291 
1292 	adev->mode_info.audio.enabled = false;
1293 }
1294 
1295 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
1296 {
1297 	struct drm_audio_component *acomp = adev->dm.audio_component;
1298 
1299 	if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
1300 		drm_dbg_kms(adev_to_drm(adev), "Notify ELD: %d\n", pin);
1301 
1302 		acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1303 						 pin, -1);
1304 	}
1305 }
1306 
1307 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1308 {
1309 	const struct dmcub_firmware_header_v1_0 *hdr;
1310 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1311 	struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1312 	const struct firmware *dmub_fw = adev->dm.dmub_fw;
1313 	struct dc *dc = adev->dm.dc;
1314 	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1315 	struct abm *abm = adev->dm.dc->res_pool->abm;
1316 	struct dc_context *ctx = adev->dm.dc->ctx;
1317 	struct dmub_srv_hw_params hw_params;
1318 	enum dmub_status status;
1319 	const unsigned char *fw_inst_const, *fw_bss_data;
1320 	u32 i, fw_inst_const_size, fw_bss_data_size;
1321 	bool has_hw_support;
1322 
1323 	if (!dmub_srv)
1324 		/* DMUB isn't supported on the ASIC. */
1325 		return 0;
1326 
1327 	if (!fb_info) {
1328 		drm_err(adev_to_drm(adev), "No framebuffer info for DMUB service.\n");
1329 		return -EINVAL;
1330 	}
1331 
1332 	if (!dmub_fw) {
1333 		/* Firmware required for DMUB support. */
1334 		drm_err(adev_to_drm(adev), "No firmware provided for DMUB.\n");
1335 		return -EINVAL;
1336 	}
1337 
1338 	/* initialize register offsets for ASICs with runtime initialization available */
1339 	if (dmub_srv->hw_funcs.init_reg_offsets)
1340 		dmub_srv->hw_funcs.init_reg_offsets(dmub_srv, ctx);
1341 
1342 	status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1343 	if (status != DMUB_STATUS_OK) {
1344 		drm_err(adev_to_drm(adev), "Error checking HW support for DMUB: %d\n", status);
1345 		return -EINVAL;
1346 	}
1347 
1348 	if (!has_hw_support) {
1349 		drm_info(adev_to_drm(adev), "DMUB unsupported on ASIC\n");
1350 		return 0;
1351 	}
1352 
1353 	/* Reset DMCUB if it was previously running - before we overwrite its memory. */
1354 	status = dmub_srv_hw_reset(dmub_srv);
1355 	if (status != DMUB_STATUS_OK)
1356 		drm_warn(adev_to_drm(adev), "Error resetting DMUB HW: %d\n", status);
1357 
1358 	hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1359 
1360 	fw_inst_const = dmub_fw->data +
1361 			le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1362 			PSP_HEADER_BYTES_256;
1363 
1364 	fw_bss_data = dmub_fw->data +
1365 		      le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1366 		      le32_to_cpu(hdr->inst_const_bytes);
1367 
1368 	/* Copy firmware and bios info into FB memory. */
1369 	fw_inst_const_size = adev->dm.fw_inst_size;
1370 
1371 	fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1372 
1373 	/* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1374 	 * amdgpu_ucode_init_single_fw will load dmub firmware
1375 	 * fw_inst_const part to cw0; otherwise, the firmware back door load
1376 	 * will be done by dm_dmub_hw_init
1377 	 */
1378 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1379 		memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1380 				fw_inst_const_size);
1381 	}
1382 
1383 	if (fw_bss_data_size)
1384 		memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1385 		       fw_bss_data, fw_bss_data_size);
1386 
1387 	/* Copy firmware bios info into FB memory. */
1388 	memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1389 	       adev->bios_size);
1390 
1391 	/* Reset regions that need to be reset. */
1392 	memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1393 	fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1394 
1395 	memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1396 	       fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1397 
1398 	memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1399 	       fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1400 
1401 	memset(fb_info->fb[DMUB_WINDOW_SHARED_STATE].cpu_addr, 0,
1402 	       fb_info->fb[DMUB_WINDOW_SHARED_STATE].size);
1403 
1404 	/* Initialize hardware. */
1405 	memset(&hw_params, 0, sizeof(hw_params));
1406 	hw_params.soc_fb_info.fb_base = adev->gmc.fb_start;
1407 	hw_params.soc_fb_info.fb_offset = adev->vm_manager.vram_base_offset;
1408 
1409 	/* backdoor load firmware and trigger dmub running */
1410 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1411 		hw_params.load_inst_const = true;
1412 
1413 	if (dmcu)
1414 		hw_params.psp_version = dmcu->psp_version;
1415 
1416 	for (i = 0; i < fb_info->num_fb; ++i)
1417 		hw_params.fb[i] = &fb_info->fb[i];
1418 
1419 	/* Enable usb4 dpia in the FW APU */
1420 	if (dc->caps.is_apu &&
1421 		dc->res_pool->usb4_dpia_count != 0 &&
1422 		!dc->debug.dpia_debug.bits.disable_dpia) {
1423 		hw_params.dpia_supported = true;
1424 		hw_params.disable_dpia = dc->debug.dpia_debug.bits.disable_dpia;
1425 		hw_params.dpia_hpd_int_enable_supported = false;
1426 		hw_params.enable_non_transparent_setconfig = dc->config.consolidated_dpia_dp_lt;
1427 		hw_params.disable_dpia_bw_allocation = !dc->config.usb4_bw_alloc_support;
1428 	}
1429 
1430 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1431 	case IP_VERSION(3, 5, 0):
1432 	case IP_VERSION(3, 5, 1):
1433 	case IP_VERSION(3, 6, 0):
1434 	case IP_VERSION(4, 2, 0):
1435 	case IP_VERSION(4, 2, 1):
1436 		hw_params.ips_sequential_ono = adev->external_rev_id > 0x10;
1437 		hw_params.lower_hbr3_phy_ssc = true;
1438 		break;
1439 	default:
1440 		break;
1441 	}
1442 
1443 	status = dmub_srv_hw_init(dmub_srv, &hw_params);
1444 	if (status != DMUB_STATUS_OK) {
1445 		drm_err(adev_to_drm(adev), "Error initializing DMUB HW: %d\n", status);
1446 		return -EINVAL;
1447 	}
1448 
1449 	/* Wait for firmware load to finish. */
1450 	status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1451 	if (status != DMUB_STATUS_OK)
1452 		drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1453 
1454 	/* Init DMCU and ABM if available. */
1455 	if (dmcu && abm) {
1456 		dmcu->funcs->dmcu_init(dmcu);
1457 		abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1458 	}
1459 
1460 	if (!adev->dm.dc->ctx->dmub_srv)
1461 		adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1462 	if (!adev->dm.dc->ctx->dmub_srv) {
1463 		drm_err(adev_to_drm(adev), "Couldn't allocate DC DMUB server!\n");
1464 		return -ENOMEM;
1465 	}
1466 
1467 	drm_info(adev_to_drm(adev), "DMUB hardware initialized: version=0x%08X\n",
1468 		 adev->dm.dmcub_fw_version);
1469 
1470 	/* Keeping sanity checks off if
1471 	 * DCN31 >= 4.0.59.0
1472 	 * DCN314 >= 8.0.16.0
1473 	 * Otherwise, turn on sanity checks
1474 	 */
1475 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1476 	case IP_VERSION(3, 1, 2):
1477 	case IP_VERSION(3, 1, 3):
1478 		if (adev->dm.dmcub_fw_version &&
1479 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1480 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(4, 0, 59))
1481 				adev->dm.dc->debug.sanity_checks = true;
1482 		break;
1483 	case IP_VERSION(3, 1, 4):
1484 		if (adev->dm.dmcub_fw_version &&
1485 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1486 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(8, 0, 16))
1487 				adev->dm.dc->debug.sanity_checks = true;
1488 		break;
1489 	default:
1490 		break;
1491 	}
1492 
1493 	return 0;
1494 }
1495 
1496 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1497 {
1498 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1499 	enum dmub_status status;
1500 	bool init;
1501 	int r;
1502 
1503 	if (!dmub_srv) {
1504 		/* DMUB isn't supported on the ASIC. */
1505 		return;
1506 	}
1507 
1508 	status = dmub_srv_is_hw_init(dmub_srv, &init);
1509 	if (status != DMUB_STATUS_OK)
1510 		drm_warn(adev_to_drm(adev), "DMUB hardware init check failed: %d\n", status);
1511 
1512 	if (status == DMUB_STATUS_OK && init) {
1513 		/* Wait for firmware load to finish. */
1514 		status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1515 		if (status != DMUB_STATUS_OK)
1516 			drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1517 	} else {
1518 		/* Perform the full hardware initialization. */
1519 		r = dm_dmub_hw_init(adev);
1520 		if (r)
1521 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
1522 	}
1523 }
1524 
1525 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1526 {
1527 	u64 pt_base;
1528 	u32 logical_addr_low;
1529 	u32 logical_addr_high;
1530 	u32 agp_base, agp_bot, agp_top;
1531 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1532 
1533 	memset(pa_config, 0, sizeof(*pa_config));
1534 
1535 	agp_base = 0;
1536 	agp_bot = adev->gmc.agp_start >> 24;
1537 	agp_top = adev->gmc.agp_end >> 24;
1538 
1539 	/* AGP aperture is disabled */
1540 	if (agp_bot > agp_top) {
1541 		logical_addr_low = adev->gmc.fb_start >> 18;
1542 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1543 				       AMD_APU_IS_RENOIR |
1544 				       AMD_APU_IS_GREEN_SARDINE))
1545 			/*
1546 			 * Raven2 has a HW issue that it is unable to use the vram which
1547 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1548 			 * workaround that increase system aperture high address (add 1)
1549 			 * to get rid of the VM fault and hardware hang.
1550 			 */
1551 			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
1552 		else
1553 			logical_addr_high = adev->gmc.fb_end >> 18;
1554 	} else {
1555 		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1556 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1557 				       AMD_APU_IS_RENOIR |
1558 				       AMD_APU_IS_GREEN_SARDINE))
1559 			/*
1560 			 * Raven2 has a HW issue that it is unable to use the vram which
1561 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1562 			 * workaround that increase system aperture high address (add 1)
1563 			 * to get rid of the VM fault and hardware hang.
1564 			 */
1565 			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1566 		else
1567 			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1568 	}
1569 
1570 	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1571 
1572 	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
1573 						   AMDGPU_GPU_PAGE_SHIFT);
1574 	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
1575 						  AMDGPU_GPU_PAGE_SHIFT);
1576 	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
1577 						 AMDGPU_GPU_PAGE_SHIFT);
1578 	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
1579 						AMDGPU_GPU_PAGE_SHIFT);
1580 	page_table_base.high_part = upper_32_bits(pt_base);
1581 	page_table_base.low_part = lower_32_bits(pt_base);
1582 
1583 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1584 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1585 
1586 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
1587 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1588 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1589 
1590 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1591 	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
1592 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1593 
1594 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1595 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1596 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1597 
1598 	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
1599 
1600 }
1601 
1602 static void force_connector_state(
1603 	struct amdgpu_dm_connector *aconnector,
1604 	enum drm_connector_force force_state)
1605 {
1606 	struct drm_connector *connector = &aconnector->base;
1607 
1608 	mutex_lock(&connector->dev->mode_config.mutex);
1609 	aconnector->base.force = force_state;
1610 	mutex_unlock(&connector->dev->mode_config.mutex);
1611 
1612 	mutex_lock(&aconnector->hpd_lock);
1613 	drm_kms_helper_connector_hotplug_event(connector);
1614 	mutex_unlock(&aconnector->hpd_lock);
1615 }
1616 
1617 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1618 {
1619 	struct hpd_rx_irq_offload_work *offload_work;
1620 	struct amdgpu_dm_connector *aconnector;
1621 	struct dc_link *dc_link;
1622 	struct amdgpu_device *adev;
1623 	enum dc_connection_type new_connection_type = dc_connection_none;
1624 	unsigned long flags;
1625 	union test_response test_response;
1626 
1627 	memset(&test_response, 0, sizeof(test_response));
1628 
1629 	offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1630 	aconnector = offload_work->offload_wq->aconnector;
1631 	adev = offload_work->adev;
1632 
1633 	if (!aconnector) {
1634 		drm_err(adev_to_drm(adev), "Can't retrieve aconnector in hpd_rx_irq_offload_work");
1635 		goto skip;
1636 	}
1637 
1638 	dc_link = aconnector->dc_link;
1639 
1640 	mutex_lock(&aconnector->hpd_lock);
1641 	if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
1642 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
1643 	mutex_unlock(&aconnector->hpd_lock);
1644 
1645 	if (new_connection_type == dc_connection_none)
1646 		goto skip;
1647 
1648 	if (amdgpu_in_reset(adev))
1649 		goto skip;
1650 
1651 	if (offload_work->data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
1652 		offload_work->data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
1653 		dm_handle_mst_sideband_msg_ready_event(&aconnector->mst_mgr, DOWN_OR_UP_MSG_RDY_EVENT);
1654 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1655 		offload_work->offload_wq->is_handling_mst_msg_rdy_event = false;
1656 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1657 		goto skip;
1658 	}
1659 
1660 	mutex_lock(&adev->dm.dc_lock);
1661 	if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
1662 		dc_link_dp_handle_automated_test(dc_link);
1663 
1664 		if (aconnector->timing_changed) {
1665 			/* force connector disconnect and reconnect */
1666 			force_connector_state(aconnector, DRM_FORCE_OFF);
1667 			msleep(100);
1668 			force_connector_state(aconnector, DRM_FORCE_UNSPECIFIED);
1669 		}
1670 
1671 		test_response.bits.ACK = 1;
1672 
1673 		core_link_write_dpcd(
1674 		dc_link,
1675 		DP_TEST_RESPONSE,
1676 		&test_response.raw,
1677 		sizeof(test_response));
1678 	} else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1679 			dc_link_check_link_loss_status(dc_link, &offload_work->data) &&
1680 			dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1681 		/* offload_work->data is from handle_hpd_rx_irq->
1682 		 * schedule_hpd_rx_offload_work.this is defer handle
1683 		 * for hpd short pulse. upon here, link status may be
1684 		 * changed, need get latest link status from dpcd
1685 		 * registers. if link status is good, skip run link
1686 		 * training again.
1687 		 */
1688 		union hpd_irq_data irq_data;
1689 
1690 		memset(&irq_data, 0, sizeof(irq_data));
1691 
1692 		/* before dc_link_dp_handle_link_loss, allow new link lost handle
1693 		 * request be added to work queue if link lost at end of dc_link_
1694 		 * dp_handle_link_loss
1695 		 */
1696 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1697 		offload_work->offload_wq->is_handling_link_loss = false;
1698 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1699 
1700 		if ((dc_link_dp_read_hpd_rx_irq_data(dc_link, &irq_data) == DC_OK) &&
1701 			dc_link_check_link_loss_status(dc_link, &irq_data))
1702 			dc_link_dp_handle_link_loss(dc_link);
1703 	}
1704 	mutex_unlock(&adev->dm.dc_lock);
1705 
1706 skip:
1707 	kfree(offload_work);
1708 
1709 }
1710 
1711 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct amdgpu_device *adev)
1712 {
1713 	struct dc *dc = adev->dm.dc;
1714 	int max_caps = dc->caps.max_links;
1715 	int i = 0;
1716 	struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1717 
1718 	hpd_rx_offload_wq = kzalloc_objs(*hpd_rx_offload_wq, max_caps);
1719 
1720 	if (!hpd_rx_offload_wq)
1721 		return NULL;
1722 
1723 
1724 	for (i = 0; i < max_caps; i++) {
1725 		hpd_rx_offload_wq[i].wq =
1726 				    create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1727 
1728 		if (hpd_rx_offload_wq[i].wq == NULL) {
1729 			drm_err(adev_to_drm(adev), "create amdgpu_dm_hpd_rx_offload_wq fail!");
1730 			goto out_err;
1731 		}
1732 
1733 		spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
1734 	}
1735 
1736 	return hpd_rx_offload_wq;
1737 
1738 out_err:
1739 	for (i = 0; i < max_caps; i++) {
1740 		if (hpd_rx_offload_wq[i].wq)
1741 			destroy_workqueue(hpd_rx_offload_wq[i].wq);
1742 	}
1743 	kfree(hpd_rx_offload_wq);
1744 	return NULL;
1745 }
1746 
1747 struct amdgpu_stutter_quirk {
1748 	u16 chip_vendor;
1749 	u16 chip_device;
1750 	u16 subsys_vendor;
1751 	u16 subsys_device;
1752 	u8 revision;
1753 };
1754 
1755 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1756 	/* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1757 	{ 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1758 	{ 0, 0, 0, 0, 0 },
1759 };
1760 
1761 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1762 {
1763 	const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1764 
1765 	while (p && p->chip_device != 0) {
1766 		if (pdev->vendor == p->chip_vendor &&
1767 		    pdev->device == p->chip_device &&
1768 		    pdev->subsystem_vendor == p->subsys_vendor &&
1769 		    pdev->subsystem_device == p->subsys_device &&
1770 		    pdev->revision == p->revision) {
1771 			return true;
1772 		}
1773 		++p;
1774 	}
1775 	return false;
1776 }
1777 
1778 
1779 void*
1780 dm_allocate_gpu_mem(
1781 		struct amdgpu_device *adev,
1782 		enum dc_gpu_mem_alloc_type type,
1783 		size_t size,
1784 		long long *addr)
1785 {
1786 	struct dal_allocation *da;
1787 	u32 domain = (type == DC_MEM_ALLOC_TYPE_GART) ?
1788 		AMDGPU_GEM_DOMAIN_GTT : AMDGPU_GEM_DOMAIN_VRAM;
1789 	int ret;
1790 
1791 	da = kzalloc_obj(struct dal_allocation);
1792 	if (!da)
1793 		return NULL;
1794 
1795 	ret = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
1796 				      domain, &da->bo,
1797 				      &da->gpu_addr, &da->cpu_ptr);
1798 
1799 	*addr = da->gpu_addr;
1800 
1801 	if (ret) {
1802 		kfree(da);
1803 		return NULL;
1804 	}
1805 
1806 	/* add da to list in dm */
1807 	list_add(&da->list, &adev->dm.da_list);
1808 
1809 	return da->cpu_ptr;
1810 }
1811 
1812 void
1813 dm_free_gpu_mem(
1814 		struct amdgpu_device *adev,
1815 		enum dc_gpu_mem_alloc_type type,
1816 		void *pvMem)
1817 {
1818 	struct dal_allocation *da;
1819 
1820 	/* walk the da list in DM */
1821 	list_for_each_entry(da, &adev->dm.da_list, list) {
1822 		if (pvMem == da->cpu_ptr) {
1823 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
1824 			list_del(&da->list);
1825 			kfree(da);
1826 			break;
1827 		}
1828 	}
1829 
1830 }
1831 
1832 static enum dmub_status
1833 dm_dmub_send_vbios_gpint_command(struct amdgpu_device *adev,
1834 				 enum dmub_gpint_command command_code,
1835 				 uint16_t param,
1836 				 uint32_t timeout_us)
1837 {
1838 	union dmub_gpint_data_register reg, test;
1839 	uint32_t i;
1840 
1841 	/* Assume that VBIOS DMUB is ready to take commands */
1842 
1843 	reg.bits.status = 1;
1844 	reg.bits.command_code = command_code;
1845 	reg.bits.param = param;
1846 
1847 	cgs_write_register(adev->dm.cgs_device, 0x34c0 + 0x01f8, reg.all);
1848 
1849 	for (i = 0; i < timeout_us; ++i) {
1850 		udelay(1);
1851 
1852 		/* Check if our GPINT got acked */
1853 		reg.bits.status = 0;
1854 		test = (union dmub_gpint_data_register)
1855 			cgs_read_register(adev->dm.cgs_device, 0x34c0 + 0x01f8);
1856 
1857 		if (test.all == reg.all)
1858 			return DMUB_STATUS_OK;
1859 	}
1860 
1861 	return DMUB_STATUS_TIMEOUT;
1862 }
1863 
1864 static void *dm_dmub_get_vbios_bounding_box(struct amdgpu_device *adev)
1865 {
1866 	void *bb;
1867 	long long addr;
1868 	unsigned int bb_size;
1869 	int i = 0;
1870 	uint16_t chunk;
1871 	enum dmub_gpint_command send_addrs[] = {
1872 		DMUB_GPINT__SET_BB_ADDR_WORD0,
1873 		DMUB_GPINT__SET_BB_ADDR_WORD1,
1874 		DMUB_GPINT__SET_BB_ADDR_WORD2,
1875 		DMUB_GPINT__SET_BB_ADDR_WORD3,
1876 	};
1877 	enum dmub_status ret;
1878 
1879 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1880 	case IP_VERSION(4, 0, 1):
1881 		bb_size = sizeof(struct dml2_soc_bb);
1882 		break;
1883 	case IP_VERSION(4, 2, 0):
1884 	case IP_VERSION(4, 2, 1):
1885 		bb_size = sizeof(struct dml2_soc_bb);
1886 		break;
1887 	default:
1888 		return NULL;
1889 	}
1890 
1891 	bb =  dm_allocate_gpu_mem(adev,
1892 				  DC_MEM_ALLOC_TYPE_GART,
1893 				  bb_size,
1894 				  &addr);
1895 	if (!bb)
1896 		return NULL;
1897 
1898 	for (i = 0; i < 4; i++) {
1899 		/* Extract 16-bit chunk */
1900 		chunk = ((uint64_t) addr >> (i * 16)) & 0xFFFF;
1901 		/* Send the chunk */
1902 		ret = dm_dmub_send_vbios_gpint_command(adev, send_addrs[i], chunk, 30000);
1903 		if (ret != DMUB_STATUS_OK)
1904 			goto free_bb;
1905 	}
1906 
1907 	/* Now ask DMUB to copy the bb */
1908 	ret = dm_dmub_send_vbios_gpint_command(adev, DMUB_GPINT__BB_COPY, 1, 200000);
1909 	if (ret != DMUB_STATUS_OK)
1910 		goto free_bb;
1911 
1912 	return bb;
1913 
1914 free_bb:
1915 	dm_free_gpu_mem(adev, DC_MEM_ALLOC_TYPE_GART, (void *) bb);
1916 	return NULL;
1917 
1918 }
1919 
1920 static enum dmub_ips_disable_type dm_get_default_ips_mode(
1921 	struct amdgpu_device *adev)
1922 {
1923 	enum dmub_ips_disable_type ret = DMUB_IPS_ENABLE;
1924 
1925 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1926 	case IP_VERSION(3, 5, 0):
1927 	case IP_VERSION(3, 6, 0):
1928 	case IP_VERSION(3, 5, 1):
1929 		ret =  DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
1930 		break;
1931 	case IP_VERSION(4, 2, 0):
1932 	case IP_VERSION(4, 2, 1):
1933 		ret =  DMUB_IPS_ENABLE;
1934 		break;
1935 	default:
1936 		/* ASICs older than DCN35 do not have IPSs */
1937 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 5, 0))
1938 			ret = DMUB_IPS_DISABLE_ALL;
1939 		break;
1940 	}
1941 
1942 	return ret;
1943 }
1944 
1945 static int amdgpu_dm_init_power_module(struct amdgpu_display_manager *dm)
1946 {
1947 	struct mod_power_init_params init_data[MAX_NUM_EDP];
1948 
1949 	if (dm->num_of_edps == 0) {
1950 		drm_dbg_driver(
1951 			dm->ddev,
1952 			"amdgpu: No eDP detected, skip initializing power module\n");
1953 		return 0;
1954 	}
1955 
1956 	/* Initialize all the power module parameters */
1957 	for (int i = 0; i < dm->num_of_edps; i++) {
1958 		init_data[i].allow_psr_smu_optimizations =
1959 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_SMU_OPT);
1960 		init_data[i].allow_psr_multi_disp_optimizations =
1961 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_MULTI_DISP_OPT);
1962 		/* See dm_late_init */
1963 		init_data[i].backlight_ramping_override = false;
1964 		init_data[i].backlight_ramping_start = 0xCCCC;
1965 		init_data[i].backlight_ramping_reduction = 0xCCCCCCCC;
1966 		init_data[i].def_varibright_level = 0;
1967 		init_data[i].abm_config_setting = 0;
1968 		init_data[i].num_backlight_levels = 101;
1969 		init_data[i].use_nits_based_brightness = false;
1970 		init_data[i].panel_max_millinits = 0;
1971 		init_data[i].panel_min_millinits = 0;
1972 		init_data[i].disable_fractional_pwm =
1973 			!(amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK);
1974 		init_data[i].use_custom_backlight_caps = false;
1975 		init_data[i].custom_backlight_caps_config_no = 0;
1976 		init_data[i].use_linear_backlight_curve = false;
1977 		init_data[i].def_varibright_enable = 0;
1978 		init_data[i].varibright_level = 0;
1979 		/*
1980 		 * Power module uses 16-bit backlight levels (0xFFFF max) rather
1981 		 * than 8-bit(0XFF max)
1982 		 */
1983 		init_data[i].min_backlight_pwm =
1984 			dm->backlight_caps[i].min_input_signal * 0x101;
1985 		init_data[i].max_backlight_pwm =
1986 			dm->backlight_caps[i].max_input_signal * 0x101;
1987 		init_data[i].min_abm_backlight =
1988 			dm->backlight_caps[i].min_input_signal * 0x101;
1989 
1990 		/* Min backlight level after ABM reduction,  Don't allow below 1%
1991 		 * 0xFFFF x 0.01 = 0x28F
1992 		 */
1993 		init_data[i].min_abm_backlight = (init_data[i].min_abm_backlight < 0x28F) ?
1994 			0x28F : init_data[i].min_abm_backlight;
1995 	}
1996 
1997 	dm->power_module = mod_power_create(dm->dc, init_data, dm->num_of_edps);
1998 	if (!dm->power_module) {
1999 		drm_err(dm->ddev, "amdgpu: Error allocating memory for power module\n");
2000 		return -ENOMEM;
2001 	}
2002 
2003 	mod_power_hw_init(dm->power_module);
2004 	drm_dbg_driver(dm->ddev, "amdgpu: Power module init done\n");
2005 
2006 	return 0;
2007 }
2008 
2009 static void hdmi_frl_status_polling_work(struct work_struct *work)
2010 {
2011 	struct amdgpu_display_manager *dm =
2012 		container_of(to_delayed_work(work), struct amdgpu_display_manager,
2013 				hdmi_frl_status_polling_work);
2014 	struct dc *dc = dm->dc;
2015 	struct dc_link *dc_link;
2016 	bool link_update = false;
2017 
2018 	for (int i = 0; i < MAX_LINKS; i++) {
2019 		dc_link = dc->links[i];
2020 
2021 		if (!dc_link || !dc_link->local_sink)
2022 			continue;
2023 
2024 		if (!dc_is_hdmi_signal(dc_link->connector_signal))
2025 			continue;
2026 
2027 		if (dc_link->connector_signal != SIGNAL_TYPE_HDMI_FRL)
2028 			continue;
2029 
2030 		link_update = dc_link_frl_poll_status_flag(dc_link);
2031 		if (link_update) {
2032 			mutex_lock(&dm->dc_lock);
2033 			dc_link_detect(dc_link, DETECT_REASON_RETRAIN);
2034 			mutex_unlock(&dm->dc_lock);
2035 		}
2036 	}
2037 
2038 	queue_delayed_work(dm->hdmi_frl_status_polling_wq,
2039 			   &dm->hdmi_frl_status_polling_work,
2040 			   msecs_to_jiffies(dm->hdmi_frl_status_polling_delay_ms));
2041 }
2042 
2043 static int amdgpu_dm_init(struct amdgpu_device *adev)
2044 {
2045 	struct dc_init_data init_data;
2046 	struct dc_callback_init init_params;
2047 	int r;
2048 
2049 	adev->dm.ddev = adev_to_drm(adev);
2050 	adev->dm.adev = adev;
2051 
2052 	/* Zero all the fields */
2053 	memset(&init_data, 0, sizeof(init_data));
2054 	memset(&init_params, 0, sizeof(init_params));
2055 
2056 	mutex_init(&adev->dm.dpia_aux_lock);
2057 	mutex_init(&adev->dm.dc_lock);
2058 	mutex_init(&adev->dm.audio_lock);
2059 
2060 	spin_lock_init(&adev->dm.dmub_lock);
2061 
2062 	if (amdgpu_dm_irq_init(adev)) {
2063 		drm_err(adev_to_drm(adev), "failed to initialize DM IRQ support.\n");
2064 		goto error;
2065 	}
2066 
2067 	/* special handling for early revisions of GC 11.5.4 */
2068 	if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(11, 5, 4))
2069 		init_data.asic_id.chip_family = AMDGPU_FAMILY_GC_11_5_4;
2070 	else
2071 		init_data.asic_id.chip_family = adev->family;
2072 
2073 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
2074 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
2075 	init_data.asic_id.chip_id = adev->pdev->device;
2076 
2077 	init_data.asic_id.vram_width = adev->gmc.vram_width;
2078 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
2079 	init_data.asic_id.atombios_base_address =
2080 		adev->mode_info.atom_context->bios;
2081 
2082 	init_data.driver = adev;
2083 
2084 	/* cgs_device was created in dm_sw_init() */
2085 	init_data.cgs_device = adev->dm.cgs_device;
2086 
2087 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
2088 
2089 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2090 	case IP_VERSION(2, 1, 0):
2091 		switch (adev->dm.dmcub_fw_version) {
2092 		case 0: /* development */
2093 		case 0x1: /* linux-firmware.git hash 6d9f399 */
2094 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
2095 			init_data.flags.disable_dmcu = false;
2096 			break;
2097 		default:
2098 			init_data.flags.disable_dmcu = true;
2099 		}
2100 		break;
2101 	case IP_VERSION(2, 0, 3):
2102 		init_data.flags.disable_dmcu = true;
2103 		break;
2104 	default:
2105 		break;
2106 	}
2107 
2108 	/* APU support S/G display by default except:
2109 	 * ASICs before Carrizo,
2110 	 * RAVEN1 (Users reported stability issue)
2111 	 */
2112 
2113 	if (adev->asic_type < CHIP_CARRIZO) {
2114 		init_data.flags.gpu_vm_support = false;
2115 	} else if (adev->asic_type == CHIP_RAVEN) {
2116 		if (adev->apu_flags & AMD_APU_IS_RAVEN)
2117 			init_data.flags.gpu_vm_support = false;
2118 		else
2119 			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
2120 	} else {
2121 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(2, 0, 3))
2122 			init_data.flags.gpu_vm_support = (amdgpu_sg_display == 1);
2123 		else
2124 			init_data.flags.gpu_vm_support =
2125 				(amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
2126 	}
2127 
2128 	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
2129 
2130 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
2131 		init_data.flags.fbc_support = true;
2132 
2133 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
2134 		init_data.flags.multi_mon_pp_mclk_switch = true;
2135 
2136 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
2137 		init_data.flags.disable_fractional_pwm = true;
2138 
2139 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
2140 		init_data.flags.edp_no_power_sequencing = true;
2141 
2142 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
2143 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
2144 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
2145 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
2146 
2147 	if (amdgpu_dc_feature_mask & DC_FRL_MASK)
2148 		init_data.flags.enable_frl = true;
2149 
2150 	init_data.flags.seamless_boot_edp_requested = false;
2151 
2152 	if (amdgpu_device_seamless_boot_supported(adev)) {
2153 		init_data.flags.seamless_boot_edp_requested = true;
2154 		init_data.flags.allow_seamless_boot_optimization = true;
2155 		drm_dbg(adev->dm.ddev, "Seamless boot requested\n");
2156 	}
2157 
2158 	init_data.flags.enable_mipi_converter_optimization = true;
2159 
2160 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
2161 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
2162 	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
2163 
2164 	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
2165 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
2166 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS_DYNAMIC)
2167 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_DYNAMIC;
2168 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS2_DYNAMIC)
2169 		init_data.flags.disable_ips = DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
2170 	else if (amdgpu_dc_debug_mask & DC_FORCE_IPS_ENABLE)
2171 		init_data.flags.disable_ips = DMUB_IPS_ENABLE;
2172 	else
2173 		init_data.flags.disable_ips = dm_get_default_ips_mode(adev);
2174 
2175 	init_data.flags.disable_ips_in_vpb = 0;
2176 
2177 	/* DCN35 and above supports dynamic DTBCLK switch */
2178 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 5, 0))
2179 		init_data.flags.allow_0_dtb_clk = true;
2180 
2181 	/* Enable DWB for tested platforms only */
2182 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
2183 		init_data.num_virtual_links = 1;
2184 
2185 	/* DCN42 and above dpia switch to unified link training path */
2186 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 2, 0)) {
2187 		init_data.flags.consolidated_dpia_dp_lt = true;
2188 		init_data.flags.enable_dpia_pre_training = true;
2189 		init_data.flags.unify_link_enc_assignment = true;
2190 		init_data.flags.usb4_bw_alloc_support = true;
2191 	}
2192 	retrieve_dmi_info(&adev->dm);
2193 	if (adev->dm.edp0_on_dp1_quirk)
2194 		init_data.flags.support_edp0_on_dp1 = true;
2195 
2196 	if (adev->dm.bb_from_dmub)
2197 		init_data.bb_from_dmub = adev->dm.bb_from_dmub;
2198 	else
2199 		init_data.bb_from_dmub = NULL;
2200 
2201 	/* Display Core create. */
2202 	adev->dm.dc = dc_create(&init_data);
2203 
2204 	if (adev->dm.dc) {
2205 		drm_info(adev_to_drm(adev), "Display Core v%s initialized on %s\n", DC_VER,
2206 			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
2207 	} else {
2208 		drm_info(adev_to_drm(adev), "Display Core failed to initialize with v%s!\n", DC_VER);
2209 		goto error;
2210 	}
2211 
2212 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
2213 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
2214 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
2215 	}
2216 
2217 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2218 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2219 	if (dm_should_disable_stutter(adev->pdev))
2220 		adev->dm.dc->debug.disable_stutter = true;
2221 
2222 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
2223 		adev->dm.dc->debug.disable_stutter = true;
2224 
2225 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
2226 		adev->dm.dc->debug.disable_dsc = true;
2227 
2228 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
2229 		adev->dm.dc->debug.disable_clock_gate = true;
2230 
2231 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
2232 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
2233 
2234 	if (amdgpu_dc_debug_mask & DC_DISABLE_SUBVP_FAMS) {
2235 		adev->dm.dc->debug.force_disable_subvp = true;
2236 		adev->dm.dc->debug.fams2_config.bits.enable = false;
2237 	}
2238 
2239 	if (amdgpu_dc_debug_mask & DC_ENABLE_DML2) {
2240 		adev->dm.dc->debug.using_dml2 = true;
2241 		adev->dm.dc->debug.using_dml21 = true;
2242 	}
2243 
2244 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_FORCE_FW_ENABLE)
2245 		adev->dm.dc->debug.hdcp_lc_force_fw_enable = true;
2246 
2247 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_ENABLE_SW_FALLBACK)
2248 		adev->dm.dc->debug.hdcp_lc_enable_sw_fallback = true;
2249 
2250 	if (amdgpu_dc_debug_mask & DC_SKIP_DETECTION_LT)
2251 		adev->dm.dc->debug.skip_detection_link_training = true;
2252 
2253 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
2254 
2255 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
2256 	adev->dm.dc->debug.ignore_cable_id = true;
2257 
2258 	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
2259 		drm_info(adev_to_drm(adev), "DP-HDMI FRL PCON supported\n");
2260 
2261 	r = dm_dmub_hw_init(adev);
2262 	if (r) {
2263 		drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
2264 		goto error;
2265 	}
2266 
2267 	dc_hardware_init(adev->dm.dc);
2268 
2269 	adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev);
2270 	if (!adev->dm.hpd_rx_offload_wq) {
2271 		drm_err(adev_to_drm(adev), "failed to create hpd rx offload workqueue.\n");
2272 		goto error;
2273 	}
2274 
2275 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
2276 		struct dc_phy_addr_space_config pa_config;
2277 
2278 		mmhub_read_system_context(adev, &pa_config);
2279 
2280 		// Call the DC init_memory func
2281 		dc_setup_system_context(adev->dm.dc, &pa_config);
2282 	}
2283 
2284 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
2285 	if (!adev->dm.freesync_module) {
2286 		drm_err(adev_to_drm(adev),
2287 		"failed to initialize freesync_module.\n");
2288 	} else
2289 		drm_dbg_driver(adev_to_drm(adev), "freesync_module init done %p.\n",
2290 				adev->dm.freesync_module);
2291 
2292 	amdgpu_dm_init_color_mod();
2293 
2294 	if (adev->dm.dc->caps.max_links > 0) {
2295 		adev->dm.vblank_control_workqueue =
2296 			create_singlethread_workqueue("dm_vblank_control_workqueue");
2297 		if (!adev->dm.vblank_control_workqueue)
2298 			drm_err(adev_to_drm(adev), "failed to initialize vblank_workqueue.\n");
2299 	}
2300 
2301 	if (adev->dm.dc->caps.ips_support &&
2302 	    adev->dm.dc->config.disable_ips != DMUB_IPS_DISABLE_ALL)
2303 		adev->dm.idle_workqueue = idle_create_workqueue(adev);
2304 
2305 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
2306 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
2307 
2308 		if (!adev->dm.hdcp_workqueue)
2309 			drm_err(adev_to_drm(adev), "failed to initialize hdcp_workqueue.\n");
2310 		else
2311 			drm_dbg_driver(adev_to_drm(adev),
2312 				       "hdcp_workqueue init done %p.\n",
2313 				       adev->dm.hdcp_workqueue);
2314 
2315 		dc_init_callbacks(adev->dm.dc, &init_params);
2316 	}
2317 	if (adev->dm.dc->caps.max_links > 0) {
2318 		adev->dm.hdmi_frl_status_polling_wq =
2319 			create_singlethread_workqueue("hdmi_frl_status_polling_workqueue");
2320 		if (!adev->dm.hdmi_frl_status_polling_wq)
2321 			drm_err(adev_to_drm(adev), "failed to initialize hdmi_frl_status_polling_workqueue\n");
2322 		adev->dm.hdmi_frl_status_polling_delay_ms = 200;
2323 		INIT_DELAYED_WORK(&adev->dm.hdmi_frl_status_polling_work, hdmi_frl_status_polling_work);
2324 	}
2325 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2326 		init_completion(&adev->dm.dmub_aux_transfer_done);
2327 		adev->dm.dmub_notify = kzalloc_obj(struct dmub_notification);
2328 		if (!adev->dm.dmub_notify) {
2329 			drm_info(adev_to_drm(adev), "fail to allocate adev->dm.dmub_notify");
2330 			goto error;
2331 		}
2332 
2333 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
2334 		if (!adev->dm.delayed_hpd_wq) {
2335 			drm_err(adev_to_drm(adev), "failed to create hpd offload workqueue.\n");
2336 			goto error;
2337 		}
2338 
2339 		amdgpu_dm_outbox_init(adev);
2340 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
2341 			dmub_aux_setconfig_callback, false)) {
2342 			drm_err(adev_to_drm(adev), "fail to register dmub aux callback");
2343 			goto error;
2344 		}
2345 
2346 		for (size_t i = 0; i < ARRAY_SIZE(adev->dm.fused_io); i++)
2347 			init_completion(&adev->dm.fused_io[i].replied);
2348 
2349 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_FUSED_IO,
2350 			dmub_aux_fused_io_callback, false)) {
2351 			drm_err(adev_to_drm(adev), "fail to register dmub fused io callback");
2352 			goto error;
2353 		}
2354 		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
2355 		 * It is expected that DMUB will resend any pending notifications at this point. Note
2356 		 * that hpd and hpd_irq handler registration are deferred to register_hpd_handlers() to
2357 		 * align legacy interface initialization sequence. Connection status will be proactivly
2358 		 * detected once in the amdgpu_dm_initialize_drm_device.
2359 		 */
2360 		dc_enable_dmub_outbox(adev->dm.dc);
2361 
2362 		/* DPIA trace goes to dmesg logs only if outbox is enabled */
2363 		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
2364 			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
2365 	}
2366 
2367 	if (amdgpu_dm_initialize_drm_device(adev)) {
2368 		drm_err(adev_to_drm(adev),
2369 		"failed to initialize sw for display support.\n");
2370 		goto error;
2371 	}
2372 
2373 	if (amdgpu_dm_init_power_module(&adev->dm))
2374 		goto error;
2375 
2376 	/* create fake encoders for MST */
2377 	dm_dp_create_fake_mst_encoders(adev);
2378 
2379 	/* TODO: Add_display_info? */
2380 
2381 	/* TODO use dynamic cursor width */
2382 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
2383 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
2384 
2385 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
2386 		drm_err(adev_to_drm(adev),
2387 		"failed to initialize vblank for display support.\n");
2388 		goto error;
2389 	}
2390 
2391 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2392 	amdgpu_dm_crtc_secure_display_create_contexts(adev);
2393 	if (!adev->dm.secure_display_ctx.crtc_ctx)
2394 		drm_err(adev_to_drm(adev), "failed to initialize secure display contexts.\n");
2395 
2396 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))
2397 		adev->dm.secure_display_ctx.support_mul_roi = true;
2398 
2399 #endif
2400 
2401 	drm_dbg_driver(adev_to_drm(adev), "KMS initialized.\n");
2402 
2403 	return 0;
2404 error:
2405 	amdgpu_dm_fini(adev);
2406 
2407 	return -EINVAL;
2408 }
2409 
2410 static int amdgpu_dm_early_fini(struct amdgpu_ip_block *ip_block)
2411 {
2412 	struct amdgpu_device *adev = ip_block->adev;
2413 
2414 	amdgpu_dm_audio_fini(adev);
2415 
2416 	return 0;
2417 }
2418 
2419 static void amdgpu_dm_fini(struct amdgpu_device *adev)
2420 {
2421 	int i;
2422 
2423 	if (adev->dm.vblank_control_workqueue) {
2424 		destroy_workqueue(adev->dm.vblank_control_workqueue);
2425 		adev->dm.vblank_control_workqueue = NULL;
2426 	}
2427 
2428 	if (adev->dm.idle_workqueue) {
2429 		if (adev->dm.idle_workqueue->running) {
2430 			adev->dm.idle_workqueue->enable = false;
2431 			flush_work(&adev->dm.idle_workqueue->work);
2432 		}
2433 
2434 		kfree(adev->dm.idle_workqueue);
2435 		adev->dm.idle_workqueue = NULL;
2436 	}
2437 
2438 	/*
2439 	 * Disable ISM before dc_destroy() invalidates dm->dc.
2440 	 *
2441 	 * Quiesce workers first without dc_lock (they take dc_lock
2442 	 * themselves, so syncing under it would deadlock), then drive the
2443 	 * FSM back to FULL_POWER_RUNNING under dc_lock.
2444 	 */
2445 	amdgpu_dm_ism_disable(&adev->dm);
2446 	scoped_guard(mutex, &adev->dm.dc_lock)
2447 		amdgpu_dm_ism_force_full_power(&adev->dm);
2448 
2449 	amdgpu_dm_destroy_drm_device(&adev->dm);
2450 
2451 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2452 	if (adev->dm.secure_display_ctx.crtc_ctx) {
2453 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
2454 			if (adev->dm.secure_display_ctx.crtc_ctx[i].crtc) {
2455 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].notify_ta_work);
2456 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].forward_roi_work);
2457 			}
2458 		}
2459 		kfree(adev->dm.secure_display_ctx.crtc_ctx);
2460 		adev->dm.secure_display_ctx.crtc_ctx = NULL;
2461 	}
2462 #endif
2463 	if (adev->dm.hdcp_workqueue) {
2464 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
2465 		adev->dm.hdcp_workqueue = NULL;
2466 	}
2467 
2468 	if (adev->dm.dc) {
2469 		dc_deinit_callbacks(adev->dm.dc);
2470 		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
2471 		if (dc_enable_dmub_notifications(adev->dm.dc)) {
2472 			kfree(adev->dm.dmub_notify);
2473 			adev->dm.dmub_notify = NULL;
2474 			destroy_workqueue(adev->dm.delayed_hpd_wq);
2475 			adev->dm.delayed_hpd_wq = NULL;
2476 		}
2477 	}
2478 
2479 	if (adev->dm.dmub_bo)
2480 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
2481 				      &adev->dm.dmub_bo_gpu_addr,
2482 				      &adev->dm.dmub_bo_cpu_addr);
2483 
2484 	if (adev->dm.boot_time_crc_info.bo_ptr)
2485 		amdgpu_bo_free_kernel(&adev->dm.boot_time_crc_info.bo_ptr,
2486 					&adev->dm.boot_time_crc_info.gpu_addr,
2487 					&adev->dm.boot_time_crc_info.cpu_addr);
2488 
2489 	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
2490 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
2491 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
2492 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
2493 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
2494 			}
2495 		}
2496 
2497 		kfree(adev->dm.hpd_rx_offload_wq);
2498 		adev->dm.hpd_rx_offload_wq = NULL;
2499 	}
2500 
2501 	/* DC Destroy TODO: Replace destroy DAL */
2502 	if (adev->dm.dc)
2503 		dc_destroy(&adev->dm.dc);
2504 	/*
2505 	 * TODO: pageflip, vlank interrupt
2506 	 *
2507 	 * amdgpu_dm_irq_fini(adev);
2508 	 */
2509 
2510 	if (adev->dm.cgs_device) {
2511 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
2512 		adev->dm.cgs_device = NULL;
2513 	}
2514 	if (adev->dm.freesync_module) {
2515 		mod_freesync_destroy(adev->dm.freesync_module);
2516 		adev->dm.freesync_module = NULL;
2517 	}
2518 
2519 	if (adev->dm.power_module) {
2520 		mod_power_destroy(adev->dm.power_module);
2521 		adev->dm.power_module = NULL;
2522 	}
2523 	mutex_destroy(&adev->dm.audio_lock);
2524 	mutex_destroy(&adev->dm.dc_lock);
2525 	mutex_destroy(&adev->dm.dpia_aux_lock);
2526 }
2527 
2528 static int load_dmcu_fw(struct amdgpu_device *adev)
2529 {
2530 	const char *fw_name_dmcu = NULL;
2531 	int r;
2532 	const struct dmcu_firmware_header_v1_0 *hdr;
2533 
2534 	switch (adev->asic_type) {
2535 #if defined(CONFIG_DRM_AMD_DC_SI)
2536 	case CHIP_TAHITI:
2537 	case CHIP_PITCAIRN:
2538 	case CHIP_VERDE:
2539 	case CHIP_OLAND:
2540 #endif
2541 	case CHIP_BONAIRE:
2542 	case CHIP_HAWAII:
2543 	case CHIP_KAVERI:
2544 	case CHIP_KABINI:
2545 	case CHIP_MULLINS:
2546 	case CHIP_TONGA:
2547 	case CHIP_FIJI:
2548 	case CHIP_CARRIZO:
2549 	case CHIP_STONEY:
2550 	case CHIP_POLARIS11:
2551 	case CHIP_POLARIS10:
2552 	case CHIP_POLARIS12:
2553 	case CHIP_VEGAM:
2554 	case CHIP_VEGA10:
2555 	case CHIP_VEGA12:
2556 	case CHIP_VEGA20:
2557 		return 0;
2558 	case CHIP_NAVI12:
2559 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
2560 		break;
2561 	case CHIP_RAVEN:
2562 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
2563 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2564 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
2565 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2566 		else
2567 			return 0;
2568 		break;
2569 	default:
2570 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2571 		case IP_VERSION(2, 0, 2):
2572 		case IP_VERSION(2, 0, 3):
2573 		case IP_VERSION(2, 0, 0):
2574 		case IP_VERSION(2, 1, 0):
2575 		case IP_VERSION(3, 0, 0):
2576 		case IP_VERSION(3, 0, 2):
2577 		case IP_VERSION(3, 0, 3):
2578 		case IP_VERSION(3, 0, 1):
2579 		case IP_VERSION(3, 1, 2):
2580 		case IP_VERSION(3, 1, 3):
2581 		case IP_VERSION(3, 1, 4):
2582 		case IP_VERSION(3, 1, 5):
2583 		case IP_VERSION(3, 1, 6):
2584 		case IP_VERSION(3, 2, 0):
2585 		case IP_VERSION(3, 2, 1):
2586 		case IP_VERSION(3, 5, 0):
2587 		case IP_VERSION(3, 5, 1):
2588 		case IP_VERSION(3, 6, 0):
2589 		case IP_VERSION(4, 0, 1):
2590 		case IP_VERSION(4, 2, 0):
2591 		case IP_VERSION(4, 2, 1):
2592 			return 0;
2593 		default:
2594 			break;
2595 		}
2596 		drm_err(adev_to_drm(adev), "Unsupported ASIC type: 0x%X\n", adev->asic_type);
2597 		return -EINVAL;
2598 	}
2599 
2600 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
2601 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not supported on direct or SMU loading\n");
2602 		return 0;
2603 	}
2604 
2605 	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, AMDGPU_UCODE_REQUIRED,
2606 				 "%s", fw_name_dmcu);
2607 	if (r == -ENODEV) {
2608 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
2609 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not found\n");
2610 		adev->dm.fw_dmcu = NULL;
2611 		return 0;
2612 	}
2613 	if (r) {
2614 		drm_err(adev_to_drm(adev), "amdgpu_dm: Can't validate firmware \"%s\"\n",
2615 			fw_name_dmcu);
2616 		amdgpu_ucode_release(&adev->dm.fw_dmcu);
2617 		return r;
2618 	}
2619 
2620 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
2621 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
2622 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
2623 	adev->firmware.fw_size +=
2624 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2625 
2626 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
2627 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
2628 	adev->firmware.fw_size +=
2629 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2630 
2631 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
2632 
2633 	drm_dbg_kms(adev_to_drm(adev), "PSP loading DMCU firmware\n");
2634 
2635 	return 0;
2636 }
2637 
2638 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
2639 {
2640 	struct amdgpu_device *adev = ctx;
2641 
2642 	return dm_read_reg(adev->dm.dc->ctx, address);
2643 }
2644 
2645 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
2646 				     uint32_t value)
2647 {
2648 	struct amdgpu_device *adev = ctx;
2649 
2650 	return dm_write_reg(adev->dm.dc->ctx, address, value);
2651 }
2652 
2653 static int dm_dmub_sw_init(struct amdgpu_device *adev)
2654 {
2655 	struct dmub_srv_create_params create_params;
2656 	struct dmub_srv_fw_meta_info_params fw_meta_info_params;
2657 	struct dmub_srv_region_params region_params;
2658 	struct dmub_srv_region_info region_info;
2659 	struct dmub_srv_memory_params memory_params;
2660 	struct dmub_fw_meta_info fw_info;
2661 	struct dmub_srv_fb_info *fb_info;
2662 	struct dmub_srv *dmub_srv;
2663 	const struct dmcub_firmware_header_v1_0 *hdr;
2664 	enum dmub_asic dmub_asic;
2665 	enum dmub_status status;
2666 	static enum dmub_window_memory_type window_memory_type[DMUB_WINDOW_TOTAL] = {
2667 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_0_INST_CONST
2668 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_1_STACK
2669 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_2_BSS_DATA
2670 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_3_VBIOS
2671 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_4_MAILBOX
2672 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_5_TRACEBUFF
2673 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_6_FW_STATE
2674 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_7_SCRATCH_MEM
2675 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_IB_MEM
2676 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_SHARED_STATE
2677 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_LSDMA_BUFFER
2678 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_CURSOR_OFFLOAD
2679 	};
2680 	int r;
2681 
2682 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2683 	case IP_VERSION(2, 1, 0):
2684 		dmub_asic = DMUB_ASIC_DCN21;
2685 		break;
2686 	case IP_VERSION(3, 0, 0):
2687 		dmub_asic = DMUB_ASIC_DCN30;
2688 		break;
2689 	case IP_VERSION(3, 0, 1):
2690 		dmub_asic = DMUB_ASIC_DCN301;
2691 		break;
2692 	case IP_VERSION(3, 0, 2):
2693 		dmub_asic = DMUB_ASIC_DCN302;
2694 		break;
2695 	case IP_VERSION(3, 0, 3):
2696 		dmub_asic = DMUB_ASIC_DCN303;
2697 		break;
2698 	case IP_VERSION(3, 1, 2):
2699 	case IP_VERSION(3, 1, 3):
2700 		dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
2701 		break;
2702 	case IP_VERSION(3, 1, 4):
2703 		dmub_asic = DMUB_ASIC_DCN314;
2704 		break;
2705 	case IP_VERSION(3, 1, 5):
2706 		dmub_asic = DMUB_ASIC_DCN315;
2707 		break;
2708 	case IP_VERSION(3, 1, 6):
2709 		dmub_asic = DMUB_ASIC_DCN316;
2710 		break;
2711 	case IP_VERSION(3, 2, 0):
2712 		dmub_asic = DMUB_ASIC_DCN32;
2713 		break;
2714 	case IP_VERSION(3, 2, 1):
2715 		dmub_asic = DMUB_ASIC_DCN321;
2716 		break;
2717 	case IP_VERSION(3, 5, 0):
2718 	case IP_VERSION(3, 5, 1):
2719 		dmub_asic = DMUB_ASIC_DCN35;
2720 		break;
2721 	case IP_VERSION(3, 6, 0):
2722 		dmub_asic = DMUB_ASIC_DCN36;
2723 		break;
2724 	case IP_VERSION(4, 0, 1):
2725 		dmub_asic = DMUB_ASIC_DCN401;
2726 		break;
2727 	case IP_VERSION(4, 2, 0):
2728 		dmub_asic = DMUB_ASIC_DCN42;
2729 		break;
2730 	case IP_VERSION(4, 2, 1):
2731 		dmub_asic = DMUB_ASIC_DCN42B;
2732 		break;
2733 	default:
2734 		/* ASIC doesn't support DMUB. */
2735 		return 0;
2736 	}
2737 
2738 	hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
2739 	adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
2740 
2741 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
2742 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
2743 			AMDGPU_UCODE_ID_DMCUB;
2744 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
2745 			adev->dm.dmub_fw;
2746 		adev->firmware.fw_size +=
2747 			ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
2748 
2749 		drm_info(adev_to_drm(adev), "Loading DMUB firmware via PSP: version=0x%08X\n",
2750 			 adev->dm.dmcub_fw_version);
2751 	}
2752 
2753 
2754 	adev->dm.dmub_srv = kzalloc_obj(*adev->dm.dmub_srv);
2755 	dmub_srv = adev->dm.dmub_srv;
2756 
2757 	if (!dmub_srv) {
2758 		drm_err(adev_to_drm(adev), "Failed to allocate DMUB service!\n");
2759 		return -ENOMEM;
2760 	}
2761 
2762 	memset(&create_params, 0, sizeof(create_params));
2763 	create_params.user_ctx = adev;
2764 	create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2765 	create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2766 	create_params.asic = dmub_asic;
2767 
2768 	/* Create the DMUB service. */
2769 	status = dmub_srv_create(dmub_srv, &create_params);
2770 	if (status != DMUB_STATUS_OK) {
2771 		drm_err(adev_to_drm(adev), "Error creating DMUB service: %d\n", status);
2772 		return -EINVAL;
2773 	}
2774 
2775 	/* Extract the FW meta info. */
2776 	memset(&fw_meta_info_params, 0, sizeof(fw_meta_info_params));
2777 
2778 	fw_meta_info_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2779 					      PSP_HEADER_BYTES_256;
2780 	fw_meta_info_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2781 	fw_meta_info_params.fw_inst_const = adev->dm.dmub_fw->data +
2782 					    le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2783 					    PSP_HEADER_BYTES_256;
2784 	fw_meta_info_params.fw_bss_data = fw_meta_info_params.bss_data_size ? adev->dm.dmub_fw->data +
2785 					  le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2786 					  le32_to_cpu(hdr->inst_const_bytes) : NULL;
2787 	fw_meta_info_params.custom_psp_footer_size = 0;
2788 
2789 	status = dmub_srv_get_fw_meta_info_from_raw_fw(&fw_meta_info_params, &fw_info);
2790 	if (status != DMUB_STATUS_OK) {
2791 		/* Skip returning early, just log the error. */
2792 		drm_err(adev_to_drm(adev), "Error getting DMUB FW meta info: %d\n", status);
2793 		// return -EINVAL;
2794 	}
2795 
2796 	/* Calculate the size of all the regions for the DMUB service. */
2797 	memset(&region_params, 0, sizeof(region_params));
2798 
2799 	region_params.inst_const_size = fw_meta_info_params.inst_const_size;
2800 	region_params.bss_data_size = fw_meta_info_params.bss_data_size;
2801 	region_params.vbios_size = adev->bios_size;
2802 	region_params.fw_bss_data = fw_meta_info_params.fw_bss_data;
2803 	region_params.fw_inst_const = fw_meta_info_params.fw_inst_const;
2804 	region_params.window_memory_type = window_memory_type;
2805 	region_params.fw_info = (status == DMUB_STATUS_OK) ? &fw_info : NULL;
2806 
2807 	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2808 					   &region_info);
2809 
2810 	if (status != DMUB_STATUS_OK) {
2811 		drm_err(adev_to_drm(adev), "Error calculating DMUB region info: %d\n", status);
2812 		return -EINVAL;
2813 	}
2814 
2815 	/*
2816 	 * Allocate a framebuffer based on the total size of all the regions.
2817 	 * TODO: Move this into GART.
2818 	 */
2819 	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2820 				    AMDGPU_GEM_DOMAIN_VRAM |
2821 				    AMDGPU_GEM_DOMAIN_GTT,
2822 				    &adev->dm.dmub_bo,
2823 				    &adev->dm.dmub_bo_gpu_addr,
2824 				    &adev->dm.dmub_bo_cpu_addr);
2825 	if (r)
2826 		return r;
2827 
2828 	/* Rebase the regions on the framebuffer address. */
2829 	memset(&memory_params, 0, sizeof(memory_params));
2830 	memory_params.cpu_fb_addr = adev->dm.dmub_bo_cpu_addr;
2831 	memory_params.gpu_fb_addr = adev->dm.dmub_bo_gpu_addr;
2832 	memory_params.region_info = &region_info;
2833 	memory_params.window_memory_type = window_memory_type;
2834 
2835 	adev->dm.dmub_fb_info = kzalloc_obj(*adev->dm.dmub_fb_info);
2836 	fb_info = adev->dm.dmub_fb_info;
2837 
2838 	if (!fb_info) {
2839 		drm_err(adev_to_drm(adev),
2840 			"Failed to allocate framebuffer info for DMUB service!\n");
2841 		return -ENOMEM;
2842 	}
2843 
2844 	status = dmub_srv_calc_mem_info(dmub_srv, &memory_params, fb_info);
2845 	if (status != DMUB_STATUS_OK) {
2846 		drm_err(adev_to_drm(adev), "Error calculating DMUB FB info: %d\n", status);
2847 		return -EINVAL;
2848 	}
2849 
2850 	adev->dm.bb_from_dmub = dm_dmub_get_vbios_bounding_box(adev);
2851 	adev->dm.fw_inst_size = fw_meta_info_params.inst_const_size;
2852 
2853 	return 0;
2854 }
2855 
2856 static int dm_sw_init(struct amdgpu_ip_block *ip_block)
2857 {
2858 	struct amdgpu_device *adev = ip_block->adev;
2859 	int r;
2860 
2861 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
2862 
2863 	if (!adev->dm.cgs_device) {
2864 		drm_err(adev_to_drm(adev), "failed to create cgs device.\n");
2865 		return -EINVAL;
2866 	}
2867 
2868 	/* Moved from dm init since we need to use allocations for storing bounding box data */
2869 	INIT_LIST_HEAD(&adev->dm.da_list);
2870 
2871 	r = dm_dmub_sw_init(adev);
2872 	if (r)
2873 		return r;
2874 
2875 	return load_dmcu_fw(adev);
2876 }
2877 
2878 static int dm_sw_fini(struct amdgpu_ip_block *ip_block)
2879 {
2880 	struct amdgpu_device *adev = ip_block->adev;
2881 	struct dal_allocation *da;
2882 
2883 	list_for_each_entry(da, &adev->dm.da_list, list) {
2884 		if (adev->dm.bb_from_dmub == (void *) da->cpu_ptr) {
2885 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
2886 			list_del(&da->list);
2887 			kfree(da);
2888 			adev->dm.bb_from_dmub = NULL;
2889 			break;
2890 		}
2891 	}
2892 
2893 
2894 	kfree(adev->dm.dmub_fb_info);
2895 	adev->dm.dmub_fb_info = NULL;
2896 
2897 	if (adev->dm.dmub_srv) {
2898 		dmub_srv_destroy(adev->dm.dmub_srv);
2899 		kfree(adev->dm.dmub_srv);
2900 		adev->dm.dmub_srv = NULL;
2901 	}
2902 
2903 	amdgpu_ucode_release(&adev->dm.dmub_fw);
2904 	amdgpu_ucode_release(&adev->dm.fw_dmcu);
2905 
2906 	return 0;
2907 }
2908 
2909 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2910 {
2911 	struct amdgpu_dm_connector *aconnector;
2912 	struct drm_connector *connector;
2913 	struct drm_connector_list_iter iter;
2914 	int ret = 0;
2915 
2916 	drm_connector_list_iter_begin(dev, &iter);
2917 	drm_for_each_connector_iter(connector, &iter) {
2918 
2919 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2920 			continue;
2921 
2922 		aconnector = to_amdgpu_dm_connector(connector);
2923 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
2924 		    aconnector->mst_mgr.aux) {
2925 			drm_dbg_kms(dev, "DM_MST: starting TM on aconnector: %p [id: %d]\n",
2926 					 aconnector,
2927 					 aconnector->base.base.id);
2928 
2929 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2930 			if (ret < 0) {
2931 				drm_err(dev, "DM_MST: Failed to start MST\n");
2932 				aconnector->dc_link->type =
2933 					dc_connection_single;
2934 				ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2935 								     aconnector->dc_link);
2936 				break;
2937 			}
2938 		}
2939 	}
2940 	drm_connector_list_iter_end(&iter);
2941 
2942 	return ret;
2943 }
2944 
2945 static void amdgpu_dm_boot_time_crc_init(struct amdgpu_device *adev)
2946 {
2947 	struct dm_boot_time_crc_info *bootcrc_info = NULL;
2948 	struct dmub_srv *dmub = NULL;
2949 	union dmub_fw_boot_options option = {0};
2950 	int ret = 0;
2951 	const uint32_t fb_size = 3 * 1024 * 1024;	/* 3MB for DCC pattern */
2952 
2953 	if (!adev || !adev->dm.dc || !adev->dm.dc->ctx ||
2954 		!adev->dm.dc->ctx->dmub_srv) {
2955 		return;
2956 	}
2957 
2958 	dmub = adev->dm.dc->ctx->dmub_srv->dmub;
2959 	bootcrc_info = &adev->dm.boot_time_crc_info;
2960 
2961 	if (!dmub || !dmub->hw_funcs.get_fw_boot_option) {
2962 		drm_dbg(adev_to_drm(adev), "failed to init boot time crc buffer\n");
2963 		return;
2964 	}
2965 
2966 	option = dmub->hw_funcs.get_fw_boot_option(dmub);
2967 
2968 	/* Return if boot time CRC is not enabled */
2969 	if (option.bits.bootcrc_en_at_S0i3 == 0)
2970 		return;
2971 
2972 	/* Create a buffer for boot time CRC */
2973 	ret = amdgpu_bo_create_kernel(adev, fb_size, PAGE_SIZE,
2974 		AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT,
2975 		&bootcrc_info->bo_ptr,
2976 		&bootcrc_info->gpu_addr,
2977 		&bootcrc_info->cpu_addr);
2978 
2979 	if (ret) {
2980 		drm_dbg(adev_to_drm(adev), "failed to create boot time crc buffer\n");
2981 	} else {
2982 		bootcrc_info->size = fb_size;
2983 
2984 		drm_dbg(adev_to_drm(adev), "boot time crc buffer created addr 0x%llx, size %u\n",
2985 			bootcrc_info->gpu_addr, bootcrc_info->size);
2986 
2987 		/* Send the buffer info to DMUB */
2988 		dc_dmub_srv_boot_time_crc_init(adev->dm.dc,
2989 			bootcrc_info->gpu_addr, bootcrc_info->size);
2990 	}
2991 }
2992 
2993 static int dm_late_init(struct amdgpu_ip_block *ip_block)
2994 {
2995 	struct amdgpu_device *adev = ip_block->adev;
2996 
2997 	struct dmcu_iram_parameters params;
2998 	unsigned int linear_lut[16];
2999 	int i;
3000 	struct dmcu *dmcu = NULL;
3001 
3002 	dmcu = adev->dm.dc->res_pool->dmcu;
3003 
3004 	/* Init the boot time CRC (skip in resume) */
3005 	if ((adev->in_suspend == 0) &&
3006 		(amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(3, 6, 0)))
3007 		amdgpu_dm_boot_time_crc_init(adev);
3008 
3009 	for (i = 0; i < 16; i++)
3010 		linear_lut[i] = 0xFFFF * i / 15;
3011 
3012 	params.set = 0;
3013 	params.backlight_ramping_override = false;
3014 	params.backlight_ramping_start = 0xCCCC;
3015 	params.backlight_ramping_reduction = 0xCCCCCCCC;
3016 	params.backlight_lut_array_size = 16;
3017 	params.backlight_lut_array = linear_lut;
3018 
3019 	/* Min backlight level after ABM reduction,  Don't allow below 1%
3020 	 * 0xFFFF x 0.01 = 0x28F
3021 	 */
3022 	params.min_abm_backlight = 0x28F;
3023 	/* In the case where abm is implemented on dmcub,
3024 	 * dmcu object will be null.
3025 	 * ABM 2.4 and up are implemented on dmcub.
3026 	 */
3027 	if (dmcu) {
3028 		if (!dmcu_load_iram(dmcu, params))
3029 			return -EINVAL;
3030 	} else if (adev->dm.dc->ctx->dmub_srv) {
3031 		struct dc_link *edp_links[MAX_NUM_EDP];
3032 		int edp_num;
3033 
3034 		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
3035 		for (i = 0; i < edp_num; i++) {
3036 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
3037 				return -EINVAL;
3038 		}
3039 	}
3040 
3041 	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
3042 }
3043 
3044 static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
3045 {
3046 	u8 buf[UUID_SIZE];
3047 	guid_t guid;
3048 	int ret;
3049 
3050 	mutex_lock(&mgr->lock);
3051 	if (!mgr->mst_primary)
3052 		goto out_fail;
3053 
3054 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
3055 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
3056 		goto out_fail;
3057 	}
3058 
3059 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
3060 				 DP_MST_EN |
3061 				 DP_UP_REQ_EN |
3062 				 DP_UPSTREAM_IS_SRC);
3063 	if (ret < 0) {
3064 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
3065 		goto out_fail;
3066 	}
3067 
3068 	/* Some hubs forget their guids after they resume */
3069 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, buf, sizeof(buf));
3070 	if (ret != sizeof(buf)) {
3071 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
3072 		goto out_fail;
3073 	}
3074 
3075 	import_guid(&guid, buf);
3076 
3077 	if (guid_is_null(&guid)) {
3078 		guid_gen(&guid);
3079 		export_guid(buf, &guid);
3080 
3081 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, buf, sizeof(buf));
3082 
3083 		if (ret != sizeof(buf)) {
3084 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
3085 			goto out_fail;
3086 		}
3087 	}
3088 
3089 	guid_copy(&mgr->mst_primary->guid, &guid);
3090 
3091 out_fail:
3092 	mutex_unlock(&mgr->lock);
3093 }
3094 
3095 void hdmi_cec_unset_edid(struct amdgpu_dm_connector *aconnector)
3096 {
3097 	struct cec_notifier *n = aconnector->notifier;
3098 
3099 	if (!n)
3100 		return;
3101 
3102 	cec_notifier_phys_addr_invalidate(n);
3103 }
3104 
3105 void hdmi_cec_set_edid(struct amdgpu_dm_connector *aconnector)
3106 {
3107 	struct drm_connector *connector = &aconnector->base;
3108 	struct cec_notifier *n = aconnector->notifier;
3109 
3110 	if (!n)
3111 		return;
3112 
3113 	cec_notifier_set_phys_addr(n,
3114 				   connector->display_info.source_physical_address);
3115 }
3116 
3117 static void s3_handle_hdmi_cec(struct drm_device *ddev, bool suspend)
3118 {
3119 	struct amdgpu_dm_connector *aconnector;
3120 	struct drm_connector *connector;
3121 	struct drm_connector_list_iter conn_iter;
3122 
3123 	drm_connector_list_iter_begin(ddev, &conn_iter);
3124 	drm_for_each_connector_iter(connector, &conn_iter) {
3125 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3126 			continue;
3127 
3128 		aconnector = to_amdgpu_dm_connector(connector);
3129 		if (suspend)
3130 			hdmi_cec_unset_edid(aconnector);
3131 		else
3132 			hdmi_cec_set_edid(aconnector);
3133 	}
3134 	drm_connector_list_iter_end(&conn_iter);
3135 }
3136 
3137 static void s3_handle_mst(struct drm_device *dev, bool suspend)
3138 {
3139 	struct amdgpu_dm_connector *aconnector;
3140 	struct drm_connector *connector;
3141 	struct drm_connector_list_iter iter;
3142 	struct drm_dp_mst_topology_mgr *mgr;
3143 
3144 	drm_connector_list_iter_begin(dev, &iter);
3145 	drm_for_each_connector_iter(connector, &iter) {
3146 
3147 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3148 			continue;
3149 
3150 		aconnector = to_amdgpu_dm_connector(connector);
3151 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3152 		    aconnector->mst_root)
3153 			continue;
3154 
3155 		mgr = &aconnector->mst_mgr;
3156 
3157 		if (suspend) {
3158 			drm_dp_mst_topology_mgr_suspend(mgr);
3159 		} else {
3160 			/* if extended timeout is supported in hardware,
3161 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
3162 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
3163 			 */
3164 			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
3165 			if (!dp_is_lttpr_present(aconnector->dc_link))
3166 				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
3167 
3168 			/* TODO: move resume_mst_branch_status() into drm mst resume again
3169 			 * once topology probing work is pulled out from mst resume into mst
3170 			 * resume 2nd step. mst resume 2nd step should be called after old
3171 			 * state getting restored (i.e. drm_atomic_helper_resume()).
3172 			 */
3173 			resume_mst_branch_status(mgr);
3174 		}
3175 	}
3176 	drm_connector_list_iter_end(&iter);
3177 }
3178 
3179 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
3180 {
3181 	int ret = 0;
3182 
3183 	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
3184 	 * on window driver dc implementation.
3185 	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
3186 	 * should be passed to smu during boot up and resume from s3.
3187 	 * boot up: dc calculate dcn watermark clock settings within dc_create,
3188 	 * dcn20_resource_construct
3189 	 * then call pplib functions below to pass the settings to smu:
3190 	 * smu_set_watermarks_for_clock_ranges
3191 	 * smu_set_watermarks_table
3192 	 * navi10_set_watermarks_table
3193 	 * smu_write_watermarks_table
3194 	 *
3195 	 * For Renoir, clock settings of dcn watermark are also fixed values.
3196 	 * dc has implemented different flow for window driver:
3197 	 * dc_hardware_init / dc_set_power_state
3198 	 * dcn10_init_hw
3199 	 * notify_wm_ranges
3200 	 * set_wm_ranges
3201 	 * -- Linux
3202 	 * smu_set_watermarks_for_clock_ranges
3203 	 * renoir_set_watermarks_table
3204 	 * smu_write_watermarks_table
3205 	 *
3206 	 * For Linux,
3207 	 * dc_hardware_init -> amdgpu_dm_init
3208 	 * dc_set_power_state --> dm_resume
3209 	 *
3210 	 * therefore, this function apply to navi10/12/14 but not Renoir
3211 	 * *
3212 	 */
3213 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
3214 	case IP_VERSION(2, 0, 2):
3215 	case IP_VERSION(2, 0, 0):
3216 		break;
3217 	default:
3218 		return 0;
3219 	}
3220 
3221 	ret = amdgpu_dpm_write_watermarks_table(adev);
3222 	if (ret) {
3223 		drm_err(adev_to_drm(adev), "Failed to update WMTABLE!\n");
3224 		return ret;
3225 	}
3226 
3227 	return 0;
3228 }
3229 
3230 static int dm_oem_i2c_hw_init(struct amdgpu_device *adev)
3231 {
3232 	struct amdgpu_display_manager *dm = &adev->dm;
3233 	struct amdgpu_i2c_adapter *oem_i2c;
3234 	struct ddc_service *oem_ddc_service;
3235 	int r;
3236 
3237 	oem_ddc_service = dc_get_oem_i2c_device(adev->dm.dc);
3238 	if (oem_ddc_service) {
3239 		oem_i2c = create_i2c(oem_ddc_service, true);
3240 		if (!oem_i2c) {
3241 			drm_info(adev_to_drm(adev), "Failed to create oem i2c adapter data\n");
3242 			return -ENOMEM;
3243 		}
3244 
3245 		r = devm_i2c_add_adapter(adev->dev, &oem_i2c->base);
3246 		if (r) {
3247 			drm_info(adev_to_drm(adev), "Failed to register oem i2c\n");
3248 			kfree(oem_i2c);
3249 			return r;
3250 		}
3251 		dm->oem_i2c = oem_i2c;
3252 	}
3253 
3254 	return 0;
3255 }
3256 
3257 /**
3258  * dm_hw_init() - Initialize DC device
3259  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3260  *
3261  * Initialize the &struct amdgpu_display_manager device. This involves calling
3262  * the initializers of each DM component, then populating the struct with them.
3263  *
3264  * Although the function implies hardware initialization, both hardware and
3265  * software are initialized here. Splitting them out to their relevant init
3266  * hooks is a future TODO item.
3267  *
3268  * Some notable things that are initialized here:
3269  *
3270  * - Display Core, both software and hardware
3271  * - DC modules that we need (freesync and color management)
3272  * - DRM software states
3273  * - Interrupt sources and handlers
3274  * - Vblank support
3275  * - Debug FS entries, if enabled
3276  */
3277 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
3278 {
3279 	struct amdgpu_device *adev = ip_block->adev;
3280 	int r;
3281 
3282 	/* Create DAL display manager */
3283 	r = amdgpu_dm_init(adev);
3284 	if (r)
3285 		return r;
3286 	amdgpu_dm_hpd_init(adev);
3287 
3288 	r = dm_oem_i2c_hw_init(adev);
3289 	if (r)
3290 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
3291 
3292 	return 0;
3293 }
3294 
3295 /**
3296  * dm_hw_fini() - Teardown DC device
3297  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3298  *
3299  * Teardown components within &struct amdgpu_display_manager that require
3300  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
3301  * were loaded. Also flush IRQ workqueues and disable them.
3302  */
3303 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
3304 {
3305 	struct amdgpu_device *adev = ip_block->adev;
3306 
3307 	amdgpu_dm_hpd_fini(adev);
3308 
3309 	amdgpu_dm_irq_fini(adev);
3310 	amdgpu_dm_fini(adev);
3311 	return 0;
3312 }
3313 
3314 
3315 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
3316 				 struct dc_state *state, bool enable)
3317 {
3318 	enum dc_irq_source irq_source;
3319 	struct amdgpu_crtc *acrtc;
3320 	int rc = -EBUSY;
3321 	int i = 0;
3322 
3323 	for (i = 0; i < state->stream_count; i++) {
3324 		acrtc = get_crtc_by_otg_inst(
3325 				adev, state->stream_status[i].primary_otg_inst);
3326 
3327 		if (acrtc && state->stream_status[i].plane_count != 0 &&
3328 		    amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
3329 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
3330 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3331 			if (rc)
3332 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
3333 					 enable ? "enable" : "disable");
3334 
3335 			if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
3336 				if (enable) {
3337 					if (amdgpu_dm_crtc_vrr_active(
3338 							to_dm_crtc_state(acrtc->base.state)))
3339 						rc = amdgpu_dm_crtc_set_vupdate_irq(
3340 							&acrtc->base, true);
3341 				} else
3342 					rc = amdgpu_dm_crtc_set_vupdate_irq(
3343 							&acrtc->base, false);
3344 
3345 				if (rc)
3346 					drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
3347 						enable ? "en" : "dis");
3348 			}
3349 
3350 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3351 			/* During gpu-reset we disable and then enable vblank irq, so
3352 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
3353 			 */
3354 			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
3355 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
3356 
3357 		} else if (acrtc && state->stream_status[i].plane_count != 0) {
3358 			/* DCN only needs to toggle VUPDATE_NO_LOCK */
3359 			rc = amdgpu_dm_crtc_set_vupdate_irq(&acrtc->base, enable);
3360 			if (rc)
3361 				drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
3362 					 enable ? "en" : "dis");
3363 		}
3364 	}
3365 
3366 }
3367 
3368 DEFINE_FREE(state_release, struct dc_state *, if (_T) dc_state_release(_T))
3369 
3370 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
3371 {
3372 	struct dc_state *context __free(state_release) = NULL;
3373 	int i;
3374 	struct dc_stream_state *del_streams[MAX_PIPES];
3375 	int del_streams_count = 0;
3376 	struct dc_commit_streams_params params = {};
3377 
3378 	memset(del_streams, 0, sizeof(del_streams));
3379 
3380 	context = dc_state_create_current_copy(dc);
3381 	if (context == NULL)
3382 		return DC_ERROR_UNEXPECTED;
3383 
3384 	/* First remove from context all streams */
3385 	for (i = 0; i < context->stream_count; i++) {
3386 		struct dc_stream_state *stream = context->streams[i];
3387 
3388 		del_streams[del_streams_count++] = stream;
3389 	}
3390 
3391 	/* Remove all planes for removed streams and then remove the streams */
3392 	for (i = 0; i < del_streams_count; i++) {
3393 		enum dc_status res;
3394 
3395 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
3396 			return DC_FAIL_DETACH_SURFACES;
3397 
3398 		res = dc_state_remove_stream(dc, context, del_streams[i]);
3399 		if (res != DC_OK)
3400 			return res;
3401 	}
3402 
3403 	params.streams = context->streams;
3404 	params.stream_count = context->stream_count;
3405 
3406 	return dc_commit_streams(dc, &params);
3407 }
3408 
3409 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
3410 {
3411 	int i;
3412 
3413 	if (dm->hpd_rx_offload_wq) {
3414 		for (i = 0; i < dm->dc->caps.max_links; i++)
3415 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
3416 	}
3417 }
3418 
3419 static int dm_cache_state(struct amdgpu_device *adev)
3420 {
3421 	int r;
3422 
3423 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
3424 	if (IS_ERR(adev->dm.cached_state)) {
3425 		r = PTR_ERR(adev->dm.cached_state);
3426 		adev->dm.cached_state = NULL;
3427 	}
3428 
3429 	return adev->dm.cached_state ? 0 : r;
3430 }
3431 
3432 static void dm_destroy_cached_state(struct amdgpu_device *adev)
3433 {
3434 	struct amdgpu_display_manager *dm = &adev->dm;
3435 	struct drm_device *ddev = adev_to_drm(adev);
3436 	struct dm_plane_state *dm_new_plane_state;
3437 	struct drm_plane_state *new_plane_state;
3438 	struct dm_crtc_state *dm_new_crtc_state;
3439 	struct drm_crtc_state *new_crtc_state;
3440 	struct drm_plane *plane;
3441 	struct drm_crtc *crtc;
3442 	int i;
3443 
3444 	if (!dm->cached_state)
3445 		return;
3446 
3447 	/* Force mode set in atomic commit */
3448 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3449 		new_crtc_state->active_changed = true;
3450 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3451 		reset_freesync_config_for_crtc(dm_new_crtc_state);
3452 	}
3453 
3454 	/*
3455 	 * atomic_check is expected to create the dc states. We need to release
3456 	 * them here, since they were duplicated as part of the suspend
3457 	 * procedure.
3458 	 */
3459 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3460 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3461 		if (dm_new_crtc_state->stream) {
3462 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
3463 			dc_stream_release(dm_new_crtc_state->stream);
3464 			dm_new_crtc_state->stream = NULL;
3465 		}
3466 		dm_new_crtc_state->base.color_mgmt_changed = true;
3467 	}
3468 
3469 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
3470 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
3471 		if (dm_new_plane_state->dc_state) {
3472 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
3473 			dc_plane_state_release(dm_new_plane_state->dc_state);
3474 			dm_new_plane_state->dc_state = NULL;
3475 		}
3476 	}
3477 
3478 	drm_atomic_helper_resume(ddev, dm->cached_state);
3479 
3480 	dm->cached_state = NULL;
3481 }
3482 
3483 static int dm_suspend(struct amdgpu_ip_block *ip_block)
3484 {
3485 	struct amdgpu_device *adev = ip_block->adev;
3486 	struct amdgpu_display_manager *dm = &adev->dm;
3487 
3488 	if (amdgpu_in_reset(adev)) {
3489 		enum dc_status res;
3490 
3491 		/* Quiesce ISM workers before taking dc_lock (workers take
3492 		 * dc_lock themselves; syncing under it would deadlock).
3493 		 */
3494 		amdgpu_dm_ism_disable(dm);
3495 
3496 		mutex_lock(&dm->dc_lock);
3497 
3498 		amdgpu_dm_ism_force_full_power(dm);
3499 		dc_allow_idle_optimizations(adev->dm.dc, false);
3500 
3501 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
3502 
3503 		if (dm->cached_dc_state)
3504 			dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
3505 
3506 		res = amdgpu_dm_commit_zero_streams(dm->dc);
3507 		if (res != DC_OK) {
3508 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
3509 			return -EINVAL;
3510 		}
3511 
3512 		amdgpu_dm_irq_suspend(adev);
3513 
3514 		hpd_rx_irq_work_suspend(dm);
3515 
3516 		return 0;
3517 	}
3518 
3519 	if (!adev->dm.cached_state) {
3520 		int r = dm_cache_state(adev);
3521 
3522 		if (r)
3523 			return r;
3524 	}
3525 
3526 	s3_handle_hdmi_cec(adev_to_drm(adev), true);
3527 
3528 	s3_handle_mst(adev_to_drm(adev), true);
3529 
3530 	amdgpu_dm_irq_suspend(adev);
3531 
3532 	/*
3533 	 * Quiesce ISM workers before taking dc_lock (workers take dc_lock
3534 	 * themselves; syncing under it would deadlock).
3535 	 */
3536 	amdgpu_dm_ism_disable(dm);
3537 	scoped_guard(mutex, &dm->dc_lock)
3538 		amdgpu_dm_ism_force_full_power(dm);
3539 
3540 	hpd_rx_irq_work_suspend(dm);
3541 
3542 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
3543 
3544 	if (dm->dc->caps.ips_support && adev->in_s0ix)
3545 		dc_allow_idle_optimizations(dm->dc, true);
3546 
3547 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
3548 
3549 	return 0;
3550 }
3551 
3552 struct drm_connector *
3553 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_commit *state,
3554 					     struct drm_crtc *crtc)
3555 {
3556 	u32 i;
3557 	struct drm_connector_state *new_con_state;
3558 	struct drm_connector *connector;
3559 	struct drm_crtc *crtc_from_state;
3560 
3561 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3562 		crtc_from_state = new_con_state->crtc;
3563 
3564 		if (crtc_from_state == crtc)
3565 			return connector;
3566 	}
3567 
3568 	return NULL;
3569 }
3570 
3571 static void emulated_link_detect(struct dc_link *link)
3572 {
3573 	struct dc_sink_init_data sink_init_data = { 0 };
3574 	struct display_sink_capability sink_caps = { 0 };
3575 	enum dc_edid_status edid_status;
3576 	struct dc_context *dc_ctx = link->ctx;
3577 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
3578 	struct dc_sink *sink = NULL;
3579 	struct dc_sink *prev_sink = NULL;
3580 
3581 	link->type = dc_connection_none;
3582 	prev_sink = link->local_sink;
3583 
3584 	if (prev_sink)
3585 		dc_sink_release(prev_sink);
3586 
3587 	switch (link->connector_signal) {
3588 	case SIGNAL_TYPE_HDMI_TYPE_A: {
3589 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3590 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
3591 		break;
3592 	}
3593 
3594 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
3595 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3596 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
3597 		break;
3598 	}
3599 
3600 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
3601 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3602 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
3603 		break;
3604 	}
3605 
3606 	case SIGNAL_TYPE_LVDS: {
3607 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3608 		sink_caps.signal = SIGNAL_TYPE_LVDS;
3609 		break;
3610 	}
3611 
3612 	case SIGNAL_TYPE_EDP: {
3613 		sink_caps.transaction_type =
3614 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3615 		sink_caps.signal = SIGNAL_TYPE_EDP;
3616 		break;
3617 	}
3618 
3619 	case SIGNAL_TYPE_DISPLAY_PORT: {
3620 		sink_caps.transaction_type =
3621 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3622 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
3623 		break;
3624 	}
3625 
3626 	default:
3627 		drm_err(dev, "Invalid connector type! signal:%d\n",
3628 			link->connector_signal);
3629 		return;
3630 	}
3631 
3632 	sink_init_data.link = link;
3633 	sink_init_data.sink_signal = sink_caps.signal;
3634 
3635 	sink = dc_sink_create(&sink_init_data);
3636 	if (!sink) {
3637 		drm_err(dev, "Failed to create sink!\n");
3638 		return;
3639 	}
3640 
3641 	/* dc_sink_create returns a new reference */
3642 	link->local_sink = sink;
3643 
3644 	edid_status = dm_helpers_read_local_edid(
3645 			link->ctx,
3646 			link,
3647 			sink);
3648 
3649 	if (edid_status != EDID_OK)
3650 		drm_err(dev, "Failed to read EDID\n");
3651 
3652 }
3653 
3654 static void dm_gpureset_commit_state(struct dc_state *dc_state,
3655 				     struct amdgpu_display_manager *dm)
3656 {
3657 	struct {
3658 		struct dc_surface_update surface_updates[MAX_SURFACES];
3659 		struct dc_plane_info plane_infos[MAX_SURFACES];
3660 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3661 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3662 		struct dc_stream_update stream_update;
3663 	} *bundle __free(kfree);
3664 	int k, m;
3665 
3666 	bundle = kzalloc_obj(*bundle);
3667 
3668 	if (!bundle) {
3669 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
3670 		return;
3671 	}
3672 
3673 	for (k = 0; k < dc_state->stream_count; k++) {
3674 		bundle->stream_update.stream = dc_state->streams[k];
3675 
3676 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
3677 			bundle->surface_updates[m].surface =
3678 				dc_state->stream_status[k].plane_states[m];
3679 			bundle->surface_updates[m].surface->force_full_update =
3680 				true;
3681 		}
3682 
3683 		update_planes_and_stream_adapter(dm->dc,
3684 					 UPDATE_TYPE_FULL,
3685 					 dc_state->stream_status[k].plane_count,
3686 					 dc_state->streams[k],
3687 					 &bundle->stream_update,
3688 					 bundle->surface_updates);
3689 	}
3690 }
3691 
3692 static void apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
3693 					    struct dc_sink *sink)
3694 {
3695 	struct dc_panel_patch *ppatch = NULL;
3696 
3697 	if (!sink)
3698 		return;
3699 
3700 	ppatch = &sink->edid_caps.panel_patch;
3701 	if (ppatch->wait_after_dpcd_poweroff_ms) {
3702 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
3703 		drm_dbg_driver(adev_to_drm(adev),
3704 			       "%s: adding a %ds delay as w/a for panel\n",
3705 			       __func__,
3706 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
3707 	}
3708 }
3709 
3710 /**
3711  * amdgpu_dm_dump_links_and_sinks - Debug dump of all DC links and their sinks
3712  * @adev: amdgpu device pointer
3713  *
3714  * Iterates through all DC links and dumps information about local and remote
3715  * (MST) sinks. Should be called after connector detection is complete to see
3716  * the final state of all links.
3717  */
3718 static void amdgpu_dm_dump_links_and_sinks(struct amdgpu_device *adev)
3719 {
3720 	struct dc *dc = adev->dm.dc;
3721 	struct drm_device *dev = adev_to_drm(adev);
3722 	int li;
3723 
3724 	if (!dc)
3725 		return;
3726 
3727 	for (li = 0; li < dc->link_count; li++) {
3728 		struct dc_link *l = dc->links[li];
3729 		const char *name = NULL;
3730 		int rs;
3731 
3732 		if (!l)
3733 			continue;
3734 		if (l->local_sink && l->local_sink->edid_caps.display_name[0])
3735 			name = l->local_sink->edid_caps.display_name;
3736 		else
3737 			name = "n/a";
3738 
3739 		drm_dbg_kms(dev,
3740 			"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",
3741 			li,
3742 			l->local_sink,
3743 			l->type,
3744 			l->local_sink ? l->local_sink->sink_signal : SIGNAL_TYPE_NONE,
3745 			l->sink_count,
3746 			name,
3747 			l->dpcd_caps.is_mst_capable,
3748 			l->mst_stream_alloc_table.stream_count);
3749 
3750 		/* Dump remote (MST) sinks if any */
3751 		for (rs = 0; rs < l->sink_count; rs++) {
3752 			struct dc_sink *rsink = l->remote_sinks[rs];
3753 			const char *rname = NULL;
3754 
3755 			if (!rsink)
3756 				continue;
3757 			if (rsink->edid_caps.display_name[0])
3758 				rname = rsink->edid_caps.display_name;
3759 			else
3760 				rname = "n/a";
3761 			drm_dbg_kms(dev,
3762 				"  REMOTE_SINK[%d:%d]: sink=%p signal=%d edid_name=%s\n",
3763 				li, rs,
3764 				rsink,
3765 				rsink->sink_signal,
3766 				rname);
3767 		}
3768 	}
3769 }
3770 
3771 static int dm_resume(struct amdgpu_ip_block *ip_block)
3772 {
3773 	struct amdgpu_device *adev = ip_block->adev;
3774 	struct drm_device *ddev = adev_to_drm(adev);
3775 	struct amdgpu_display_manager *dm = &adev->dm;
3776 	struct amdgpu_dm_connector *aconnector;
3777 	struct drm_connector *connector;
3778 	struct drm_connector_list_iter iter;
3779 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
3780 	enum dc_connection_type new_connection_type = dc_connection_none;
3781 	struct dc_state *dc_state;
3782 	int i, r, j;
3783 	struct dc_commit_streams_params commit_params = {};
3784 
3785 	if (dm->dc->caps.ips_support) {
3786 		if (!amdgpu_in_reset(adev))
3787 			mutex_lock(&dm->dc_lock);
3788 
3789 		/* Need to set POWER_STATE_D0 first or it will not execute
3790 		 * idle_power_optimizations command to DMUB.
3791 		 */
3792 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3793 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
3794 
3795 		if (!amdgpu_in_reset(adev))
3796 			mutex_unlock(&dm->dc_lock);
3797 	}
3798 
3799 	if (amdgpu_in_reset(adev)) {
3800 		dc_state = dm->cached_dc_state;
3801 
3802 		/*
3803 		 * The dc->current_state is backed up into dm->cached_dc_state
3804 		 * before we commit 0 streams.
3805 		 *
3806 		 * DC will clear link encoder assignments on the real state
3807 		 * but the changes won't propagate over to the copy we made
3808 		 * before the 0 streams commit.
3809 		 *
3810 		 * DC expects that link encoder assignments are *not* valid
3811 		 * when committing a state, so as a workaround we can copy
3812 		 * off of the current state.
3813 		 *
3814 		 * We lose the previous assignments, but we had already
3815 		 * commit 0 streams anyway.
3816 		 */
3817 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
3818 
3819 		r = dm_dmub_hw_init(adev);
3820 		if (r) {
3821 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
3822 			return r;
3823 		}
3824 
3825 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3826 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3827 
3828 		dc_resume(dm->dc);
3829 
3830 		amdgpu_dm_ism_enable(dm);
3831 		amdgpu_dm_irq_resume_early(adev);
3832 
3833 		for (i = 0; i < dc_state->stream_count; i++) {
3834 			dc_state->streams[i]->mode_changed = true;
3835 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
3836 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
3837 					= 0xffffffff;
3838 			}
3839 		}
3840 
3841 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3842 			amdgpu_dm_outbox_init(adev);
3843 			dc_enable_dmub_outbox(adev->dm.dc);
3844 		}
3845 
3846 		commit_params.streams = dc_state->streams;
3847 		commit_params.stream_count = dc_state->stream_count;
3848 		dc_exit_ips_for_hw_access(dm->dc);
3849 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
3850 
3851 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
3852 
3853 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
3854 
3855 		dc_state_release(dm->cached_dc_state);
3856 		dm->cached_dc_state = NULL;
3857 
3858 		amdgpu_dm_irq_resume_late(adev);
3859 
3860 		mutex_unlock(&dm->dc_lock);
3861 
3862 		/* set the backlight after a reset */
3863 		for (i = 0; i < dm->num_of_edps; i++) {
3864 			if (dm->backlight_dev[i])
3865 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
3866 		}
3867 
3868 		return 0;
3869 	}
3870 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
3871 	dc_state_release(dm_state->context);
3872 	dm_state->context = dc_state_create(dm->dc, NULL);
3873 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
3874 
3875 	/* Before powering on DC we need to re-initialize DMUB. */
3876 	dm_dmub_hw_resume(adev);
3877 
3878 	/* Re-enable outbox interrupts for DPIA. */
3879 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3880 		amdgpu_dm_outbox_init(adev);
3881 		dc_enable_dmub_outbox(adev->dm.dc);
3882 	}
3883 
3884 	/* power on hardware */
3885 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3886 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3887 
3888 	/* program HPD filter */
3889 	dc_resume(dm->dc);
3890 
3891 	scoped_guard(mutex, &dm->dc_lock)
3892 		amdgpu_dm_ism_enable(dm);
3893 
3894 	/*
3895 	 * early enable HPD Rx IRQ, should be done before set mode as short
3896 	 * pulse interrupts are used for MST
3897 	 */
3898 	amdgpu_dm_irq_resume_early(adev);
3899 
3900 	s3_handle_hdmi_cec(ddev, false);
3901 
3902 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
3903 	s3_handle_mst(ddev, false);
3904 
3905 	/* Do detection*/
3906 	drm_connector_list_iter_begin(ddev, &iter);
3907 	drm_for_each_connector_iter(connector, &iter) {
3908 		bool ret;
3909 
3910 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3911 			continue;
3912 
3913 		aconnector = to_amdgpu_dm_connector(connector);
3914 
3915 		if (!aconnector->dc_link)
3916 			continue;
3917 
3918 		/*
3919 		 * this is the case when traversing through already created end sink
3920 		 * MST connectors, should be skipped
3921 		 */
3922 		if (aconnector->mst_root)
3923 			continue;
3924 
3925 		/* Skip eDP detection, when there is no sink present */
3926 		if (aconnector->dc_link->connector_signal == SIGNAL_TYPE_EDP &&
3927 		    !aconnector->dc_link->edp_sink_present)
3928 			continue;
3929 
3930 		guard(mutex)(&aconnector->hpd_lock);
3931 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3932 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3933 
3934 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3935 			emulated_link_detect(aconnector->dc_link);
3936 		} else {
3937 			guard(mutex)(&dm->dc_lock);
3938 			dc_exit_ips_for_hw_access(dm->dc);
3939 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
3940 			if (ret) {
3941 				/* w/a delay for certain panels */
3942 				apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3943 			}
3944 		}
3945 
3946 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
3947 			aconnector->fake_enable = false;
3948 
3949 		if (aconnector->dc_sink)
3950 			dc_sink_release(aconnector->dc_sink);
3951 		aconnector->dc_sink = NULL;
3952 		amdgpu_dm_update_connector_after_detect(aconnector);
3953 	}
3954 	drm_connector_list_iter_end(&iter);
3955 
3956 	dm_destroy_cached_state(adev);
3957 
3958 	/* Do mst topology probing after resuming cached state*/
3959 	drm_connector_list_iter_begin(ddev, &iter);
3960 	drm_for_each_connector_iter(connector, &iter) {
3961 		bool init = false;
3962 
3963 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3964 			continue;
3965 
3966 		aconnector = to_amdgpu_dm_connector(connector);
3967 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3968 		    aconnector->mst_root)
3969 			continue;
3970 
3971 		scoped_guard(mutex, &aconnector->mst_mgr.lock) {
3972 			init = !aconnector->mst_mgr.mst_primary;
3973 		}
3974 		if (init)
3975 			dm_helpers_dp_mst_start_top_mgr(aconnector->dc_link->ctx,
3976 				aconnector->dc_link, false);
3977 		else
3978 			drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
3979 	}
3980 	drm_connector_list_iter_end(&iter);
3981 
3982 	/* Debug dump: list all DC links and their associated sinks after detection
3983 	 * is complete for all connectors. This provides a comprehensive view of the
3984 	 * final state without repeating the dump for each connector.
3985 	 */
3986 	amdgpu_dm_dump_links_and_sinks(adev);
3987 
3988 	amdgpu_dm_irq_resume_late(adev);
3989 
3990 	amdgpu_dm_smu_write_watermarks_table(adev);
3991 
3992 	drm_kms_helper_hotplug_event(ddev);
3993 
3994 	return 0;
3995 }
3996 
3997 /**
3998  * DOC: DM Lifecycle
3999  *
4000  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
4001  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
4002  * the base driver's device list to be initialized and torn down accordingly.
4003  *
4004  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
4005  */
4006 
4007 static const struct amd_ip_funcs amdgpu_dm_funcs = {
4008 	.name = "dm",
4009 	.early_init = dm_early_init,
4010 	.late_init = dm_late_init,
4011 	.sw_init = dm_sw_init,
4012 	.sw_fini = dm_sw_fini,
4013 	.early_fini = amdgpu_dm_early_fini,
4014 	.hw_init = dm_hw_init,
4015 	.hw_fini = dm_hw_fini,
4016 	.suspend = dm_suspend,
4017 	.resume = dm_resume,
4018 	.is_idle = dm_is_idle,
4019 	.wait_for_idle = dm_wait_for_idle,
4020 	.check_soft_reset = dm_check_soft_reset,
4021 	.soft_reset = dm_soft_reset,
4022 	.set_clockgating_state = dm_set_clockgating_state,
4023 	.set_powergating_state = dm_set_powergating_state,
4024 };
4025 
4026 const struct amdgpu_ip_block_version dm_ip_block = {
4027 	.type = AMD_IP_BLOCK_TYPE_DCE,
4028 	.major = 1,
4029 	.minor = 0,
4030 	.rev = 0,
4031 	.funcs = &amdgpu_dm_funcs,
4032 };
4033 
4034 
4035 /**
4036  * DOC: atomic
4037  *
4038  * *WIP*
4039  */
4040 
4041 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
4042 	.fb_create = amdgpu_display_user_framebuffer_create,
4043 	.get_format_info = amdgpu_dm_plane_get_format_info,
4044 	.atomic_check = amdgpu_dm_atomic_check,
4045 	.atomic_commit = drm_atomic_helper_commit,
4046 };
4047 
4048 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
4049 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
4050 	.atomic_commit_setup = amdgpu_dm_atomic_setup_commit,
4051 };
4052 
4053 #define DDC_MANUFACTURERNAME_SAMSUNG 0x2D4C
4054 
4055 static void dm_set_panel_type(struct amdgpu_dm_connector *aconnector)
4056 {
4057 	struct drm_connector *connector = &aconnector->base;
4058 	struct drm_display_info *display_info = &connector->display_info;
4059 	struct dc_link *link = aconnector->dc_link;
4060 	struct amdgpu_device *adev;
4061 
4062 	adev = drm_to_adev(connector->dev);
4063 
4064 	link->panel_type = PANEL_TYPE_NONE;
4065 
4066 	switch (display_info->amd_vsdb.panel_type) {
4067 	case AMD_VSDB_PANEL_TYPE_OLED:
4068 		link->panel_type = PANEL_TYPE_OLED;
4069 		break;
4070 	case AMD_VSDB_PANEL_TYPE_MINILED:
4071 		link->panel_type = PANEL_TYPE_MINILED;
4072 		break;
4073 	}
4074 
4075 	/* If VSDB didn't determine panel type, check DPCD ext caps */
4076 	if (link->panel_type == PANEL_TYPE_NONE) {
4077 		if (link->dpcd_sink_ext_caps.bits.miniled == 1)
4078 			link->panel_type = PANEL_TYPE_MINILED;
4079 		if (link->dpcd_sink_ext_caps.bits.oled == 1)
4080 			link->panel_type = PANEL_TYPE_OLED;
4081 	}
4082 
4083 	/*
4084 	 * TODO: get panel type from DID2 that has device technology field
4085 	 * to specify if it's OLED or not. But we need to wait for DID2
4086 	 * support in DC and EDID parser to be able to use it here.
4087 	 */
4088 
4089 	if (link->panel_type == PANEL_TYPE_NONE) {
4090 		struct drm_amd_vsdb_info *vsdb = &display_info->amd_vsdb;
4091 		u32 lum1_max = vsdb->luminance_range1.max_luminance;
4092 		u32 lum2_max = vsdb->luminance_range2.max_luminance;
4093 
4094 		if (vsdb->version && link->local_sink &&
4095 		    link->local_sink->edid_caps.manufacturer_id ==
4096 		    DDC_MANUFACTURERNAME_SAMSUNG &&
4097 		    lum1_max >= ((lum2_max * 3) / 2))
4098 			link->panel_type = PANEL_TYPE_MINILED;
4099 	}
4100 
4101 	if (link->panel_type == PANEL_TYPE_OLED)
4102 		drm_object_property_set_value(&connector->base,
4103 		    adev_to_drm(adev)->mode_config.panel_type_property,
4104 		    DRM_MODE_PANEL_TYPE_OLED);
4105 	else
4106 		drm_object_property_set_value(&connector->base,
4107 		    adev_to_drm(adev)->mode_config.panel_type_property,
4108 		    DRM_MODE_PANEL_TYPE_UNKNOWN);
4109 
4110 	drm_dbg_kms(aconnector->base.dev, "Panel type: %d\n", link->panel_type);
4111 }
4112 
4113 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
4114 {
4115 	const struct drm_panel_backlight_quirk *panel_backlight_quirk;
4116 	struct amdgpu_dm_backlight_caps *caps;
4117 	struct drm_connector *conn_base;
4118 	struct amdgpu_device *adev;
4119 	struct drm_luminance_range_info *luminance_range;
4120 	struct drm_device *drm;
4121 
4122 	if (aconnector->bl_idx == -1 ||
4123 	    aconnector->dc_link->connector_signal != SIGNAL_TYPE_EDP)
4124 		return;
4125 
4126 	conn_base = &aconnector->base;
4127 	drm = conn_base->dev;
4128 	adev = drm_to_adev(drm);
4129 
4130 	caps = &adev->dm.backlight_caps[aconnector->bl_idx];
4131 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
4132 	caps->aux_support = false;
4133 
4134 	panel_backlight_quirk = drm_get_panel_backlight_quirk(aconnector->drm_edid);
4135 
4136 	if (caps->ext_caps->bits.oled == 1
4137 	    /*
4138 	     * ||
4139 	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
4140 	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
4141 	     */)
4142 		caps->aux_support = true;
4143 
4144 	if (amdgpu_backlight == 0)
4145 		caps->aux_support = false;
4146 	else if (amdgpu_backlight == 1)
4147 		caps->aux_support = true;
4148 	else if (!IS_ERR_OR_NULL(panel_backlight_quirk) &&
4149 		 panel_backlight_quirk->force_pwm)
4150 		caps->aux_support = false;
4151 	if (caps->aux_support)
4152 		aconnector->dc_link->backlight_control_type = BACKLIGHT_CONTROL_AMD_AUX;
4153 
4154 	luminance_range = &conn_base->display_info.luminance_range;
4155 
4156 	if (luminance_range->max_luminance)
4157 		caps->aux_max_input_signal = luminance_range->max_luminance;
4158 	else
4159 		caps->aux_max_input_signal = 512;
4160 
4161 	if (luminance_range->min_luminance)
4162 		caps->aux_min_input_signal = luminance_range->min_luminance;
4163 	else
4164 		caps->aux_min_input_signal = 1;
4165 
4166 	if (!IS_ERR_OR_NULL(panel_backlight_quirk)) {
4167 		if (panel_backlight_quirk->min_brightness) {
4168 			caps->min_input_signal =
4169 				panel_backlight_quirk->min_brightness - 1;
4170 			drm_info(drm,
4171 				 "Applying panel backlight quirk, min_brightness: %d\n",
4172 				 caps->min_input_signal);
4173 		}
4174 		if (panel_backlight_quirk->brightness_mask) {
4175 			drm_info(drm,
4176 				 "Applying panel backlight quirk, brightness_mask: 0x%X\n",
4177 				 panel_backlight_quirk->brightness_mask);
4178 			caps->brightness_mask =
4179 				panel_backlight_quirk->brightness_mask;
4180 		}
4181 	}
4182 }
4183 
4184 DEFINE_FREE(sink_release, struct dc_sink *, if (_T) dc_sink_release(_T))
4185 
4186 void amdgpu_dm_update_connector_after_detect(
4187 		struct amdgpu_dm_connector *aconnector)
4188 {
4189 	struct drm_connector *connector = &aconnector->base;
4190 	struct dc_sink *sink __free(sink_release) = NULL;
4191 	struct drm_device *dev = connector->dev;
4192 
4193 	/* MST handled by drm_mst framework */
4194 	if (aconnector->mst_mgr.mst_state == true)
4195 		return;
4196 
4197 	sink = aconnector->dc_link->local_sink;
4198 	if (sink)
4199 		dc_sink_retain(sink);
4200 
4201 	/*
4202 	 * Edid mgmt connector gets first update only in mode_valid hook and then
4203 	 * the connector sink is set to either fake or physical sink depends on link status.
4204 	 * Skip if already done during boot.
4205 	 */
4206 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
4207 			&& aconnector->dc_em_sink) {
4208 
4209 		/*
4210 		 * For S3 resume with headless use eml_sink to fake stream
4211 		 * because on resume connector->sink is set to NULL
4212 		 */
4213 		guard(mutex)(&dev->mode_config.mutex);
4214 
4215 		if (sink) {
4216 			if (aconnector->dc_sink) {
4217 				amdgpu_dm_update_freesync_caps(connector, NULL, true);
4218 				/*
4219 				 * retain and release below are used to
4220 				 * bump up refcount for sink because the link doesn't point
4221 				 * to it anymore after disconnect, so on next crtc to connector
4222 				 * reshuffle by UMD we will get into unwanted dc_sink release
4223 				 */
4224 				dc_sink_release(aconnector->dc_sink);
4225 			}
4226 			aconnector->dc_sink = sink;
4227 			dc_sink_retain(aconnector->dc_sink);
4228 			amdgpu_dm_update_freesync_caps(connector,
4229 					aconnector->drm_edid, true);
4230 		} else {
4231 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4232 			if (!aconnector->dc_sink) {
4233 				aconnector->dc_sink = aconnector->dc_em_sink;
4234 				dc_sink_retain(aconnector->dc_sink);
4235 			}
4236 		}
4237 
4238 		return;
4239 	}
4240 
4241 	/*
4242 	 * TODO: temporary guard to look for proper fix
4243 	 * if this sink is MST sink, we should not do anything
4244 	 */
4245 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
4246 		return;
4247 
4248 	if (aconnector->dc_sink == sink) {
4249 		/*
4250 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
4251 		 * Do nothing!!
4252 		 */
4253 		drm_dbg_kms(dev, "DCHPD: connector_id=%d: dc_sink didn't change.\n",
4254 				 aconnector->connector_id);
4255 		return;
4256 	}
4257 
4258 	drm_dbg_kms(dev, "DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
4259 		    aconnector->connector_id, aconnector->dc_sink, sink);
4260 
4261 	/* When polling, DRM has already locked the mutex for us. */
4262 	if (!drm_kms_helper_is_poll_worker())
4263 		mutex_lock(&dev->mode_config.mutex);
4264 
4265 	/*
4266 	 * 1. Update status of the drm connector
4267 	 * 2. Send an event and let userspace tell us what to do
4268 	 */
4269 	if (sink) {
4270 		/*
4271 		 * TODO: check if we still need the S3 mode update workaround.
4272 		 * If yes, put it here.
4273 		 */
4274 		if (aconnector->dc_sink) {
4275 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4276 			dc_sink_release(aconnector->dc_sink);
4277 		}
4278 
4279 		aconnector->dc_sink = sink;
4280 		dc_sink_retain(aconnector->dc_sink);
4281 		drm_edid_free(aconnector->drm_edid);
4282 		aconnector->drm_edid = NULL;
4283 		if (sink->dc_edid.length == 0) {
4284 			hdmi_cec_unset_edid(aconnector);
4285 			if (aconnector->dc_link->aux_mode) {
4286 				drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4287 			}
4288 		} else {
4289 			const struct edid *edid = (const struct edid *)sink->dc_edid.raw_edid;
4290 
4291 			aconnector->drm_edid = drm_edid_alloc(edid, sink->dc_edid.length);
4292 			drm_edid_connector_update(connector, aconnector->drm_edid);
4293 
4294 			hdmi_cec_set_edid(aconnector);
4295 			if (aconnector->dc_link->aux_mode)
4296 				drm_dp_cec_attach(&aconnector->dm_dp_aux.aux,
4297 						  connector->display_info.source_physical_address);
4298 		}
4299 
4300 		if (!aconnector->timing_requested) {
4301 			aconnector->timing_requested =
4302 				kzalloc_obj(struct dc_crtc_timing);
4303 			if (!aconnector->timing_requested)
4304 				drm_err(dev,
4305 					"failed to create aconnector->requested_timing\n");
4306 		}
4307 
4308 		amdgpu_dm_update_freesync_caps(connector, aconnector->drm_edid, true);
4309 		update_connector_ext_caps(aconnector);
4310 		dm_set_panel_type(aconnector);
4311 	} else {
4312 		hdmi_cec_unset_edid(aconnector);
4313 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4314 		amdgpu_dm_update_freesync_caps(connector, NULL, true);
4315 		aconnector->num_modes = 0;
4316 		dc_sink_release(aconnector->dc_sink);
4317 		aconnector->dc_sink = NULL;
4318 		drm_edid_free(aconnector->drm_edid);
4319 		aconnector->drm_edid = NULL;
4320 		kfree(aconnector->timing_requested);
4321 		aconnector->timing_requested = NULL;
4322 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
4323 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
4324 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
4325 	}
4326 
4327 	update_subconnector_property(aconnector);
4328 
4329 	/* When polling, the mutex will be unlocked for us by DRM. */
4330 	if (!drm_kms_helper_is_poll_worker())
4331 		mutex_unlock(&dev->mode_config.mutex);
4332 }
4333 
4334 static bool are_sinks_equal(const struct dc_sink *sink1, const struct dc_sink *sink2)
4335 {
4336 	if (!sink1 || !sink2)
4337 		return false;
4338 	if (sink1->sink_signal != sink2->sink_signal)
4339 		return false;
4340 
4341 	if (sink1->dc_edid.length != sink2->dc_edid.length)
4342 		return false;
4343 
4344 	if (memcmp(sink1->dc_edid.raw_edid, sink2->dc_edid.raw_edid,
4345 		   sink1->dc_edid.length) != 0)
4346 		return false;
4347 	return true;
4348 }
4349 
4350 
4351 /**
4352  * DOC: hdmi_hpd_debounce_work
4353  *
4354  * HDMI HPD debounce delay in milliseconds. When an HDMI display toggles HPD
4355  * (such as during power save transitions), this delay determines how long to
4356  * wait before processing the HPD event. This allows distinguishing between a
4357  * physical unplug (>hdmi_hpd_debounce_delay)
4358  * and a spontaneous RX HPD toggle (<hdmi_hpd_debounce_delay).
4359  *
4360  * If the toggle is less than this delay, the driver compares sink capabilities
4361  * and permits a hotplug event if they changed.
4362  *
4363  * The default value of 1500ms was chosen based on experimental testing with
4364  * various monitors that exhibit spontaneous HPD toggling behavior.
4365  */
4366 static void hdmi_hpd_debounce_work(struct work_struct *work)
4367 {
4368 	struct amdgpu_dm_connector *aconnector =
4369 		container_of(to_delayed_work(work), struct amdgpu_dm_connector,
4370 			     hdmi_hpd_debounce_work);
4371 	struct drm_connector *connector = &aconnector->base;
4372 	struct drm_device *dev = connector->dev;
4373 	struct amdgpu_device *adev = drm_to_adev(dev);
4374 	struct dc *dc = aconnector->dc_link->ctx->dc;
4375 	bool fake_reconnect = false;
4376 	bool reallow_idle = false;
4377 	bool ret = false;
4378 	guard(mutex)(&aconnector->hpd_lock);
4379 
4380 	/* Re-detect the display */
4381 	scoped_guard(mutex, &adev->dm.dc_lock) {
4382 		if (dc->caps.ips_support && dc->ctx->dmub_srv->idle_allowed) {
4383 			dc_allow_idle_optimizations(dc, false);
4384 			reallow_idle = true;
4385 		}
4386 		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4387 	}
4388 
4389 	if (ret) {
4390 		/* Apply workaround delay for certain panels */
4391 		apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4392 		/* Compare sinks to determine if this was a spontaneous HPD toggle */
4393 		if (are_sinks_equal(aconnector->dc_link->local_sink, aconnector->hdmi_prev_sink)) {
4394 			/*
4395 			* Sinks match - this was a spontaneous HDMI HPD toggle.
4396 			*/
4397 			drm_dbg_kms(dev, "HDMI HPD: Sink unchanged after debounce, internal re-enable\n");
4398 			fake_reconnect = true;
4399 		}
4400 
4401 		/* Update connector state */
4402 		amdgpu_dm_update_connector_after_detect(aconnector);
4403 
4404 		drm_modeset_lock_all(dev);
4405 		dm_restore_drm_connector_state(dev, connector);
4406 		drm_modeset_unlock_all(dev);
4407 
4408 		/* Only notify OS if sink actually changed */
4409 		if (!fake_reconnect && aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4410 			drm_kms_helper_hotplug_event(dev);
4411 	}
4412 
4413 	/* Release the cached sink reference */
4414 	if (aconnector->hdmi_prev_sink) {
4415 		dc_sink_release(aconnector->hdmi_prev_sink);
4416 		aconnector->hdmi_prev_sink = NULL;
4417 	}
4418 
4419 	scoped_guard(mutex, &adev->dm.dc_lock) {
4420 		if (reallow_idle && dc->caps.ips_support)
4421 			dc_allow_idle_optimizations(dc, true);
4422 	}
4423 }
4424 
4425 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
4426 {
4427 	struct drm_connector *connector = &aconnector->base;
4428 	struct drm_device *dev = connector->dev;
4429 	enum dc_connection_type new_connection_type = dc_connection_none;
4430 	struct amdgpu_device *adev = drm_to_adev(dev);
4431 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
4432 	struct dc *dc = aconnector->dc_link->ctx->dc;
4433 	bool ret = false;
4434 	bool debounce_required = false;
4435 
4436 	if (adev->dm.disable_hpd_irq)
4437 		return;
4438 
4439 	/*
4440 	 * In case of failure or MST no need to update connector status or notify the OS
4441 	 * since (for MST case) MST does this in its own context.
4442 	 */
4443 	guard(mutex)(&aconnector->hpd_lock);
4444 
4445 	if (adev->dm.hdcp_workqueue) {
4446 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
4447 		dm_con_state->update_hdcp = true;
4448 	}
4449 	if (aconnector->fake_enable)
4450 		aconnector->fake_enable = false;
4451 
4452 	aconnector->timing_changed = false;
4453 
4454 	if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
4455 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4456 
4457 	/*
4458 	 * Check for HDMI disconnect with debounce enabled.
4459 	 */
4460 	debounce_required = (aconnector->hdmi_hpd_debounce_delay_ms > 0 &&
4461 			      dc_is_hdmi_signal(aconnector->dc_link->connector_signal) &&
4462 			      new_connection_type == dc_connection_none &&
4463 			      aconnector->dc_link->local_sink != NULL);
4464 
4465 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
4466 		emulated_link_detect(aconnector->dc_link);
4467 
4468 		drm_modeset_lock_all(dev);
4469 		dm_restore_drm_connector_state(dev, connector);
4470 		drm_modeset_unlock_all(dev);
4471 
4472 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4473 			drm_kms_helper_connector_hotplug_event(connector);
4474 	} else if (debounce_required) {
4475 		/*
4476 		 * HDMI disconnect detected - schedule delayed work instead of
4477 		 * processing immediately. This allows us to coalesce spurious
4478 		 * HDMI signals from physical unplugs.
4479 		 */
4480 		drm_dbg_kms(dev, "HDMI HPD: Disconnect detected, scheduling debounce work (%u ms)\n",
4481 			    aconnector->hdmi_hpd_debounce_delay_ms);
4482 
4483 		/* Cache the current sink for later comparison */
4484 		if (aconnector->hdmi_prev_sink)
4485 			dc_sink_release(aconnector->hdmi_prev_sink);
4486 		aconnector->hdmi_prev_sink = aconnector->dc_link->local_sink;
4487 		if (aconnector->hdmi_prev_sink)
4488 			dc_sink_retain(aconnector->hdmi_prev_sink);
4489 
4490 		/* Schedule delayed detection. */
4491 		if (mod_delayed_work(system_percpu_wq,
4492 				 &aconnector->hdmi_hpd_debounce_work,
4493 				 msecs_to_jiffies(aconnector->hdmi_hpd_debounce_delay_ms)))
4494 			drm_dbg_kms(dev, "HDMI HPD: Re-scheduled debounce work\n");
4495 
4496 	} else {
4497 
4498 		/* If the aconnector->hdmi_hpd_debounce_work is scheduled, exit early */
4499 		if (delayed_work_pending(&aconnector->hdmi_hpd_debounce_work))
4500 			return;
4501 
4502 		scoped_guard(mutex, &adev->dm.dc_lock) {
4503 			dc_exit_ips_for_hw_access(dc);
4504 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4505 		}
4506 		if (ret) {
4507 			/* w/a delay for certain panels */
4508 			apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4509 			amdgpu_dm_update_connector_after_detect(aconnector);
4510 
4511 			drm_modeset_lock_all(dev);
4512 			dm_restore_drm_connector_state(dev, connector);
4513 			drm_modeset_unlock_all(dev);
4514 
4515 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4516 				drm_kms_helper_connector_hotplug_event(connector);
4517 		}
4518 	}
4519 }
4520 
4521 static void handle_hpd_irq(void *param)
4522 {
4523 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4524 
4525 	handle_hpd_irq_helper(aconnector);
4526 
4527 }
4528 
4529 static void schedule_hpd_rx_offload_work(struct amdgpu_device *adev, struct hpd_rx_irq_offload_work_queue *offload_wq,
4530 							union hpd_irq_data hpd_irq_data)
4531 {
4532 	struct hpd_rx_irq_offload_work *offload_work = kzalloc_obj(*offload_work);
4533 
4534 	if (!offload_work) {
4535 		drm_err(adev_to_drm(adev), "Failed to allocate hpd_rx_irq_offload_work.\n");
4536 		return;
4537 	}
4538 
4539 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
4540 	offload_work->data = hpd_irq_data;
4541 	offload_work->offload_wq = offload_wq;
4542 	offload_work->adev = adev;
4543 
4544 	queue_work(offload_wq->wq, &offload_work->work);
4545 	drm_dbg_kms(adev_to_drm(adev), "queue work to handle hpd_rx offload work");
4546 }
4547 
4548 static void handle_hpd_rx_irq(void *param)
4549 {
4550 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4551 	struct drm_connector *connector = &aconnector->base;
4552 	struct drm_device *dev = connector->dev;
4553 	struct dc_link *dc_link = aconnector->dc_link;
4554 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
4555 	bool result = false;
4556 	enum dc_connection_type new_connection_type = dc_connection_none;
4557 	struct amdgpu_device *adev = drm_to_adev(dev);
4558 	union hpd_irq_data hpd_irq_data;
4559 	bool link_loss = false;
4560 	bool has_left_work = false;
4561 	int idx = dc_link->link_index;
4562 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
4563 	struct dc *dc = aconnector->dc_link->ctx->dc;
4564 
4565 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
4566 
4567 	if (adev->dm.disable_hpd_irq)
4568 		return;
4569 
4570 	/*
4571 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
4572 	 * conflict, after implement i2c helper, this mutex should be
4573 	 * retired.
4574 	 */
4575 	mutex_lock(&aconnector->hpd_lock);
4576 
4577 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
4578 						&link_loss, true, &has_left_work);
4579 
4580 	if (!has_left_work)
4581 		goto out;
4582 
4583 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
4584 		schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4585 		goto out;
4586 	}
4587 
4588 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
4589 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
4590 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
4591 			bool skip = false;
4592 
4593 			/*
4594 			 * DOWN_REP_MSG_RDY is also handled by polling method
4595 			 * mgr->cbs->poll_hpd_irq()
4596 			 */
4597 			spin_lock(&offload_wq->offload_lock);
4598 			skip = offload_wq->is_handling_mst_msg_rdy_event;
4599 
4600 			if (!skip)
4601 				offload_wq->is_handling_mst_msg_rdy_event = true;
4602 
4603 			spin_unlock(&offload_wq->offload_lock);
4604 
4605 			if (!skip)
4606 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4607 
4608 			goto out;
4609 		}
4610 
4611 		if (link_loss) {
4612 			bool skip = false;
4613 
4614 			spin_lock(&offload_wq->offload_lock);
4615 			skip = offload_wq->is_handling_link_loss;
4616 
4617 			if (!skip)
4618 				offload_wq->is_handling_link_loss = true;
4619 
4620 			spin_unlock(&offload_wq->offload_lock);
4621 
4622 			if (!skip)
4623 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4624 
4625 			goto out;
4626 		}
4627 	}
4628 
4629 out:
4630 	if (result && !is_mst_root_connector) {
4631 		/* Downstream Port status changed. */
4632 		if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
4633 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4634 
4635 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4636 			emulated_link_detect(dc_link);
4637 
4638 			if (aconnector->fake_enable)
4639 				aconnector->fake_enable = false;
4640 
4641 			amdgpu_dm_update_connector_after_detect(aconnector);
4642 
4643 
4644 			drm_modeset_lock_all(dev);
4645 			dm_restore_drm_connector_state(dev, connector);
4646 			drm_modeset_unlock_all(dev);
4647 
4648 			drm_kms_helper_connector_hotplug_event(connector);
4649 		} else {
4650 			bool ret = false;
4651 
4652 			mutex_lock(&adev->dm.dc_lock);
4653 			dc_exit_ips_for_hw_access(dc);
4654 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
4655 			mutex_unlock(&adev->dm.dc_lock);
4656 
4657 			if (ret) {
4658 				if (aconnector->fake_enable)
4659 					aconnector->fake_enable = false;
4660 
4661 				amdgpu_dm_update_connector_after_detect(aconnector);
4662 
4663 				drm_modeset_lock_all(dev);
4664 				dm_restore_drm_connector_state(dev, connector);
4665 				drm_modeset_unlock_all(dev);
4666 
4667 				drm_kms_helper_connector_hotplug_event(connector);
4668 			}
4669 		}
4670 	}
4671 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
4672 		if (adev->dm.hdcp_workqueue)
4673 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
4674 	}
4675 
4676 	if (dc_link->type != dc_connection_mst_branch)
4677 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
4678 
4679 	mutex_unlock(&aconnector->hpd_lock);
4680 }
4681 
4682 static int register_hpd_handlers(struct amdgpu_device *adev)
4683 {
4684 	struct drm_device *dev = adev_to_drm(adev);
4685 	struct drm_connector *connector;
4686 	struct amdgpu_dm_connector *aconnector;
4687 	const struct dc_link *dc_link;
4688 	struct dc_interrupt_params int_params = {0};
4689 
4690 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4691 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4692 
4693 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
4694 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD,
4695 			dmub_hpd_callback, true)) {
4696 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4697 			return -EINVAL;
4698 		}
4699 
4700 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ,
4701 			dmub_hpd_callback, true)) {
4702 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4703 			return -EINVAL;
4704 		}
4705 
4706 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_SENSE_NOTIFY,
4707 			dmub_hpd_sense_callback, true)) {
4708 			drm_err(adev_to_drm(adev), "fail to register dmub hpd sense callback");
4709 			return -EINVAL;
4710 		}
4711 	}
4712 
4713 	list_for_each_entry(connector,
4714 			&dev->mode_config.connector_list, head)	{
4715 
4716 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
4717 			continue;
4718 
4719 		aconnector = to_amdgpu_dm_connector(connector);
4720 		dc_link = aconnector->dc_link;
4721 
4722 		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
4723 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4724 			int_params.irq_source = dc_link->irq_source_hpd;
4725 
4726 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4727 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1 ||
4728 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6) {
4729 				drm_err(adev_to_drm(adev), "Failed to register hpd irq!\n");
4730 				return -EINVAL;
4731 			}
4732 
4733 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4734 				handle_hpd_irq, (void *) aconnector))
4735 				return -ENOMEM;
4736 		}
4737 
4738 		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
4739 
4740 			/* Also register for DP short pulse (hpd_rx). */
4741 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4742 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
4743 
4744 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4745 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1RX ||
4746 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6RX) {
4747 				drm_err(adev_to_drm(adev), "Failed to register hpd rx irq!\n");
4748 				return -EINVAL;
4749 			}
4750 
4751 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4752 				handle_hpd_rx_irq, (void *) aconnector))
4753 				return -ENOMEM;
4754 		}
4755 	}
4756 	return 0;
4757 }
4758 
4759 /* Register IRQ sources and initialize IRQ callbacks */
4760 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
4761 {
4762 	struct dc *dc = adev->dm.dc;
4763 	struct common_irq_params *c_irq_params;
4764 	struct dc_interrupt_params int_params = {0};
4765 	int r;
4766 	int i;
4767 	unsigned int src_id;
4768 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4769 	/* Use different interrupts for VBLANK on DCE 6 vs. newer. */
4770 	const unsigned int vblank_d1 =
4771 		adev->dm.dc->ctx->dce_version >= DCE_VERSION_8_0
4772 		? VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0 : 1;
4773 
4774 	if (adev->family >= AMDGPU_FAMILY_AI)
4775 		client_id = SOC15_IH_CLIENTID_DCE;
4776 
4777 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4778 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4779 
4780 	/*
4781 	 * Actions of amdgpu_irq_add_id():
4782 	 * 1. Register a set() function with base driver.
4783 	 *    Base driver will call set() function to enable/disable an
4784 	 *    interrupt in DC hardware.
4785 	 * 2. Register amdgpu_dm_irq_handler().
4786 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4787 	 *    coming from DC hardware.
4788 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4789 	 *    for acknowledging and handling.
4790 	 */
4791 
4792 	/* Use VBLANK interrupt */
4793 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
4794 		src_id = vblank_d1 + i;
4795 		r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->crtc_irq);
4796 		if (r) {
4797 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4798 			return r;
4799 		}
4800 
4801 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4802 		int_params.irq_source =
4803 			dc_interrupt_to_irq_source(dc, src_id, 0);
4804 
4805 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4806 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4807 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4808 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4809 			return -EINVAL;
4810 		}
4811 
4812 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4813 
4814 		c_irq_params->adev = adev;
4815 		c_irq_params->irq_src = int_params.irq_source;
4816 
4817 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4818 			dm_crtc_high_irq, c_irq_params))
4819 			return -ENOMEM;
4820 	}
4821 
4822 	if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
4823 		/* Use VUPDATE interrupt */
4824 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
4825 			src_id = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT + i * 2;
4826 			r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->vupdate_irq);
4827 			if (r) {
4828 				drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4829 				return r;
4830 			}
4831 
4832 			int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4833 			int_params.irq_source =
4834 				dc_interrupt_to_irq_source(dc, src_id, 0);
4835 
4836 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4837 				int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4838 				int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4839 				drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4840 				return -EINVAL;
4841 			}
4842 
4843 			c_irq_params = &adev->dm.vupdate_params[
4844 				int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4845 			c_irq_params->adev = adev;
4846 			c_irq_params->irq_src = int_params.irq_source;
4847 
4848 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4849 				dm_vupdate_high_irq, c_irq_params))
4850 				return -ENOMEM;
4851 		}
4852 	}
4853 
4854 	/* Use GRPH_PFLIP interrupt */
4855 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4856 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4857 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4858 		if (r) {
4859 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4860 			return r;
4861 		}
4862 
4863 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4864 		int_params.irq_source =
4865 			dc_interrupt_to_irq_source(dc, i, 0);
4866 
4867 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4868 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4869 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4870 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4871 			return -EINVAL;
4872 		}
4873 
4874 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4875 
4876 		c_irq_params->adev = adev;
4877 		c_irq_params->irq_src = int_params.irq_source;
4878 
4879 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4880 			dm_pflip_high_irq, c_irq_params))
4881 			return -ENOMEM;
4882 	}
4883 
4884 	/* HPD */
4885 	r = amdgpu_irq_add_id(adev, client_id,
4886 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4887 	if (r) {
4888 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4889 		return r;
4890 	}
4891 
4892 	r = register_hpd_handlers(adev);
4893 
4894 	return r;
4895 }
4896 
4897 /* Register IRQ sources and initialize IRQ callbacks */
4898 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
4899 {
4900 	struct dc *dc = adev->dm.dc;
4901 	struct common_irq_params *c_irq_params;
4902 	struct dc_interrupt_params int_params = {0};
4903 	int r;
4904 	int i;
4905 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4906 	static const unsigned int vrtl_int_srcid[] = {
4907 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
4908 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
4909 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
4910 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
4911 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
4912 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
4913 	};
4914 #endif
4915 
4916 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4917 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4918 
4919 	/*
4920 	 * Actions of amdgpu_irq_add_id():
4921 	 * 1. Register a set() function with base driver.
4922 	 *    Base driver will call set() function to enable/disable an
4923 	 *    interrupt in DC hardware.
4924 	 * 2. Register amdgpu_dm_irq_handler().
4925 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4926 	 *    coming from DC hardware.
4927 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4928 	 *    for acknowledging and handling.
4929 	 */
4930 
4931 	/* Use otg vertical line interrupt */
4932 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4933 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
4934 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
4935 				vrtl_int_srcid[i], &adev->vline0_irq);
4936 
4937 		if (r) {
4938 			drm_err(adev_to_drm(adev), "Failed to add vline0 irq id!\n");
4939 			return r;
4940 		}
4941 
4942 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4943 		int_params.irq_source =
4944 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
4945 
4946 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4947 			int_params.irq_source < DC_IRQ_SOURCE_DC1_VLINE0 ||
4948 			int_params.irq_source > DC_IRQ_SOURCE_DC6_VLINE0) {
4949 			drm_err(adev_to_drm(adev), "Failed to register vline0 irq!\n");
4950 			return -EINVAL;
4951 		}
4952 
4953 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
4954 					- DC_IRQ_SOURCE_DC1_VLINE0];
4955 
4956 		c_irq_params->adev = adev;
4957 		c_irq_params->irq_src = int_params.irq_source;
4958 
4959 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4960 			dm_dcn_vertical_interrupt0_high_irq,
4961 			c_irq_params))
4962 			return -ENOMEM;
4963 	}
4964 #endif
4965 
4966 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
4967 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
4968 	 * to trigger at end of each vblank, regardless of state of the lock,
4969 	 * matching DCE behaviour.
4970 	 */
4971 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
4972 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
4973 	     i++) {
4974 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
4975 
4976 		if (r) {
4977 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4978 			return r;
4979 		}
4980 
4981 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4982 		int_params.irq_source =
4983 			dc_interrupt_to_irq_source(dc, i, 0);
4984 
4985 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4986 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4987 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4988 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4989 			return -EINVAL;
4990 		}
4991 
4992 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4993 
4994 		c_irq_params->adev = adev;
4995 		c_irq_params->irq_src = int_params.irq_source;
4996 
4997 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4998 			dm_vupdate_high_irq, c_irq_params))
4999 			return -ENOMEM;
5000 	}
5001 
5002 	/* HPD */
5003 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
5004 			&adev->hpd_irq);
5005 	if (r) {
5006 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
5007 		return r;
5008 	}
5009 
5010 	r = register_hpd_handlers(adev);
5011 
5012 	return r;
5013 }
5014 /* Register Outbox IRQ sources and initialize IRQ callbacks */
5015 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
5016 {
5017 	struct dc *dc = adev->dm.dc;
5018 	struct common_irq_params *c_irq_params;
5019 	struct dc_interrupt_params int_params = {0};
5020 	int r, i;
5021 
5022 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
5023 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
5024 
5025 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
5026 			&adev->dmub_outbox_irq);
5027 	if (r) {
5028 		drm_err(adev_to_drm(adev), "Failed to add outbox irq id!\n");
5029 		return r;
5030 	}
5031 
5032 	if (dc->ctx->dmub_srv) {
5033 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
5034 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
5035 		int_params.irq_source =
5036 		dc_interrupt_to_irq_source(dc, i, 0);
5037 
5038 		c_irq_params = &adev->dm.dmub_outbox_params[0];
5039 
5040 		c_irq_params->adev = adev;
5041 		c_irq_params->irq_src = int_params.irq_source;
5042 
5043 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
5044 			dm_dmub_outbox1_low_irq, c_irq_params))
5045 			return -ENOMEM;
5046 	}
5047 
5048 	return 0;
5049 }
5050 
5051 /*
5052  * Acquires the lock for the atomic state object and returns
5053  * the new atomic state.
5054  *
5055  * This should only be called during atomic check.
5056  */
5057 int dm_atomic_get_state(struct drm_atomic_commit *state,
5058 			struct dm_atomic_state **dm_state)
5059 {
5060 	struct drm_device *dev = state->dev;
5061 	struct amdgpu_device *adev = drm_to_adev(dev);
5062 	struct amdgpu_display_manager *dm = &adev->dm;
5063 	struct drm_private_state *priv_state;
5064 
5065 	if (*dm_state)
5066 		return 0;
5067 
5068 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
5069 	if (IS_ERR(priv_state))
5070 		return PTR_ERR(priv_state);
5071 
5072 	*dm_state = to_dm_atomic_state(priv_state);
5073 
5074 	return 0;
5075 }
5076 
5077 static struct dm_atomic_state *
5078 dm_atomic_get_new_state(struct drm_atomic_commit *state)
5079 {
5080 	struct drm_device *dev = state->dev;
5081 	struct amdgpu_device *adev = drm_to_adev(dev);
5082 	struct amdgpu_display_manager *dm = &adev->dm;
5083 	struct drm_private_obj *obj;
5084 	struct drm_private_state *new_obj_state;
5085 	int i;
5086 
5087 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
5088 		if (obj->funcs == dm->atomic_obj.funcs)
5089 			return to_dm_atomic_state(new_obj_state);
5090 	}
5091 
5092 	return NULL;
5093 }
5094 
5095 static struct drm_private_state *
5096 dm_atomic_duplicate_state(struct drm_private_obj *obj)
5097 {
5098 	struct dm_atomic_state *old_state, *new_state;
5099 
5100 	new_state = kzalloc_obj(*new_state);
5101 	if (!new_state)
5102 		return NULL;
5103 
5104 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
5105 
5106 	old_state = to_dm_atomic_state(obj->state);
5107 
5108 	if (old_state && old_state->context)
5109 		new_state->context = dc_state_create_copy(old_state->context);
5110 
5111 	if (!new_state->context) {
5112 		kfree(new_state);
5113 		return NULL;
5114 	}
5115 
5116 	return &new_state->base;
5117 }
5118 
5119 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
5120 				    struct drm_private_state *state)
5121 {
5122 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
5123 
5124 	if (dm_state && dm_state->context)
5125 		dc_state_release(dm_state->context);
5126 
5127 	kfree(dm_state);
5128 }
5129 
5130 static struct drm_private_state *
5131 dm_atomic_create_state(struct drm_private_obj *obj)
5132 {
5133 	struct amdgpu_device *adev = drm_to_adev(obj->dev);
5134 	struct dm_atomic_state *dm_state;
5135 	struct dc_state *context;
5136 
5137 	dm_state = kzalloc_obj(*dm_state);
5138 	if (!dm_state)
5139 		return ERR_PTR(-ENOMEM);
5140 
5141 	context = dc_state_create_current_copy(adev->dm.dc);
5142 	if (!context) {
5143 		kfree(dm_state);
5144 		return ERR_PTR(-ENOMEM);
5145 	}
5146 
5147 	__drm_atomic_helper_private_obj_create_state(obj, &dm_state->base);
5148 	dm_state->context = context;
5149 
5150 	return &dm_state->base;
5151 }
5152 
5153 static struct drm_private_state_funcs dm_atomic_state_funcs = {
5154 	.atomic_create_state = dm_atomic_create_state,
5155 	.atomic_duplicate_state = dm_atomic_duplicate_state,
5156 	.atomic_destroy_state = dm_atomic_destroy_state,
5157 };
5158 
5159 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
5160 {
5161 	int r;
5162 
5163 	adev->mode_info.mode_config_initialized = true;
5164 
5165 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
5166 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
5167 
5168 	adev_to_drm(adev)->mode_config.max_width = 16384;
5169 	adev_to_drm(adev)->mode_config.max_height = 16384;
5170 
5171 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
5172 	if (adev->asic_type == CHIP_HAWAII)
5173 		/* disable prefer shadow for now due to hibernation issues */
5174 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
5175 	else
5176 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
5177 	/* indicates support for immediate flip */
5178 	adev_to_drm(adev)->mode_config.async_page_flip = true;
5179 
5180 	drm_atomic_private_obj_init(adev_to_drm(adev),
5181 				    &adev->dm.atomic_obj,
5182 				    &dm_atomic_state_funcs);
5183 
5184 	r = amdgpu_display_modeset_create_props(adev);
5185 	if (r)
5186 		return r;
5187 
5188 #ifdef AMD_PRIVATE_COLOR
5189 	if (amdgpu_dm_create_color_properties(adev))
5190 		return -ENOMEM;
5191 #endif
5192 
5193 	r = amdgpu_dm_audio_init(adev);
5194 	if (r)
5195 		return r;
5196 
5197 	return 0;
5198 }
5199 
5200 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
5201 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
5202 #define AMDGPU_DM_MIN_SPREAD ((AMDGPU_DM_DEFAULT_MAX_BACKLIGHT - AMDGPU_DM_DEFAULT_MIN_BACKLIGHT) / 2)
5203 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
5204 
5205 void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
5206 				     int bl_idx)
5207 {
5208 	struct amdgpu_dm_backlight_caps *caps = &dm->backlight_caps[bl_idx];
5209 
5210 	if (caps->caps_valid)
5211 		return;
5212 
5213 #if defined(CONFIG_ACPI)
5214 	amdgpu_acpi_get_backlight_caps(caps);
5215 
5216 	/* validate the firmware value is sane */
5217 	if (caps->caps_valid) {
5218 		int spread = caps->max_input_signal - caps->min_input_signal;
5219 
5220 		if (caps->max_input_signal > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5221 		    caps->min_input_signal < 0 ||
5222 		    spread > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5223 		    spread < AMDGPU_DM_MIN_SPREAD) {
5224 			drm_dbg_kms(adev_to_drm(dm->adev), "DM: Invalid backlight caps: min=%d, max=%d\n",
5225 				      caps->min_input_signal, caps->max_input_signal);
5226 			caps->caps_valid = false;
5227 		}
5228 	}
5229 
5230 	if (!caps->caps_valid) {
5231 		caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5232 		caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5233 		caps->caps_valid = true;
5234 	}
5235 #else
5236 	if (caps->aux_support)
5237 		return;
5238 
5239 	caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5240 	caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5241 	caps->caps_valid = true;
5242 #endif
5243 }
5244 
5245 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
5246 				unsigned int *min, unsigned int *max)
5247 {
5248 	if (!caps)
5249 		return 0;
5250 
5251 	if (caps->aux_support) {
5252 		// Firmware limits are in nits, DC API wants millinits.
5253 		*max = 1000 * caps->aux_max_input_signal;
5254 		*min = 1000 * caps->aux_min_input_signal;
5255 	} else {
5256 		// Firmware limits are 8-bit, PWM control is 16-bit.
5257 		*max = 0x101 * caps->max_input_signal;
5258 		*min = 0x101 * caps->min_input_signal;
5259 	}
5260 	return 1;
5261 }
5262 
5263 /* Rescale from [min..max] to [0..AMDGPU_MAX_BL_LEVEL] */
5264 static inline u32 scale_input_to_fw(int min, int max, u64 input)
5265 {
5266 	return DIV_ROUND_CLOSEST_ULL(input * AMDGPU_MAX_BL_LEVEL, max - min);
5267 }
5268 
5269 /* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [min..max] */
5270 static inline u32 scale_fw_to_input(int min, int max, u64 input)
5271 {
5272 	return min + DIV_ROUND_CLOSEST_ULL(input * (max - min), AMDGPU_MAX_BL_LEVEL);
5273 }
5274 
5275 static void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps,
5276 				      unsigned int min, unsigned int max,
5277 				      uint32_t *user_brightness)
5278 {
5279 	u32 brightness = scale_input_to_fw(min, max, *user_brightness);
5280 	u8 lower_signal, upper_signal, upper_lum, lower_lum, lum;
5281 	int left, right;
5282 
5283 	if (amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)
5284 		return;
5285 
5286 	if (!caps->data_points)
5287 		return;
5288 
5289 	/*
5290 	 * Handle the case where brightness is below the first data point
5291 	 * Interpolate between (0,0) and (first_signal, first_lum)
5292 	 */
5293 	if (brightness < caps->luminance_data[0].input_signal) {
5294 		lum = DIV_ROUND_CLOSEST(caps->luminance_data[0].luminance * brightness,
5295 					caps->luminance_data[0].input_signal);
5296 		goto scale;
5297 	}
5298 
5299 	left = 0;
5300 	right = caps->data_points - 1;
5301 	while (left <= right) {
5302 		int mid = left + (right - left) / 2;
5303 		u8 signal = caps->luminance_data[mid].input_signal;
5304 
5305 		/* Exact match found */
5306 		if (signal == brightness) {
5307 			lum = caps->luminance_data[mid].luminance;
5308 			goto scale;
5309 		}
5310 
5311 		if (signal < brightness)
5312 			left = mid + 1;
5313 		else
5314 			right = mid - 1;
5315 	}
5316 
5317 	/* verify bound */
5318 	if (left >= caps->data_points)
5319 		left = caps->data_points - 1;
5320 
5321 	/* At this point, left > right */
5322 	lower_signal = caps->luminance_data[right].input_signal;
5323 	upper_signal = caps->luminance_data[left].input_signal;
5324 	lower_lum = caps->luminance_data[right].luminance;
5325 	upper_lum = caps->luminance_data[left].luminance;
5326 
5327 	/* interpolate */
5328 	if (right == left || !lower_lum)
5329 		lum = upper_lum;
5330 	else
5331 		lum = lower_lum + DIV_ROUND_CLOSEST((upper_lum - lower_lum) *
5332 						    (brightness - lower_signal),
5333 						    upper_signal - lower_signal);
5334 scale:
5335 	*user_brightness = scale_fw_to_input(min, max,
5336 					     DIV_ROUND_CLOSEST(lum * brightness, 101));
5337 }
5338 
5339 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
5340 					uint32_t brightness)
5341 {
5342 	unsigned int min, max;
5343 
5344 	if (!get_brightness_range(caps, &min, &max))
5345 		return brightness;
5346 
5347 	convert_custom_brightness(caps, min, max, &brightness);
5348 
5349 	// Rescale 0..max to min..max
5350 	return min + DIV_ROUND_CLOSEST_ULL((u64)(max - min) * brightness, max);
5351 }
5352 
5353 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
5354 				      uint32_t brightness)
5355 {
5356 	unsigned int min, max;
5357 
5358 	if (!get_brightness_range(caps, &min, &max))
5359 		return brightness;
5360 
5361 	if (brightness < min)
5362 		return 0;
5363 	// Rescale min..max to 0..max
5364 	return DIV_ROUND_CLOSEST_ULL((u64)max * (brightness - min),
5365 				 max - min);
5366 }
5367 
5368 static struct dc_stream_state *dm_find_stream_with_link(
5369 	struct amdgpu_display_manager *dm,
5370 	struct dc_link *link)
5371 {
5372 	struct dc_state *cur_dc_state = dm->dc->current_state;
5373 	struct dc_stream_state *stream = NULL;
5374 	int i;
5375 
5376 	for (i = 0; i < cur_dc_state->stream_count; i++) {
5377 		stream = cur_dc_state->streams[i];
5378 		if (stream->link == link)
5379 			return stream;
5380 	}
5381 
5382 	return NULL;
5383 }
5384 
5385 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
5386 					 int bl_idx,
5387 					 u32 user_brightness)
5388 {
5389 	struct amdgpu_dm_backlight_caps *caps;
5390 	struct dc_link *link;
5391 	u32 brightness = 0;
5392 	bool rc = false, reallow_idle = false;
5393 	struct drm_connector *connector;
5394 	struct dc_stream_state *stream;
5395 	unsigned int min, max;
5396 
5397 	list_for_each_entry(connector, &dm->ddev->mode_config.connector_list, head) {
5398 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5399 
5400 		if (aconnector->bl_idx != bl_idx)
5401 			continue;
5402 
5403 		/* if connector is off, save the brightness for next time it's on */
5404 		if (!aconnector->base.encoder) {
5405 			dm->brightness[bl_idx] = user_brightness;
5406 			dm->actual_brightness[bl_idx] = 0;
5407 			return;
5408 		}
5409 	}
5410 
5411 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5412 	caps = &dm->backlight_caps[bl_idx];
5413 
5414 	dm->brightness[bl_idx] = user_brightness;
5415 	/* update scratch register */
5416 	if (bl_idx == 0)
5417 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
5418 	brightness = convert_brightness_from_user(caps, dm->brightness[bl_idx]);
5419 	link = (struct dc_link *)dm->backlight_link[bl_idx];
5420 
5421 	/* Apply brightness quirk */
5422 	if (caps->brightness_mask)
5423 		brightness |= caps->brightness_mask;
5424 
5425 	if (trace_amdgpu_dm_brightness_enabled()) {
5426 		trace_amdgpu_dm_brightness(__builtin_return_address(0),
5427 					   user_brightness,
5428 					   brightness,
5429 					   caps->aux_support,
5430 					   power_supply_is_system_supplied() > 0);
5431 	}
5432 
5433 	stream = dm_find_stream_with_link(dm, link);
5434 	if (!stream)
5435 		return;
5436 
5437 	mutex_lock(&dm->dc_lock);
5438 	if (dm->dc->caps.ips_support && dm->dc->ctx->dmub_srv->idle_allowed) {
5439 		dc_allow_idle_optimizations(dm->dc, false);
5440 		reallow_idle = true;
5441 	}
5442 
5443 	if (caps->aux_support) {
5444 		rc = mod_power_set_backlight_nits(dm->power_module, stream, brightness,
5445 			AUX_BL_DEFAULT_TRANSITION_TIME_MS, false, true);
5446 	} else {
5447 		/* power module uses millipercent */
5448 		get_brightness_range(caps, &min, &max);
5449 		brightness = DIV_ROUND_CLOSEST(brightness * 100, (max - min)) * 1000;
5450 		rc = mod_power_set_backlight_percent(dm->power_module, stream,
5451 						     brightness, 0, false);
5452 	}
5453 
5454 	/*
5455 	 * Some kms clients create a ramped backlight transition effect
5456 	 * by rapidly changing the backlight. Yet we must wait on dmcub
5457 	 * fw to exit psr/replay before programming backlight. To
5458 	 * prevent lag, keep disable psr/replay and let the next atomic
5459 	 * flip clear the event.
5460 	 *
5461 	 * ToDo: use ISM to handle rapidly backlight change
5462 	 *
5463 	 * Rapidly backlight change is similar to rapidly cursor events,
5464 	 * which is now handled by ISM. ISM can delay the event until system
5465 	 * is really idle, so we may use ISM to handle backlight change as well.
5466 	 */
5467 	amdgpu_dm_psr_set_event(dm, stream, true,
5468 		psr_event_hw_programming, true);
5469 	amdgpu_dm_replay_set_event(dm, stream, true,
5470 		replay_event_hw_programming, true);
5471 
5472 	if (dm->dc->caps.ips_support && reallow_idle)
5473 		dc_allow_idle_optimizations(dm->dc, true);
5474 
5475 	mutex_unlock(&dm->dc_lock);
5476 
5477 	if (rc)
5478 		dm->actual_brightness[bl_idx] = user_brightness;
5479 }
5480 
5481 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
5482 {
5483 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5484 	int i;
5485 
5486 	for (i = 0; i < dm->num_of_edps; i++) {
5487 		if (bd == dm->backlight_dev[i])
5488 			break;
5489 	}
5490 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5491 		i = 0;
5492 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
5493 
5494 	return 0;
5495 }
5496 
5497 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
5498 					 int bl_idx)
5499 {
5500 	int ret;
5501 	struct amdgpu_dm_backlight_caps caps;
5502 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
5503 
5504 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5505 	caps = dm->backlight_caps[bl_idx];
5506 
5507 	if (caps.aux_support) {
5508 		u32 avg, peak;
5509 
5510 		if (!dc_link_get_backlight_level_nits(link, &avg, &peak))
5511 			return dm->brightness[bl_idx];
5512 		return convert_brightness_to_user(&caps, avg);
5513 	}
5514 
5515 	ret = dc_link_get_backlight_level(link);
5516 
5517 	if (ret == DC_ERROR_UNEXPECTED)
5518 		return dm->brightness[bl_idx];
5519 
5520 	return convert_brightness_to_user(&caps, ret);
5521 }
5522 
5523 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
5524 {
5525 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5526 	int i;
5527 
5528 	for (i = 0; i < dm->num_of_edps; i++) {
5529 		if (bd == dm->backlight_dev[i])
5530 			break;
5531 	}
5532 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5533 		i = 0;
5534 	return amdgpu_dm_backlight_get_level(dm, i);
5535 }
5536 
5537 static const struct backlight_ops amdgpu_dm_backlight_ops = {
5538 	.options = BL_CORE_SUSPENDRESUME,
5539 	.get_brightness = amdgpu_dm_backlight_get_brightness,
5540 	.update_status	= amdgpu_dm_backlight_update_status,
5541 };
5542 
5543 static void
5544 amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector *aconnector)
5545 {
5546 	struct drm_device *drm = aconnector->base.dev;
5547 	struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
5548 	struct backlight_properties props = { 0 };
5549 	struct amdgpu_dm_backlight_caps *caps;
5550 	char bl_name[16];
5551 	int min, max;
5552 	int real_brightness;
5553 	int init_brightness;
5554 
5555 	if (aconnector->bl_idx == -1)
5556 		return;
5557 
5558 	if (!acpi_video_backlight_use_native()) {
5559 		drm_info(drm, "Skipping amdgpu DM backlight registration\n");
5560 		/* Try registering an ACPI video backlight device instead. */
5561 		acpi_video_register_backlight();
5562 		return;
5563 	}
5564 
5565 	caps = &dm->backlight_caps[aconnector->bl_idx];
5566 	if (get_brightness_range(caps, &min, &max)) {
5567 		if (power_supply_is_system_supplied() > 0)
5568 			props.brightness = DIV_ROUND_CLOSEST(max * caps->ac_level, 100);
5569 		else
5570 			props.brightness = DIV_ROUND_CLOSEST(max * caps->dc_level, 100);
5571 		/* min is zero, so max needs to be adjusted */
5572 		props.max_brightness = max;
5573 		drm_dbg(drm, "Backlight caps: min: %d, max: %d, ac %d, dc %d\n", min, max,
5574 			caps->ac_level, caps->dc_level);
5575 	} else
5576 		props.brightness = props.max_brightness = MAX_BACKLIGHT_LEVEL;
5577 
5578 	init_brightness = props.brightness;
5579 
5580 	if (caps->data_points && !(amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)) {
5581 		drm_info(drm, "Using custom brightness curve\n");
5582 		props.scale = BACKLIGHT_SCALE_NON_LINEAR;
5583 	} else
5584 		props.scale = BACKLIGHT_SCALE_LINEAR;
5585 	props.type = BACKLIGHT_RAW;
5586 
5587 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
5588 		 drm->primary->index + aconnector->bl_idx);
5589 
5590 	dm->backlight_dev[aconnector->bl_idx] =
5591 		backlight_device_register(bl_name, aconnector->base.kdev, dm,
5592 					  &amdgpu_dm_backlight_ops, &props);
5593 	dm->brightness[aconnector->bl_idx] = props.brightness;
5594 
5595 	if (IS_ERR(dm->backlight_dev[aconnector->bl_idx])) {
5596 		drm_err(drm, "DM: Backlight registration failed!\n");
5597 		dm->backlight_dev[aconnector->bl_idx] = NULL;
5598 	} else {
5599 		/*
5600 		 * dm->brightness[x] can be inconsistent just after startup until
5601 		 * ops.get_brightness is called.
5602 		 */
5603 		real_brightness =
5604 			amdgpu_dm_backlight_ops.get_brightness(dm->backlight_dev[aconnector->bl_idx]);
5605 
5606 		if (real_brightness != init_brightness) {
5607 			dm->actual_brightness[aconnector->bl_idx] = real_brightness;
5608 			dm->brightness[aconnector->bl_idx] = real_brightness;
5609 		}
5610 		drm_dbg_driver(drm, "DM: Registered Backlight device: %s\n", bl_name);
5611 	}
5612 }
5613 
5614 static int initialize_plane(struct amdgpu_display_manager *dm,
5615 			    struct amdgpu_mode_info *mode_info, int plane_id,
5616 			    enum drm_plane_type plane_type,
5617 			    const struct dc_plane_cap *plane_cap)
5618 {
5619 	struct drm_plane *plane;
5620 	unsigned long possible_crtcs;
5621 	int ret = 0;
5622 
5623 	plane = kzalloc_obj(struct drm_plane);
5624 	if (!plane) {
5625 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
5626 		return -ENOMEM;
5627 	}
5628 	plane->type = plane_type;
5629 
5630 	/*
5631 	 * HACK: IGT tests expect that the primary plane for a CRTC
5632 	 * can only have one possible CRTC. Only expose support for
5633 	 * any CRTC if they're not going to be used as a primary plane
5634 	 * for a CRTC - like overlay or underlay planes.
5635 	 */
5636 	possible_crtcs = 1 << plane_id;
5637 	if (plane_id >= dm->dc->caps.max_streams)
5638 		possible_crtcs = 0xff;
5639 
5640 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
5641 
5642 	if (ret) {
5643 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
5644 		kfree(plane);
5645 		return ret;
5646 	}
5647 
5648 	if (mode_info)
5649 		mode_info->planes[plane_id] = plane;
5650 
5651 	return ret;
5652 }
5653 
5654 
5655 static void setup_backlight_device(struct amdgpu_display_manager *dm,
5656 				   struct amdgpu_dm_connector *aconnector)
5657 {
5658 	struct amdgpu_dm_backlight_caps *caps;
5659 	struct dc_link *link = aconnector->dc_link;
5660 	int bl_idx = dm->num_of_edps;
5661 
5662 	if (!(link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) ||
5663 	    link->type == dc_connection_none)
5664 		return;
5665 
5666 	if (dm->num_of_edps >= AMDGPU_DM_MAX_NUM_EDP) {
5667 		drm_warn(adev_to_drm(dm->adev), "Too much eDP connections, skipping backlight setup for additional eDPs\n");
5668 		return;
5669 	}
5670 
5671 	aconnector->bl_idx = bl_idx;
5672 
5673 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5674 	dm->backlight_link[bl_idx] = link;
5675 	dm->num_of_edps++;
5676 
5677 	update_connector_ext_caps(aconnector);
5678 	caps = &dm->backlight_caps[aconnector->bl_idx];
5679 
5680 	/* Only offer ABM property when non-OLED and user didn't turn off by module parameter */
5681 	if (caps->ext_caps && !caps->ext_caps->bits.oled && amdgpu_dm_abm_level < 0)
5682 		drm_object_attach_property(&aconnector->base.base,
5683 					   dm->adev->mode_info.abm_level_property,
5684 					   ABM_SYSFS_CONTROL);
5685 }
5686 
5687 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
5688 
5689 
5690 
5691 /*
5692  * In this architecture, the association
5693  * connector -> encoder -> crtc
5694  * id not really requried. The crtc and connector will hold the
5695  * display_index as an abstraction to use with DAL component
5696  *
5697  * Returns 0 on success
5698  */
5699 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
5700 {
5701 	struct amdgpu_display_manager *dm = &adev->dm;
5702 	s32 i;
5703 	struct amdgpu_dm_connector *aconnector = NULL;
5704 	struct amdgpu_encoder *aencoder = NULL;
5705 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5706 	u32 link_cnt;
5707 	s32 primary_planes;
5708 	enum dc_connection_type new_connection_type = dc_connection_none;
5709 	const struct dc_plane_cap *plane;
5710 	bool psr_feature_enabled = false;
5711 	bool replay_feature_enabled = false;
5712 	int max_overlay = dm->dc->caps.max_slave_planes;
5713 
5714 	dm->display_indexes_num = dm->dc->caps.max_streams;
5715 	/* Update the actual used number of crtc */
5716 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
5717 
5718 	amdgpu_dm_set_irq_funcs(adev);
5719 
5720 	link_cnt = dm->dc->caps.max_links;
5721 	if (amdgpu_dm_mode_config_init(dm->adev)) {
5722 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
5723 		return -EINVAL;
5724 	}
5725 
5726 	/* There is one primary plane per CRTC */
5727 	primary_planes = dm->dc->caps.max_streams;
5728 	if (primary_planes > AMDGPU_MAX_PLANES) {
5729 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
5730 		return -EINVAL;
5731 	}
5732 
5733 	/*
5734 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
5735 	 * Order is reversed to match iteration order in atomic check.
5736 	 */
5737 	for (i = (primary_planes - 1); i >= 0; i--) {
5738 		plane = &dm->dc->caps.planes[i];
5739 
5740 		if (initialize_plane(dm, mode_info, i,
5741 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
5742 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
5743 			goto fail;
5744 		}
5745 	}
5746 
5747 	/*
5748 	 * Initialize overlay planes, index starting after primary planes.
5749 	 * These planes have a higher DRM index than the primary planes since
5750 	 * they should be considered as having a higher z-order.
5751 	 * Order is reversed to match iteration order in atomic check.
5752 	 *
5753 	 * Only support DCN for now, and only expose one so we don't encourage
5754 	 * userspace to use up all the pipes.
5755 	 */
5756 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
5757 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
5758 
5759 		/* Do not create overlay if MPO disabled */
5760 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
5761 			break;
5762 
5763 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
5764 			continue;
5765 
5766 		if (!plane->pixel_format_support.argb8888)
5767 			continue;
5768 
5769 		if (max_overlay-- == 0)
5770 			break;
5771 
5772 		if (initialize_plane(dm, NULL, primary_planes + i,
5773 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
5774 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
5775 			goto fail;
5776 		}
5777 	}
5778 
5779 	for (i = 0; i < dm->dc->caps.max_streams; i++)
5780 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
5781 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
5782 			goto fail;
5783 		}
5784 
5785 	/* Use Outbox interrupt */
5786 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5787 	case IP_VERSION(3, 0, 0):
5788 	case IP_VERSION(3, 1, 2):
5789 	case IP_VERSION(3, 1, 3):
5790 	case IP_VERSION(3, 1, 4):
5791 	case IP_VERSION(3, 1, 5):
5792 	case IP_VERSION(3, 1, 6):
5793 	case IP_VERSION(3, 2, 0):
5794 	case IP_VERSION(3, 2, 1):
5795 	case IP_VERSION(2, 1, 0):
5796 	case IP_VERSION(3, 5, 0):
5797 	case IP_VERSION(3, 5, 1):
5798 	case IP_VERSION(3, 6, 0):
5799 	case IP_VERSION(4, 0, 1):
5800 	case IP_VERSION(4, 2, 0):
5801 	case IP_VERSION(4, 2, 1):
5802 		if (register_outbox_irq_handlers(dm->adev)) {
5803 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5804 			goto fail;
5805 		}
5806 		break;
5807 	default:
5808 		drm_dbg_kms(adev_to_drm(adev), "Unsupported DCN IP version for outbox: 0x%X\n",
5809 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
5810 	}
5811 
5812 	/* Determine whether to enable PSR support by default. */
5813 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
5814 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5815 		case IP_VERSION(3, 1, 2):
5816 		case IP_VERSION(3, 1, 3):
5817 		case IP_VERSION(3, 1, 4):
5818 		case IP_VERSION(3, 1, 5):
5819 		case IP_VERSION(3, 1, 6):
5820 		case IP_VERSION(3, 2, 0):
5821 		case IP_VERSION(3, 2, 1):
5822 		case IP_VERSION(3, 5, 0):
5823 		case IP_VERSION(3, 5, 1):
5824 		case IP_VERSION(3, 6, 0):
5825 		case IP_VERSION(4, 0, 1):
5826 		case IP_VERSION(4, 2, 0):
5827 		case IP_VERSION(4, 2, 1):
5828 			psr_feature_enabled = true;
5829 			break;
5830 		default:
5831 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
5832 			break;
5833 		}
5834 	}
5835 
5836 	/* Determine whether to enable Replay support by default. */
5837 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
5838 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5839 		case IP_VERSION(3, 1, 4):
5840 		case IP_VERSION(3, 2, 0):
5841 		case IP_VERSION(3, 2, 1):
5842 		case IP_VERSION(3, 5, 0):
5843 		case IP_VERSION(3, 5, 1):
5844 		case IP_VERSION(3, 6, 0):
5845 		case IP_VERSION(4, 2, 0):
5846 		case IP_VERSION(4, 2, 1):
5847 			replay_feature_enabled = true;
5848 			break;
5849 
5850 		default:
5851 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
5852 			break;
5853 		}
5854 	}
5855 
5856 	if (link_cnt > MAX_LINKS) {
5857 		drm_err(adev_to_drm(adev),
5858 			"KMS: Cannot support more than %d display indexes\n",
5859 				MAX_LINKS);
5860 		goto fail;
5861 	}
5862 
5863 	/* loops over all connectors on the board */
5864 	for (i = 0; i < link_cnt; i++) {
5865 		struct dc_link *link = NULL;
5866 
5867 		link = dc_get_link_at_index(dm->dc, i);
5868 
5869 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
5870 			struct amdgpu_dm_wb_connector *wbcon = kzalloc_obj(*wbcon);
5871 
5872 			if (!wbcon) {
5873 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
5874 				continue;
5875 			}
5876 
5877 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
5878 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
5879 				kfree(wbcon);
5880 				continue;
5881 			}
5882 
5883 			link->psr_settings.psr_feature_enabled = false;
5884 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
5885 
5886 			continue;
5887 		}
5888 
5889 		aconnector = kzalloc_obj(*aconnector);
5890 		if (!aconnector)
5891 			goto fail;
5892 
5893 		aencoder = kzalloc_obj(*aencoder);
5894 		if (!aencoder)
5895 			goto fail;
5896 
5897 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
5898 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
5899 			goto fail;
5900 		}
5901 
5902 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
5903 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
5904 			goto fail;
5905 		}
5906 
5907 		if (dm->hpd_rx_offload_wq)
5908 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
5909 				aconnector;
5910 
5911 		if (!dc_link_detect_connection_type(link, &new_connection_type))
5912 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
5913 
5914 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
5915 			emulated_link_detect(link);
5916 			amdgpu_dm_update_connector_after_detect(aconnector);
5917 		} else {
5918 			bool ret = false;
5919 
5920 			mutex_lock(&dm->dc_lock);
5921 			dc_exit_ips_for_hw_access(dm->dc);
5922 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
5923 			mutex_unlock(&dm->dc_lock);
5924 
5925 			if (ret) {
5926 				amdgpu_dm_update_connector_after_detect(aconnector);
5927 				setup_backlight_device(dm, aconnector);
5928 
5929 				/* Disable PSR if Replay can be enabled */
5930 				if (replay_feature_enabled)
5931 					if (amdgpu_dm_set_replay_caps(link, aconnector))
5932 						psr_feature_enabled = false;
5933 
5934 				if (psr_feature_enabled) {
5935 					amdgpu_dm_set_psr_caps(link, aconnector);
5936 					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",
5937 						 aconnector->base.name,
5938 						 link->psr_settings.psr_feature_enabled,
5939 						 link->psr_settings.psr_version,
5940 						 link->dpcd_caps.psr_info.psr_version,
5941 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
5942 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
5943 				}
5944 			}
5945 		}
5946 		amdgpu_set_panel_orientation(&aconnector->base);
5947 	}
5948 
5949 	/* Debug dump: list all DC links and their associated sinks after detection
5950 	 * is complete for all connectors. This provides a comprehensive view of the
5951 	 * final state without repeating the dump for each connector.
5952 	 */
5953 	amdgpu_dm_dump_links_and_sinks(adev);
5954 
5955 	/* Software is initialized. Now we can register interrupt handlers. */
5956 	switch (adev->asic_type) {
5957 #if defined(CONFIG_DRM_AMD_DC_SI)
5958 	case CHIP_TAHITI:
5959 	case CHIP_PITCAIRN:
5960 	case CHIP_VERDE:
5961 	case CHIP_OLAND:
5962 #endif
5963 	case CHIP_BONAIRE:
5964 	case CHIP_HAWAII:
5965 	case CHIP_KAVERI:
5966 	case CHIP_KABINI:
5967 	case CHIP_MULLINS:
5968 	case CHIP_TONGA:
5969 	case CHIP_FIJI:
5970 	case CHIP_CARRIZO:
5971 	case CHIP_STONEY:
5972 	case CHIP_POLARIS11:
5973 	case CHIP_POLARIS10:
5974 	case CHIP_POLARIS12:
5975 	case CHIP_VEGAM:
5976 	case CHIP_VEGA10:
5977 	case CHIP_VEGA12:
5978 	case CHIP_VEGA20:
5979 		if (dce110_register_irq_handlers(dm->adev)) {
5980 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5981 			goto fail;
5982 		}
5983 		break;
5984 	default:
5985 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5986 		case IP_VERSION(1, 0, 0):
5987 		case IP_VERSION(1, 0, 1):
5988 		case IP_VERSION(2, 0, 2):
5989 		case IP_VERSION(2, 0, 3):
5990 		case IP_VERSION(2, 0, 0):
5991 		case IP_VERSION(2, 1, 0):
5992 		case IP_VERSION(3, 0, 0):
5993 		case IP_VERSION(3, 0, 2):
5994 		case IP_VERSION(3, 0, 3):
5995 		case IP_VERSION(3, 0, 1):
5996 		case IP_VERSION(3, 1, 2):
5997 		case IP_VERSION(3, 1, 3):
5998 		case IP_VERSION(3, 1, 4):
5999 		case IP_VERSION(3, 1, 5):
6000 		case IP_VERSION(3, 1, 6):
6001 		case IP_VERSION(3, 2, 0):
6002 		case IP_VERSION(3, 2, 1):
6003 		case IP_VERSION(3, 5, 0):
6004 		case IP_VERSION(3, 5, 1):
6005 		case IP_VERSION(3, 6, 0):
6006 		case IP_VERSION(4, 0, 1):
6007 		case IP_VERSION(4, 2, 0):
6008 		case IP_VERSION(4, 2, 1):
6009 			if (dcn10_register_irq_handlers(dm->adev)) {
6010 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
6011 				goto fail;
6012 			}
6013 			break;
6014 		default:
6015 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
6016 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6017 			goto fail;
6018 		}
6019 		break;
6020 	}
6021 
6022 	return 0;
6023 fail:
6024 	kfree(aencoder);
6025 	kfree(aconnector);
6026 
6027 	return -EINVAL;
6028 }
6029 
6030 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
6031 {
6032 	if (dm->atomic_obj.state)
6033 		drm_atomic_private_obj_fini(&dm->atomic_obj);
6034 }
6035 
6036 /******************************************************************************
6037  * amdgpu_display_funcs functions
6038  *****************************************************************************/
6039 
6040 /*
6041  * dm_bandwidth_update - program display watermarks
6042  *
6043  * @adev: amdgpu_device pointer
6044  *
6045  * Calculate and program the display watermarks and line buffer allocation.
6046  */
6047 static void dm_bandwidth_update(struct amdgpu_device *adev)
6048 {
6049 	/* TODO: implement later */
6050 }
6051 
6052 static const struct amdgpu_display_funcs dm_display_funcs = {
6053 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
6054 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
6055 	.backlight_set_level = NULL, /* never called for DC */
6056 	.backlight_get_level = NULL, /* never called for DC */
6057 	.hpd_sense = NULL,/* called unconditionally */
6058 	.hpd_set_polarity = NULL, /* called unconditionally */
6059 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
6060 	.page_flip_get_scanoutpos =
6061 		dm_crtc_get_scanoutpos,/* called unconditionally */
6062 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
6063 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
6064 };
6065 
6066 #if defined(CONFIG_DEBUG_KERNEL_DC)
6067 
6068 static ssize_t s3_debug_store(struct device *device,
6069 			      struct device_attribute *attr,
6070 			      const char *buf,
6071 			      size_t count)
6072 {
6073 	int ret;
6074 	int s3_state;
6075 	struct drm_device *drm_dev = dev_get_drvdata(device);
6076 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
6077 	struct amdgpu_ip_block *ip_block;
6078 
6079 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
6080 	if (!ip_block)
6081 		return -EINVAL;
6082 
6083 	ret = kstrtoint(buf, 0, &s3_state);
6084 
6085 	if (ret == 0) {
6086 		if (s3_state) {
6087 			dm_resume(ip_block);
6088 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
6089 		} else
6090 			dm_suspend(ip_block);
6091 	}
6092 
6093 	return ret == 0 ? count : 0;
6094 }
6095 
6096 DEVICE_ATTR_WO(s3_debug);
6097 
6098 #endif
6099 
6100 static int dm_init_microcode(struct amdgpu_device *adev)
6101 {
6102 	char *fw_name_dmub;
6103 	int r;
6104 
6105 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6106 	case IP_VERSION(2, 1, 0):
6107 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
6108 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
6109 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
6110 		break;
6111 	case IP_VERSION(3, 0, 0):
6112 		if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(10, 3, 0))
6113 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
6114 		else
6115 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
6116 		break;
6117 	case IP_VERSION(3, 0, 1):
6118 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
6119 		break;
6120 	case IP_VERSION(3, 0, 2):
6121 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
6122 		break;
6123 	case IP_VERSION(3, 0, 3):
6124 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
6125 		break;
6126 	case IP_VERSION(3, 1, 2):
6127 	case IP_VERSION(3, 1, 3):
6128 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
6129 		break;
6130 	case IP_VERSION(3, 1, 4):
6131 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
6132 		break;
6133 	case IP_VERSION(3, 1, 5):
6134 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
6135 		break;
6136 	case IP_VERSION(3, 1, 6):
6137 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
6138 		break;
6139 	case IP_VERSION(3, 2, 0):
6140 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
6141 		break;
6142 	case IP_VERSION(3, 2, 1):
6143 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
6144 		break;
6145 	case IP_VERSION(3, 5, 0):
6146 		fw_name_dmub = FIRMWARE_DCN_35_DMUB;
6147 		break;
6148 	case IP_VERSION(3, 5, 1):
6149 		fw_name_dmub = FIRMWARE_DCN_351_DMUB;
6150 		break;
6151 	case IP_VERSION(3, 6, 0):
6152 		fw_name_dmub = FIRMWARE_DCN_36_DMUB;
6153 		break;
6154 	case IP_VERSION(4, 0, 1):
6155 		fw_name_dmub = FIRMWARE_DCN_401_DMUB;
6156 		break;
6157 	case IP_VERSION(4, 2, 0):
6158 		fw_name_dmub = FIRMWARE_DCN_42_DMUB;
6159 		break;
6160 	case IP_VERSION(4, 2, 1):
6161 		fw_name_dmub = FIRMWARE_DCN_42B_DMUB;
6162 		break;
6163 	default:
6164 		/* ASIC doesn't support DMUB. */
6165 		return 0;
6166 	}
6167 	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, AMDGPU_UCODE_REQUIRED,
6168 				 "%s", fw_name_dmub);
6169 	return r;
6170 }
6171 
6172 static int dm_early_init(struct amdgpu_ip_block *ip_block)
6173 {
6174 	struct amdgpu_device *adev = ip_block->adev;
6175 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
6176 	struct atom_context *ctx = mode_info->atom_context;
6177 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
6178 	u16 data_offset;
6179 
6180 	/* if there is no object header, skip DM */
6181 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
6182 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
6183 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
6184 		return -ENOENT;
6185 	}
6186 
6187 	switch (adev->asic_type) {
6188 #if defined(CONFIG_DRM_AMD_DC_SI)
6189 	case CHIP_TAHITI:
6190 	case CHIP_PITCAIRN:
6191 	case CHIP_VERDE:
6192 		adev->mode_info.num_crtc = 6;
6193 		adev->mode_info.num_hpd = 6;
6194 		adev->mode_info.num_dig = 6;
6195 		break;
6196 	case CHIP_OLAND:
6197 		adev->mode_info.num_crtc = 2;
6198 		adev->mode_info.num_hpd = 2;
6199 		adev->mode_info.num_dig = 2;
6200 		break;
6201 #endif
6202 	case CHIP_BONAIRE:
6203 	case CHIP_HAWAII:
6204 		adev->mode_info.num_crtc = 6;
6205 		adev->mode_info.num_hpd = 6;
6206 		adev->mode_info.num_dig = 6;
6207 		break;
6208 	case CHIP_KAVERI:
6209 		adev->mode_info.num_crtc = 4;
6210 		adev->mode_info.num_hpd = 6;
6211 		adev->mode_info.num_dig = 7;
6212 		break;
6213 	case CHIP_KABINI:
6214 	case CHIP_MULLINS:
6215 		adev->mode_info.num_crtc = 2;
6216 		adev->mode_info.num_hpd = 6;
6217 		adev->mode_info.num_dig = 6;
6218 		break;
6219 	case CHIP_FIJI:
6220 	case CHIP_TONGA:
6221 		adev->mode_info.num_crtc = 6;
6222 		adev->mode_info.num_hpd = 6;
6223 		adev->mode_info.num_dig = 7;
6224 		break;
6225 	case CHIP_CARRIZO:
6226 		adev->mode_info.num_crtc = 3;
6227 		adev->mode_info.num_hpd = 6;
6228 		adev->mode_info.num_dig = 9;
6229 		break;
6230 	case CHIP_STONEY:
6231 		adev->mode_info.num_crtc = 2;
6232 		adev->mode_info.num_hpd = 6;
6233 		adev->mode_info.num_dig = 9;
6234 		break;
6235 	case CHIP_POLARIS11:
6236 	case CHIP_POLARIS12:
6237 		adev->mode_info.num_crtc = 5;
6238 		adev->mode_info.num_hpd = 5;
6239 		adev->mode_info.num_dig = 5;
6240 		break;
6241 	case CHIP_POLARIS10:
6242 	case CHIP_VEGAM:
6243 		adev->mode_info.num_crtc = 6;
6244 		adev->mode_info.num_hpd = 6;
6245 		adev->mode_info.num_dig = 6;
6246 		break;
6247 	case CHIP_VEGA10:
6248 	case CHIP_VEGA12:
6249 	case CHIP_VEGA20:
6250 		adev->mode_info.num_crtc = 6;
6251 		adev->mode_info.num_hpd = 6;
6252 		adev->mode_info.num_dig = 6;
6253 		break;
6254 	default:
6255 
6256 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6257 		case IP_VERSION(2, 0, 2):
6258 		case IP_VERSION(3, 0, 0):
6259 			adev->mode_info.num_crtc = 6;
6260 			adev->mode_info.num_hpd = 6;
6261 			adev->mode_info.num_dig = 6;
6262 			break;
6263 		case IP_VERSION(2, 0, 0):
6264 		case IP_VERSION(3, 0, 2):
6265 			adev->mode_info.num_crtc = 5;
6266 			adev->mode_info.num_hpd = 5;
6267 			adev->mode_info.num_dig = 5;
6268 			break;
6269 		case IP_VERSION(2, 0, 3):
6270 		case IP_VERSION(3, 0, 3):
6271 			adev->mode_info.num_crtc = 2;
6272 			adev->mode_info.num_hpd = 2;
6273 			adev->mode_info.num_dig = 2;
6274 			break;
6275 		case IP_VERSION(1, 0, 0):
6276 		case IP_VERSION(1, 0, 1):
6277 		case IP_VERSION(3, 0, 1):
6278 		case IP_VERSION(2, 1, 0):
6279 		case IP_VERSION(3, 1, 2):
6280 		case IP_VERSION(3, 1, 3):
6281 		case IP_VERSION(3, 1, 4):
6282 		case IP_VERSION(3, 1, 5):
6283 		case IP_VERSION(3, 1, 6):
6284 		case IP_VERSION(3, 2, 0):
6285 		case IP_VERSION(3, 2, 1):
6286 		case IP_VERSION(3, 5, 0):
6287 		case IP_VERSION(3, 5, 1):
6288 		case IP_VERSION(3, 6, 0):
6289 		case IP_VERSION(4, 0, 1):
6290 		case IP_VERSION(4, 2, 0):
6291 		case IP_VERSION(4, 2, 1):
6292 			adev->mode_info.num_crtc = 4;
6293 			adev->mode_info.num_hpd = 4;
6294 			adev->mode_info.num_dig = 4;
6295 			break;
6296 		default:
6297 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
6298 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6299 			return -EINVAL;
6300 		}
6301 		break;
6302 	}
6303 
6304 	if (adev->mode_info.funcs == NULL)
6305 		adev->mode_info.funcs = &dm_display_funcs;
6306 
6307 	/*
6308 	 * Note: Do NOT change adev->reg.audio_endpt.rreg and
6309 	 * adev->reg.audio_endpt.wreg because they are initialised in
6310 	 * amdgpu_device_init()
6311 	 */
6312 #if defined(CONFIG_DEBUG_KERNEL_DC)
6313 	device_create_file(
6314 		adev_to_drm(adev)->dev,
6315 		&dev_attr_s3_debug);
6316 #endif
6317 	adev->dc_enabled = true;
6318 
6319 	return dm_init_microcode(adev);
6320 }
6321 
6322 static bool modereset_required(struct drm_crtc_state *crtc_state)
6323 {
6324 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
6325 }
6326 
6327 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
6328 {
6329 	drm_encoder_cleanup(encoder);
6330 	kfree(encoder);
6331 }
6332 
6333 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
6334 	.destroy = amdgpu_dm_encoder_destroy,
6335 };
6336 
6337 static int
6338 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
6339 			    const enum surface_pixel_format format,
6340 			    enum dc_color_space *color_space)
6341 {
6342 	bool full_range;
6343 
6344 	*color_space = COLOR_SPACE_SRGB;
6345 
6346 	/* Ignore properties when DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE is set */
6347 	if (plane_state->state && plane_state->state->plane_color_pipeline)
6348 		return 0;
6349 
6350 	/* DRM color properties only affect non-RGB formats. */
6351 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
6352 		return 0;
6353 
6354 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
6355 
6356 	switch (plane_state->color_encoding) {
6357 	case DRM_COLOR_YCBCR_BT601:
6358 		if (full_range)
6359 			*color_space = COLOR_SPACE_YCBCR601;
6360 		else
6361 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
6362 		break;
6363 
6364 	case DRM_COLOR_YCBCR_BT709:
6365 		if (full_range)
6366 			*color_space = COLOR_SPACE_YCBCR709;
6367 		else
6368 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
6369 		break;
6370 
6371 	case DRM_COLOR_YCBCR_BT2020:
6372 		if (full_range)
6373 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
6374 		else
6375 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6376 		break;
6377 
6378 	default:
6379 		return -EINVAL;
6380 	}
6381 
6382 	return 0;
6383 }
6384 
6385 static int
6386 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
6387 			    const struct drm_plane_state *plane_state,
6388 			    const u64 tiling_flags,
6389 			    struct dc_plane_info *plane_info,
6390 			    struct dc_plane_address *address,
6391 			    bool tmz_surface)
6392 {
6393 	const struct drm_framebuffer *fb = plane_state->fb;
6394 	const struct amdgpu_framebuffer *afb =
6395 		to_amdgpu_framebuffer(plane_state->fb);
6396 	int ret;
6397 
6398 	memset(plane_info, 0, sizeof(*plane_info));
6399 
6400 	switch (fb->format->format) {
6401 	case DRM_FORMAT_C8:
6402 		plane_info->format =
6403 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
6404 		break;
6405 	case DRM_FORMAT_RGB565:
6406 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
6407 		break;
6408 	case DRM_FORMAT_XRGB8888:
6409 	case DRM_FORMAT_ARGB8888:
6410 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6411 		break;
6412 	case DRM_FORMAT_XRGB2101010:
6413 	case DRM_FORMAT_ARGB2101010:
6414 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
6415 		break;
6416 	case DRM_FORMAT_XBGR2101010:
6417 	case DRM_FORMAT_ABGR2101010:
6418 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
6419 		break;
6420 	case DRM_FORMAT_XBGR8888:
6421 	case DRM_FORMAT_ABGR8888:
6422 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
6423 		break;
6424 	case DRM_FORMAT_NV21:
6425 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
6426 		break;
6427 	case DRM_FORMAT_NV12:
6428 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
6429 		break;
6430 	case DRM_FORMAT_P010:
6431 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
6432 		break;
6433 	case DRM_FORMAT_XRGB16161616F:
6434 	case DRM_FORMAT_ARGB16161616F:
6435 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
6436 		break;
6437 	case DRM_FORMAT_XBGR16161616F:
6438 	case DRM_FORMAT_ABGR16161616F:
6439 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
6440 		break;
6441 	case DRM_FORMAT_XRGB16161616:
6442 	case DRM_FORMAT_ARGB16161616:
6443 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
6444 		break;
6445 	case DRM_FORMAT_XBGR16161616:
6446 	case DRM_FORMAT_ABGR16161616:
6447 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
6448 		break;
6449 	default:
6450 		drm_err(adev_to_drm(adev),
6451 			"Unsupported screen format %p4cc\n",
6452 			&fb->format->format);
6453 		return -EINVAL;
6454 	}
6455 
6456 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
6457 	case DRM_MODE_ROTATE_0:
6458 		plane_info->rotation = ROTATION_ANGLE_0;
6459 		break;
6460 	case DRM_MODE_ROTATE_90:
6461 		plane_info->rotation = ROTATION_ANGLE_90;
6462 		break;
6463 	case DRM_MODE_ROTATE_180:
6464 		plane_info->rotation = ROTATION_ANGLE_180;
6465 		break;
6466 	case DRM_MODE_ROTATE_270:
6467 		plane_info->rotation = ROTATION_ANGLE_270;
6468 		break;
6469 	default:
6470 		plane_info->rotation = ROTATION_ANGLE_0;
6471 		break;
6472 	}
6473 
6474 
6475 	plane_info->visible = true;
6476 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
6477 
6478 	plane_info->layer_index = plane_state->normalized_zpos;
6479 
6480 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
6481 					  &plane_info->color_space);
6482 	if (ret)
6483 		return ret;
6484 
6485 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
6486 					   plane_info->rotation, tiling_flags,
6487 					   &plane_info->tiling_info,
6488 					   &plane_info->plane_size,
6489 					   &plane_info->dcc, address,
6490 					   tmz_surface);
6491 	if (ret)
6492 		return ret;
6493 
6494 	amdgpu_dm_plane_fill_blending_from_plane_state(
6495 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
6496 		&plane_info->global_alpha, &plane_info->global_alpha_value);
6497 
6498 	return 0;
6499 }
6500 
6501 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
6502 				    struct dc_plane_state *dc_plane_state,
6503 				    struct drm_plane_state *plane_state,
6504 				    struct drm_crtc_state *crtc_state)
6505 {
6506 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6507 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
6508 	struct dc_scaling_info scaling_info;
6509 	struct dc_plane_info plane_info;
6510 	int ret;
6511 
6512 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
6513 	if (ret)
6514 		return ret;
6515 
6516 	dc_plane_state->src_rect = scaling_info.src_rect;
6517 	dc_plane_state->dst_rect = scaling_info.dst_rect;
6518 	dc_plane_state->clip_rect = scaling_info.clip_rect;
6519 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
6520 
6521 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
6522 					  afb->tiling_flags,
6523 					  &plane_info,
6524 					  &dc_plane_state->address,
6525 					  afb->tmz_surface);
6526 	if (ret)
6527 		return ret;
6528 
6529 	dc_plane_state->format = plane_info.format;
6530 	dc_plane_state->color_space = plane_info.color_space;
6531 	dc_plane_state->format = plane_info.format;
6532 	dc_plane_state->plane_size = plane_info.plane_size;
6533 	dc_plane_state->rotation = plane_info.rotation;
6534 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
6535 	dc_plane_state->stereo_format = plane_info.stereo_format;
6536 	dc_plane_state->tiling_info = plane_info.tiling_info;
6537 	dc_plane_state->visible = plane_info.visible;
6538 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
6539 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
6540 	dc_plane_state->global_alpha = plane_info.global_alpha;
6541 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
6542 	dc_plane_state->dcc = plane_info.dcc;
6543 	dc_plane_state->layer_index = plane_info.layer_index;
6544 	dc_plane_state->flip_int_enabled = true;
6545 
6546 	/*
6547 	 * Always set input transfer function, since plane state is refreshed
6548 	 * every time.
6549 	 */
6550 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
6551 						plane_state,
6552 						dc_plane_state);
6553 	if (ret)
6554 		return ret;
6555 
6556 	return 0;
6557 }
6558 
6559 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
6560 				      struct rect *dirty_rect, int32_t x,
6561 				      s32 y, s32 width, s32 height,
6562 				      int *i, bool ffu)
6563 {
6564 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
6565 
6566 	dirty_rect->x = x;
6567 	dirty_rect->y = y;
6568 	dirty_rect->width = width;
6569 	dirty_rect->height = height;
6570 
6571 	if (ffu)
6572 		drm_dbg(plane->dev,
6573 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
6574 			plane->base.id, width, height);
6575 	else
6576 		drm_dbg(plane->dev,
6577 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
6578 			plane->base.id, x, y, width, height);
6579 
6580 	(*i)++;
6581 }
6582 
6583 /**
6584  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
6585  *
6586  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
6587  *         remote fb
6588  * @old_plane_state: Old state of @plane
6589  * @new_plane_state: New state of @plane
6590  * @crtc_state: New state of CRTC connected to the @plane
6591  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
6592  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
6593  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
6594  *             that have changed will be updated. If PSR SU is not enabled,
6595  *             or if damage clips are not available, the entire screen will be updated.
6596  * @dirty_regions_changed: dirty regions changed
6597  *
6598  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
6599  * (referred to as "damage clips" in DRM nomenclature) that require updating on
6600  * the eDP remote buffer. The responsibility of specifying the dirty regions is
6601  * amdgpu_dm's.
6602  *
6603  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
6604  * plane with regions that require flushing to the eDP remote buffer. In
6605  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
6606  * implicitly provide damage clips without any client support via the plane
6607  * bounds.
6608  */
6609 static void fill_dc_dirty_rects(struct drm_plane *plane,
6610 				struct drm_plane_state *old_plane_state,
6611 				struct drm_plane_state *new_plane_state,
6612 				struct drm_crtc_state *crtc_state,
6613 				struct dc_flip_addrs *flip_addrs,
6614 				bool is_psr_su,
6615 				bool *dirty_regions_changed)
6616 {
6617 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6618 	struct rect *dirty_rects = flip_addrs->dirty_rects;
6619 	u32 num_clips = 0;
6620 	struct drm_mode_rect *clips = NULL;
6621 	bool bb_changed;
6622 	bool fb_changed;
6623 	u32 i = 0;
6624 	*dirty_regions_changed = false;
6625 
6626 	/*
6627 	 * Cursor plane has it's own dirty rect update interface. See
6628 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
6629 	 */
6630 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
6631 		return;
6632 
6633 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
6634 		goto ffu;
6635 
6636 	if (!new_plane_state->ignore_damage_clips) {
6637 		num_clips = drm_plane_get_damage_clips_count(new_plane_state);
6638 		clips = drm_plane_get_damage_clips(new_plane_state);
6639 	}
6640 
6641 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
6642 						   is_psr_su)))
6643 		goto ffu;
6644 
6645 	if (!dm_crtc_state->mpo_requested) {
6646 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
6647 			goto ffu;
6648 
6649 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
6650 			fill_dc_dirty_rect(new_plane_state->plane,
6651 					   &dirty_rects[flip_addrs->dirty_rect_count],
6652 					   clips->x1, clips->y1,
6653 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
6654 					   &flip_addrs->dirty_rect_count,
6655 					   false);
6656 		return;
6657 	}
6658 
6659 	/*
6660 	 * MPO is requested. Add entire plane bounding box to dirty rects if
6661 	 * flipped to or damaged.
6662 	 *
6663 	 * If plane is moved or resized, also add old bounding box to dirty
6664 	 * rects.
6665 	 */
6666 	fb_changed = old_plane_state->fb->base.id !=
6667 		     new_plane_state->fb->base.id;
6668 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
6669 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
6670 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
6671 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
6672 
6673 	drm_dbg(plane->dev,
6674 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
6675 		new_plane_state->plane->base.id,
6676 		bb_changed, fb_changed, num_clips);
6677 
6678 	*dirty_regions_changed = bb_changed;
6679 
6680 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
6681 		goto ffu;
6682 
6683 	if (bb_changed) {
6684 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6685 				   new_plane_state->crtc_x,
6686 				   new_plane_state->crtc_y,
6687 				   new_plane_state->crtc_w,
6688 				   new_plane_state->crtc_h, &i, false);
6689 
6690 		/* Add old plane bounding-box if plane is moved or resized */
6691 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6692 				   old_plane_state->crtc_x,
6693 				   old_plane_state->crtc_y,
6694 				   old_plane_state->crtc_w,
6695 				   old_plane_state->crtc_h, &i, false);
6696 	}
6697 
6698 	if (num_clips) {
6699 		for (; i < num_clips; clips++)
6700 			fill_dc_dirty_rect(new_plane_state->plane,
6701 					   &dirty_rects[i], clips->x1,
6702 					   clips->y1, clips->x2 - clips->x1,
6703 					   clips->y2 - clips->y1, &i, false);
6704 	} else if (fb_changed && !bb_changed) {
6705 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6706 				   new_plane_state->crtc_x,
6707 				   new_plane_state->crtc_y,
6708 				   new_plane_state->crtc_w,
6709 				   new_plane_state->crtc_h, &i, false);
6710 	}
6711 
6712 	flip_addrs->dirty_rect_count = i;
6713 	return;
6714 
6715 ffu:
6716 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
6717 			   dm_crtc_state->base.mode.crtc_hdisplay,
6718 			   dm_crtc_state->base.mode.crtc_vdisplay,
6719 			   &flip_addrs->dirty_rect_count, true);
6720 }
6721 
6722 static void update_stream_scaling_settings(struct drm_device *dev,
6723 					   const struct drm_display_mode *mode,
6724 					   const struct dm_connector_state *dm_state,
6725 					   struct dc_stream_state *stream)
6726 {
6727 	enum amdgpu_rmx_type rmx_type;
6728 
6729 	struct rect src = { 0 }; /* viewport in composition space*/
6730 	struct rect dst = { 0 }; /* stream addressable area */
6731 
6732 	/* no mode. nothing to be done */
6733 	if (!mode)
6734 		return;
6735 
6736 	/* Full screen scaling by default */
6737 	src.width = mode->hdisplay;
6738 	src.height = mode->vdisplay;
6739 	dst.width = stream->timing.h_addressable;
6740 	dst.height = stream->timing.v_addressable;
6741 
6742 	if (dm_state) {
6743 		rmx_type = dm_state->scaling;
6744 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
6745 			if (src.width * dst.height <
6746 					src.height * dst.width) {
6747 				/* height needs less upscaling/more downscaling */
6748 				dst.width = src.width *
6749 						dst.height / src.height;
6750 			} else {
6751 				/* width needs less upscaling/more downscaling */
6752 				dst.height = src.height *
6753 						dst.width / src.width;
6754 			}
6755 		} else if (rmx_type == RMX_CENTER) {
6756 			dst = src;
6757 		}
6758 
6759 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
6760 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
6761 
6762 		if (dm_state->underscan_enable) {
6763 			dst.x += dm_state->underscan_hborder / 2;
6764 			dst.y += dm_state->underscan_vborder / 2;
6765 			dst.width -= dm_state->underscan_hborder;
6766 			dst.height -= dm_state->underscan_vborder;
6767 		}
6768 	}
6769 
6770 	stream->src = src;
6771 	stream->dst = dst;
6772 
6773 	drm_dbg_kms(dev, "Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
6774 		    dst.x, dst.y, dst.width, dst.height);
6775 
6776 }
6777 
6778 static enum dc_color_depth
6779 convert_color_depth_from_display_info(const struct drm_connector *connector,
6780 				      bool is_y420, int requested_bpc)
6781 {
6782 	u8 bpc;
6783 
6784 	if (is_y420) {
6785 		bpc = 8;
6786 
6787 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
6788 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
6789 			bpc = 16;
6790 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
6791 			bpc = 12;
6792 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
6793 			bpc = 10;
6794 	} else {
6795 		bpc = (uint8_t)connector->display_info.bpc;
6796 		/* Assume 8 bpc by default if no bpc is specified. */
6797 		bpc = bpc ? bpc : 8;
6798 	}
6799 
6800 	if (requested_bpc > 0) {
6801 		/*
6802 		 * Cap display bpc based on the user requested value.
6803 		 *
6804 		 * The value for state->max_bpc may not correctly updated
6805 		 * depending on when the connector gets added to the state
6806 		 * or if this was called outside of atomic check, so it
6807 		 * can't be used directly.
6808 		 */
6809 		bpc = min_t(u8, bpc, requested_bpc);
6810 
6811 		/* Round down to the nearest even number. */
6812 		bpc = bpc - (bpc & 1);
6813 	}
6814 
6815 	switch (bpc) {
6816 	case 0:
6817 		/*
6818 		 * Temporary Work around, DRM doesn't parse color depth for
6819 		 * EDID revision before 1.4
6820 		 * TODO: Fix edid parsing
6821 		 */
6822 		return COLOR_DEPTH_888;
6823 	case 6:
6824 		return COLOR_DEPTH_666;
6825 	case 8:
6826 		return COLOR_DEPTH_888;
6827 	case 10:
6828 		return COLOR_DEPTH_101010;
6829 	case 12:
6830 		return COLOR_DEPTH_121212;
6831 	case 14:
6832 		return COLOR_DEPTH_141414;
6833 	case 16:
6834 		return COLOR_DEPTH_161616;
6835 	default:
6836 		return COLOR_DEPTH_UNDEFINED;
6837 	}
6838 }
6839 
6840 static enum dc_aspect_ratio
6841 get_aspect_ratio(const struct drm_display_mode *mode_in)
6842 {
6843 	/* 1-1 mapping, since both enums follow the HDMI spec. */
6844 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
6845 }
6846 
6847 static enum dc_color_space
6848 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
6849 		       const struct drm_connector_state *connector_state)
6850 {
6851 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
6852 
6853 	switch (connector_state->colorspace) {
6854 	case DRM_MODE_COLORIMETRY_BT601_YCC:
6855 		if (dc_crtc_timing->flags.Y_ONLY)
6856 			color_space = COLOR_SPACE_YCBCR601_LIMITED;
6857 		else
6858 			color_space = COLOR_SPACE_YCBCR601;
6859 		break;
6860 	case DRM_MODE_COLORIMETRY_BT709_YCC:
6861 		if (dc_crtc_timing->flags.Y_ONLY)
6862 			color_space = COLOR_SPACE_YCBCR709_LIMITED;
6863 		else
6864 			color_space = COLOR_SPACE_YCBCR709;
6865 		break;
6866 	case DRM_MODE_COLORIMETRY_OPRGB:
6867 		color_space = COLOR_SPACE_ADOBERGB;
6868 		break;
6869 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
6870 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
6871 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
6872 			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
6873 		else
6874 			color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6875 		break;
6876 	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
6877 	default:
6878 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
6879 			color_space = COLOR_SPACE_SRGB;
6880 			if (connector_state->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_LIMITED)
6881 				color_space = COLOR_SPACE_SRGB_LIMITED;
6882 		/*
6883 		 * 27030khz is the separation point between HDTV and SDTV
6884 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
6885 		 * respectively
6886 		 */
6887 		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
6888 			if (dc_crtc_timing->flags.Y_ONLY)
6889 				color_space =
6890 					COLOR_SPACE_YCBCR709_LIMITED;
6891 			else
6892 				color_space = COLOR_SPACE_YCBCR709;
6893 		} else {
6894 			if (dc_crtc_timing->flags.Y_ONLY)
6895 				color_space =
6896 					COLOR_SPACE_YCBCR601_LIMITED;
6897 			else
6898 				color_space = COLOR_SPACE_YCBCR601;
6899 		}
6900 		break;
6901 	}
6902 
6903 	return color_space;
6904 }
6905 
6906 static enum display_content_type
6907 get_output_content_type(const struct drm_connector_state *connector_state)
6908 {
6909 	switch (connector_state->content_type) {
6910 	default:
6911 	case DRM_MODE_CONTENT_TYPE_NO_DATA:
6912 		return DISPLAY_CONTENT_TYPE_NO_DATA;
6913 	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
6914 		return DISPLAY_CONTENT_TYPE_GRAPHICS;
6915 	case DRM_MODE_CONTENT_TYPE_PHOTO:
6916 		return DISPLAY_CONTENT_TYPE_PHOTO;
6917 	case DRM_MODE_CONTENT_TYPE_CINEMA:
6918 		return DISPLAY_CONTENT_TYPE_CINEMA;
6919 	case DRM_MODE_CONTENT_TYPE_GAME:
6920 		return DISPLAY_CONTENT_TYPE_GAME;
6921 	}
6922 }
6923 
6924 static bool adjust_colour_depth_from_display_info(
6925 	struct dc_crtc_timing *timing_out,
6926 	const struct drm_display_info *info)
6927 {
6928 	enum dc_color_depth depth = timing_out->display_color_depth;
6929 	int normalized_clk;
6930 
6931 	do {
6932 		normalized_clk = timing_out->pix_clk_100hz / 10;
6933 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
6934 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
6935 			normalized_clk /= 2;
6936 		/* Adjusting pix clock following on HDMI spec based on colour depth */
6937 		switch (depth) {
6938 		case COLOR_DEPTH_888:
6939 			break;
6940 		case COLOR_DEPTH_101010:
6941 			normalized_clk = (normalized_clk * 30) / 24;
6942 			break;
6943 		case COLOR_DEPTH_121212:
6944 			normalized_clk = (normalized_clk * 36) / 24;
6945 			break;
6946 		case COLOR_DEPTH_161616:
6947 			normalized_clk = (normalized_clk * 48) / 24;
6948 			break;
6949 		default:
6950 			/* The above depths are the only ones valid for HDMI. */
6951 			return false;
6952 		}
6953 		if (normalized_clk <= info->max_tmds_clock) {
6954 			timing_out->display_color_depth = depth;
6955 			return true;
6956 		}
6957 	} while (--depth > COLOR_DEPTH_666);
6958 	return false;
6959 }
6960 
6961 static void fill_stream_properties_from_drm_display_mode(
6962 	struct dc_stream_state *stream,
6963 	const struct drm_display_mode *mode_in,
6964 	const struct drm_connector *connector,
6965 	const struct drm_connector_state *connector_state,
6966 	const struct dc_stream_state *old_stream,
6967 	int requested_bpc)
6968 {
6969 	struct dc_crtc_timing *timing_out = &stream->timing;
6970 	const struct drm_display_info *info = &connector->display_info;
6971 	struct amdgpu_dm_connector *aconnector = NULL;
6972 	struct hdmi_vendor_infoframe hv_frame;
6973 	struct hdmi_avi_infoframe avi_frame;
6974 	ssize_t err;
6975 
6976 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
6977 		aconnector = to_amdgpu_dm_connector(connector);
6978 
6979 	memset(&hv_frame, 0, sizeof(hv_frame));
6980 	memset(&avi_frame, 0, sizeof(avi_frame));
6981 
6982 	timing_out->h_border_left = 0;
6983 	timing_out->h_border_right = 0;
6984 	timing_out->v_border_top = 0;
6985 	timing_out->v_border_bottom = 0;
6986 	/* TODO: un-hardcode */
6987 	if (drm_mode_is_420_only(info, mode_in)
6988 			&& (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
6989 			    stream->signal == SIGNAL_TYPE_HDMI_FRL)
6990 			&& aconnector
6991 			&& aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR420)
6992 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6993 	else if (drm_mode_is_420_also(info, mode_in)
6994 			&& aconnector
6995 			&& (aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR420
6996 			|| aconnector->force_yuv420_output))
6997 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6998 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR422))
6999 			&& aconnector
7000 			&& (aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR422
7001 			|| aconnector->force_yuv422_output))
7002 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR422;
7003 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR444))
7004 			&& (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7005 			    stream->signal == SIGNAL_TYPE_HDMI_FRL)
7006 			&& aconnector
7007 			&& aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR444)
7008 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
7009 	else
7010 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
7011 
7012 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
7013 	timing_out->display_color_depth = convert_color_depth_from_display_info(
7014 		connector,
7015 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
7016 		requested_bpc);
7017 	timing_out->scan_type = SCANNING_TYPE_NODATA;
7018 	timing_out->hdmi_vic = 0;
7019 
7020 	if (old_stream) {
7021 		timing_out->vic = old_stream->timing.vic;
7022 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
7023 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
7024 	} else {
7025 		timing_out->vic = drm_match_cea_mode(mode_in);
7026 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
7027 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
7028 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
7029 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
7030 	}
7031 
7032 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7033 		stream->signal == SIGNAL_TYPE_HDMI_FRL) {
7034 		err = drm_hdmi_avi_infoframe_from_display_mode(&avi_frame,
7035 							       (struct drm_connector *)connector,
7036 							       mode_in);
7037 		if (err < 0)
7038 			drm_warn_once(connector->dev, "Failed to setup avi infoframe on connector %s: %zd\n",
7039 				      connector->name, err);
7040 		timing_out->vic = avi_frame.video_code;
7041 		err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame,
7042 								  (struct drm_connector *)connector,
7043 								  mode_in);
7044 		if (err < 0)
7045 			drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n",
7046 				      connector->name, err);
7047 		timing_out->hdmi_vic = hv_frame.vic;
7048 	}
7049 
7050 	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
7051 		timing_out->h_addressable = mode_in->hdisplay;
7052 		timing_out->h_total = mode_in->htotal;
7053 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
7054 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
7055 		timing_out->v_total = mode_in->vtotal;
7056 		timing_out->v_addressable = mode_in->vdisplay;
7057 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
7058 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
7059 		timing_out->pix_clk_100hz = mode_in->clock * 10;
7060 	} else {
7061 		timing_out->h_addressable = mode_in->crtc_hdisplay;
7062 		timing_out->h_total = mode_in->crtc_htotal;
7063 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
7064 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
7065 		timing_out->v_total = mode_in->crtc_vtotal;
7066 		timing_out->v_addressable = mode_in->crtc_vdisplay;
7067 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
7068 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
7069 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
7070 	}
7071 
7072 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
7073 
7074 	stream->out_transfer_func.type = TF_TYPE_PREDEFINED;
7075 	stream->out_transfer_func.tf = TRANSFER_FUNCTION_SRGB;
7076 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
7077 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
7078 		    drm_mode_is_420_also(info, mode_in) &&
7079 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
7080 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
7081 			adjust_colour_depth_from_display_info(timing_out, info);
7082 		}
7083 	}
7084 
7085 	stream->output_color_space = get_output_color_space(timing_out, connector_state);
7086 	stream->content_type = get_output_content_type(connector_state);
7087 }
7088 
7089 static void fill_audio_info(struct audio_info *audio_info,
7090 			    const struct drm_connector *drm_connector,
7091 			    const struct dc_sink *dc_sink)
7092 {
7093 	int i = 0;
7094 	int cea_revision = 0;
7095 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
7096 
7097 	audio_info->manufacture_id = edid_caps->manufacturer_id;
7098 	audio_info->product_id = edid_caps->product_id;
7099 
7100 	cea_revision = drm_connector->display_info.cea_rev;
7101 
7102 	strscpy(audio_info->display_name,
7103 		edid_caps->display_name,
7104 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
7105 
7106 	if (cea_revision >= 3) {
7107 		audio_info->mode_count = edid_caps->audio_mode_count;
7108 
7109 		for (i = 0; i < audio_info->mode_count; ++i) {
7110 			audio_info->modes[i].format_code =
7111 					(enum audio_format_code)
7112 					(edid_caps->audio_modes[i].format_code);
7113 			audio_info->modes[i].channel_count =
7114 					edid_caps->audio_modes[i].channel_count;
7115 			audio_info->modes[i].sample_rates.all =
7116 					edid_caps->audio_modes[i].sample_rate;
7117 			audio_info->modes[i].sample_size =
7118 					edid_caps->audio_modes[i].sample_size;
7119 		}
7120 	}
7121 
7122 	audio_info->flags.all = edid_caps->speaker_flags;
7123 
7124 	/* TODO: We only check for the progressive mode, check for interlace mode too */
7125 	if (drm_connector->latency_present[0]) {
7126 		audio_info->video_latency = drm_connector->video_latency[0];
7127 		audio_info->audio_latency = drm_connector->audio_latency[0];
7128 	}
7129 
7130 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
7131 
7132 }
7133 
7134 static void
7135 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
7136 				      struct drm_display_mode *dst_mode)
7137 {
7138 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
7139 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
7140 	dst_mode->crtc_clock = src_mode->crtc_clock;
7141 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
7142 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
7143 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
7144 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
7145 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
7146 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
7147 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
7148 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
7149 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
7150 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
7151 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
7152 }
7153 
7154 static void
7155 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
7156 					const struct drm_display_mode *native_mode,
7157 					bool scale_enabled)
7158 {
7159 	if (scale_enabled || (
7160 	    native_mode->clock == drm_mode->clock &&
7161 	    native_mode->htotal == drm_mode->htotal &&
7162 	    native_mode->vtotal == drm_mode->vtotal)) {
7163 		if (native_mode->crtc_clock)
7164 			copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
7165 	} else {
7166 		/* no scaling nor amdgpu inserted, no need to patch */
7167 	}
7168 }
7169 
7170 static struct dc_sink *
7171 create_fake_sink(struct drm_device *dev, struct dc_link *link)
7172 {
7173 	struct dc_sink_init_data sink_init_data = { 0 };
7174 	struct dc_sink *sink = NULL;
7175 
7176 	sink_init_data.link = link;
7177 	sink_init_data.sink_signal = link->connector_signal;
7178 
7179 	sink = dc_sink_create(&sink_init_data);
7180 	if (!sink) {
7181 		drm_err(dev, "Failed to create sink!\n");
7182 		return NULL;
7183 	}
7184 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
7185 
7186 	return sink;
7187 }
7188 
7189 static void set_multisync_trigger_params(
7190 		struct dc_stream_state *stream)
7191 {
7192 	struct dc_stream_state *master = NULL;
7193 
7194 	if (stream->triggered_crtc_reset.enabled) {
7195 		master = stream->triggered_crtc_reset.event_source;
7196 		stream->triggered_crtc_reset.event =
7197 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
7198 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
7199 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
7200 	}
7201 }
7202 
7203 static void set_master_stream(struct dc_stream_state *stream_set[],
7204 			      int stream_count)
7205 {
7206 	int j, highest_rfr = 0, master_stream = 0;
7207 
7208 	for (j = 0;  j < stream_count; j++) {
7209 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
7210 			int refresh_rate = 0;
7211 
7212 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
7213 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
7214 			if (refresh_rate > highest_rfr) {
7215 				highest_rfr = refresh_rate;
7216 				master_stream = j;
7217 			}
7218 		}
7219 	}
7220 	for (j = 0;  j < stream_count; j++) {
7221 		if (stream_set[j])
7222 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
7223 	}
7224 }
7225 
7226 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
7227 {
7228 	int i = 0;
7229 	struct dc_stream_state *stream;
7230 
7231 	if (context->stream_count < 2)
7232 		return;
7233 	for (i = 0; i < context->stream_count ; i++) {
7234 		if (!context->streams[i])
7235 			continue;
7236 		/*
7237 		 * TODO: add a function to read AMD VSDB bits and set
7238 		 * crtc_sync_master.multi_sync_enabled flag
7239 		 * For now it's set to false
7240 		 */
7241 	}
7242 
7243 	set_master_stream(context->streams, context->stream_count);
7244 
7245 	for (i = 0; i < context->stream_count ; i++) {
7246 		stream = context->streams[i];
7247 
7248 		if (!stream)
7249 			continue;
7250 
7251 		set_multisync_trigger_params(stream);
7252 	}
7253 }
7254 
7255 /**
7256  * DOC: FreeSync Video
7257  *
7258  * When a userspace application wants to play a video, the content follows a
7259  * standard format definition that usually specifies the FPS for that format.
7260  * The below list illustrates some video format and the expected FPS,
7261  * respectively:
7262  *
7263  * - TV/NTSC (23.976 FPS)
7264  * - Cinema (24 FPS)
7265  * - TV/PAL (25 FPS)
7266  * - TV/NTSC (29.97 FPS)
7267  * - TV/NTSC (30 FPS)
7268  * - Cinema HFR (48 FPS)
7269  * - TV/PAL (50 FPS)
7270  * - Commonly used (60 FPS)
7271  * - Multiples of 24 (48,72,96 FPS)
7272  *
7273  * The list of standards video format is not huge and can be added to the
7274  * connector modeset list beforehand. With that, userspace can leverage
7275  * FreeSync to extends the front porch in order to attain the target refresh
7276  * rate. Such a switch will happen seamlessly, without screen blanking or
7277  * reprogramming of the output in any other way. If the userspace requests a
7278  * modesetting change compatible with FreeSync modes that only differ in the
7279  * refresh rate, DC will skip the full update and avoid blink during the
7280  * transition. For example, the video player can change the modesetting from
7281  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
7282  * causing any display blink. This same concept can be applied to a mode
7283  * setting change.
7284  */
7285 static struct drm_display_mode *
7286 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
7287 		bool use_probed_modes)
7288 {
7289 	struct drm_display_mode *m, *m_pref = NULL;
7290 	u16 current_refresh, highest_refresh;
7291 	struct list_head *list_head = use_probed_modes ?
7292 		&aconnector->base.probed_modes :
7293 		&aconnector->base.modes;
7294 
7295 	if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
7296 		return NULL;
7297 
7298 	if (aconnector->freesync_vid_base.clock != 0)
7299 		return &aconnector->freesync_vid_base;
7300 
7301 	/* Find the preferred mode */
7302 	list_for_each_entry(m, list_head, head) {
7303 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
7304 			m_pref = m;
7305 			break;
7306 		}
7307 	}
7308 
7309 	if (!m_pref) {
7310 		/* Probably an EDID with no preferred mode. Fallback to first entry */
7311 		m_pref = list_first_entry_or_null(
7312 				&aconnector->base.modes, struct drm_display_mode, head);
7313 		if (!m_pref) {
7314 			drm_dbg_driver(aconnector->base.dev, "No preferred mode found in EDID\n");
7315 			return NULL;
7316 		}
7317 	}
7318 
7319 	highest_refresh = drm_mode_vrefresh(m_pref);
7320 
7321 	/*
7322 	 * Find the mode with highest refresh rate with same resolution.
7323 	 * For some monitors, preferred mode is not the mode with highest
7324 	 * supported refresh rate.
7325 	 */
7326 	list_for_each_entry(m, list_head, head) {
7327 		current_refresh  = drm_mode_vrefresh(m);
7328 
7329 		if (m->hdisplay == m_pref->hdisplay &&
7330 		    m->vdisplay == m_pref->vdisplay &&
7331 		    highest_refresh < current_refresh) {
7332 			highest_refresh = current_refresh;
7333 			m_pref = m;
7334 		}
7335 	}
7336 
7337 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
7338 	return m_pref;
7339 }
7340 
7341 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
7342 		struct amdgpu_dm_connector *aconnector)
7343 {
7344 	struct drm_display_mode *high_mode;
7345 	int timing_diff;
7346 
7347 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
7348 	if (!high_mode || !mode)
7349 		return false;
7350 
7351 	timing_diff = high_mode->vtotal - mode->vtotal;
7352 
7353 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
7354 	    high_mode->hdisplay != mode->hdisplay ||
7355 	    high_mode->vdisplay != mode->vdisplay ||
7356 	    high_mode->hsync_start != mode->hsync_start ||
7357 	    high_mode->hsync_end != mode->hsync_end ||
7358 	    high_mode->htotal != mode->htotal ||
7359 	    high_mode->hskew != mode->hskew ||
7360 	    high_mode->vscan != mode->vscan ||
7361 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
7362 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
7363 		return false;
7364 	else
7365 		return true;
7366 }
7367 
7368 #if defined(CONFIG_DRM_AMD_DC_FP)
7369 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
7370 			    struct dc_sink *sink, struct dc_stream_state *stream,
7371 			    struct dsc_dec_dpcd_caps *dsc_caps)
7372 {
7373 	stream->timing.flags.DSC = 0;
7374 	dsc_caps->is_dsc_supported = false;
7375 
7376 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
7377 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
7378 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE)
7379 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7380 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7381 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7382 				dsc_caps);
7383 		else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7384 			if (aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.fields.dsc_support.DSC_PASSTHROUGH_SUPPORT &&
7385 					!aconnector->dsc_settings.dsc_force_disable_passthrough &&
7386 					aconnector->dc_link->dpcd_caps.dongle_caps.dp_hdmi_frl_max_link_bw_in_kbps > 0 &&
7387 					sink->edid_caps.frl_dsc_support &&
7388 					sink->edid_caps.max_frl_rate > 0 &&
7389 					sink->edid_caps.frl_dsc_max_frl_rate > 0)
7390 				dc_dsc_parse_dsc_edid(aconnector->dc_link->ctx->dc, &sink->edid_caps, dsc_caps);
7391 			else
7392 				dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7393 				      aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7394 				      aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7395 				      dsc_caps);
7396 		}
7397 	} else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_HDMI_FRL) {
7398 		if (sink->edid_caps.frl_dsc_support &&
7399 				sink->edid_caps.max_frl_rate > 0 &&
7400 				sink->edid_caps.frl_dsc_max_frl_rate > 0)
7401 			dc_dsc_parse_dsc_edid(aconnector->dc_link->ctx->dc, &sink->edid_caps, dsc_caps);
7402 	}
7403 }
7404 
7405 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
7406 				    struct dc_sink *sink, struct dc_stream_state *stream,
7407 				    struct dsc_dec_dpcd_caps *dsc_caps,
7408 				    uint32_t max_dsc_target_bpp_limit_override)
7409 {
7410 	const struct dc_link_settings *verified_link_cap = NULL;
7411 	u32 link_bw_in_kbps;
7412 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
7413 	struct dc *dc = sink->ctx->dc;
7414 	struct dc_dsc_bw_range bw_range = {0};
7415 	struct dc_dsc_config dsc_cfg = {0};
7416 	struct dc_dsc_config_options dsc_options = {0};
7417 
7418 	dc_dsc_get_default_config_option(dc, &dsc_options);
7419 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7420 
7421 	verified_link_cap = dc_link_get_link_cap(stream->link);
7422 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
7423 	edp_min_bpp_x16 = 8 * 16;
7424 	edp_max_bpp_x16 = 8 * 16;
7425 
7426 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
7427 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
7428 
7429 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
7430 		edp_min_bpp_x16 = edp_max_bpp_x16;
7431 
7432 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
7433 				dc->debug.dsc_min_slice_height_override,
7434 				edp_min_bpp_x16, edp_max_bpp_x16,
7435 				dsc_caps,
7436 				&stream->timing,
7437 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7438 				&bw_range)) {
7439 
7440 		if (bw_range.max_kbps < link_bw_in_kbps) {
7441 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7442 					dsc_caps,
7443 					&dsc_options,
7444 					0,
7445 					&stream->timing,
7446 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7447 					&dsc_cfg)) {
7448 				stream->timing.dsc_cfg = dsc_cfg;
7449 				stream->timing.flags.DSC = 1;
7450 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
7451 			}
7452 			return;
7453 		}
7454 	}
7455 
7456 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7457 				dsc_caps,
7458 				&dsc_options,
7459 				link_bw_in_kbps,
7460 				&stream->timing,
7461 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7462 				&dsc_cfg)) {
7463 		stream->timing.dsc_cfg = dsc_cfg;
7464 		stream->timing.flags.DSC = 1;
7465 	}
7466 }
7467 
7468 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
7469 					struct dc_sink *sink, struct dc_stream_state *stream,
7470 					struct dsc_dec_dpcd_caps *dsc_caps)
7471 {
7472 	struct drm_connector *drm_connector = &aconnector->base;
7473 	u32 link_bandwidth_kbps;
7474 	struct dc *dc = sink->ctx->dc;
7475 	const struct dc_hdmi_frl_link_settings *frl_verified_link_cap = NULL;
7476 	u32 converter_bw_in_kbps;
7477 	u32 sink_bw_in_kbps;
7478 	u32 dsc_sink_bw_in_kbps;
7479 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
7480 	u32 dsc_max_supported_bw_in_kbps;
7481 	u32 max_dsc_target_bpp_limit_override =
7482 		drm_connector->display_info.max_dsc_bpp;
7483 	struct dc_dsc_config_options dsc_options = {0};
7484 
7485 	dc_dsc_get_default_config_option(dc, &dsc_options);
7486 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7487 
7488 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
7489 							dc_link_get_link_cap(aconnector->dc_link));
7490 
7491 	/* Set DSC policy according to dsc_clock_en */
7492 	dc_dsc_policy_set_enable_dsc_when_not_needed(
7493 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
7494 
7495 	if (sink->sink_signal == SIGNAL_TYPE_EDP &&
7496 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
7497 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
7498 
7499 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
7500 
7501 	} else if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
7502 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
7503 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7504 						dsc_caps,
7505 						&dsc_options,
7506 						link_bandwidth_kbps,
7507 						&stream->timing,
7508 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7509 						&stream->timing.dsc_cfg)) {
7510 				stream->timing.flags.DSC = 1;
7511 				drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from SST RX\n",
7512 							__func__, drm_connector->name);
7513 			}
7514 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7515 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
7516 					dc_link_get_highest_encoding_format(aconnector->dc_link));
7517 			converter_bw_in_kbps = aconnector->dc_link->dpcd_caps.dongle_caps.dp_hdmi_frl_max_link_bw_in_kbps;
7518 			sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.max_frl_rate);
7519 			dsc_sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.frl_dsc_max_frl_rate);
7520 
7521 			if (dsc_caps->is_frl) {
7522 				max_supported_bw_in_kbps = min(link_bandwidth_kbps, converter_bw_in_kbps);
7523 				max_supported_bw_in_kbps = min(max_supported_bw_in_kbps, sink_bw_in_kbps);
7524 				dsc_max_supported_bw_in_kbps = min(max_supported_bw_in_kbps, dsc_sink_bw_in_kbps);
7525 			} else {
7526 				max_supported_bw_in_kbps = link_bandwidth_kbps;
7527 				dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
7528 			}
7529 
7530 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
7531 					max_supported_bw_in_kbps > 0 &&
7532 					dsc_max_supported_bw_in_kbps > 0)
7533 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7534 						dsc_caps,
7535 						&dsc_options,
7536 						dsc_max_supported_bw_in_kbps,
7537 						&stream->timing,
7538 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7539 						&stream->timing.dsc_cfg)) {
7540 					stream->timing.flags.DSC = 1;
7541 					drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from %s\n",
7542 							__func__, drm_connector->name,
7543 							(dsc_caps->is_frl == 1) ? "HDMI FRL RX" : "DP-HDMI PCON");
7544 				}
7545 		}
7546 	}
7547 	else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_HDMI_FRL) {
7548 		struct dc_dsc_policy dsc_policy = {0};
7549 
7550 		frl_verified_link_cap = dc_link_get_frl_link_cap(stream->link);
7551 		if (frl_verified_link_cap->frl_link_rate != HDMI_FRL_LINK_RATE_DISABLE &&
7552 			aconnector->dc_link->frl_flags.force_frl_dsc) {
7553 			dc_dsc_policy_set_enable_dsc_when_not_needed(true);
7554 			dc_dsc_get_policy_for_timing(&stream->timing, 0, &dsc_policy, dc_link_get_highest_encoding_format(stream->link));
7555 		}
7556 
7557 		timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing, DC_LINK_ENCODING_HDMI_FRL);
7558 		link_bandwidth_kbps = dc_link_frl_bandwidth_kbps(stream->link, frl_verified_link_cap->frl_link_rate);
7559 		dsc_sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.frl_dsc_max_frl_rate);
7560 
7561 		if ((timing_bw_in_kbps > link_bandwidth_kbps && dsc_sink_bw_in_kbps > 0) ||
7562 		    (dsc_policy.enable_dsc_when_not_needed || dsc_options.force_dsc_when_not_needed)) {
7563 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7564 					dsc_caps,
7565 					&dsc_options,
7566 					dsc_sink_bw_in_kbps,
7567 					&stream->timing,
7568 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7569 					&stream->timing.dsc_cfg)) {
7570 				stream->timing.flags.DSC = 1;
7571 				drm_dbg_driver(drm_connector->dev, "%s: HDMI_FRL_DSC [%s] DSC is selected from HDMI FRL RX\n",
7572 						__func__, drm_connector->name);
7573 			}
7574 		}
7575 	}
7576 
7577 	/* Overwrite the stream flag if DSC is enabled through debugfs */
7578 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
7579 		stream->timing.flags.DSC = 1;
7580 
7581 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
7582 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
7583 
7584 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
7585 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
7586 
7587 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
7588 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
7589 }
7590 #endif
7591 
7592 static struct dc_stream_state *
7593 create_stream_for_sink(struct drm_connector *connector,
7594 		       const struct drm_display_mode *drm_mode,
7595 		       const struct dm_connector_state *dm_state,
7596 		       const struct dc_stream_state *old_stream,
7597 		       int requested_bpc)
7598 {
7599 	struct drm_device *dev = connector->dev;
7600 	struct amdgpu_dm_connector *aconnector = NULL;
7601 	struct drm_display_mode *preferred_mode = NULL;
7602 	const struct drm_connector_state *con_state = &dm_state->base;
7603 	struct dc_stream_state *stream = NULL;
7604 	struct drm_display_mode mode;
7605 	struct drm_display_mode saved_mode;
7606 	struct drm_display_mode *freesync_mode = NULL;
7607 	bool native_mode_found = false;
7608 	bool recalculate_timing = false;
7609 	bool scale = dm_state->scaling != RMX_OFF;
7610 	int mode_refresh;
7611 	int preferred_refresh = 0;
7612 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
7613 #if defined(CONFIG_DRM_AMD_DC_FP)
7614 	struct dsc_dec_dpcd_caps dsc_caps = {0};
7615 #endif
7616 	struct dc_link *link = NULL;
7617 	struct dc_sink *sink = NULL;
7618 
7619 	drm_mode_init(&mode, drm_mode);
7620 	memset(&saved_mode, 0, sizeof(saved_mode));
7621 
7622 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK) {
7623 		aconnector = NULL;
7624 		aconnector = to_amdgpu_dm_connector(connector);
7625 		link = aconnector->dc_link;
7626 	} else {
7627 		struct drm_writeback_connector *wbcon = NULL;
7628 		struct amdgpu_dm_wb_connector *dm_wbcon = NULL;
7629 
7630 		wbcon = drm_connector_to_writeback(connector);
7631 		dm_wbcon = to_amdgpu_dm_wb_connector(wbcon);
7632 		link = dm_wbcon->link;
7633 	}
7634 
7635 	if (!aconnector || !aconnector->dc_sink) {
7636 		sink = create_fake_sink(dev, link);
7637 		if (!sink)
7638 			return stream;
7639 
7640 	} else {
7641 		sink = aconnector->dc_sink;
7642 		dc_sink_retain(sink);
7643 	}
7644 
7645 	stream = dc_create_stream_for_sink(sink);
7646 
7647 	if (stream == NULL) {
7648 		drm_err(dev, "Failed to create stream for sink!\n");
7649 		goto finish;
7650 	}
7651 
7652 	/* We leave this NULL for writeback connectors */
7653 	stream->dm_stream_context = aconnector;
7654 
7655 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
7656 		connector->display_info.hdmi.scdc.scrambling.low_rates;
7657 
7658 	list_for_each_entry(preferred_mode, &connector->modes, head) {
7659 		/* Search for preferred mode */
7660 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
7661 			native_mode_found = true;
7662 			break;
7663 		}
7664 	}
7665 	if (!native_mode_found)
7666 		preferred_mode = list_first_entry_or_null(
7667 				&connector->modes,
7668 				struct drm_display_mode,
7669 				head);
7670 
7671 	mode_refresh = drm_mode_vrefresh(&mode);
7672 
7673 	if (preferred_mode == NULL) {
7674 		/*
7675 		 * This may not be an error, the use case is when we have no
7676 		 * usermode calls to reset and set mode upon hotplug. In this
7677 		 * case, we call set mode ourselves to restore the previous mode
7678 		 * and the modelist may not be filled in time.
7679 		 */
7680 		drm_dbg_driver(dev, "No preferred mode found\n");
7681 	} else if (aconnector) {
7682 		recalculate_timing = amdgpu_freesync_vid_mode &&
7683 				 is_freesync_video_mode(&mode, aconnector);
7684 		if (recalculate_timing) {
7685 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
7686 			drm_mode_copy(&saved_mode, &mode);
7687 			saved_mode.picture_aspect_ratio = mode.picture_aspect_ratio;
7688 			drm_mode_copy(&mode, freesync_mode);
7689 			mode.picture_aspect_ratio = saved_mode.picture_aspect_ratio;
7690 		} else {
7691 			decide_crtc_timing_for_drm_display_mode(
7692 					&mode, preferred_mode, scale);
7693 
7694 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
7695 		}
7696 	}
7697 
7698 	if (recalculate_timing)
7699 		drm_mode_set_crtcinfo(&saved_mode, 0);
7700 
7701 	/*
7702 	 * If scaling is enabled and refresh rate didn't change
7703 	 * we copy the vic and polarities of the old timings
7704 	 */
7705 	if (!scale || mode_refresh != preferred_refresh)
7706 		fill_stream_properties_from_drm_display_mode(
7707 			stream, &mode, connector, con_state, NULL,
7708 			requested_bpc);
7709 	else
7710 		fill_stream_properties_from_drm_display_mode(
7711 			stream, &mode, connector, con_state, old_stream,
7712 			requested_bpc);
7713 
7714 	/* The rest isn't needed for writeback connectors */
7715 	if (!aconnector)
7716 		goto finish;
7717 
7718 	if (aconnector->timing_changed) {
7719 		drm_dbg(aconnector->base.dev,
7720 			"overriding timing for automated test, bpc %d, changing to %d\n",
7721 			stream->timing.display_color_depth,
7722 			aconnector->timing_requested->display_color_depth);
7723 		stream->timing = *aconnector->timing_requested;
7724 	}
7725 
7726 #if defined(CONFIG_DRM_AMD_DC_FP)
7727 	/* SST DSC determination policy */
7728 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
7729 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
7730 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
7731 #endif
7732 
7733 	update_stream_scaling_settings(dev, &mode, dm_state, stream);
7734 
7735 	fill_audio_info(
7736 		&stream->audio_info,
7737 		connector,
7738 		sink);
7739 
7740 	update_stream_signal(stream, sink);
7741 
7742 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7743 	    stream->signal == SIGNAL_TYPE_HDMI_FRL)
7744 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket, false, false);
7745 
7746 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT ||
7747 	    stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
7748 	    stream->signal == SIGNAL_TYPE_EDP) {
7749 		const struct dc_edid_caps *edid_caps;
7750 		unsigned int disable_colorimetry = 0;
7751 
7752 		if (aconnector->dc_sink) {
7753 			edid_caps = &aconnector->dc_sink->edid_caps;
7754 			disable_colorimetry = edid_caps->panel_patch.disable_colorimetry;
7755 		}
7756 
7757 		//
7758 		// should decide stream support vsc sdp colorimetry capability
7759 		// before building vsc info packet
7760 		//
7761 		stream->use_vsc_sdp_for_colorimetry = stream->link->dpcd_caps.dpcd_rev.raw >= 0x14 &&
7762 						      stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED &&
7763 						      !disable_colorimetry;
7764 
7765 		if (stream->out_transfer_func.tf == TRANSFER_FUNCTION_GAMMA22)
7766 			tf = TRANSFER_FUNC_GAMMA_22;
7767 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
7768 		aconnector->sr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
7769 
7770 	}
7771 finish:
7772 	dc_sink_release(sink);
7773 
7774 	return stream;
7775 }
7776 
7777 /**
7778  * amdgpu_dm_connector_poll - Poll a connector to see if it's connected to a display
7779  * @aconnector: DM connector to poll (owns @base drm_connector and @dc_link)
7780  * @force: if true, force polling even when DAC load detection was used
7781  *
7782  * Used for connectors that don't support HPD (hotplug detection) to
7783  * periodically check whether the connector is connected to a display.
7784  *
7785  * When connection was determined via DAC load detection, we avoid
7786  * re-running it on normal polls to prevent visible glitches, unless
7787  * @force is set.
7788  *
7789  * Return: The probed connector status (connected/disconnected/unknown).
7790  */
7791 static enum drm_connector_status
7792 amdgpu_dm_connector_poll(struct amdgpu_dm_connector *aconnector, bool force)
7793 {
7794 	struct drm_connector *connector = &aconnector->base;
7795 	struct drm_device *dev = connector->dev;
7796 	struct amdgpu_device *adev = drm_to_adev(dev);
7797 	struct dc_link *link = aconnector->dc_link;
7798 	enum dc_connection_type conn_type = dc_connection_none;
7799 	enum drm_connector_status status = connector_status_disconnected;
7800 
7801 	/* When we determined the connection using DAC load detection,
7802 	 * do NOT poll the connector do detect disconnect because
7803 	 * that would run DAC load detection again which can cause
7804 	 * visible visual glitches.
7805 	 *
7806 	 * Only allow to poll such a connector again when forcing.
7807 	 */
7808 	if (!force && link->local_sink && link->type == dc_connection_analog_load)
7809 		return connector->status;
7810 
7811 	mutex_lock(&aconnector->hpd_lock);
7812 
7813 	if (dc_link_detect_connection_type(aconnector->dc_link, &conn_type) &&
7814 	    conn_type != dc_connection_none) {
7815 		mutex_lock(&adev->dm.dc_lock);
7816 
7817 		/* Only call full link detection when a sink isn't created yet,
7818 		 * ie. just when the display is plugged in, otherwise we risk flickering.
7819 		 */
7820 		if (link->local_sink ||
7821 			dc_link_detect(link, DETECT_REASON_HPD))
7822 			status = connector_status_connected;
7823 
7824 		mutex_unlock(&adev->dm.dc_lock);
7825 	}
7826 
7827 	if (connector->status != status) {
7828 		if (status == connector_status_disconnected) {
7829 			if (link->local_sink)
7830 				dc_sink_release(link->local_sink);
7831 
7832 			link->local_sink = NULL;
7833 			link->dpcd_sink_count = 0;
7834 			link->type = dc_connection_none;
7835 		}
7836 
7837 		amdgpu_dm_update_connector_after_detect(aconnector);
7838 	}
7839 
7840 	mutex_unlock(&aconnector->hpd_lock);
7841 	return status;
7842 }
7843 
7844 /**
7845  * amdgpu_dm_connector_detect() - Detect whether a DRM connector is connected to a display
7846  *
7847  * A connector is considered connected when it has a sink that is not NULL.
7848  * For connectors that support HPD (hotplug detection), the connection is
7849  * handled in the HPD interrupt.
7850  * For connectors that may not support HPD, such as analog connectors,
7851  * DRM will call this function repeatedly to poll them.
7852  *
7853  * Notes:
7854  * 1. This interface is NOT called in context of HPD irq.
7855  * 2. This interface *is called* in context of user-mode ioctl. Which
7856  *    makes it a bad place for *any* MST-related activity.
7857  *
7858  * @connector: The DRM connector we are checking. We convert it to
7859  *             amdgpu_dm_connector so we can read the DC link and state.
7860  * @force:     If true, do a full detect again. This is used even when
7861  *             a lighter check would normally be used to avoid flicker.
7862  *
7863  * Return: The connector status (connected, disconnected, or unknown).
7864  *
7865  */
7866 static enum drm_connector_status
7867 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
7868 {
7869 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7870 
7871 	update_subconnector_property(aconnector);
7872 
7873 	if (aconnector->base.force == DRM_FORCE_ON ||
7874 		aconnector->base.force == DRM_FORCE_ON_DIGITAL)
7875 		return connector_status_connected;
7876 	else if (aconnector->base.force == DRM_FORCE_OFF)
7877 		return connector_status_disconnected;
7878 
7879 	/* Poll analog connectors and only when either
7880 	 * disconnected or connected to an analog display.
7881 	 */
7882 	if (drm_kms_helper_is_poll_worker() &&
7883 		dc_connector_supports_analog(aconnector->dc_link->link_id.id) &&
7884 		(!aconnector->dc_sink || aconnector->dc_sink->edid_caps.analog))
7885 		return amdgpu_dm_connector_poll(aconnector, force);
7886 
7887 	return (aconnector->dc_sink ? connector_status_connected :
7888 			connector_status_disconnected);
7889 }
7890 
7891 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
7892 					    struct drm_connector_state *connector_state,
7893 					    struct drm_property *property,
7894 					    uint64_t val)
7895 {
7896 	struct drm_device *dev = connector->dev;
7897 	struct amdgpu_device *adev = drm_to_adev(dev);
7898 	struct dm_connector_state *dm_old_state =
7899 		to_dm_connector_state(connector->state);
7900 	struct dm_connector_state *dm_new_state =
7901 		to_dm_connector_state(connector_state);
7902 
7903 	int ret = -EINVAL;
7904 
7905 	if (property == dev->mode_config.scaling_mode_property) {
7906 		enum amdgpu_rmx_type rmx_type;
7907 
7908 		switch (val) {
7909 		case DRM_MODE_SCALE_CENTER:
7910 			rmx_type = RMX_CENTER;
7911 			break;
7912 		case DRM_MODE_SCALE_ASPECT:
7913 			rmx_type = RMX_ASPECT;
7914 			break;
7915 		case DRM_MODE_SCALE_FULLSCREEN:
7916 			rmx_type = RMX_FULL;
7917 			break;
7918 		case DRM_MODE_SCALE_NONE:
7919 		default:
7920 			rmx_type = RMX_OFF;
7921 			break;
7922 		}
7923 
7924 		if (dm_old_state->scaling == rmx_type)
7925 			return 0;
7926 
7927 		dm_new_state->scaling = rmx_type;
7928 		ret = 0;
7929 	} else if (property == adev->mode_info.underscan_hborder_property) {
7930 		dm_new_state->underscan_hborder = val;
7931 		ret = 0;
7932 	} else if (property == adev->mode_info.underscan_vborder_property) {
7933 		dm_new_state->underscan_vborder = val;
7934 		ret = 0;
7935 	} else if (property == adev->mode_info.underscan_property) {
7936 		dm_new_state->underscan_enable = val;
7937 		ret = 0;
7938 	} else if (property == adev->mode_info.abm_level_property) {
7939 		switch (val) {
7940 		case ABM_SYSFS_CONTROL:
7941 			dm_new_state->abm_sysfs_forbidden = false;
7942 			break;
7943 		case ABM_LEVEL_OFF:
7944 			dm_new_state->abm_sysfs_forbidden = true;
7945 			dm_new_state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7946 			break;
7947 		default:
7948 			dm_new_state->abm_sysfs_forbidden = true;
7949 			dm_new_state->abm_level = val;
7950 		}
7951 		ret = 0;
7952 	}
7953 
7954 	return ret;
7955 }
7956 
7957 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
7958 					    const struct drm_connector_state *state,
7959 					    struct drm_property *property,
7960 					    uint64_t *val)
7961 {
7962 	struct drm_device *dev = connector->dev;
7963 	struct amdgpu_device *adev = drm_to_adev(dev);
7964 	struct dm_connector_state *dm_state =
7965 		to_dm_connector_state(state);
7966 	int ret = -EINVAL;
7967 
7968 	if (property == dev->mode_config.scaling_mode_property) {
7969 		switch (dm_state->scaling) {
7970 		case RMX_CENTER:
7971 			*val = DRM_MODE_SCALE_CENTER;
7972 			break;
7973 		case RMX_ASPECT:
7974 			*val = DRM_MODE_SCALE_ASPECT;
7975 			break;
7976 		case RMX_FULL:
7977 			*val = DRM_MODE_SCALE_FULLSCREEN;
7978 			break;
7979 		case RMX_OFF:
7980 		default:
7981 			*val = DRM_MODE_SCALE_NONE;
7982 			break;
7983 		}
7984 		ret = 0;
7985 	} else if (property == adev->mode_info.underscan_hborder_property) {
7986 		*val = dm_state->underscan_hborder;
7987 		ret = 0;
7988 	} else if (property == adev->mode_info.underscan_vborder_property) {
7989 		*val = dm_state->underscan_vborder;
7990 		ret = 0;
7991 	} else if (property == adev->mode_info.underscan_property) {
7992 		*val = dm_state->underscan_enable;
7993 		ret = 0;
7994 	} else if (property == adev->mode_info.abm_level_property) {
7995 		if (!dm_state->abm_sysfs_forbidden)
7996 			*val = ABM_SYSFS_CONTROL;
7997 		else
7998 			*val = (dm_state->abm_level != ABM_LEVEL_IMMEDIATE_DISABLE) ?
7999 				dm_state->abm_level : 0;
8000 		ret = 0;
8001 	}
8002 
8003 	return ret;
8004 }
8005 
8006 /**
8007  * DOC: panel power savings
8008  *
8009  * The display manager allows you to set your desired **panel power savings**
8010  * level (between 0-4, with 0 representing off), e.g. using the following::
8011  *
8012  *   # echo 3 > /sys/class/drm/card0-eDP-1/amdgpu/panel_power_savings
8013  *
8014  * Modifying this value can have implications on color accuracy, so tread
8015  * carefully.
8016  */
8017 
8018 static ssize_t panel_power_savings_show(struct device *device,
8019 					struct device_attribute *attr,
8020 					char *buf)
8021 {
8022 	struct drm_connector *connector = dev_get_drvdata(device);
8023 	struct drm_device *dev = connector->dev;
8024 	u8 val;
8025 
8026 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
8027 	val = to_dm_connector_state(connector->state)->abm_level ==
8028 		ABM_LEVEL_IMMEDIATE_DISABLE ? 0 :
8029 		to_dm_connector_state(connector->state)->abm_level;
8030 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
8031 
8032 	return sysfs_emit(buf, "%u\n", val);
8033 }
8034 
8035 static ssize_t panel_power_savings_store(struct device *device,
8036 					 struct device_attribute *attr,
8037 					 const char *buf, size_t count)
8038 {
8039 	struct drm_connector *connector = dev_get_drvdata(device);
8040 	struct drm_device *dev = connector->dev;
8041 	long val;
8042 	int ret;
8043 
8044 	ret = kstrtol(buf, 0, &val);
8045 
8046 	if (ret)
8047 		return ret;
8048 
8049 	if (val < 0 || val > 4)
8050 		return -EINVAL;
8051 
8052 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
8053 	if (to_dm_connector_state(connector->state)->abm_sysfs_forbidden)
8054 		ret = -EBUSY;
8055 	else
8056 		to_dm_connector_state(connector->state)->abm_level = val ?:
8057 			ABM_LEVEL_IMMEDIATE_DISABLE;
8058 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
8059 
8060 	if (ret)
8061 		return ret;
8062 
8063 	drm_kms_helper_hotplug_event(dev);
8064 
8065 	return count;
8066 }
8067 
8068 static DEVICE_ATTR_RW(panel_power_savings);
8069 
8070 static struct attribute *amdgpu_attrs[] = {
8071 	&dev_attr_panel_power_savings.attr,
8072 	NULL
8073 };
8074 
8075 static const struct attribute_group amdgpu_group = {
8076 	.name = "amdgpu",
8077 	.attrs = amdgpu_attrs
8078 };
8079 
8080 static bool
8081 amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector *amdgpu_dm_connector)
8082 {
8083 	if (amdgpu_dm_abm_level >= 0)
8084 		return false;
8085 
8086 	if (amdgpu_dm_connector->base.connector_type != DRM_MODE_CONNECTOR_eDP)
8087 		return false;
8088 
8089 	/* check for OLED panels */
8090 	if (amdgpu_dm_connector->bl_idx >= 0) {
8091 		struct drm_device *drm = amdgpu_dm_connector->base.dev;
8092 		struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
8093 		struct amdgpu_dm_backlight_caps *caps;
8094 
8095 		caps = &dm->backlight_caps[amdgpu_dm_connector->bl_idx];
8096 		if (caps->aux_support)
8097 			return false;
8098 	}
8099 
8100 	return true;
8101 }
8102 
8103 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
8104 {
8105 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
8106 
8107 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector))
8108 		sysfs_remove_group(&connector->kdev->kobj, &amdgpu_group);
8109 
8110 	cec_notifier_conn_unregister(amdgpu_dm_connector->notifier);
8111 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
8112 }
8113 
8114 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
8115 {
8116 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8117 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8118 	struct amdgpu_display_manager *dm = &adev->dm;
8119 
8120 	/*
8121 	 * Call only if mst_mgr was initialized before since it's not done
8122 	 * for all connector types.
8123 	 */
8124 	if (aconnector->mst_mgr.dev)
8125 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
8126 
8127 	/* Cancel and flush any pending HDMI HPD debounce work */
8128 	if (aconnector->hdmi_hpd_debounce_delay_ms) {
8129 		cancel_delayed_work_sync(&aconnector->hdmi_hpd_debounce_work);
8130 		if (aconnector->hdmi_prev_sink) {
8131 			dc_sink_release(aconnector->hdmi_prev_sink);
8132 			aconnector->hdmi_prev_sink = NULL;
8133 		}
8134 	}
8135 
8136 	if (aconnector->bl_idx != -1) {
8137 		backlight_device_unregister(dm->backlight_dev[aconnector->bl_idx]);
8138 		dm->backlight_dev[aconnector->bl_idx] = NULL;
8139 	}
8140 
8141 	if (aconnector->dc_em_sink)
8142 		dc_sink_release(aconnector->dc_em_sink);
8143 	aconnector->dc_em_sink = NULL;
8144 	if (aconnector->dc_sink)
8145 		dc_sink_release(aconnector->dc_sink);
8146 	aconnector->dc_sink = NULL;
8147 
8148 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
8149 	drm_connector_unregister(connector);
8150 	drm_connector_cleanup(connector);
8151 	kfree(aconnector->dm_dp_aux.aux.name);
8152 
8153 	kfree(connector);
8154 }
8155 
8156 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
8157 {
8158 	struct dm_connector_state *state =
8159 		to_dm_connector_state(connector->state);
8160 
8161 	if (connector->state)
8162 		__drm_atomic_helper_connector_destroy_state(connector->state);
8163 
8164 	kfree(state);
8165 
8166 	state = kzalloc_obj(*state);
8167 
8168 	if (state) {
8169 		state->scaling = RMX_OFF;
8170 		state->underscan_enable = false;
8171 		state->underscan_hborder = 0;
8172 		state->underscan_vborder = 0;
8173 		state->base.max_requested_bpc = 8;
8174 		state->vcpi_slots = 0;
8175 		state->pbn = 0;
8176 
8177 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) {
8178 			if (amdgpu_dm_abm_level <= 0)
8179 				state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
8180 			else
8181 				state->abm_level = amdgpu_dm_abm_level;
8182 		}
8183 
8184 		__drm_atomic_helper_connector_reset(connector, &state->base);
8185 	}
8186 }
8187 
8188 struct drm_connector_state *
8189 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
8190 {
8191 	struct dm_connector_state *state =
8192 		to_dm_connector_state(connector->state);
8193 
8194 	struct dm_connector_state *new_state =
8195 			kmemdup(state, sizeof(*state), GFP_KERNEL);
8196 
8197 	if (!new_state)
8198 		return NULL;
8199 
8200 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
8201 
8202 	new_state->freesync_capable = state->freesync_capable;
8203 	new_state->abm_level = state->abm_level;
8204 	new_state->scaling = state->scaling;
8205 	new_state->underscan_enable = state->underscan_enable;
8206 	new_state->underscan_hborder = state->underscan_hborder;
8207 	new_state->underscan_vborder = state->underscan_vborder;
8208 	new_state->vcpi_slots = state->vcpi_slots;
8209 	new_state->pbn = state->pbn;
8210 	return &new_state->base;
8211 }
8212 
8213 static int
8214 amdgpu_dm_connector_late_register(struct drm_connector *connector)
8215 {
8216 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8217 		to_amdgpu_dm_connector(connector);
8218 	int r;
8219 
8220 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector)) {
8221 		r = sysfs_create_group(&connector->kdev->kobj,
8222 				       &amdgpu_group);
8223 		if (r)
8224 			return r;
8225 	}
8226 
8227 	amdgpu_dm_register_backlight_device(amdgpu_dm_connector);
8228 
8229 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
8230 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
8231 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
8232 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
8233 		if (r)
8234 			return r;
8235 	}
8236 
8237 #if defined(CONFIG_DEBUG_FS)
8238 	connector_debugfs_init(amdgpu_dm_connector);
8239 #endif
8240 
8241 	return 0;
8242 }
8243 
8244 static void amdgpu_dm_connector_funcs_force(struct drm_connector *connector)
8245 {
8246 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8247 	struct dc_link *dc_link = aconnector->dc_link;
8248 	struct dc_sink *dc_em_sink = aconnector->dc_em_sink;
8249 	const struct drm_edid *drm_edid;
8250 	struct i2c_adapter *ddc;
8251 	struct drm_device *dev = connector->dev;
8252 
8253 	if (dc_link && dc_link->aux_mode)
8254 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8255 	else
8256 		ddc = &aconnector->i2c->base;
8257 
8258 	drm_edid = drm_edid_read_ddc(connector, ddc);
8259 	drm_edid_connector_update(connector, drm_edid);
8260 	if (!drm_edid) {
8261 		drm_err(dev, "No EDID found on connector: %s.\n", connector->name);
8262 		return;
8263 	}
8264 
8265 	aconnector->drm_edid = drm_edid;
8266 	/* Update emulated (virtual) sink's EDID */
8267 	if (dc_em_sink && dc_link) {
8268 		// FIXME: Get rid of drm_edid_raw()
8269 		const struct edid *edid = drm_edid_raw(drm_edid);
8270 
8271 		memset(&dc_em_sink->edid_caps, 0, sizeof(struct dc_edid_caps));
8272 		memmove(dc_em_sink->dc_edid.raw_edid, edid,
8273 			(edid->extensions + 1) * EDID_LENGTH);
8274 		dm_helpers_parse_edid_caps(
8275 			dc_link,
8276 			&dc_em_sink->dc_edid,
8277 			&dc_em_sink->edid_caps);
8278 	}
8279 }
8280 
8281 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
8282 	.reset = amdgpu_dm_connector_funcs_reset,
8283 	.detect = amdgpu_dm_connector_detect,
8284 	.fill_modes = drm_helper_probe_single_connector_modes,
8285 	.destroy = amdgpu_dm_connector_destroy,
8286 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
8287 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
8288 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
8289 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
8290 	.late_register = amdgpu_dm_connector_late_register,
8291 	.early_unregister = amdgpu_dm_connector_unregister,
8292 	.force = amdgpu_dm_connector_funcs_force
8293 };
8294 
8295 static int get_modes(struct drm_connector *connector)
8296 {
8297 	return amdgpu_dm_connector_get_modes(connector);
8298 }
8299 
8300 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
8301 {
8302 	struct drm_connector *connector = &aconnector->base;
8303 	struct dc_link *dc_link = aconnector->dc_link;
8304 	struct dc_sink_init_data init_params = {
8305 			.link = aconnector->dc_link,
8306 			.sink_signal = SIGNAL_TYPE_VIRTUAL
8307 	};
8308 	const struct drm_edid *drm_edid;
8309 	const struct edid *edid;
8310 	struct i2c_adapter *ddc;
8311 
8312 	if (dc_link && dc_link->aux_mode)
8313 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8314 	else
8315 		ddc = &aconnector->i2c->base;
8316 
8317 	drm_edid = drm_edid_read_ddc(connector, ddc);
8318 	drm_edid_connector_update(connector, drm_edid);
8319 	if (!drm_edid) {
8320 		drm_err(connector->dev, "No EDID found on connector: %s.\n", connector->name);
8321 		return;
8322 	}
8323 
8324 	if (connector->display_info.is_hdmi)
8325 		init_params.sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
8326 
8327 	aconnector->drm_edid = drm_edid;
8328 
8329 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
8330 	aconnector->dc_em_sink = dc_link_add_remote_sink(
8331 		aconnector->dc_link,
8332 		(uint8_t *)edid,
8333 		(edid->extensions + 1) * EDID_LENGTH,
8334 		&init_params);
8335 
8336 	if (aconnector->base.force == DRM_FORCE_ON) {
8337 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
8338 		aconnector->dc_link->local_sink :
8339 		aconnector->dc_em_sink;
8340 		if (aconnector->dc_sink)
8341 			dc_sink_retain(aconnector->dc_sink);
8342 	}
8343 }
8344 
8345 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
8346 {
8347 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
8348 
8349 	/*
8350 	 * In case of headless boot with force on for DP managed connector
8351 	 * Those settings have to be != 0 to get initial modeset
8352 	 */
8353 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
8354 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
8355 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
8356 	}
8357 
8358 	create_eml_sink(aconnector);
8359 }
8360 
8361 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
8362 						struct dc_stream_state *stream)
8363 {
8364 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
8365 	struct dc_plane_state *dc_plane_state = NULL;
8366 	struct dc_state *dc_state = NULL;
8367 
8368 	if (!stream)
8369 		goto cleanup;
8370 
8371 	dc_plane_state = dc_create_plane_state(dc);
8372 	if (!dc_plane_state)
8373 		goto cleanup;
8374 
8375 	dc_state = dc_state_create(dc, NULL);
8376 	if (!dc_state)
8377 		goto cleanup;
8378 
8379 	/* populate stream to plane */
8380 	dc_plane_state->src_rect.height  = stream->src.height;
8381 	dc_plane_state->src_rect.width   = stream->src.width;
8382 	dc_plane_state->dst_rect.height  = stream->src.height;
8383 	dc_plane_state->dst_rect.width   = stream->src.width;
8384 	dc_plane_state->clip_rect.height = stream->src.height;
8385 	dc_plane_state->clip_rect.width  = stream->src.width;
8386 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
8387 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
8388 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
8389 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
8390 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
8391 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
8392 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
8393 	dc_plane_state->rotation = ROTATION_ANGLE_0;
8394 	dc_plane_state->is_tiling_rotated = false;
8395 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
8396 
8397 	dc_result = dc_validate_stream(dc, stream);
8398 	if (dc_result == DC_OK)
8399 		dc_result = dc_validate_plane(dc, dc_plane_state);
8400 
8401 	if (dc_result == DC_OK)
8402 		dc_result = dc_state_add_stream(dc, dc_state, stream);
8403 
8404 	if (dc_result == DC_OK && !dc_state_add_plane(
8405 						dc,
8406 						stream,
8407 						dc_plane_state,
8408 						dc_state))
8409 		dc_result = DC_FAIL_ATTACH_SURFACES;
8410 
8411 	if (dc_result == DC_OK)
8412 		dc_result = dc_validate_global_state(dc, dc_state, DC_VALIDATE_MODE_ONLY);
8413 
8414 cleanup:
8415 	if (dc_state)
8416 		dc_state_release(dc_state);
8417 
8418 	if (dc_plane_state)
8419 		dc_plane_state_release(dc_plane_state);
8420 
8421 	return dc_result;
8422 }
8423 
8424 struct dc_stream_state *
8425 create_validate_stream_for_sink(struct drm_connector *connector,
8426 				const struct drm_display_mode *drm_mode,
8427 				const struct dm_connector_state *dm_state,
8428 				const struct dc_stream_state *old_stream)
8429 {
8430 	struct amdgpu_dm_connector *aconnector = NULL;
8431 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8432 	struct dc_stream_state *stream;
8433 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
8434 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
8435 	enum dc_status dc_result = DC_OK;
8436 	uint8_t bpc_limit = 6;
8437 
8438 	if (!dm_state)
8439 		return NULL;
8440 
8441 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
8442 		aconnector = to_amdgpu_dm_connector(connector);
8443 
8444 	if (aconnector &&
8445 	    (aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
8446 	     aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_FRL ||
8447 	     aconnector->dc_link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER))
8448 		bpc_limit = 8;
8449 
8450 	do {
8451 		drm_dbg_kms(connector->dev, "Trying with %d bpc\n", requested_bpc);
8452 		stream = create_stream_for_sink(connector, drm_mode,
8453 						dm_state, old_stream,
8454 						requested_bpc);
8455 		if (stream == NULL) {
8456 			drm_err(adev_to_drm(adev), "Failed to create stream for sink!\n");
8457 			break;
8458 		}
8459 
8460 		dc_result = dc_validate_stream(adev->dm.dc, stream);
8461 
8462 		if (!aconnector) /* writeback connector */
8463 			return stream;
8464 
8465 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
8466 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
8467 
8468 		if (dc_result == DC_OK)
8469 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
8470 
8471 		if (dc_result != DC_OK) {
8472 			drm_dbg_kms(connector->dev, "Pruned mode %d x %d (clk %d) %s %s -- %s\n",
8473 				      drm_mode->hdisplay,
8474 				      drm_mode->vdisplay,
8475 				      drm_mode->clock,
8476 				      dc_pixel_encoding_to_str(stream->timing.pixel_encoding),
8477 				      dc_color_depth_to_str(stream->timing.display_color_depth),
8478 				      dc_status_to_str(dc_result));
8479 
8480 			dc_stream_release(stream);
8481 			stream = NULL;
8482 			requested_bpc -= 2; /* lower bpc to retry validation */
8483 		}
8484 
8485 	} while (stream == NULL && requested_bpc >= bpc_limit);
8486 
8487 	switch (dc_result) {
8488 	/*
8489 	 * If we failed to validate DP bandwidth stream with the requested RGB color depth,
8490 	 * we try to fallback and configure in order:
8491 	 * YUV422 (8bpc, 6bpc)
8492 	 * YUV420 (8bpc, 6bpc)
8493 	 */
8494 	case DC_FAIL_ENC_VALIDATE:
8495 	case DC_EXCEED_DONGLE_CAP:
8496 	case DC_NO_DP_LINK_BANDWIDTH:
8497 		/* recursively entered twice and already tried both YUV422 and YUV420 */
8498 		if (aconnector->force_yuv422_output && aconnector->force_yuv420_output)
8499 			break;
8500 		/* first failure; try YUV422 */
8501 		if (!aconnector->force_yuv422_output) {
8502 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV422\n",
8503 				    __func__, __LINE__, dc_result);
8504 			aconnector->force_yuv422_output = true;
8505 		/* recursively entered and YUV422 failed, try YUV420 */
8506 		} else if (!aconnector->force_yuv420_output) {
8507 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV420\n",
8508 				    __func__, __LINE__, dc_result);
8509 			aconnector->force_yuv420_output = true;
8510 		}
8511 		stream = create_validate_stream_for_sink(connector, drm_mode,
8512 							 dm_state, old_stream);
8513 		aconnector->force_yuv422_output = false;
8514 		aconnector->force_yuv420_output = false;
8515 		break;
8516 	case DC_OK:
8517 		break;
8518 	default:
8519 		drm_dbg_kms(connector->dev, "%s:%d Unhandled validation failure %d\n",
8520 			    __func__, __LINE__, dc_result);
8521 		break;
8522 	}
8523 
8524 	return stream;
8525 }
8526 
8527 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
8528 				   const struct drm_display_mode *mode)
8529 {
8530 	int result = MODE_ERROR;
8531 	struct dc_sink *dc_sink;
8532 	struct drm_display_mode *test_mode;
8533 	/* TODO: Unhardcode stream count */
8534 	struct dc_stream_state *stream;
8535 	/* we always have an amdgpu_dm_connector here since we got
8536 	 * here via the amdgpu_dm_connector_helper_funcs
8537 	 */
8538 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8539 
8540 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
8541 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
8542 		return result;
8543 
8544 	/*
8545 	 * Only run this the first time mode_valid is called to initilialize
8546 	 * EDID mgmt
8547 	 */
8548 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
8549 		!aconnector->dc_em_sink)
8550 		handle_edid_mgmt(aconnector);
8551 
8552 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
8553 
8554 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
8555 				aconnector->base.force != DRM_FORCE_ON) {
8556 		drm_err(connector->dev, "dc_sink is NULL!\n");
8557 		goto fail;
8558 	}
8559 
8560 	test_mode = drm_mode_duplicate(connector->dev, mode);
8561 	if (!test_mode)
8562 		goto fail;
8563 
8564 	drm_mode_set_crtcinfo(test_mode, 0);
8565 
8566 	stream = create_validate_stream_for_sink(connector, test_mode,
8567 						 to_dm_connector_state(connector->state),
8568 						 NULL);
8569 	drm_mode_destroy(connector->dev, test_mode);
8570 	if (stream) {
8571 		dc_stream_release(stream);
8572 		result = MODE_OK;
8573 	}
8574 
8575 fail:
8576 	/* TODO: error handling*/
8577 	return result;
8578 }
8579 
8580 static int fill_hdr_info_packet(const struct drm_connector_state *state,
8581 				struct dc_info_packet *out)
8582 {
8583 	struct hdmi_drm_infoframe frame;
8584 	unsigned char buf[30]; /* 26 + 4 */
8585 	ssize_t len;
8586 	int ret, i;
8587 
8588 	memset(out, 0, sizeof(*out));
8589 
8590 	if (!state->hdr_output_metadata)
8591 		return 0;
8592 
8593 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
8594 	if (ret)
8595 		return ret;
8596 
8597 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
8598 	if (len < 0)
8599 		return (int)len;
8600 
8601 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
8602 	if (len != 30)
8603 		return -EINVAL;
8604 
8605 	/* Prepare the infopacket for DC. */
8606 	switch (state->connector->connector_type) {
8607 	case DRM_MODE_CONNECTOR_HDMIA:
8608 		out->hb0 = 0x87; /* type */
8609 		out->hb1 = 0x01; /* version */
8610 		out->hb2 = 0x1A; /* length */
8611 		out->sb[0] = buf[3]; /* checksum */
8612 		i = 1;
8613 		break;
8614 
8615 	case DRM_MODE_CONNECTOR_DisplayPort:
8616 	case DRM_MODE_CONNECTOR_eDP:
8617 		out->hb0 = 0x00; /* sdp id, zero */
8618 		out->hb1 = 0x87; /* type */
8619 		out->hb2 = 0x1D; /* payload len - 1 */
8620 		out->hb3 = (0x13 << 2); /* sdp version */
8621 		out->sb[0] = 0x01; /* version */
8622 		out->sb[1] = 0x1A; /* length */
8623 		i = 2;
8624 		break;
8625 
8626 	default:
8627 		return -EINVAL;
8628 	}
8629 
8630 	memcpy(&out->sb[i], &buf[4], 26);
8631 	out->valid = true;
8632 
8633 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
8634 		       sizeof(out->sb), false);
8635 
8636 	return 0;
8637 }
8638 
8639 static int
8640 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
8641 				 struct drm_atomic_commit *state)
8642 {
8643 	struct drm_connector_state *new_con_state =
8644 		drm_atomic_get_new_connector_state(state, conn);
8645 	struct drm_connector_state *old_con_state =
8646 		drm_atomic_get_old_connector_state(state, conn);
8647 	struct drm_crtc *crtc = new_con_state->crtc;
8648 	struct drm_crtc_state *new_crtc_state;
8649 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
8650 	int ret;
8651 
8652 	if (WARN_ON(unlikely(!old_con_state || !new_con_state)))
8653 		return -EINVAL;
8654 
8655 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
8656 
8657 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
8658 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
8659 		if (ret < 0)
8660 			return ret;
8661 	}
8662 
8663 	if (!crtc)
8664 		return 0;
8665 
8666 	if (new_con_state->privacy_screen_sw_state != old_con_state->privacy_screen_sw_state) {
8667 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8668 		if (IS_ERR(new_crtc_state))
8669 			return PTR_ERR(new_crtc_state);
8670 
8671 		new_crtc_state->mode_changed = true;
8672 	}
8673 
8674 	if (new_con_state->colorspace != old_con_state->colorspace) {
8675 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8676 		if (IS_ERR(new_crtc_state))
8677 			return PTR_ERR(new_crtc_state);
8678 
8679 		new_crtc_state->mode_changed = true;
8680 	}
8681 
8682 	if (new_con_state->content_type != old_con_state->content_type) {
8683 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8684 		if (IS_ERR(new_crtc_state))
8685 			return PTR_ERR(new_crtc_state);
8686 
8687 		new_crtc_state->mode_changed = true;
8688 	}
8689 
8690 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
8691 		struct dc_info_packet hdr_infopacket;
8692 
8693 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
8694 		if (ret)
8695 			return ret;
8696 
8697 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8698 		if (IS_ERR(new_crtc_state))
8699 			return PTR_ERR(new_crtc_state);
8700 
8701 		/*
8702 		 * DC considers the stream backends changed if the
8703 		 * static metadata changes. Forcing the modeset also
8704 		 * gives a simple way for userspace to switch from
8705 		 * 8bpc to 10bpc when setting the metadata to enter
8706 		 * or exit HDR.
8707 		 *
8708 		 * Changing the static metadata after it's been
8709 		 * set is permissible, however. So only force a
8710 		 * modeset if we're entering or exiting HDR.
8711 		 */
8712 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
8713 			!old_con_state->hdr_output_metadata ||
8714 			!new_con_state->hdr_output_metadata;
8715 	}
8716 
8717 	return 0;
8718 }
8719 
8720 static const struct drm_connector_helper_funcs
8721 amdgpu_dm_connector_helper_funcs = {
8722 	/*
8723 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
8724 	 * modes will be filtered by drm_mode_validate_size(), and those modes
8725 	 * are missing after user start lightdm. So we need to renew modes list.
8726 	 * in get_modes call back, not just return the modes count
8727 	 */
8728 	.get_modes = get_modes,
8729 	.mode_valid = amdgpu_dm_connector_mode_valid,
8730 	.atomic_check = amdgpu_dm_connector_atomic_check,
8731 };
8732 
8733 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
8734 {
8735 
8736 }
8737 
8738 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
8739 {
8740 	switch (display_color_depth) {
8741 	case COLOR_DEPTH_666:
8742 		return 6;
8743 	case COLOR_DEPTH_888:
8744 		return 8;
8745 	case COLOR_DEPTH_101010:
8746 		return 10;
8747 	case COLOR_DEPTH_121212:
8748 		return 12;
8749 	case COLOR_DEPTH_141414:
8750 		return 14;
8751 	case COLOR_DEPTH_161616:
8752 		return 16;
8753 	default:
8754 		break;
8755 	}
8756 	return 0;
8757 }
8758 
8759 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
8760 					  struct drm_crtc_state *crtc_state,
8761 					  struct drm_connector_state *conn_state)
8762 {
8763 	struct drm_atomic_commit *state = crtc_state->state;
8764 	struct drm_connector *connector = conn_state->connector;
8765 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8766 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
8767 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
8768 	struct drm_dp_mst_topology_mgr *mst_mgr;
8769 	struct drm_dp_mst_port *mst_port;
8770 	struct drm_dp_mst_topology_state *mst_state;
8771 	enum dc_color_depth color_depth;
8772 	int clock, bpp = 0;
8773 	bool is_y420 = false;
8774 
8775 	if ((connector->connector_type == DRM_MODE_CONNECTOR_eDP) ||
8776 	    (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)) {
8777 		struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8778 		struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8779 		enum drm_mode_status result;
8780 
8781 		result = drm_crtc_helper_mode_valid_fixed(encoder->crtc, adjusted_mode, native_mode);
8782 		if (result != MODE_OK && dm_new_connector_state->scaling == RMX_OFF) {
8783 			drm_dbg_driver(encoder->dev,
8784 				       "mode %dx%d@%dHz is not native, enabling scaling\n",
8785 				       adjusted_mode->hdisplay, adjusted_mode->vdisplay,
8786 				       drm_mode_vrefresh(adjusted_mode));
8787 			dm_new_connector_state->scaling = RMX_ASPECT;
8788 		}
8789 		return 0;
8790 	}
8791 
8792 	if (!aconnector->mst_output_port)
8793 		return 0;
8794 
8795 	mst_port = aconnector->mst_output_port;
8796 	mst_mgr = &aconnector->mst_root->mst_mgr;
8797 
8798 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
8799 		return 0;
8800 
8801 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
8802 	if (IS_ERR(mst_state))
8803 		return PTR_ERR(mst_state);
8804 
8805 	mst_state->pbn_div.full = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
8806 
8807 	if (!state->duplicated) {
8808 		int max_bpc = conn_state->max_requested_bpc;
8809 
8810 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
8811 			  aconnector->force_yuv420_output;
8812 		color_depth = convert_color_depth_from_display_info(connector,
8813 								    is_y420,
8814 								    max_bpc);
8815 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
8816 		clock = adjusted_mode->clock;
8817 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
8818 	}
8819 
8820 	dm_new_connector_state->vcpi_slots =
8821 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
8822 					      dm_new_connector_state->pbn);
8823 	if (dm_new_connector_state->vcpi_slots < 0) {
8824 		drm_dbg_atomic(connector->dev, "failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
8825 		return dm_new_connector_state->vcpi_slots;
8826 	}
8827 	return 0;
8828 }
8829 
8830 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
8831 	.disable = dm_encoder_helper_disable,
8832 	.atomic_check = dm_encoder_helper_atomic_check
8833 };
8834 
8835 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_commit *state,
8836 					    struct dc_state *dc_state,
8837 					    struct dsc_mst_fairness_vars *vars)
8838 {
8839 	struct dc_stream_state *stream = NULL;
8840 	struct drm_connector *connector;
8841 	struct drm_connector_state *new_con_state;
8842 	struct amdgpu_dm_connector *aconnector;
8843 	struct dm_connector_state *dm_conn_state;
8844 	int i, j, ret;
8845 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
8846 
8847 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8848 
8849 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
8850 			continue;
8851 
8852 		aconnector = to_amdgpu_dm_connector(connector);
8853 
8854 		if (!aconnector->mst_output_port)
8855 			continue;
8856 
8857 		if (!new_con_state || !new_con_state->crtc)
8858 			continue;
8859 
8860 		dm_conn_state = to_dm_connector_state(new_con_state);
8861 
8862 		for (j = 0; j < dc_state->stream_count; j++) {
8863 			stream = dc_state->streams[j];
8864 			if (!stream)
8865 				continue;
8866 
8867 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
8868 				break;
8869 
8870 			stream = NULL;
8871 		}
8872 
8873 		if (!stream)
8874 			continue;
8875 
8876 		pbn_div = dm_mst_get_pbn_divider(stream->link);
8877 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
8878 		for (j = 0; j < dc_state->stream_count; j++) {
8879 			if (vars[j].aconnector == aconnector) {
8880 				pbn = vars[j].pbn;
8881 				break;
8882 			}
8883 		}
8884 
8885 		if (j == dc_state->stream_count || pbn_div == 0)
8886 			continue;
8887 
8888 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
8889 
8890 		if (stream->timing.flags.DSC != 1) {
8891 			dm_conn_state->pbn = pbn;
8892 			dm_conn_state->vcpi_slots = slot_num;
8893 
8894 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
8895 							   dm_conn_state->pbn, false);
8896 			if (ret < 0)
8897 				return ret;
8898 
8899 			continue;
8900 		}
8901 
8902 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
8903 		if (vcpi < 0)
8904 			return vcpi;
8905 
8906 		dm_conn_state->pbn = pbn;
8907 		dm_conn_state->vcpi_slots = vcpi;
8908 	}
8909 	return 0;
8910 }
8911 
8912 static int to_drm_connector_type(enum signal_type st, uint32_t connector_id)
8913 {
8914 	switch (st) {
8915 	case SIGNAL_TYPE_HDMI_TYPE_A:
8916 		return DRM_MODE_CONNECTOR_HDMIA;
8917 	case SIGNAL_TYPE_EDP:
8918 		return DRM_MODE_CONNECTOR_eDP;
8919 	case SIGNAL_TYPE_LVDS:
8920 		return DRM_MODE_CONNECTOR_LVDS;
8921 	case SIGNAL_TYPE_RGB:
8922 		return DRM_MODE_CONNECTOR_VGA;
8923 	case SIGNAL_TYPE_DISPLAY_PORT:
8924 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
8925 		/* External DP bridges have a different connector type. */
8926 		if (connector_id == CONNECTOR_ID_VGA)
8927 			return DRM_MODE_CONNECTOR_VGA;
8928 		else if (connector_id == CONNECTOR_ID_LVDS)
8929 			return DRM_MODE_CONNECTOR_LVDS;
8930 
8931 		return DRM_MODE_CONNECTOR_DisplayPort;
8932 	case SIGNAL_TYPE_DVI_DUAL_LINK:
8933 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
8934 		if (connector_id == CONNECTOR_ID_SINGLE_LINK_DVII ||
8935 			connector_id == CONNECTOR_ID_DUAL_LINK_DVII)
8936 			return DRM_MODE_CONNECTOR_DVII;
8937 
8938 		return DRM_MODE_CONNECTOR_DVID;
8939 	case SIGNAL_TYPE_VIRTUAL:
8940 		return DRM_MODE_CONNECTOR_VIRTUAL;
8941 
8942 	default:
8943 		return DRM_MODE_CONNECTOR_Unknown;
8944 	}
8945 }
8946 
8947 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
8948 {
8949 	struct drm_encoder *encoder;
8950 
8951 	/* There is only one encoder per connector */
8952 	drm_connector_for_each_possible_encoder(connector, encoder)
8953 		return encoder;
8954 
8955 	return NULL;
8956 }
8957 
8958 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
8959 {
8960 	struct drm_encoder *encoder;
8961 	struct amdgpu_encoder *amdgpu_encoder;
8962 
8963 	encoder = amdgpu_dm_connector_to_encoder(connector);
8964 
8965 	if (encoder == NULL)
8966 		return;
8967 
8968 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8969 
8970 	amdgpu_encoder->native_mode.clock = 0;
8971 
8972 	if (!list_empty(&connector->probed_modes)) {
8973 		struct drm_display_mode *preferred_mode = NULL;
8974 
8975 		list_for_each_entry(preferred_mode,
8976 				    &connector->probed_modes,
8977 				    head) {
8978 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
8979 				amdgpu_encoder->native_mode = *preferred_mode;
8980 
8981 			break;
8982 		}
8983 
8984 	}
8985 }
8986 
8987 static struct drm_display_mode *
8988 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
8989 			     const char *name,
8990 			     int hdisplay, int vdisplay)
8991 {
8992 	struct drm_device *dev = encoder->dev;
8993 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8994 	struct drm_display_mode *mode = NULL;
8995 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8996 
8997 	mode = drm_mode_duplicate(dev, native_mode);
8998 
8999 	if (mode == NULL)
9000 		return NULL;
9001 
9002 	mode->hdisplay = hdisplay;
9003 	mode->vdisplay = vdisplay;
9004 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
9005 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
9006 
9007 	return mode;
9008 
9009 }
9010 
9011 static const struct amdgpu_dm_mode_size {
9012 	char name[DRM_DISPLAY_MODE_LEN];
9013 	int w;
9014 	int h;
9015 } common_modes[] = {
9016 	{  "640x480",  640,  480},
9017 	{  "800x600",  800,  600},
9018 	{ "1024x768", 1024,  768},
9019 	{ "1280x720", 1280,  720},
9020 	{ "1280x800", 1280,  800},
9021 	{"1280x1024", 1280, 1024},
9022 	{ "1440x900", 1440,  900},
9023 	{"1680x1050", 1680, 1050},
9024 	{"1600x1200", 1600, 1200},
9025 	{"1920x1080", 1920, 1080},
9026 	{"1920x1200", 1920, 1200}
9027 };
9028 
9029 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
9030 						 struct drm_connector *connector)
9031 {
9032 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
9033 	struct drm_display_mode *mode = NULL;
9034 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
9035 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9036 				to_amdgpu_dm_connector(connector);
9037 	int i;
9038 	int n;
9039 
9040 	if ((connector->connector_type != DRM_MODE_CONNECTOR_eDP) &&
9041 	    (connector->connector_type != DRM_MODE_CONNECTOR_LVDS))
9042 		return;
9043 
9044 	n = ARRAY_SIZE(common_modes);
9045 
9046 	for (i = 0; i < n; i++) {
9047 		struct drm_display_mode *curmode = NULL;
9048 		bool mode_existed = false;
9049 
9050 		if (common_modes[i].w > native_mode->hdisplay ||
9051 		    common_modes[i].h > native_mode->vdisplay ||
9052 		   (common_modes[i].w == native_mode->hdisplay &&
9053 		    common_modes[i].h == native_mode->vdisplay))
9054 			continue;
9055 
9056 		list_for_each_entry(curmode, &connector->probed_modes, head) {
9057 			if (common_modes[i].w == curmode->hdisplay &&
9058 			    common_modes[i].h == curmode->vdisplay) {
9059 				mode_existed = true;
9060 				break;
9061 			}
9062 		}
9063 
9064 		if (mode_existed)
9065 			continue;
9066 
9067 		mode = amdgpu_dm_create_common_mode(encoder,
9068 				common_modes[i].name, common_modes[i].w,
9069 				common_modes[i].h);
9070 		if (!mode)
9071 			continue;
9072 
9073 		drm_mode_probed_add(connector, mode);
9074 		amdgpu_dm_connector->num_modes++;
9075 	}
9076 }
9077 
9078 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
9079 {
9080 	struct drm_encoder *encoder;
9081 	struct amdgpu_encoder *amdgpu_encoder;
9082 	const struct drm_display_mode *native_mode;
9083 
9084 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
9085 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
9086 		return;
9087 
9088 	mutex_lock(&connector->dev->mode_config.mutex);
9089 	amdgpu_dm_connector_get_modes(connector);
9090 	mutex_unlock(&connector->dev->mode_config.mutex);
9091 
9092 	encoder = amdgpu_dm_connector_to_encoder(connector);
9093 	if (!encoder)
9094 		return;
9095 
9096 	amdgpu_encoder = to_amdgpu_encoder(encoder);
9097 
9098 	native_mode = &amdgpu_encoder->native_mode;
9099 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
9100 		return;
9101 
9102 	drm_connector_set_panel_orientation_with_quirk(connector,
9103 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
9104 						       native_mode->hdisplay,
9105 						       native_mode->vdisplay);
9106 }
9107 
9108 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
9109 					      const struct drm_edid *drm_edid)
9110 {
9111 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9112 			to_amdgpu_dm_connector(connector);
9113 
9114 	if (drm_edid) {
9115 		/* empty probed_modes */
9116 		INIT_LIST_HEAD(&connector->probed_modes);
9117 		amdgpu_dm_connector->num_modes =
9118 				drm_edid_connector_add_modes(connector);
9119 
9120 		/* sorting the probed modes before calling function
9121 		 * amdgpu_dm_get_native_mode() since EDID can have
9122 		 * more than one preferred mode. The modes that are
9123 		 * later in the probed mode list could be of higher
9124 		 * and preferred resolution. For example, 3840x2160
9125 		 * resolution in base EDID preferred timing and 4096x2160
9126 		 * preferred resolution in DID extension block later.
9127 		 */
9128 		drm_mode_sort(&connector->probed_modes);
9129 		amdgpu_dm_get_native_mode(connector);
9130 
9131 		/* Freesync capabilities are reset by calling
9132 		 * drm_edid_connector_add_modes() and need to be
9133 		 * restored here.
9134 		 */
9135 		amdgpu_dm_update_freesync_caps(connector, drm_edid, false);
9136 	} else {
9137 		amdgpu_dm_connector->num_modes = 0;
9138 	}
9139 }
9140 
9141 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
9142 			      struct drm_display_mode *mode)
9143 {
9144 	struct drm_display_mode *m;
9145 
9146 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
9147 		if (drm_mode_equal(m, mode))
9148 			return true;
9149 	}
9150 
9151 	return false;
9152 }
9153 
9154 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
9155 {
9156 	const struct drm_display_mode *m;
9157 	struct drm_display_mode *new_mode;
9158 	uint i;
9159 	u32 new_modes_count = 0;
9160 
9161 	/* Standard FPS values
9162 	 *
9163 	 * 23.976       - TV/NTSC
9164 	 * 24           - Cinema
9165 	 * 25           - TV/PAL
9166 	 * 29.97        - TV/NTSC
9167 	 * 30           - TV/NTSC
9168 	 * 48           - Cinema HFR
9169 	 * 50           - TV/PAL
9170 	 * 60           - Commonly used
9171 	 * 48,72,96,120 - Multiples of 24
9172 	 */
9173 	static const u32 common_rates[] = {
9174 		23976, 24000, 25000, 29970, 30000,
9175 		48000, 50000, 60000, 72000, 96000, 120000
9176 	};
9177 
9178 	/*
9179 	 * Find mode with highest refresh rate with the same resolution
9180 	 * as the preferred mode. Some monitors report a preferred mode
9181 	 * with lower resolution than the highest refresh rate supported.
9182 	 */
9183 
9184 	m = get_highest_refresh_rate_mode(aconnector, true);
9185 	if (!m)
9186 		return 0;
9187 
9188 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
9189 		u64 target_vtotal, target_vtotal_diff;
9190 		u64 num, den;
9191 
9192 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
9193 			continue;
9194 
9195 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
9196 		    common_rates[i] > aconnector->max_vfreq * 1000)
9197 			continue;
9198 
9199 		num = (unsigned long long)m->clock * 1000 * 1000;
9200 		den = common_rates[i] * (unsigned long long)m->htotal;
9201 		target_vtotal = div_u64(num, den);
9202 		target_vtotal_diff = target_vtotal - m->vtotal;
9203 
9204 		/* Check for illegal modes */
9205 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
9206 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
9207 		    m->vtotal + target_vtotal_diff < m->vsync_end)
9208 			continue;
9209 
9210 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
9211 		if (!new_mode)
9212 			goto out;
9213 
9214 		new_mode->vtotal += (u16)target_vtotal_diff;
9215 		new_mode->vsync_start += (u16)target_vtotal_diff;
9216 		new_mode->vsync_end += (u16)target_vtotal_diff;
9217 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
9218 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
9219 
9220 		if (!is_duplicate_mode(aconnector, new_mode)) {
9221 			drm_mode_probed_add(&aconnector->base, new_mode);
9222 			new_modes_count += 1;
9223 		} else
9224 			drm_mode_destroy(aconnector->base.dev, new_mode);
9225 	}
9226  out:
9227 	return new_modes_count;
9228 }
9229 
9230 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
9231 						   const struct drm_edid *drm_edid)
9232 {
9233 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9234 		to_amdgpu_dm_connector(connector);
9235 
9236 	if (!(amdgpu_freesync_vid_mode && drm_edid))
9237 		return;
9238 
9239 	if (!amdgpu_dm_connector->dc_sink || !amdgpu_dm_connector->dc_link)
9240 		return;
9241 
9242 	if (!dc_supports_vrr(amdgpu_dm_connector->dc_sink->ctx->dce_version))
9243 		return;
9244 
9245 	if (dc_connector_supports_analog(amdgpu_dm_connector->dc_link->link_id.id) &&
9246 	    amdgpu_dm_connector->dc_sink->edid_caps.analog)
9247 		return;
9248 
9249 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
9250 		amdgpu_dm_connector->num_modes +=
9251 			add_fs_modes(amdgpu_dm_connector);
9252 }
9253 
9254 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
9255 {
9256 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9257 			to_amdgpu_dm_connector(connector);
9258 	struct dc_link *dc_link = amdgpu_dm_connector->dc_link;
9259 	struct drm_encoder *encoder;
9260 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
9261 	struct dc_link_settings *verified_link_cap = &dc_link->verified_link_cap;
9262 	const struct dc *dc = dc_link->dc;
9263 
9264 	encoder = amdgpu_dm_connector_to_encoder(connector);
9265 
9266 	if (!drm_edid) {
9267 		amdgpu_dm_connector->num_modes =
9268 				drm_add_modes_noedid(connector, 640, 480);
9269 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
9270 			amdgpu_dm_connector->num_modes +=
9271 				drm_add_modes_noedid(connector, 1920, 1080);
9272 
9273 		if (amdgpu_dm_connector->dc_sink &&
9274 		    amdgpu_dm_connector->dc_sink->edid_caps.analog &&
9275 		    dc_connector_supports_analog(dc_link->link_id.id)) {
9276 			/* Analog monitor connected by DAC load detection.
9277 			 * Add common modes. It will be up to the user to select one that works.
9278 			 */
9279 			for (int i = 0; i < ARRAY_SIZE(common_modes); i++)
9280 				amdgpu_dm_connector->num_modes += drm_add_modes_noedid(
9281 					connector, common_modes[i].w, common_modes[i].h);
9282 		}
9283 	} else {
9284 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
9285 		if (encoder)
9286 			amdgpu_dm_connector_add_common_modes(encoder, connector);
9287 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
9288 	}
9289 	amdgpu_dm_fbc_init(connector);
9290 
9291 	return amdgpu_dm_connector->num_modes;
9292 }
9293 
9294 static const u32 supported_colorspaces =
9295 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
9296 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
9297 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
9298 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
9299 
9300 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
9301 				     struct amdgpu_dm_connector *aconnector,
9302 				     int connector_type,
9303 				     struct dc_link *link,
9304 				     int link_index)
9305 {
9306 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
9307 
9308 	/*
9309 	 * Some of the properties below require access to state, like bpc.
9310 	 * Allocate some default initial connector state with our reset helper.
9311 	 */
9312 	if (aconnector->base.funcs->reset)
9313 		aconnector->base.funcs->reset(&aconnector->base);
9314 
9315 	aconnector->connector_id = link_index;
9316 	aconnector->bl_idx = -1;
9317 	aconnector->dc_link = link;
9318 	aconnector->base.interlace_allowed = false;
9319 	aconnector->base.doublescan_allowed = false;
9320 	aconnector->base.stereo_allowed = false;
9321 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
9322 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
9323 	aconnector->audio_inst = -1;
9324 	aconnector->pack_sdp_v1_3 = false;
9325 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
9326 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
9327 	mutex_init(&aconnector->hpd_lock);
9328 	mutex_init(&aconnector->handle_mst_msg_ready);
9329 
9330 	/*
9331 	 * If HDMI HPD debounce delay is set, use the minimum between selected
9332 	 * value and AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS
9333 	 */
9334 	if (amdgpu_hdmi_hpd_debounce_delay_ms) {
9335 		aconnector->hdmi_hpd_debounce_delay_ms = min(amdgpu_hdmi_hpd_debounce_delay_ms,
9336 							     AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS);
9337 		INIT_DELAYED_WORK(&aconnector->hdmi_hpd_debounce_work, hdmi_hpd_debounce_work);
9338 		aconnector->hdmi_prev_sink = NULL;
9339 	} else {
9340 		aconnector->hdmi_hpd_debounce_delay_ms = 0;
9341 	}
9342 
9343 	/*
9344 	 * configure support HPD hot plug connector_>polled default value is 0
9345 	 * which means HPD hot plug not supported
9346 	 */
9347 	switch (connector_type) {
9348 	case DRM_MODE_CONNECTOR_HDMIA:
9349 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9350 		aconnector->base.ycbcr_420_allowed =
9351 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
9352 		break;
9353 	case DRM_MODE_CONNECTOR_DisplayPort:
9354 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9355 		link->link_enc = link_enc_cfg_get_link_enc(link);
9356 		ASSERT(link->link_enc);
9357 		if (link->link_enc)
9358 			aconnector->base.ycbcr_420_allowed =
9359 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
9360 		break;
9361 	case DRM_MODE_CONNECTOR_DVID:
9362 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9363 		break;
9364 	case DRM_MODE_CONNECTOR_DVII:
9365 	case DRM_MODE_CONNECTOR_VGA:
9366 		aconnector->base.polled =
9367 			DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT;
9368 		break;
9369 	default:
9370 		break;
9371 	}
9372 
9373 	drm_object_attach_property(&aconnector->base.base,
9374 				dm->ddev->mode_config.scaling_mode_property,
9375 				DRM_MODE_SCALE_NONE);
9376 
9377 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA
9378 		|| (connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root))
9379 		drm_connector_attach_broadcast_rgb_property(&aconnector->base);
9380 
9381 	drm_object_attach_property(&aconnector->base.base,
9382 				adev->mode_info.underscan_property,
9383 				UNDERSCAN_OFF);
9384 	drm_object_attach_property(&aconnector->base.base,
9385 				adev->mode_info.underscan_hborder_property,
9386 				0);
9387 	drm_object_attach_property(&aconnector->base.base,
9388 				adev->mode_info.underscan_vborder_property,
9389 				0);
9390 
9391 	if (!aconnector->mst_root)
9392 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
9393 
9394 	aconnector->base.state->max_bpc = 16;
9395 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
9396 
9397 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9398 		/* Content Type is currently only implemented for HDMI. */
9399 		drm_connector_attach_content_type_property(&aconnector->base);
9400 	}
9401 
9402 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9403 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
9404 			drm_connector_attach_colorspace_property(&aconnector->base);
9405 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
9406 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
9407 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
9408 			drm_connector_attach_colorspace_property(&aconnector->base);
9409 	}
9410 
9411 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9412 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
9413 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
9414 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
9415 
9416 		if (!aconnector->mst_root)
9417 			drm_connector_attach_vrr_capable_property(&aconnector->base);
9418 
9419 		if (adev->dm.hdcp_workqueue)
9420 			drm_connector_attach_content_protection_property(&aconnector->base, true);
9421 	}
9422 
9423 	if (connector_type == DRM_MODE_CONNECTOR_eDP) {
9424 		struct drm_privacy_screen *privacy_screen;
9425 
9426 		drm_connector_attach_panel_type_property(&aconnector->base);
9427 
9428 		privacy_screen = drm_privacy_screen_get(adev_to_drm(adev)->dev, NULL);
9429 		if (!IS_ERR(privacy_screen)) {
9430 			drm_connector_attach_privacy_screen_provider(&aconnector->base,
9431 								     privacy_screen);
9432 		} else if (PTR_ERR(privacy_screen) != -ENODEV) {
9433 			drm_warn(adev_to_drm(adev), "Error getting privacy-screen\n");
9434 		}
9435 	}
9436 }
9437 
9438 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
9439 			      struct i2c_msg *msgs, int num)
9440 {
9441 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
9442 	struct ddc_service *ddc_service = i2c->ddc_service;
9443 	struct i2c_command cmd;
9444 	int i;
9445 	int result = -EIO;
9446 
9447 	if (!ddc_service->ddc_pin)
9448 		return result;
9449 
9450 	cmd.payloads = kzalloc_objs(struct i2c_payload, num);
9451 
9452 	if (!cmd.payloads)
9453 		return result;
9454 
9455 	cmd.number_of_payloads = num;
9456 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
9457 	cmd.speed = 100;
9458 
9459 	for (i = 0; i < num; i++) {
9460 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
9461 		cmd.payloads[i].address = msgs[i].addr;
9462 		cmd.payloads[i].length = msgs[i].len;
9463 		cmd.payloads[i].data = msgs[i].buf;
9464 	}
9465 
9466 	if (i2c->oem) {
9467 		if (dc_submit_i2c_oem(
9468 			    ddc_service->ctx->dc,
9469 			    &cmd))
9470 			result = num;
9471 	} else {
9472 		if (dc_submit_i2c(
9473 			    ddc_service->ctx->dc,
9474 			    ddc_service->link->link_index,
9475 			    &cmd))
9476 			result = num;
9477 	}
9478 
9479 	kfree(cmd.payloads);
9480 	return result;
9481 }
9482 
9483 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
9484 {
9485 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
9486 }
9487 
9488 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
9489 	.master_xfer = amdgpu_dm_i2c_xfer,
9490 	.functionality = amdgpu_dm_i2c_func,
9491 };
9492 
9493 static struct amdgpu_i2c_adapter *
9494 create_i2c(struct ddc_service *ddc_service, bool oem)
9495 {
9496 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
9497 	struct amdgpu_i2c_adapter *i2c;
9498 
9499 	i2c = kzalloc_obj(struct amdgpu_i2c_adapter);
9500 	if (!i2c)
9501 		return NULL;
9502 	i2c->base.owner = THIS_MODULE;
9503 	i2c->base.dev.parent = &adev->pdev->dev;
9504 	i2c->base.algo = &amdgpu_dm_i2c_algo;
9505 	if (oem)
9506 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c OEM bus");
9507 	else
9508 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d",
9509 			 ddc_service->link->link_index);
9510 	i2c_set_adapdata(&i2c->base, i2c);
9511 	i2c->ddc_service = ddc_service;
9512 	i2c->oem = oem;
9513 
9514 	return i2c;
9515 }
9516 
9517 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
9518 {
9519 	struct cec_connector_info conn_info;
9520 	struct drm_device *ddev = aconnector->base.dev;
9521 	struct device *hdmi_dev = ddev->dev;
9522 
9523 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
9524 		drm_info(ddev, "HDMI-CEC feature masked\n");
9525 		return -EINVAL;
9526 	}
9527 
9528 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
9529 	aconnector->notifier =
9530 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
9531 	if (!aconnector->notifier) {
9532 		drm_err(ddev, "Failed to create cec notifier\n");
9533 		return -ENOMEM;
9534 	}
9535 
9536 	return 0;
9537 }
9538 
9539 /*
9540  * Note: this function assumes that dc_link_detect() was called for the
9541  * dc_link which will be represented by this aconnector.
9542  */
9543 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
9544 				    struct amdgpu_dm_connector *aconnector,
9545 				    u32 link_index,
9546 				    struct amdgpu_encoder *aencoder)
9547 {
9548 	int res = 0;
9549 	int connector_type;
9550 	struct dc *dc = dm->dc;
9551 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
9552 	struct amdgpu_i2c_adapter *i2c;
9553 
9554 	/* Not needed for writeback connector */
9555 	link->priv = aconnector;
9556 
9557 
9558 	i2c = create_i2c(link->ddc, false);
9559 	if (!i2c) {
9560 		drm_err(adev_to_drm(dm->adev), "Failed to create i2c adapter data\n");
9561 		return -ENOMEM;
9562 	}
9563 
9564 	aconnector->i2c = i2c;
9565 	res = devm_i2c_add_adapter(dm->adev->dev, &i2c->base);
9566 
9567 	if (res) {
9568 		drm_err(adev_to_drm(dm->adev), "Failed to register hw i2c %d\n", link->link_index);
9569 		goto out_free;
9570 	}
9571 
9572 	connector_type = to_drm_connector_type(link->connector_signal, link->link_id.id);
9573 
9574 	res = drm_connector_init_with_ddc(
9575 			dm->ddev,
9576 			&aconnector->base,
9577 			&amdgpu_dm_connector_funcs,
9578 			connector_type,
9579 			&i2c->base);
9580 
9581 	if (res) {
9582 		drm_err(adev_to_drm(dm->adev), "connector_init failed\n");
9583 		aconnector->connector_id = -1;
9584 		goto out_free;
9585 	}
9586 
9587 	drm_connector_helper_add(
9588 			&aconnector->base,
9589 			&amdgpu_dm_connector_helper_funcs);
9590 
9591 	amdgpu_dm_connector_init_helper(
9592 		dm,
9593 		aconnector,
9594 		connector_type,
9595 		link,
9596 		link_index);
9597 
9598 	drm_connector_attach_encoder(
9599 		&aconnector->base, &aencoder->base);
9600 
9601 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9602 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
9603 		amdgpu_dm_initialize_hdmi_connector(aconnector);
9604 
9605 	if (dc_is_dp_signal(link->connector_signal))
9606 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
9607 
9608 out_free:
9609 	if (res) {
9610 		kfree(i2c);
9611 		aconnector->i2c = NULL;
9612 	}
9613 	return res;
9614 }
9615 
9616 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
9617 {
9618 	switch (adev->mode_info.num_crtc) {
9619 	case 1:
9620 		return 0x1;
9621 	case 2:
9622 		return 0x3;
9623 	case 3:
9624 		return 0x7;
9625 	case 4:
9626 		return 0xf;
9627 	case 5:
9628 		return 0x1f;
9629 	case 6:
9630 	default:
9631 		return 0x3f;
9632 	}
9633 }
9634 
9635 static int amdgpu_dm_encoder_init(struct drm_device *dev,
9636 				  struct amdgpu_encoder *aencoder,
9637 				  uint32_t link_index)
9638 {
9639 	struct amdgpu_device *adev = drm_to_adev(dev);
9640 
9641 	int res = drm_encoder_init(dev,
9642 				   &aencoder->base,
9643 				   &amdgpu_dm_encoder_funcs,
9644 				   DRM_MODE_ENCODER_TMDS,
9645 				   NULL);
9646 
9647 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
9648 
9649 	if (!res)
9650 		aencoder->encoder_id = link_index;
9651 	else
9652 		aencoder->encoder_id = -1;
9653 
9654 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
9655 
9656 	return res;
9657 }
9658 
9659 static void manage_dm_interrupts(struct amdgpu_device *adev,
9660 				 struct amdgpu_crtc *acrtc,
9661 				 struct dm_crtc_state *acrtc_state)
9662 {	/*
9663 	 * We cannot be sure that the frontend index maps to the same
9664 	 * backend index - some even map to more than one.
9665 	 * So we have to go through the CRTC to find the right IRQ.
9666 	 */
9667 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
9668 			adev,
9669 			acrtc->crtc_id);
9670 	struct drm_device *dev = adev_to_drm(adev);
9671 
9672 	struct drm_vblank_crtc_config config = {0};
9673 	struct dc_crtc_timing *timing;
9674 	int offdelay;
9675 
9676 	if (acrtc_state) {
9677 		timing = &acrtc_state->stream->timing;
9678 
9679 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
9680 			   IP_VERSION(3, 5, 0) ||
9681 			   !(adev->flags & AMD_IS_APU)) {
9682 			/*
9683 			 * Older HW and DGPU have issues with instant off;
9684 			 * use a 2 frame offdelay.
9685 			 */
9686 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
9687 						      timing->v_total *
9688 						      timing->h_total,
9689 						      timing->pix_clk_100hz);
9690 
9691 			config.offdelay_ms = offdelay ?: 30;
9692 		} else {
9693 			/* offdelay_ms = 0 will never disable vblank */
9694 			config.offdelay_ms = 1;
9695 			config.disable_immediate = true;
9696 		}
9697 
9698 		drm_crtc_vblank_on_config(&acrtc->base,
9699 					  &config);
9700 		/*
9701 		 * Since pflip_high_irq is no longer registered for DCN, grab an
9702 		 * extra reference to vupdate irq instead to workaround this
9703 		 * issue:
9704 		 * https://gitlab.freedesktop.org/drm/amd/-/work_items/3936
9705 		 *
9706 		 * The callbacks to drm_vblank_on/off should really take care of
9707 		 * this though.
9708 		 */
9709 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9710 		case IP_VERSION(3, 0, 0):
9711 		case IP_VERSION(3, 0, 2):
9712 		case IP_VERSION(3, 0, 3):
9713 		case IP_VERSION(3, 2, 0):
9714 			if (amdgpu_irq_get(adev, &adev->vupdate_irq, irq_type))
9715 				drm_err(dev, "DM_IRQ: Cannot get vupdate irq!\n");
9716 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9717 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
9718 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
9719 #endif
9720 		}
9721 
9722 	} else {
9723 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
9724 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9725 		case IP_VERSION(3, 0, 0):
9726 		case IP_VERSION(3, 0, 2):
9727 		case IP_VERSION(3, 0, 3):
9728 		case IP_VERSION(3, 2, 0):
9729 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9730 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
9731 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
9732 #endif
9733 			if (amdgpu_irq_put(adev, &adev->vupdate_irq, irq_type))
9734 				drm_err(dev, "DM_IRQ: Cannot put vupdate irq!\n");
9735 		}
9736 
9737 		drm_crtc_vblank_off(&acrtc->base);
9738 	}
9739 }
9740 
9741 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
9742 				      struct amdgpu_crtc *acrtc)
9743 {
9744 	int irq_type =
9745 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
9746 
9747 	/* GRPH_PFLIP is not used on DCN; nothing to reapply. */
9748 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) != 0)
9749 		return;
9750 
9751 	/**
9752 	 * This reads the current state for the IRQ and force reapplies
9753 	 * the setting to hardware.
9754 	 */
9755 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
9756 }
9757 
9758 static bool
9759 is_scaling_state_different(const struct dm_connector_state *dm_state,
9760 			   const struct dm_connector_state *old_dm_state)
9761 {
9762 	if (dm_state->scaling != old_dm_state->scaling)
9763 		return true;
9764 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
9765 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
9766 			return true;
9767 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
9768 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
9769 			return true;
9770 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
9771 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
9772 		return true;
9773 	return false;
9774 }
9775 
9776 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
9777 					    struct drm_crtc_state *old_crtc_state,
9778 					    struct drm_connector_state *new_conn_state,
9779 					    struct drm_connector_state *old_conn_state,
9780 					    const struct drm_connector *connector,
9781 					    struct hdcp_workqueue *hdcp_w)
9782 {
9783 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
9784 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
9785 
9786 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
9787 		connector->index, connector->status, connector->dpms);
9788 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
9789 		old_conn_state->content_protection, new_conn_state->content_protection);
9790 
9791 	if (old_crtc_state)
9792 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9793 		old_crtc_state->enable,
9794 		old_crtc_state->active,
9795 		old_crtc_state->mode_changed,
9796 		old_crtc_state->active_changed,
9797 		old_crtc_state->connectors_changed);
9798 
9799 	if (new_crtc_state)
9800 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9801 		new_crtc_state->enable,
9802 		new_crtc_state->active,
9803 		new_crtc_state->mode_changed,
9804 		new_crtc_state->active_changed,
9805 		new_crtc_state->connectors_changed);
9806 
9807 	/* hdcp content type change */
9808 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
9809 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
9810 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9811 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
9812 		return true;
9813 	}
9814 
9815 	/* CP is being re enabled, ignore this */
9816 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
9817 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9818 		if (new_crtc_state && new_crtc_state->mode_changed) {
9819 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9820 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
9821 			return true;
9822 		}
9823 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
9824 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
9825 		return false;
9826 	}
9827 
9828 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
9829 	 *
9830 	 * Handles:	UNDESIRED -> ENABLED
9831 	 */
9832 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
9833 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
9834 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9835 
9836 	/* Stream removed and re-enabled
9837 	 *
9838 	 * Can sometimes overlap with the HPD case,
9839 	 * thus set update_hdcp to false to avoid
9840 	 * setting HDCP multiple times.
9841 	 *
9842 	 * Handles:	DESIRED -> DESIRED (Special case)
9843 	 */
9844 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
9845 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
9846 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9847 		dm_con_state->update_hdcp = false;
9848 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
9849 			__func__);
9850 		return true;
9851 	}
9852 
9853 	/* Hot-plug, headless s3, dpms
9854 	 *
9855 	 * Only start HDCP if the display is connected/enabled.
9856 	 * update_hdcp flag will be set to false until the next
9857 	 * HPD comes in.
9858 	 *
9859 	 * Handles:	DESIRED -> DESIRED (Special case)
9860 	 */
9861 	if (dm_con_state->update_hdcp &&
9862 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
9863 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
9864 		dm_con_state->update_hdcp = false;
9865 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
9866 			__func__);
9867 		return true;
9868 	}
9869 
9870 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
9871 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9872 			if (new_crtc_state && new_crtc_state->mode_changed) {
9873 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
9874 					__func__);
9875 				return true;
9876 			}
9877 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
9878 				__func__);
9879 			return false;
9880 		}
9881 
9882 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
9883 		return false;
9884 	}
9885 
9886 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9887 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
9888 			__func__);
9889 		return true;
9890 	}
9891 
9892 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
9893 	return false;
9894 }
9895 
9896 static void remove_stream(struct amdgpu_device *adev,
9897 			  struct amdgpu_crtc *acrtc,
9898 			  struct dc_stream_state *stream)
9899 {
9900 	/* this is the update mode case */
9901 
9902 	acrtc->otg_inst = -1;
9903 	acrtc->enabled = false;
9904 }
9905 
9906 static void update_freesync_state_on_stream(
9907 	struct amdgpu_display_manager *dm,
9908 	struct dm_crtc_state *new_crtc_state,
9909 	struct dc_stream_state *new_stream,
9910 	struct dc_plane_state *surface,
9911 	u32 flip_timestamp_in_us)
9912 {
9913 	struct mod_vrr_params vrr_params;
9914 	struct dc_info_packet vrr_infopacket = {0};
9915 	struct amdgpu_device *adev = dm->adev;
9916 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9917 	unsigned long flags;
9918 	bool pack_sdp_v1_3 = false;
9919 	struct amdgpu_dm_connector *aconn;
9920 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
9921 
9922 	if (!new_stream)
9923 		return;
9924 
9925 	/*
9926 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9927 	 * For now it's sufficient to just guard against these conditions.
9928 	 */
9929 
9930 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9931 		return;
9932 
9933 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9934 	vrr_params = acrtc->dm_irq_params.vrr_params;
9935 
9936 	if (surface) {
9937 		mod_freesync_handle_preflip(
9938 			dm->freesync_module,
9939 			surface,
9940 			new_stream,
9941 			flip_timestamp_in_us,
9942 			&vrr_params);
9943 
9944 		if (adev->family < AMDGPU_FAMILY_AI &&
9945 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
9946 			mod_freesync_handle_v_update(dm->freesync_module,
9947 						     new_stream, &vrr_params);
9948 
9949 			/* Need to call this before the frame ends. */
9950 			dc_stream_adjust_vmin_vmax(dm->dc,
9951 						   new_crtc_state->stream,
9952 						   &vrr_params.adjust);
9953 		}
9954 	}
9955 
9956 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
9957 
9958 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
9959 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
9960 
9961 		if (aconn->vsdb_info.amd_vsdb_version == 1)
9962 			packet_type = PACKET_TYPE_FS_V1;
9963 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
9964 			packet_type = PACKET_TYPE_FS_V2;
9965 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
9966 			packet_type = PACKET_TYPE_FS_V3;
9967 
9968 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
9969 					&new_stream->adaptive_sync_infopacket);
9970 	}
9971 
9972 	mod_freesync_build_vrr_infopacket(
9973 		dm->freesync_module,
9974 		new_stream,
9975 		&vrr_params,
9976 		packet_type,
9977 		TRANSFER_FUNC_UNKNOWN,
9978 		&vrr_infopacket,
9979 		pack_sdp_v1_3);
9980 
9981 	new_crtc_state->freesync_vrr_info_changed |=
9982 		(memcmp(&new_crtc_state->vrr_infopacket,
9983 			&vrr_infopacket,
9984 			sizeof(vrr_infopacket)) != 0);
9985 
9986 	acrtc->dm_irq_params.vrr_params = vrr_params;
9987 	new_crtc_state->vrr_infopacket = vrr_infopacket;
9988 
9989 	new_stream->vrr_infopacket = vrr_infopacket;
9990 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
9991 
9992 	if (new_crtc_state->freesync_vrr_info_changed)
9993 		drm_dbg_kms(adev_to_drm(adev), "VRR packet update: crtc=%u enabled=%d state=%d",
9994 			      new_crtc_state->base.crtc->base.id,
9995 			      (int)new_crtc_state->base.vrr_enabled,
9996 			      (int)vrr_params.state);
9997 
9998 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9999 }
10000 
10001 static void update_stream_irq_parameters(
10002 	struct amdgpu_display_manager *dm,
10003 	struct dm_crtc_state *new_crtc_state)
10004 {
10005 	struct dc_stream_state *new_stream = new_crtc_state->stream;
10006 	struct mod_vrr_params vrr_params;
10007 	struct mod_freesync_config config = new_crtc_state->freesync_config;
10008 	struct amdgpu_device *adev = dm->adev;
10009 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
10010 	unsigned long flags;
10011 
10012 	if (!new_stream)
10013 		return;
10014 
10015 	/*
10016 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
10017 	 * For now it's sufficient to just guard against these conditions.
10018 	 */
10019 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
10020 		return;
10021 
10022 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
10023 	vrr_params = acrtc->dm_irq_params.vrr_params;
10024 
10025 	if (new_crtc_state->vrr_supported &&
10026 	    config.min_refresh_in_uhz &&
10027 	    config.max_refresh_in_uhz) {
10028 		/*
10029 		 * if freesync compatible mode was set, config.state will be set
10030 		 * in atomic check
10031 		 */
10032 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
10033 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
10034 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
10035 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
10036 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
10037 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
10038 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
10039 		} else {
10040 			config.state = new_crtc_state->base.vrr_enabled ?
10041 						     VRR_STATE_ACTIVE_VARIABLE :
10042 						     VRR_STATE_INACTIVE;
10043 		}
10044 	} else {
10045 		config.state = VRR_STATE_UNSUPPORTED;
10046 	}
10047 
10048 	mod_freesync_build_vrr_params(dm->freesync_module,
10049 				      new_stream,
10050 				      &config, &vrr_params);
10051 
10052 	new_crtc_state->freesync_config = config;
10053 	/* Copy state for access from DM IRQ handler */
10054 	acrtc->dm_irq_params.freesync_config = config;
10055 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
10056 	acrtc->dm_irq_params.vrr_params = vrr_params;
10057 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10058 }
10059 
10060 static void amdgpu_dm_handle_vrr_transition(struct amdgpu_display_manager *dm,
10061 					    struct dm_crtc_state *old_state,
10062 					    struct dm_crtc_state *new_state)
10063 {
10064 	struct amdgpu_device *adev = drm_to_adev(new_state->base.crtc->dev);
10065 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
10066 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
10067 
10068 	/* Only DCE gates vupdate on VRR, keep it enabled for DCN */
10069 	bool vrr_gates_vupdate = amdgpu_ip_version(adev, DCE_HWIP, 0) == 0;
10070 
10071 	if (!old_vrr_active && new_vrr_active) {
10072 		/* Transition VRR inactive -> active:
10073 		 * While VRR is active, we must not disable vblank irq, as a
10074 		 * reenable after disable would compute bogus vblank/pflip
10075 		 * timestamps if it likely happened inside display front-porch.
10076 		 *
10077 		 * We also need vupdate irq for the actual core vblank handling
10078 		 * at end of vblank.
10079 		 */
10080 		if (vrr_gates_vupdate)
10081 			WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
10082 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
10083 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR off->on: Get vblank ref\n",
10084 				 __func__, new_state->base.crtc->base.id);
10085 
10086 		scoped_guard(mutex, &dm->dc_lock) {
10087 			dc_exit_ips_for_hw_access(dm->dc);
10088 			amdgpu_dm_psr_set_event(dm, new_state->stream, true,
10089 				psr_event_vrr_transition, true);
10090 			amdgpu_dm_replay_set_event(dm, new_state->stream, true,
10091 				replay_event_vrr, true);
10092 		}
10093 	} else if (old_vrr_active && !new_vrr_active) {
10094 		/* Transition VRR active -> inactive:
10095 		 * Allow vblank irq disable again for fixed refresh rate.
10096 		 */
10097 		if (vrr_gates_vupdate)
10098 			WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
10099 		drm_crtc_vblank_put(new_state->base.crtc);
10100 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR on->off: Drop vblank ref\n",
10101 				 __func__, new_state->base.crtc->base.id);
10102 
10103 		scoped_guard(mutex, &dm->dc_lock) {
10104 			dc_exit_ips_for_hw_access(dm->dc);
10105 			amdgpu_dm_psr_set_event(dm, new_state->stream, false,
10106 				psr_event_vrr_transition, false);
10107 			amdgpu_dm_replay_set_event(dm, new_state->stream, false,
10108 				replay_event_vrr, false);
10109 		}
10110 	}
10111 }
10112 
10113 static void amdgpu_dm_commit_cursors(struct drm_atomic_commit *state)
10114 {
10115 	struct drm_plane *plane;
10116 	struct drm_plane_state *old_plane_state;
10117 	int i;
10118 
10119 	/*
10120 	 * TODO: Make this per-stream so we don't issue redundant updates for
10121 	 * commits with multiple streams.
10122 	 */
10123 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
10124 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
10125 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
10126 }
10127 
10128 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
10129 {
10130 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
10131 
10132 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
10133 }
10134 
10135 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
10136 				    struct drm_plane_state *old_plane_state,
10137 				    struct dc_stream_update *update)
10138 {
10139 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
10140 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
10141 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
10142 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
10143 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
10144 	uint64_t address = afb ? afb->address : 0;
10145 	struct dc_cursor_position position = {0};
10146 	struct dc_cursor_attributes attributes;
10147 	int ret;
10148 
10149 	if (!plane->state->fb && !old_plane_state->fb)
10150 		return;
10151 
10152 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
10153 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
10154 		       plane->state->crtc_h);
10155 
10156 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
10157 	if (ret)
10158 		return;
10159 
10160 	if (!position.enable) {
10161 		/* turn off cursor */
10162 		if (crtc_state && crtc_state->stream) {
10163 			dc_stream_set_cursor_position(crtc_state->stream,
10164 						      &position);
10165 			update->cursor_position = &crtc_state->stream->cursor_position;
10166 		}
10167 		return;
10168 	}
10169 
10170 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
10171 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
10172 
10173 	memset(&attributes, 0, sizeof(attributes));
10174 	attributes.address.high_part = upper_32_bits(address);
10175 	attributes.address.low_part  = lower_32_bits(address);
10176 	attributes.width             = plane->state->crtc_w;
10177 	attributes.height            = plane->state->crtc_h;
10178 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
10179 	attributes.rotation_angle    = 0;
10180 	attributes.attribute_flags.value = 0;
10181 
10182 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
10183 	 * legacy gamma setup.
10184 	 */
10185 	if (crtc_state->cm_is_degamma_srgb &&
10186 	    adev->dm.dc->caps.color.dpp.gamma_corr)
10187 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
10188 
10189 	if (afb)
10190 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
10191 
10192 	if (crtc_state->stream) {
10193 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
10194 						     &attributes))
10195 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
10196 
10197 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
10198 
10199 		if (!dc_stream_set_cursor_position(crtc_state->stream,
10200 						   &position))
10201 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
10202 
10203 		update->cursor_position = &crtc_state->stream->cursor_position;
10204 	}
10205 }
10206 
10207 static void amdgpu_dm_enable_self_refresh(struct amdgpu_display_manager *dm,
10208 					  struct amdgpu_crtc *acrtc_attach,
10209 					  const struct dm_crtc_state *acrtc_state,
10210 					  const u64 current_ts)
10211 {
10212 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
10213 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
10214 	struct amdgpu_dm_connector *aconn =
10215 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
10216 
10217 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
10218 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
10219 	    (psr->psr_feature_enabled || pr->replay_feature_enabled)) {
10220 		if (aconn->sr_skip_count > 0)
10221 			aconn->sr_skip_count--;
10222 
10223 		/* Allow SR when skip count is 0. */
10224 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
10225 
10226 		/*
10227 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
10228 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
10229 		 * can be enabled immediately once OS demonstrates an
10230 		 * adequate number of fast atomic commits to notify KMD
10231 		 * of update events.
10232 		 * See `amdgpu_dm_crtc_vblank_control_worker()`.
10233 		 */
10234 		if (acrtc_attach->dm_irq_params.allow_sr_entry &&
10235 			(current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
10236 			amdgpu_dm_psr_set_event(dm, acrtc_state->stream, false,
10237 				psr_event_hw_programming, false);
10238 
10239 			amdgpu_dm_replay_set_event(dm, acrtc_state->stream, false,
10240 				replay_event_hw_programming, false);
10241 		}
10242 	} else {
10243 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
10244 	}
10245 }
10246 
10247 static void dm_arm_vblank_event(struct amdgpu_crtc *acrtc,
10248 				struct dm_crtc_state *acrtc_state,
10249 				bool pflip_update,
10250 				bool cursor_update)
10251 {
10252 	assert_spin_locked(&acrtc->base.dev->event_lock);
10253 
10254 	if (!acrtc->base.state->event || acrtc_state->active_planes == 0)
10255 		return;
10256 
10257 	if (pflip_update) {
10258 		WARN_ON(acrtc->pflip_status != AMDGPU_FLIP_NONE);
10259 		WARN_ON(acrtc->event);
10260 
10261 		acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
10262 		acrtc->event = acrtc->base.state->event;
10263 		acrtc->base.state->event = NULL;
10264 
10265 		drm_dbg_state(acrtc->base.dev,
10266 			      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
10267 			      acrtc->crtc_id);
10268 	} else if (cursor_update) {
10269 		acrtc->event = acrtc->base.state->event;
10270 		acrtc->base.state->event = NULL;
10271 	}
10272 }
10273 
10274 /**
10275  * dm_arm_vblank_event_pre_programming - Prepare for programming
10276  * @acrtc: The amdgpu CRTC to prepare
10277  * @acrtc_state: The new CRTC state
10278  * @pflip_update: Whether a page flip is being programmed
10279  * @cursor_update: Whether a cursor update is being programmed
10280  *
10281  * Grab a reference on the vblank counter if a page flip or cursor update is to
10282  * be programmed. Do this before programming so the HW is not in any
10283  * idle-optimized state (such as PSR).
10284  */
10285 static void dm_arm_vblank_event_pre_programming(struct amdgpu_crtc *acrtc,
10286 						struct dm_crtc_state *acrtc_state,
10287 						bool pflip_update,
10288 						bool cursor_update)
10289 {
10290 	assert_spin_locked(&acrtc->base.dev->event_lock);
10291 
10292 	if (!acrtc->base.state->event || acrtc_state->active_planes == 0)
10293 		return;
10294 
10295 	if (pflip_update || cursor_update)
10296 		drm_crtc_vblank_get(&acrtc->base);
10297 }
10298 
10299 static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state,
10300 				    struct drm_device *dev,
10301 				    struct amdgpu_display_manager *dm,
10302 				    struct drm_crtc *pcrtc,
10303 				    bool wait_for_vblank)
10304 {
10305 	u32 i;
10306 	u64 timestamp_ns = ktime_get_ns();
10307 	struct drm_plane *plane;
10308 	struct drm_plane_state *old_plane_state, *new_plane_state;
10309 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
10310 	struct drm_crtc_state *new_pcrtc_state =
10311 			drm_atomic_get_new_crtc_state(state, pcrtc);
10312 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
10313 	struct dm_crtc_state *dm_old_crtc_state =
10314 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
10315 	int planes_count = 0, vpos, hpos;
10316 	unsigned long flags;
10317 	u32 target_vblank, last_flip_vblank;
10318 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
10319 	bool cursor_update = false;
10320 	bool pflip_present = false;
10321 	bool immediate_flip = false;
10322 	bool flip_latched_during_prog = false;
10323 	bool dirty_rects_changed = false;
10324 	bool updated_planes_and_streams = false;
10325 	struct {
10326 		struct dc_surface_update surface_updates[MAX_SURFACES];
10327 		struct dc_plane_info plane_infos[MAX_SURFACES];
10328 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
10329 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
10330 		struct dc_stream_update stream_update;
10331 	} *bundle;
10332 
10333 	bundle = kzalloc_obj(*bundle);
10334 
10335 	if (!bundle) {
10336 		drm_err(dev, "Failed to allocate update bundle\n");
10337 		goto cleanup;
10338 	}
10339 
10340 	/*
10341 	 * Disable the cursor first if we're disabling all the planes.
10342 	 * It'll remain on the screen after the planes are re-enabled
10343 	 * if we don't.
10344 	 *
10345 	 * If the cursor is transitioning from native to overlay mode, the
10346 	 * native cursor needs to be disabled first.
10347 	 */
10348 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
10349 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10350 		struct dc_cursor_position cursor_position = {0};
10351 
10352 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
10353 						   &cursor_position))
10354 			drm_err(dev, "DC failed to disable native cursor\n");
10355 
10356 		bundle->stream_update.cursor_position =
10357 				&acrtc_state->stream->cursor_position;
10358 	}
10359 
10360 	if (acrtc_state->active_planes == 0 &&
10361 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10362 		amdgpu_dm_commit_cursors(state);
10363 
10364 	/* update planes when needed */
10365 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
10366 		struct drm_crtc *crtc = new_plane_state->crtc;
10367 		struct drm_crtc_state *new_crtc_state;
10368 		struct drm_framebuffer *fb = new_plane_state->fb;
10369 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
10370 		bool plane_needs_flip;
10371 		struct dc_plane_state *dc_plane;
10372 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
10373 
10374 		/* Cursor plane is handled after stream updates */
10375 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
10376 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10377 			if ((fb && crtc == pcrtc) ||
10378 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
10379 				cursor_update = true;
10380 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
10381 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
10382 			}
10383 
10384 			continue;
10385 		}
10386 
10387 		if (!fb || !crtc || pcrtc != crtc)
10388 			continue;
10389 
10390 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
10391 		if (!new_crtc_state->active)
10392 			continue;
10393 
10394 		dc_plane = dm_new_plane_state->dc_state;
10395 		if (!dc_plane)
10396 			continue;
10397 
10398 		bundle->surface_updates[planes_count].surface = dc_plane;
10399 		if (new_pcrtc_state->color_mgmt_changed || new_plane_state->color_mgmt_changed) {
10400 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
10401 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
10402 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
10403 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
10404 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
10405 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
10406 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
10407 		}
10408 
10409 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
10410 				     &bundle->scaling_infos[planes_count]);
10411 
10412 		bundle->surface_updates[planes_count].scaling_info =
10413 			&bundle->scaling_infos[planes_count];
10414 
10415 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
10416 
10417 		pflip_present = pflip_present || plane_needs_flip;
10418 
10419 		if (!plane_needs_flip) {
10420 			planes_count += 1;
10421 			continue;
10422 		}
10423 
10424 		fill_dc_plane_info_and_addr(
10425 			dm->adev, new_plane_state,
10426 			afb->tiling_flags,
10427 			&bundle->plane_infos[planes_count],
10428 			&bundle->flip_addrs[planes_count].address,
10429 			afb->tmz_surface);
10430 
10431 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
10432 				 new_plane_state->plane->index,
10433 				 bundle->plane_infos[planes_count].dcc.enable);
10434 
10435 		bundle->surface_updates[planes_count].plane_info =
10436 			&bundle->plane_infos[planes_count];
10437 
10438 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
10439 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
10440 			fill_dc_dirty_rects(plane, old_plane_state,
10441 					    new_plane_state, new_crtc_state,
10442 					    &bundle->flip_addrs[planes_count],
10443 					    acrtc_state->stream->link->psr_settings.psr_version ==
10444 					    DC_PSR_VERSION_SU_1,
10445 					    &dirty_rects_changed);
10446 
10447 			/*
10448 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
10449 			 * and enabled it again after dirty regions are stable to avoid video glitch.
10450 			 * PSR-SU will be enabled in
10451 			 * amdgpu_dm_crtc_vblank_control_worker() if user
10452 			 * pause the video during the PSR-SU was disabled.
10453 			 */
10454 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
10455 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
10456 			    dirty_rects_changed) {
10457 				mutex_lock(&dm->dc_lock);
10458 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
10459 				timestamp_ns;
10460 				dc_exit_ips_for_hw_access(dm->dc);
10461 				amdgpu_dm_psr_set_event(dm, acrtc_state->stream, true,
10462 					psr_event_hw_programming, true);
10463 				mutex_unlock(&dm->dc_lock);
10464 			}
10465 		}
10466 
10467 		/*
10468 		 * Only allow immediate flips for fast updates that don't
10469 		 * change memory domain, FB pitch, DCC state, rotation or
10470 		 * mirroring.
10471 		 *
10472 		 * dm_crtc_helper_atomic_check() only accepts async flips with
10473 		 * fast updates.
10474 		 */
10475 		if (crtc->state->async_flip &&
10476 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
10477 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
10478 			drm_warn_once(state->dev,
10479 				      "[PLANE:%d:%s] async flip with non-fast update\n",
10480 				      plane->base.id, plane->name);
10481 
10482 		bundle->flip_addrs[planes_count].flip_immediate =
10483 			crtc->state->async_flip &&
10484 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
10485 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
10486 
10487 		immediate_flip |= bundle->flip_addrs[planes_count].flip_immediate;
10488 
10489 		timestamp_ns = ktime_get_ns();
10490 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
10491 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
10492 		bundle->surface_updates[planes_count].surface = dc_plane;
10493 
10494 		if (!bundle->surface_updates[planes_count].surface) {
10495 			drm_err(dev, "No surface for CRTC: id=%d\n",
10496 					acrtc_attach->crtc_id);
10497 			continue;
10498 		}
10499 
10500 		if (plane == pcrtc->primary)
10501 			update_freesync_state_on_stream(
10502 				dm,
10503 				acrtc_state,
10504 				acrtc_state->stream,
10505 				dc_plane,
10506 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
10507 
10508 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
10509 				 __func__,
10510 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
10511 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
10512 
10513 		planes_count += 1;
10514 
10515 	}
10516 
10517 	if (pflip_present) {
10518 		if (!vrr_active) {
10519 			/* Use old throttling in non-vrr fixed refresh rate mode
10520 			 * to keep flip scheduling based on target vblank counts
10521 			 * working in a backwards compatible way, e.g., for
10522 			 * clients using the GLX_OML_sync_control extension or
10523 			 * DRI3/Present extension with defined target_msc.
10524 			 */
10525 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
10526 		} else {
10527 			/* For variable refresh rate mode only:
10528 			 * Get vblank of last completed flip to avoid > 1 vrr
10529 			 * flips per video frame by use of throttling, but allow
10530 			 * flip programming anywhere in the possibly large
10531 			 * variable vrr vblank interval for fine-grained flip
10532 			 * timing control and more opportunity to avoid stutter
10533 			 * on late submission of flips.
10534 			 */
10535 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10536 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
10537 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10538 		}
10539 
10540 		target_vblank = last_flip_vblank + wait_for_vblank;
10541 
10542 		/*
10543 		 * Wait until we're out of the vertical blank period before the one
10544 		 * targeted by the flip
10545 		 */
10546 		while ((acrtc_attach->enabled &&
10547 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
10548 							    0, &vpos, &hpos, NULL,
10549 							    NULL, &pcrtc->hwmode)
10550 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
10551 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
10552 			(int)(target_vblank -
10553 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
10554 			usleep_range(1000, 1100);
10555 		}
10556 
10557 		if (acrtc_state->stream) {
10558 			if (acrtc_state->freesync_vrr_info_changed)
10559 				bundle->stream_update.vrr_infopacket =
10560 					&acrtc_state->stream->vrr_infopacket;
10561 		}
10562 	}
10563 
10564 	scoped_guard(spinlock_irqsave, &pcrtc->dev->event_lock) {
10565 		dm_arm_vblank_event_pre_programming(acrtc_attach, acrtc_state,
10566 						    pflip_present,
10567 						    cursor_update);
10568 		/*
10569 		 * DCE depends on a combination of GRPH_FLIP, VLINE0, and
10570 		 * VUPDATE for event delivery. Only GRPH_FLIP handler can send
10571 		 * pflip events, and it only fires if HW latched to the flip.
10572 		 * Maintain legacy behavior by arming event before programming.
10573 		 */
10574 		if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) {
10575 			dm_arm_vblank_event(acrtc_attach, acrtc_state,
10576 					    pflip_present, cursor_update);
10577 		}
10578 	}
10579 
10580 	/* Update the planes if changed or disable if we don't have any. */
10581 	if ((planes_count || acrtc_state->active_planes == 0) &&
10582 		acrtc_state->stream) {
10583 		/*
10584 		 * If PSR or idle optimizations are enabled then flush out
10585 		 * any pending work before hardware programming.
10586 		 */
10587 		if (dm->vblank_control_workqueue)
10588 			flush_workqueue(dm->vblank_control_workqueue);
10589 
10590 		bundle->stream_update.stream = acrtc_state->stream;
10591 		if (new_pcrtc_state->mode_changed) {
10592 			bundle->stream_update.src = acrtc_state->stream->src;
10593 			bundle->stream_update.dst = acrtc_state->stream->dst;
10594 		}
10595 
10596 		if (new_pcrtc_state->color_mgmt_changed) {
10597 			/*
10598 			 * TODO: This isn't fully correct since we've actually
10599 			 * already modified the stream in place.
10600 			 */
10601 			bundle->stream_update.gamut_remap =
10602 				&acrtc_state->stream->gamut_remap_matrix;
10603 			bundle->stream_update.output_csc_transform =
10604 				&acrtc_state->stream->csc_color_matrix;
10605 			bundle->stream_update.out_transfer_func =
10606 				&acrtc_state->stream->out_transfer_func;
10607 			bundle->stream_update.lut3d_func =
10608 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
10609 			bundle->stream_update.func_shaper =
10610 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
10611 		}
10612 
10613 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
10614 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
10615 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
10616 
10617 		/*
10618 		 * If FreeSync state on the stream has changed then we need to
10619 		 * re-adjust the min/max bounds now that DC doesn't handle this
10620 		 * as part of commit.
10621 		 */
10622 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
10623 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10624 			dc_stream_adjust_vmin_vmax(
10625 				dm->dc, acrtc_state->stream,
10626 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
10627 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10628 		}
10629 		mutex_lock(&dm->dc_lock);
10630 		update_planes_and_stream_adapter(dm->dc,
10631 					 acrtc_state->update_type,
10632 					 planes_count,
10633 					 acrtc_state->stream,
10634 					 &bundle->stream_update,
10635 					 bundle->surface_updates);
10636 		updated_planes_and_streams = true;
10637 
10638 		/**
10639 		 * Enable or disable the interrupts on the backend.
10640 		 *
10641 		 * Most pipes are put into power gating when unused.
10642 		 *
10643 		 * When power gating is enabled on a pipe we lose the
10644 		 * interrupt enablement state when power gating is disabled.
10645 		 *
10646 		 * So we need to update the IRQ control state in hardware
10647 		 * whenever the pipe turns on (since it could be previously
10648 		 * power gated) or off (since some pipes can't be power gated
10649 		 * on some ASICs).
10650 		 */
10651 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
10652 			dm_update_pflip_irq_state(drm_to_adev(dev),
10653 						  acrtc_attach);
10654 		amdgpu_dm_enable_self_refresh(dm, acrtc_attach, acrtc_state,
10655 					      timestamp_ns);
10656 		mutex_unlock(&dm->dc_lock);
10657 	}
10658 
10659 	/*
10660 	 * Update cursor state *after* programming all the planes.
10661 	 * This avoids redundant programming in the case where we're going
10662 	 * to be disabling a single plane - those pipes are being disabled.
10663 	 */
10664 	if (acrtc_state->active_planes &&
10665 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
10666 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10667 		amdgpu_dm_commit_cursors(state);
10668 
10669 	/*
10670 	 * DCN specific vblank handling
10671 	 * ============================
10672 	 *
10673 	 * With the event_lock held, arm the vblank event, and determine whether
10674 	 * deliver it immediately, or in VUPDATE_NO_LOCK IRQ (i.e. HW latch
10675 	 * point) handler. Do this *after* programming so that the IRQ handler
10676 	 * will not deliver the event before HW laches onto the programmed
10677 	 * values:
10678 	 *
10679 	 *     Commit thread      IRQ handler                       HW
10680 	 *     -----------------------------------------------------------------
10681 	 *     arm_vblank_event()
10682 	 *                                                          vupdate()
10683 	 *                        vupdate_handler()
10684 	 *                          cook_timestamp()
10685 	 *                          # prev flip already latched,
10686 	 *                          # so flip_latched == true.
10687 	 *                          if event_armed && flip_latched:
10688 	 *                            send_vblank_event()
10689 	 *                            # sent before latch, **BAD!**
10690 	 *     hw_program()
10691 	 *                                                          vupdate()
10692 	 *                                                          **latch**
10693 	 *
10694 	 * There's a consequence of arming after: it's possible for HW to latch
10695 	 * between start of HW programming and acrtc->event/pflip_status arming.
10696 	 * When this happens, the IRQ handler will send the event on the next
10697 	 * immediate latch point, even though HW has already latched. This is
10698 	 * handled by optimistically checking for HW latch after programming,
10699 	 * and if latched, send the event immediately:
10700 	 *
10701 	 *     Commit thread             IRQ handler                HW
10702 	 *     -----------------------------------------------------------------
10703 	 *     hw_program()
10704 	 *                                                          vupdate()
10705 	 *                                                          **latch**
10706 	 *                               vupdate_handler()
10707 	 *                                 cook_timestamp()
10708 	 *                                 # event_armed == false
10709 	 *                                 # **no event sent!**
10710 	 *     arm_vblank_event()
10711 	 *     if flip_latched:
10712 	 *       **send_vblank_event()**
10713 	 *       disarm_vblank_event()
10714 	 *
10715 	 * The IRQ handler is expected to cook the timestamp, but we need to
10716 	 * cook the timestamp before optimistic sending as well. That's because
10717 	 * the following sequence is possible:
10718 	 *
10719 	 *     Commit thread              IRQ handler              HW
10720 	 *     -----------------------------------------------------------------
10721 	 *     hw_program()
10722 	 *     arm_vblank_event()
10723 	 *                                                         vupdate()
10724 	 *                                                         **latch**
10725 	 *     if flip_latched:
10726 	 *       # Need cook before send!
10727 	 *       **cook_timestamp()**
10728 	 *       send_vblank_event()
10729 	 *       disarm_vblank_event()
10730 	 *                                vupdate_handler()
10731 	 *                                  cook_timestamp()
10732 	 *                                  # event_armed == false
10733 	 *                                  # no event sent!
10734 	 *
10735 	 * Cooking twice is OK, since DRM scanout accurate timestamps report A)
10736 	 * the previous vactive start if currently in vactive, or B) the next
10737 	 * vactive start if currently in vblank (see &get_vblank_counter). 'A)'
10738 	 * is what we want for the optimistic send, and for 'B)', we'll cook a
10739 	 * timestamp no later than the next IRQ handler run.
10740 	 *
10741 	 * The more correct fix is to wrap programming and arming with the
10742 	 * event_lock and thus serializing it with the IRQ handler. However,
10743 	 * there are various sleep-waits within
10744 	 * update_planes_and_stream_adapter() that makes spin locking illegal.
10745 	 * And on full updates, it can take 1-2 frame-times to return (see
10746 	 * commit_planes_for_stream).
10747 	 *
10748 	 * On DCE, GRPH_PFLIP IRQ is used and takes care of this.
10749 	 */
10750 	if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0) {
10751 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10752 
10753 		if (updated_planes_and_streams) {
10754 			flip_latched_during_prog =
10755 				!dc_get_flip_pending_on_otg(dm->dc, acrtc_attach->otg_inst);
10756 		}
10757 
10758 		dm_arm_vblank_event(acrtc_attach, acrtc_state,
10759 				    pflip_present, cursor_update);
10760 
10761 		/*
10762 		 * Deliver the event immediately on immediate flip, or on a
10763 		 * update that has already latched.
10764 		 */
10765 		if ((immediate_flip || flip_latched_during_prog) &&
10766 		    acrtc_attach->pflip_status == AMDGPU_FLIP_SUBMITTED &&
10767 		    acrtc_attach->event) {
10768 			drm_crtc_accurate_vblank_count(&acrtc_attach->base);
10769 			drm_crtc_send_vblank_event(&acrtc_attach->base,
10770 						   acrtc_attach->event);
10771 			acrtc_attach->event = NULL;
10772 			drm_crtc_vblank_put(&acrtc_attach->base);
10773 			acrtc_attach->pflip_status = AMDGPU_FLIP_NONE;
10774 		}
10775 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10776 	}
10777 
10778 cleanup:
10779 	kfree(bundle);
10780 }
10781 
10782 static void amdgpu_dm_commit_audio(struct drm_device *dev,
10783 				   struct drm_atomic_commit *state)
10784 {
10785 	struct amdgpu_device *adev = drm_to_adev(dev);
10786 	struct amdgpu_dm_connector *aconnector;
10787 	struct drm_connector *connector;
10788 	struct drm_connector_state *old_con_state, *new_con_state;
10789 	struct drm_crtc_state *new_crtc_state;
10790 	struct dm_crtc_state *new_dm_crtc_state;
10791 	const struct dc_stream_status *status;
10792 	int i, inst;
10793 
10794 	/* Notify device removals. */
10795 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10796 		if (old_con_state->crtc != new_con_state->crtc) {
10797 			/* CRTC changes require notification. */
10798 			goto notify;
10799 		}
10800 
10801 		if (!new_con_state->crtc)
10802 			continue;
10803 
10804 		new_crtc_state = drm_atomic_get_new_crtc_state(
10805 			state, new_con_state->crtc);
10806 
10807 		if (!new_crtc_state)
10808 			continue;
10809 
10810 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10811 			continue;
10812 
10813 notify:
10814 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10815 			continue;
10816 
10817 		aconnector = to_amdgpu_dm_connector(connector);
10818 
10819 		mutex_lock(&adev->dm.audio_lock);
10820 		inst = aconnector->audio_inst;
10821 		aconnector->audio_inst = -1;
10822 		mutex_unlock(&adev->dm.audio_lock);
10823 
10824 		amdgpu_dm_audio_eld_notify(adev, inst);
10825 	}
10826 
10827 	/* Notify audio device additions. */
10828 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10829 		if (!new_con_state->crtc)
10830 			continue;
10831 
10832 		new_crtc_state = drm_atomic_get_new_crtc_state(
10833 			state, new_con_state->crtc);
10834 
10835 		if (!new_crtc_state)
10836 			continue;
10837 
10838 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10839 			continue;
10840 
10841 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
10842 		if (!new_dm_crtc_state->stream)
10843 			continue;
10844 
10845 		status = dc_stream_get_status(new_dm_crtc_state->stream);
10846 		if (!status)
10847 			continue;
10848 
10849 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10850 			continue;
10851 
10852 		aconnector = to_amdgpu_dm_connector(connector);
10853 
10854 		mutex_lock(&adev->dm.audio_lock);
10855 		inst = status->audio_inst;
10856 		aconnector->audio_inst = inst;
10857 		mutex_unlock(&adev->dm.audio_lock);
10858 
10859 		amdgpu_dm_audio_eld_notify(adev, inst);
10860 	}
10861 }
10862 
10863 /*
10864  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
10865  * @crtc_state: the DRM CRTC state
10866  * @stream_state: the DC stream state.
10867  *
10868  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
10869  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
10870  */
10871 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
10872 						struct dc_stream_state *stream_state)
10873 {
10874 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
10875 }
10876 
10877 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
10878 			      struct dm_crtc_state *crtc_state)
10879 {
10880 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
10881 }
10882 
10883 /**
10884  * amdgpu_dm_mod_power_update_streams - update mod_power stream state on modeset
10885  * @state: the drm atomic state
10886  * @dm: the display manager to update mod_power on
10887  *
10888  * Notify mod_power of stream changes on modeset events, and disable PSR/Replay
10889  * in preparation for hardware programming. See also
10890  * amdgpu_dm_mod_power_setup_streams() for post-modeset mod_power setup.
10891  */
10892 static void amdgpu_dm_mod_power_update_streams(struct drm_atomic_commit *state,
10893 					       struct amdgpu_display_manager *dm)
10894 {
10895 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10896 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10897 	struct amdgpu_dm_connector *aconnector;
10898 	struct drm_crtc *crtc;
10899 	int i = 0;
10900 
10901 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10902 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10903 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10904 
10905 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10906 			continue;
10907 
10908 		/*
10909 		 * Update mod_power on modeset event in preparation for hw
10910 		 * programming. Always use the old stream, since it would have
10911 		 * been previously added to mod_power. If old stream is null (on
10912 		 * crtc enable, for example), mod_power will no-op, which is the
10913 		 * desried behavior.
10914 		 */
10915 		if (old_crtc_state->active) {
10916 			scoped_guard(mutex, &dm->dc_lock) {
10917 				dc_exit_ips_for_hw_access(dm->dc);
10918 				amdgpu_dm_psr_set_event(dm, dm_old_crtc_state->stream, true,
10919 					psr_event_hw_programming, true);
10920 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, true,
10921 					replay_event_hw_programming, true);
10922 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, false,
10923 					replay_event_general_ui, false);
10924 			}
10925 		}
10926 
10927 		if (new_crtc_state->active) {
10928 			aconnector = (struct amdgpu_dm_connector *)
10929 				dm_new_crtc_state->stream->dm_stream_context;
10930 			if (old_crtc_state->active) {
10931 				mod_power_replace_stream(dm->power_module,
10932 					dm_old_crtc_state->stream,
10933 					dm_new_crtc_state->stream,
10934 					&aconnector->psr_caps);
10935 			} else {
10936 				mod_power_add_stream(dm->power_module,
10937 					dm_new_crtc_state->stream,
10938 					&aconnector->psr_caps);
10939 			}
10940 		} else if (old_crtc_state->active) {
10941 			mod_power_remove_stream(dm->power_module,
10942 				dm_old_crtc_state->stream);
10943 		}
10944 	}
10945 }
10946 
10947 /**
10948  * amdgpu_dm_mod_power_setup_streams - setup mod_power stream state post modeset
10949  * @state: the drm atomic state
10950  * @dm: the display manager to update mod_power on
10951  *
10952  * Notify mod_power of mode_change. This needs to be done after dc_stream
10953  * updates have been committed, and VRR parameters have been updated.
10954  */
10955 static void amdgpu_dm_mod_power_setup_streams(struct drm_atomic_commit *state,
10956 					      struct amdgpu_display_manager *dm)
10957 {
10958 	struct dm_crtc_state *dm_new_crtc_state;
10959 	struct drm_crtc_state *new_crtc_state;
10960 	struct amdgpu_crtc *acrtc;
10961 	struct drm_crtc *crtc;
10962 	int i = 0;
10963 
10964 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10965 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10966 		acrtc = to_amdgpu_crtc(crtc);
10967 
10968 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10969 			continue;
10970 
10971 		if (new_crtc_state->active) {
10972 			amdgpu_dm_link_setup_replay(dm_new_crtc_state->stream,
10973 					&acrtc->dm_irq_params.vrr_params);
10974 			mod_power_notify_mode_change(dm->power_module,
10975 						dm_new_crtc_state->stream,
10976 						false);
10977 
10978 			/*
10979 			 * Block PSR / Replay on the new stream until display settles post-modeset.
10980 			 * These events will be cleared by amdgpu_dm_enable_self_refresh() once
10981 			 * allow_sr_entry becomes true.
10982 			 */
10983 			amdgpu_dm_psr_set_event(dm, dm_new_crtc_state->stream, true,
10984 				psr_event_hw_programming, true);
10985 
10986 			amdgpu_dm_replay_set_event(dm, dm_new_crtc_state->stream, true,
10987 				replay_event_hw_programming | replay_event_general_ui,
10988 				true);
10989 		}
10990 	}
10991 
10992 }
10993 
10994 static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state,
10995 					struct dc_state *dc_state)
10996 {
10997 	struct drm_device *dev = state->dev;
10998 	struct amdgpu_device *adev = drm_to_adev(dev);
10999 	struct amdgpu_display_manager *dm = &adev->dm;
11000 	struct drm_crtc *crtc;
11001 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11002 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11003 	struct drm_connector_state *old_con_state;
11004 	struct drm_connector *connector;
11005 	bool mode_set_reset_required = false;
11006 	u32 i;
11007 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
11008 	bool set_backlight_level = false;
11009 
11010 	/* Disable writeback */
11011 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
11012 		struct dm_connector_state *dm_old_con_state;
11013 		struct amdgpu_crtc *acrtc;
11014 
11015 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11016 			continue;
11017 
11018 		old_crtc_state = NULL;
11019 
11020 		dm_old_con_state = to_dm_connector_state(old_con_state);
11021 		if (!dm_old_con_state->base.crtc)
11022 			continue;
11023 
11024 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
11025 		if (acrtc)
11026 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11027 
11028 		if (!acrtc || !acrtc->wb_enabled)
11029 			continue;
11030 
11031 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11032 
11033 		dm_clear_writeback(dm, dm_old_crtc_state);
11034 		acrtc->wb_enabled = false;
11035 	}
11036 
11037 	amdgpu_dm_mod_power_update_streams(state, dm);
11038 
11039 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
11040 				      new_crtc_state, i) {
11041 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11042 
11043 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11044 
11045 		if (old_crtc_state->active &&
11046 		    (!new_crtc_state->active ||
11047 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11048 			manage_dm_interrupts(adev, acrtc, NULL);
11049 			dc_stream_release(dm_old_crtc_state->stream);
11050 		}
11051 	}
11052 
11053 	drm_atomic_helper_calc_timestamping_constants(state);
11054 
11055 	/* update changed items */
11056 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11057 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11058 
11059 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11060 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11061 
11062 		drm_dbg_state(state->dev,
11063 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
11064 			acrtc->crtc_id,
11065 			new_crtc_state->enable,
11066 			new_crtc_state->active,
11067 			new_crtc_state->planes_changed,
11068 			new_crtc_state->mode_changed,
11069 			new_crtc_state->active_changed,
11070 			new_crtc_state->connectors_changed);
11071 
11072 		/* Disable cursor if disabling crtc */
11073 		if (old_crtc_state->active && !new_crtc_state->active) {
11074 			struct dc_cursor_position position;
11075 
11076 			memset(&position, 0, sizeof(position));
11077 			mutex_lock(&dm->dc_lock);
11078 			dc_exit_ips_for_hw_access(dm->dc);
11079 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
11080 			mutex_unlock(&dm->dc_lock);
11081 		}
11082 
11083 		/* Copy all transient state flags into dc state */
11084 		if (dm_new_crtc_state->stream) {
11085 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
11086 							    dm_new_crtc_state->stream);
11087 		}
11088 
11089 		/* handles headless hotplug case, updating new_state and
11090 		 * aconnector as needed
11091 		 */
11092 
11093 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
11094 
11095 			drm_dbg_atomic(dev,
11096 				       "Atomic commit: SET crtc id %d: [%p]\n",
11097 				       acrtc->crtc_id, acrtc);
11098 
11099 			if (!dm_new_crtc_state->stream) {
11100 				/*
11101 				 * this could happen because of issues with
11102 				 * userspace notifications delivery.
11103 				 * In this case userspace tries to set mode on
11104 				 * display which is disconnected in fact.
11105 				 * dc_sink is NULL in this case on aconnector.
11106 				 * We expect reset mode will come soon.
11107 				 *
11108 				 * This can also happen when unplug is done
11109 				 * during resume sequence ended
11110 				 *
11111 				 * In this case, we want to pretend we still
11112 				 * have a sink to keep the pipe running so that
11113 				 * hw state is consistent with the sw state
11114 				 */
11115 				drm_dbg_atomic(dev,
11116 					       "Failed to create new stream for crtc %d\n",
11117 						acrtc->base.base.id);
11118 				continue;
11119 			}
11120 
11121 			if (dm_old_crtc_state->stream)
11122 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
11123 
11124 			pm_runtime_get_noresume(dev->dev);
11125 
11126 			acrtc->enabled = true;
11127 			acrtc->hw_mode = new_crtc_state->mode;
11128 			crtc->hwmode = new_crtc_state->mode;
11129 			mode_set_reset_required = true;
11130 			set_backlight_level = true;
11131 		} else if (modereset_required(new_crtc_state)) {
11132 			drm_dbg_atomic(dev,
11133 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
11134 				       acrtc->crtc_id, acrtc);
11135 			/* i.e. reset mode */
11136 			if (dm_old_crtc_state->stream)
11137 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
11138 
11139 			mode_set_reset_required = true;
11140 		}
11141 	} /* for_each_crtc_in_state() */
11142 
11143 	/* if there mode set or reset, flush vblank work queue */
11144 	if (mode_set_reset_required) {
11145 		if (dm->vblank_control_workqueue)
11146 			flush_workqueue(dm->vblank_control_workqueue);
11147 	}
11148 
11149 	dm_enable_per_frame_crtc_master_sync(dc_state);
11150 	mutex_lock(&dm->dc_lock);
11151 	dc_exit_ips_for_hw_access(dm->dc);
11152 	WARN_ON(!dc_commit_streams(dm->dc, &params));
11153 
11154 	bool frl_stream_found = false;
11155 
11156 	for (i = 0; i < params.stream_count; i++) {
11157 		struct dc_stream_state *stream = params.streams[i];
11158 
11159 		if (stream->signal == SIGNAL_TYPE_HDMI_FRL) {
11160 			frl_stream_found = true;
11161 			break;
11162 		}
11163 	}
11164 	if (frl_stream_found) {
11165 		if (queue_delayed_work(dm->hdmi_frl_status_polling_wq,
11166 				       &dm->hdmi_frl_status_polling_work,
11167 				       msecs_to_jiffies(dm->hdmi_frl_status_polling_delay_ms)))
11168 			drm_dbg_kms(dev, "200ms frl status polling starts ...\n");
11169 	} else {
11170 		if (cancel_delayed_work_sync(&dm->hdmi_frl_status_polling_work))
11171 			drm_dbg_kms(dev, "200ms frl status polling stops ...\n");
11172 	}
11173 	/* Allow idle optimization when vblank count is 0 for display off */
11174 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
11175 		dc_allow_idle_optimizations(dm->dc, true);
11176 	mutex_unlock(&dm->dc_lock);
11177 
11178 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11179 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11180 
11181 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11182 
11183 		if (dm_new_crtc_state->stream != NULL) {
11184 			const struct dc_stream_status *status =
11185 					dc_stream_get_status(dm_new_crtc_state->stream);
11186 
11187 			if (!status)
11188 				status = dc_state_get_stream_status(dc_state,
11189 									 dm_new_crtc_state->stream);
11190 			if (!status)
11191 				drm_err(dev,
11192 					"got no status for stream %p on acrtc%p\n",
11193 					dm_new_crtc_state->stream, acrtc);
11194 			else
11195 				acrtc->otg_inst = status->primary_otg_inst;
11196 		}
11197 	}
11198 
11199 	/* During boot up and resume the DC layer will reset the panel brightness
11200 	 * to fix a flicker issue.
11201 	 * It will cause the dm->actual_brightness is not the current panel brightness
11202 	 * level. (the dm->brightness is the correct panel level)
11203 	 * So we set the backlight level with dm->brightness value after set mode
11204 	 */
11205 	if (set_backlight_level) {
11206 		for (i = 0; i < dm->num_of_edps; i++) {
11207 			if (dm->backlight_dev[i])
11208 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11209 		}
11210 	}
11211 }
11212 
11213 static void dm_set_writeback(struct amdgpu_display_manager *dm,
11214 			      struct dm_crtc_state *crtc_state,
11215 			      struct drm_connector *connector,
11216 			      struct drm_connector_state *new_con_state)
11217 {
11218 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
11219 	struct amdgpu_device *adev = dm->adev;
11220 	struct amdgpu_crtc *acrtc;
11221 	struct dc_writeback_info *wb_info;
11222 	struct pipe_ctx *pipe = NULL;
11223 	struct amdgpu_framebuffer *afb;
11224 	int i = 0;
11225 
11226 	wb_info = kzalloc_obj(*wb_info);
11227 	if (!wb_info) {
11228 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
11229 		return;
11230 	}
11231 
11232 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
11233 	if (!acrtc) {
11234 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
11235 		kfree(wb_info);
11236 		return;
11237 	}
11238 
11239 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
11240 	if (!afb) {
11241 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
11242 		kfree(wb_info);
11243 		return;
11244 	}
11245 
11246 	for (i = 0; i < MAX_PIPES; i++) {
11247 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
11248 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
11249 			break;
11250 		}
11251 	}
11252 
11253 	/* fill in wb_info */
11254 	wb_info->wb_enabled = true;
11255 
11256 	wb_info->dwb_pipe_inst = 0;
11257 	wb_info->dwb_params.dwbscl_black_color = 0;
11258 	wb_info->dwb_params.hdr_mult = 0x1F000;
11259 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
11260 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
11261 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
11262 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
11263 
11264 	/* width & height from crtc */
11265 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
11266 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
11267 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
11268 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
11269 
11270 	wb_info->dwb_params.cnv_params.crop_en = false;
11271 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
11272 
11273 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
11274 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
11275 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
11276 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
11277 
11278 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
11279 
11280 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
11281 
11282 	wb_info->dwb_params.scaler_taps.h_taps = 1;
11283 	wb_info->dwb_params.scaler_taps.v_taps = 1;
11284 	wb_info->dwb_params.scaler_taps.h_taps_c = 1;
11285 	wb_info->dwb_params.scaler_taps.v_taps_c = 1;
11286 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
11287 
11288 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
11289 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
11290 
11291 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
11292 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
11293 		wb_info->mcif_buf_params.chroma_address[i] = 0;
11294 	}
11295 
11296 	wb_info->mcif_buf_params.p_vmid = 1;
11297 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
11298 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
11299 		wb_info->mcif_warmup_params.region_size =
11300 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
11301 	}
11302 	wb_info->mcif_warmup_params.p_vmid = 1;
11303 	wb_info->writeback_source_plane = pipe->plane_state;
11304 
11305 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
11306 
11307 	acrtc->wb_pending = true;
11308 	acrtc->wb_conn = wb_conn;
11309 	drm_writeback_queue_job(wb_conn, new_con_state);
11310 }
11311 
11312 static void amdgpu_dm_update_hdcp(struct drm_atomic_commit *state)
11313 {
11314 	struct drm_connector_state *old_con_state, *new_con_state;
11315 	struct drm_device *dev = state->dev;
11316 	struct drm_connector *connector;
11317 	struct amdgpu_device *adev = drm_to_adev(dev);
11318 	int i;
11319 
11320 	if (!adev->dm.hdcp_workqueue)
11321 		return;
11322 
11323 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11324 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11325 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11326 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11327 		struct dm_crtc_state *dm_new_crtc_state;
11328 		struct amdgpu_dm_connector *aconnector;
11329 
11330 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11331 			continue;
11332 
11333 		aconnector = to_amdgpu_dm_connector(connector);
11334 
11335 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
11336 
11337 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
11338 			connector->index, connector->status, connector->dpms);
11339 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
11340 			old_con_state->content_protection, new_con_state->content_protection);
11341 
11342 		if (aconnector->dc_sink) {
11343 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
11344 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
11345 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
11346 				aconnector->dc_sink->edid_caps.display_name);
11347 			}
11348 		}
11349 
11350 		new_crtc_state = NULL;
11351 		old_crtc_state = NULL;
11352 
11353 		if (acrtc) {
11354 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11355 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11356 		}
11357 
11358 		if (old_crtc_state)
11359 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11360 			old_crtc_state->enable,
11361 			old_crtc_state->active,
11362 			old_crtc_state->mode_changed,
11363 			old_crtc_state->active_changed,
11364 			old_crtc_state->connectors_changed);
11365 
11366 		if (new_crtc_state)
11367 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11368 			new_crtc_state->enable,
11369 			new_crtc_state->active,
11370 			new_crtc_state->mode_changed,
11371 			new_crtc_state->active_changed,
11372 			new_crtc_state->connectors_changed);
11373 
11374 
11375 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11376 
11377 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
11378 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
11379 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
11380 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
11381 			dm_new_con_state->update_hdcp = true;
11382 			continue;
11383 		}
11384 
11385 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
11386 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
11387 			/* when display is unplugged from mst hub, connctor will
11388 			 * be destroyed within dm_dp_mst_connector_destroy. connector
11389 			 * hdcp perperties, like type, undesired, desired, enabled,
11390 			 * will be lost. So, save hdcp properties into hdcp_work within
11391 			 * amdgpu_dm_atomic_commit_tail. if the same display is
11392 			 * plugged back with same display index, its hdcp properties
11393 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
11394 			 */
11395 
11396 			bool enable_encryption = false;
11397 
11398 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
11399 				enable_encryption = true;
11400 
11401 			if (aconnector->dc_link && aconnector->dc_sink &&
11402 				aconnector->dc_link->type == dc_connection_mst_branch) {
11403 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
11404 				struct hdcp_workqueue *hdcp_w =
11405 					&hdcp_work[aconnector->dc_link->link_index];
11406 
11407 				hdcp_w->hdcp_content_type[connector->index] =
11408 					new_con_state->hdcp_content_type;
11409 				hdcp_w->content_protection[connector->index] =
11410 					new_con_state->content_protection;
11411 			}
11412 
11413 			if (new_crtc_state && new_crtc_state->mode_changed &&
11414 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
11415 				enable_encryption = true;
11416 
11417 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
11418 
11419 			if (aconnector->dc_link)
11420 				hdcp_update_display(
11421 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
11422 					new_con_state->hdcp_content_type, enable_encryption);
11423 		}
11424 	}
11425 }
11426 
11427 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state)
11428 {
11429 	struct drm_crtc *crtc;
11430 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11431 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11432 	int i, ret;
11433 
11434 	ret = drm_dp_mst_atomic_setup_commit(state);
11435 	if (ret)
11436 		return ret;
11437 
11438 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11439 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11440 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11441 		/*
11442 		 * Color management settings. We also update color properties
11443 		 * when a modeset is needed, to ensure it gets reprogrammed.
11444 		 */
11445 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
11446 		    (dm_new_crtc_state->base.color_mgmt_changed ||
11447 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11448 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11449 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
11450 			if (ret) {
11451 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
11452 				return ret;
11453 			}
11454 		}
11455 	}
11456 
11457 	return 0;
11458 }
11459 
11460 /**
11461  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
11462  * @state: The atomic state to commit
11463  *
11464  * This will tell DC to commit the constructed DC state from atomic_check,
11465  * programming the hardware. Any failures here implies a hardware failure, since
11466  * atomic check should have filtered anything non-kosher.
11467  */
11468 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state)
11469 {
11470 	struct drm_device *dev = state->dev;
11471 	struct amdgpu_device *adev = drm_to_adev(dev);
11472 	struct amdgpu_display_manager *dm = &adev->dm;
11473 	struct dm_atomic_state *dm_state;
11474 	struct dc_state *dc_state = NULL;
11475 	u32 i, j;
11476 	struct drm_crtc *crtc;
11477 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11478 	unsigned long flags;
11479 	bool wait_for_vblank = true;
11480 	struct drm_connector *connector;
11481 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
11482 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11483 	int crtc_disable_count = 0;
11484 
11485 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
11486 
11487 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
11488 	drm_dp_mst_atomic_wait_for_dependencies(state);
11489 
11490 	dm_state = dm_atomic_get_new_state(state);
11491 	if (dm_state && dm_state->context) {
11492 		dc_state = dm_state->context;
11493 		amdgpu_dm_commit_streams(state, dc_state);
11494 	}
11495 
11496 	amdgpu_dm_update_hdcp(state);
11497 
11498 	/* Handle connector state changes */
11499 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11500 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11501 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
11502 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11503 		struct dc_surface_update *dummy_updates;
11504 		struct dc_stream_update stream_update;
11505 		struct dc_info_packet hdr_packet;
11506 		struct dc_stream_status *status = NULL;
11507 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
11508 
11509 		memset(&stream_update, 0, sizeof(stream_update));
11510 
11511 		if (acrtc) {
11512 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11513 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11514 		}
11515 
11516 		/* Skip any modesets/resets */
11517 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
11518 			continue;
11519 
11520 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11521 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11522 
11523 		scaling_changed = is_scaling_state_different(dm_new_con_state,
11524 							     dm_old_con_state);
11525 
11526 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
11527 			(dm_old_crtc_state->stream->output_color_space !=
11528 				get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
11529 			output_color_space_changed = true;
11530 
11531 		abm_changed = dm_new_crtc_state->abm_level !=
11532 			      dm_old_crtc_state->abm_level;
11533 
11534 		hdr_changed =
11535 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
11536 
11537 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
11538 			continue;
11539 
11540 		stream_update.stream = dm_new_crtc_state->stream;
11541 		if (scaling_changed) {
11542 			update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
11543 					dm_new_con_state, dm_new_crtc_state->stream);
11544 
11545 			stream_update.src = dm_new_crtc_state->stream->src;
11546 			stream_update.dst = dm_new_crtc_state->stream->dst;
11547 		}
11548 
11549 		if (output_color_space_changed) {
11550 			dm_new_crtc_state->stream->output_color_space
11551 				= get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
11552 
11553 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
11554 		}
11555 
11556 		if (abm_changed) {
11557 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
11558 
11559 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
11560 		}
11561 
11562 		if (hdr_changed) {
11563 			fill_hdr_info_packet(new_con_state, &hdr_packet);
11564 			stream_update.hdr_static_metadata = &hdr_packet;
11565 		}
11566 
11567 		status = dc_stream_get_status(dm_new_crtc_state->stream);
11568 
11569 		if (WARN_ON(!status))
11570 			continue;
11571 
11572 		WARN_ON(!status->plane_count);
11573 
11574 		/*
11575 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
11576 		 * Here we create an empty update on each plane.
11577 		 * To fix this, DC should permit updating only stream properties.
11578 		 */
11579 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
11580 		if (!dummy_updates) {
11581 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
11582 			continue;
11583 		}
11584 		for (j = 0; j < status->plane_count; j++)
11585 			dummy_updates[j].surface = status->plane_states[j];
11586 
11587 		sort(dummy_updates, status->plane_count,
11588 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
11589 
11590 		mutex_lock(&dm->dc_lock);
11591 		dc_exit_ips_for_hw_access(dm->dc);
11592 		dc_update_planes_and_stream(dm->dc,
11593 					    dummy_updates,
11594 					    status->plane_count,
11595 					    dm_new_crtc_state->stream,
11596 					    &stream_update);
11597 		mutex_unlock(&dm->dc_lock);
11598 		kfree(dummy_updates);
11599 
11600 		drm_connector_update_privacy_screen(new_con_state);
11601 	}
11602 
11603 	/**
11604 	 * Enable interrupts for CRTCs that are newly enabled or went through
11605 	 * a modeset. It was intentionally deferred until after the front end
11606 	 * state was modified to wait until the OTG was on and so the IRQ
11607 	 * handlers didn't access stale or invalid state.
11608 	 */
11609 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11610 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11611 #ifdef CONFIG_DEBUG_FS
11612 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
11613 #endif
11614 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
11615 		if (old_crtc_state->active && !new_crtc_state->active)
11616 			crtc_disable_count++;
11617 
11618 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11619 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11620 
11621 		/* For freesync config update on crtc state and params for irq */
11622 		update_stream_irq_parameters(dm, dm_new_crtc_state);
11623 
11624 #ifdef CONFIG_DEBUG_FS
11625 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11626 		cur_crc_src = acrtc->dm_irq_params.crc_src;
11627 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11628 #endif
11629 
11630 		if (new_crtc_state->active &&
11631 		    (!old_crtc_state->active ||
11632 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11633 			dc_stream_retain(dm_new_crtc_state->stream);
11634 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
11635 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
11636 		}
11637 		/* Handle vrr on->off / off->on transitions */
11638 		amdgpu_dm_handle_vrr_transition(dm, dm_old_crtc_state, dm_new_crtc_state);
11639 
11640 #ifdef CONFIG_DEBUG_FS
11641 		if (new_crtc_state->active &&
11642 		    (!old_crtc_state->active ||
11643 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11644 			/**
11645 			 * Frontend may have changed so reapply the CRC capture
11646 			 * settings for the stream.
11647 			 */
11648 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
11649 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
11650 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
11651 					uint8_t cnt;
11652 
11653 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11654 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
11655 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
11656 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
11657 
11658 							/**
11659 							 * It takes 2 frames for HW to stably generate CRC when
11660 							 * resuming from suspend, so we set skip_frame_cnt 2.
11661 							 */
11662 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
11663 						}
11664 					}
11665 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11666 				}
11667 #endif
11668 				if (amdgpu_dm_crtc_configure_crc_source(
11669 					crtc, dm_new_crtc_state, cur_crc_src))
11670 					drm_dbg_atomic(dev, "Failed to configure crc source");
11671 			}
11672 		}
11673 #endif
11674 	}
11675 
11676 	amdgpu_dm_mod_power_setup_streams(state, dm);
11677 
11678 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
11679 		if (new_crtc_state->async_flip)
11680 			wait_for_vblank = false;
11681 
11682 	/* update planes when needed per crtc*/
11683 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
11684 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11685 
11686 		if (dm_new_crtc_state->stream)
11687 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
11688 	}
11689 
11690 	/* Enable writeback */
11691 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11692 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11693 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11694 
11695 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11696 			continue;
11697 
11698 		if (!new_con_state->writeback_job)
11699 			continue;
11700 
11701 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11702 
11703 		if (!new_crtc_state)
11704 			continue;
11705 
11706 		if (acrtc->wb_enabled)
11707 			continue;
11708 
11709 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11710 
11711 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
11712 		acrtc->wb_enabled = true;
11713 	}
11714 
11715 	/* Update audio instances for each connector. */
11716 	amdgpu_dm_commit_audio(dev, state);
11717 
11718 	/* restore the backlight level */
11719 	for (i = 0; i < dm->num_of_edps; i++) {
11720 		if (dm->backlight_dev[i] &&
11721 		    (dm->actual_brightness[i] != dm->brightness[i]))
11722 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11723 	}
11724 
11725 	/*
11726 	 * send vblank event on all events not handled in flip and
11727 	 * mark consumed event for drm_atomic_helper_commit_hw_done
11728 	 */
11729 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11730 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11731 
11732 		if (new_crtc_state->event)
11733 			drm_send_event_locked(dev, &new_crtc_state->event->base);
11734 
11735 		new_crtc_state->event = NULL;
11736 	}
11737 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11738 
11739 	/* Signal HW programming completion */
11740 	drm_atomic_helper_commit_hw_done(state);
11741 
11742 	if (wait_for_vblank)
11743 		drm_atomic_helper_wait_for_flip_done(dev, state);
11744 
11745 	drm_atomic_helper_cleanup_planes(dev, state);
11746 
11747 	/* Don't free the memory if we are hitting this as part of suspend.
11748 	 * This way we don't free any memory during suspend; see
11749 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
11750 	 * non-suspend modeset or when the driver is torn down.
11751 	 */
11752 	if (!adev->in_suspend) {
11753 		/* return the stolen vga memory back to VRAM */
11754 		if (!adev->mman.keep_stolen_vga_memory)
11755 			amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_VGA);
11756 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_EXTENDED);
11757 	}
11758 
11759 	/*
11760 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
11761 	 * so we can put the GPU into runtime suspend if we're not driving any
11762 	 * displays anymore
11763 	 */
11764 	for (i = 0; i < crtc_disable_count; i++)
11765 		pm_runtime_put_autosuspend(dev->dev);
11766 	pm_runtime_mark_last_busy(dev->dev);
11767 
11768 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
11769 }
11770 
11771 static int dm_force_atomic_commit(struct drm_connector *connector)
11772 {
11773 	int ret = 0;
11774 	struct drm_device *ddev = connector->dev;
11775 	struct drm_atomic_commit *state = drm_atomic_commit_alloc(ddev);
11776 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11777 	struct drm_plane *plane = disconnected_acrtc->base.primary;
11778 	struct drm_connector_state *conn_state;
11779 	struct drm_crtc_state *crtc_state;
11780 	struct drm_plane_state *plane_state;
11781 
11782 	if (!state)
11783 		return -ENOMEM;
11784 
11785 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
11786 
11787 	/* Construct an atomic state to restore previous display setting */
11788 
11789 	/*
11790 	 * Attach connectors to drm_atomic_commit
11791 	 */
11792 	conn_state = drm_atomic_get_connector_state(state, connector);
11793 
11794 	/* Check for error in getting connector state */
11795 	if (IS_ERR(conn_state)) {
11796 		ret = PTR_ERR(conn_state);
11797 		goto out;
11798 	}
11799 
11800 	/* Attach crtc to drm_atomic_commit*/
11801 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
11802 
11803 	/* Check for error in getting crtc state */
11804 	if (IS_ERR(crtc_state)) {
11805 		ret = PTR_ERR(crtc_state);
11806 		goto out;
11807 	}
11808 
11809 	/* force a restore */
11810 	crtc_state->mode_changed = true;
11811 
11812 	/* Attach plane to drm_atomic_commit */
11813 	plane_state = drm_atomic_get_plane_state(state, plane);
11814 
11815 	/* Check for error in getting plane state */
11816 	if (IS_ERR(plane_state)) {
11817 		ret = PTR_ERR(plane_state);
11818 		goto out;
11819 	}
11820 
11821 	/* Call commit internally with the state we just constructed */
11822 	ret = drm_atomic_commit(state);
11823 
11824 out:
11825 	drm_atomic_commit_put(state);
11826 	if (ret)
11827 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
11828 
11829 	return ret;
11830 }
11831 
11832 /*
11833  * This function handles all cases when set mode does not come upon hotplug.
11834  * This includes when a display is unplugged then plugged back into the
11835  * same port and when running without usermode desktop manager supprot
11836  */
11837 void dm_restore_drm_connector_state(struct drm_device *dev,
11838 				    struct drm_connector *connector)
11839 {
11840 	struct amdgpu_dm_connector *aconnector;
11841 	struct amdgpu_crtc *disconnected_acrtc;
11842 	struct dm_crtc_state *acrtc_state;
11843 
11844 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11845 		return;
11846 
11847 	aconnector = to_amdgpu_dm_connector(connector);
11848 
11849 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
11850 		return;
11851 
11852 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11853 	if (!disconnected_acrtc)
11854 		return;
11855 
11856 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
11857 	if (!acrtc_state->stream)
11858 		return;
11859 
11860 	/*
11861 	 * If the previous sink is not released and different from the current,
11862 	 * we deduce we are in a state where we can not rely on usermode call
11863 	 * to turn on the display, so we do it here
11864 	 */
11865 	if (acrtc_state->stream->sink != aconnector->dc_sink)
11866 		dm_force_atomic_commit(&aconnector->base);
11867 }
11868 
11869 /*
11870  * Grabs all modesetting locks to serialize against any blocking commits,
11871  * Waits for completion of all non blocking commits.
11872  */
11873 static int do_aquire_global_lock(struct drm_device *dev,
11874 				 struct drm_atomic_commit *state)
11875 {
11876 	struct drm_crtc *crtc;
11877 	struct drm_crtc_commit *commit;
11878 	long ret;
11879 
11880 	/*
11881 	 * Adding all modeset locks to aquire_ctx will
11882 	 * ensure that when the framework release it the
11883 	 * extra locks we are locking here will get released to
11884 	 */
11885 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
11886 	if (ret)
11887 		return ret;
11888 
11889 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
11890 		spin_lock(&crtc->commit_lock);
11891 		commit = list_first_entry_or_null(&crtc->commit_list,
11892 				struct drm_crtc_commit, commit_entry);
11893 		if (commit)
11894 			drm_crtc_commit_get(commit);
11895 		spin_unlock(&crtc->commit_lock);
11896 
11897 		if (!commit)
11898 			continue;
11899 
11900 		/*
11901 		 * Make sure all pending HW programming completed and
11902 		 * page flips done
11903 		 */
11904 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
11905 
11906 		if (ret > 0)
11907 			ret = wait_for_completion_interruptible_timeout(
11908 					&commit->flip_done, 10*HZ);
11909 
11910 		if (ret == 0)
11911 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
11912 				  crtc->base.id, crtc->name);
11913 
11914 		drm_crtc_commit_put(commit);
11915 	}
11916 
11917 	return ret < 0 ? ret : 0;
11918 }
11919 
11920 static void get_freesync_config_for_crtc(
11921 	struct dm_crtc_state *new_crtc_state,
11922 	struct dm_connector_state *new_con_state)
11923 {
11924 	struct mod_freesync_config config = {0};
11925 	struct amdgpu_dm_connector *aconnector;
11926 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
11927 	int vrefresh = drm_mode_vrefresh(mode);
11928 	bool fs_vid_mode = false;
11929 
11930 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11931 		return;
11932 
11933 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
11934 
11935 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
11936 					vrefresh >= aconnector->min_vfreq &&
11937 					vrefresh <= aconnector->max_vfreq;
11938 
11939 	if (new_crtc_state->vrr_supported) {
11940 		new_crtc_state->stream->ignore_msa_timing_param = true;
11941 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
11942 
11943 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
11944 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
11945 		config.vsif_supported = true;
11946 		config.btr = true;
11947 
11948 		if (fs_vid_mode) {
11949 			config.state = VRR_STATE_ACTIVE_FIXED;
11950 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
11951 			goto out;
11952 		} else if (new_crtc_state->base.vrr_enabled) {
11953 			config.state = VRR_STATE_ACTIVE_VARIABLE;
11954 		} else {
11955 			config.state = VRR_STATE_INACTIVE;
11956 		}
11957 	} else {
11958 		config.state = VRR_STATE_UNSUPPORTED;
11959 	}
11960 out:
11961 	new_crtc_state->freesync_config = config;
11962 }
11963 
11964 static void reset_freesync_config_for_crtc(
11965 	struct dm_crtc_state *new_crtc_state)
11966 {
11967 	new_crtc_state->vrr_supported = false;
11968 
11969 	memset(&new_crtc_state->vrr_infopacket, 0,
11970 	       sizeof(new_crtc_state->vrr_infopacket));
11971 }
11972 
11973 static bool
11974 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
11975 				 struct drm_crtc_state *new_crtc_state)
11976 {
11977 	const struct drm_display_mode *old_mode, *new_mode;
11978 
11979 	if (!old_crtc_state || !new_crtc_state)
11980 		return false;
11981 
11982 	old_mode = &old_crtc_state->mode;
11983 	new_mode = &new_crtc_state->mode;
11984 
11985 	if (old_mode->clock       == new_mode->clock &&
11986 	    old_mode->hdisplay    == new_mode->hdisplay &&
11987 	    old_mode->vdisplay    == new_mode->vdisplay &&
11988 	    old_mode->htotal      == new_mode->htotal &&
11989 	    old_mode->vtotal      != new_mode->vtotal &&
11990 	    old_mode->hsync_start == new_mode->hsync_start &&
11991 	    old_mode->vsync_start != new_mode->vsync_start &&
11992 	    old_mode->hsync_end   == new_mode->hsync_end &&
11993 	    old_mode->vsync_end   != new_mode->vsync_end &&
11994 	    old_mode->hskew       == new_mode->hskew &&
11995 	    old_mode->vscan       == new_mode->vscan &&
11996 	    (old_mode->vsync_end - old_mode->vsync_start) ==
11997 	    (new_mode->vsync_end - new_mode->vsync_start))
11998 		return true;
11999 
12000 	return false;
12001 }
12002 
12003 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
12004 {
12005 	u64 num, den, res;
12006 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
12007 
12008 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
12009 
12010 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
12011 	den = (unsigned long long)new_crtc_state->mode.htotal *
12012 	      (unsigned long long)new_crtc_state->mode.vtotal;
12013 
12014 	res = div_u64(num, den);
12015 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
12016 }
12017 
12018 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
12019 			 struct drm_atomic_commit *state,
12020 			 struct drm_crtc *crtc,
12021 			 struct drm_crtc_state *old_crtc_state,
12022 			 struct drm_crtc_state *new_crtc_state,
12023 			 bool enable,
12024 			 bool *lock_and_validation_needed)
12025 {
12026 	struct dm_atomic_state *dm_state = NULL;
12027 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12028 	struct dc_stream_state *new_stream;
12029 	struct amdgpu_device *adev = dm->adev;
12030 	int ret = 0;
12031 
12032 	/*
12033 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
12034 	 * update changed items
12035 	 */
12036 	struct amdgpu_crtc *acrtc = NULL;
12037 	struct drm_connector *connector = NULL;
12038 	struct amdgpu_dm_connector *aconnector = NULL;
12039 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
12040 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
12041 
12042 	new_stream = NULL;
12043 
12044 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12045 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12046 	acrtc = to_amdgpu_crtc(crtc);
12047 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
12048 	if (connector)
12049 		aconnector = to_amdgpu_dm_connector(connector);
12050 
12051 	/* TODO This hack should go away */
12052 	if (connector && enable) {
12053 		/* Make sure fake sink is created in plug-in scenario */
12054 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
12055 									connector);
12056 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
12057 									connector);
12058 
12059 		if (WARN_ON(!drm_new_conn_state)) {
12060 			ret = -EINVAL;
12061 			goto fail;
12062 		}
12063 
12064 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
12065 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
12066 
12067 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
12068 			goto skip_modeset;
12069 
12070 		new_stream = create_validate_stream_for_sink(connector,
12071 							     &new_crtc_state->mode,
12072 							     dm_new_conn_state,
12073 							     dm_old_crtc_state->stream);
12074 
12075 		/*
12076 		 * we can have no stream on ACTION_SET if a display
12077 		 * was disconnected during S3, in this case it is not an
12078 		 * error, the OS will be updated after detection, and
12079 		 * will do the right thing on next atomic commit
12080 		 */
12081 
12082 		if (!new_stream) {
12083 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
12084 					__func__, acrtc->base.base.id);
12085 			ret = -ENOMEM;
12086 			goto fail;
12087 		}
12088 
12089 		/*
12090 		 * TODO: Check VSDB bits to decide whether this should
12091 		 * be enabled or not.
12092 		 */
12093 		new_stream->triggered_crtc_reset.enabled =
12094 			dm->force_timing_sync;
12095 
12096 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
12097 
12098 		ret = fill_hdr_info_packet(drm_new_conn_state,
12099 					   &new_stream->hdr_static_metadata);
12100 		if (ret)
12101 			goto fail;
12102 
12103 		/*
12104 		 * If we already removed the old stream from the context
12105 		 * (and set the new stream to NULL) then we can't reuse
12106 		 * the old stream even if the stream and scaling are unchanged.
12107 		 * We'll hit the BUG_ON and black screen.
12108 		 *
12109 		 * TODO: Refactor this function to allow this check to work
12110 		 * in all conditions.
12111 		 */
12112 		if (amdgpu_freesync_vid_mode &&
12113 		    dm_new_crtc_state->stream &&
12114 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
12115 			goto skip_modeset;
12116 
12117 		if (dm_new_crtc_state->stream &&
12118 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
12119 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
12120 			new_crtc_state->mode_changed = false;
12121 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
12122 					 new_crtc_state->mode_changed);
12123 		}
12124 	}
12125 
12126 	/* mode_changed flag may get updated above, need to check again */
12127 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
12128 		goto skip_modeset;
12129 
12130 	drm_dbg_state(state->dev,
12131 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
12132 		acrtc->crtc_id,
12133 		new_crtc_state->enable,
12134 		new_crtc_state->active,
12135 		new_crtc_state->planes_changed,
12136 		new_crtc_state->mode_changed,
12137 		new_crtc_state->active_changed,
12138 		new_crtc_state->connectors_changed);
12139 
12140 	/* Remove stream for any changed/disabled CRTC */
12141 	if (!enable) {
12142 
12143 		if (!dm_old_crtc_state->stream)
12144 			goto skip_modeset;
12145 
12146 		/* Unset freesync video if it was active before */
12147 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
12148 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
12149 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
12150 		}
12151 
12152 		/* Now check if we should set freesync video mode */
12153 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
12154 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
12155 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
12156 		    is_timing_unchanged_for_freesync(new_crtc_state,
12157 						     old_crtc_state)) {
12158 			new_crtc_state->mode_changed = false;
12159 			drm_dbg_driver(adev_to_drm(adev),
12160 				"Mode change not required for front porch change, setting mode_changed to %d",
12161 				new_crtc_state->mode_changed);
12162 
12163 			set_freesync_fixed_config(dm_new_crtc_state);
12164 
12165 			goto skip_modeset;
12166 		} else if (amdgpu_freesync_vid_mode && aconnector &&
12167 			   is_freesync_video_mode(&new_crtc_state->mode,
12168 						  aconnector)) {
12169 			struct drm_display_mode *high_mode;
12170 
12171 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
12172 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
12173 				set_freesync_fixed_config(dm_new_crtc_state);
12174 		}
12175 
12176 		ret = dm_atomic_get_state(state, &dm_state);
12177 		if (ret)
12178 			goto fail;
12179 
12180 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
12181 				crtc->base.id);
12182 
12183 		/* i.e. reset mode */
12184 		if (dc_state_remove_stream(
12185 				dm->dc,
12186 				dm_state->context,
12187 				dm_old_crtc_state->stream) != DC_OK) {
12188 			ret = -EINVAL;
12189 			goto fail;
12190 		}
12191 
12192 		dc_stream_release(dm_old_crtc_state->stream);
12193 		dm_new_crtc_state->stream = NULL;
12194 
12195 		reset_freesync_config_for_crtc(dm_new_crtc_state);
12196 
12197 		*lock_and_validation_needed = true;
12198 
12199 	} else {/* Add stream for any updated/enabled CRTC */
12200 		/*
12201 		 * Quick fix to prevent NULL pointer on new_stream when
12202 		 * added MST connectors not found in existing crtc_state in the chained mode
12203 		 * TODO: need to dig out the root cause of that
12204 		 */
12205 		if (!connector)
12206 			goto skip_modeset;
12207 
12208 		if (modereset_required(new_crtc_state))
12209 			goto skip_modeset;
12210 
12211 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
12212 				     dm_old_crtc_state->stream)) {
12213 
12214 			WARN_ON(dm_new_crtc_state->stream);
12215 
12216 			ret = dm_atomic_get_state(state, &dm_state);
12217 			if (ret)
12218 				goto fail;
12219 
12220 			dm_new_crtc_state->stream = new_stream;
12221 
12222 			dc_stream_retain(new_stream);
12223 
12224 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
12225 					 crtc->base.id);
12226 
12227 			if (dc_state_add_stream(
12228 					dm->dc,
12229 					dm_state->context,
12230 					dm_new_crtc_state->stream) != DC_OK) {
12231 				ret = -EINVAL;
12232 				goto fail;
12233 			}
12234 
12235 			*lock_and_validation_needed = true;
12236 		}
12237 	}
12238 
12239 skip_modeset:
12240 	/* Release extra reference */
12241 	if (new_stream)
12242 		dc_stream_release(new_stream);
12243 	new_stream = NULL;
12244 
12245 	/*
12246 	 * We want to do dc stream updates that do not require a
12247 	 * full modeset below.
12248 	 */
12249 	if (!(enable && connector && new_crtc_state->active))
12250 		return 0;
12251 	/*
12252 	 * Given above conditions, the dc state cannot be NULL because:
12253 	 * 1. We're in the process of enabling CRTCs (just been added
12254 	 *    to the dc context, or already is on the context)
12255 	 * 2. Has a valid connector attached, and
12256 	 * 3. Is currently active and enabled.
12257 	 * => The dc stream state currently exists.
12258 	 */
12259 	BUG_ON(dm_new_crtc_state->stream == NULL);
12260 
12261 	/* Scaling or underscan settings */
12262 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
12263 				drm_atomic_crtc_needs_modeset(new_crtc_state))
12264 		update_stream_scaling_settings(adev_to_drm(adev),
12265 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
12266 
12267 	/* ABM settings */
12268 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
12269 
12270 	/*
12271 	 * Color management settings. We also update color properties
12272 	 * when a modeset is needed, to ensure it gets reprogrammed.
12273 	 */
12274 	if (dm_new_crtc_state->base.color_mgmt_changed ||
12275 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
12276 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
12277 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
12278 		if (ret)
12279 			goto fail;
12280 	}
12281 
12282 	/* Update Freesync settings. */
12283 	get_freesync_config_for_crtc(dm_new_crtc_state,
12284 				     dm_new_conn_state);
12285 
12286 	return ret;
12287 
12288 fail:
12289 	if (new_stream)
12290 		dc_stream_release(new_stream);
12291 	return ret;
12292 }
12293 
12294 static bool should_reset_plane(struct drm_atomic_commit *state,
12295 			       struct drm_plane *plane,
12296 			       struct drm_plane_state *old_plane_state,
12297 			       struct drm_plane_state *new_plane_state)
12298 {
12299 	struct drm_plane *other;
12300 	struct drm_plane_state *old_other_state, *new_other_state;
12301 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12302 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
12303 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
12304 	struct drm_connector_state *new_con_state;
12305 	struct drm_connector *connector;
12306 	int i;
12307 
12308 	/*
12309 	 * TODO: Remove this hack for all asics once it proves that the
12310 	 * fast updates works fine on DCN3.2+.
12311 	 */
12312 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
12313 	    state->allow_modeset)
12314 		return true;
12315 
12316 	/* Check for writeback commit */
12317 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
12318 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
12319 			continue;
12320 
12321 		if (new_con_state->writeback_job)
12322 			return true;
12323 	}
12324 
12325 	if (amdgpu_in_reset(adev) && state->allow_modeset)
12326 		return true;
12327 
12328 	/* Exit early if we know that we're adding or removing the plane. */
12329 	if (old_plane_state->crtc != new_plane_state->crtc)
12330 		return true;
12331 
12332 	/* old crtc == new_crtc == NULL, plane not in context. */
12333 	if (!new_plane_state->crtc)
12334 		return false;
12335 
12336 	new_crtc_state =
12337 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
12338 	old_crtc_state =
12339 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
12340 
12341 	if (!new_crtc_state)
12342 		return true;
12343 
12344 	/*
12345 	 * A change in cursor mode means a new dc pipe needs to be acquired or
12346 	 * released from the state
12347 	 */
12348 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
12349 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
12350 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
12351 	    old_dm_crtc_state != NULL &&
12352 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
12353 		return true;
12354 	}
12355 
12356 	/* CRTC Degamma changes currently require us to recreate planes. */
12357 	if (new_crtc_state->color_mgmt_changed)
12358 		return true;
12359 
12360 	/* Plane color pipeline or its colorop changes. */
12361 	if (new_plane_state->color_mgmt_changed)
12362 		return true;
12363 
12364 	/*
12365 	 * On zpos change, planes need to be reordered by removing and re-adding
12366 	 * them one by one to the dc state, in order of descending zpos.
12367 	 *
12368 	 * TODO: We can likely skip bandwidth validation if the only thing that
12369 	 * changed about the plane was it'z z-ordering.
12370 	 */
12371 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
12372 		return true;
12373 
12374 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
12375 		return true;
12376 
12377 	/*
12378 	 * If there are any new primary or overlay planes being added or
12379 	 * removed then the z-order can potentially change. To ensure
12380 	 * correct z-order and pipe acquisition the current DC architecture
12381 	 * requires us to remove and recreate all existing planes.
12382 	 *
12383 	 * TODO: Come up with a more elegant solution for this.
12384 	 */
12385 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
12386 		struct amdgpu_framebuffer *old_afb, *new_afb;
12387 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
12388 
12389 		dm_new_other_state = to_dm_plane_state(new_other_state);
12390 		dm_old_other_state = to_dm_plane_state(old_other_state);
12391 
12392 		if (other->type == DRM_PLANE_TYPE_CURSOR)
12393 			continue;
12394 
12395 		if (old_other_state->crtc != new_plane_state->crtc &&
12396 		    new_other_state->crtc != new_plane_state->crtc)
12397 			continue;
12398 
12399 		if (old_other_state->crtc != new_other_state->crtc)
12400 			return true;
12401 
12402 		/* Src/dst size and scaling updates. */
12403 		if (old_other_state->src_w != new_other_state->src_w ||
12404 		    old_other_state->src_h != new_other_state->src_h ||
12405 		    old_other_state->crtc_w != new_other_state->crtc_w ||
12406 		    old_other_state->crtc_h != new_other_state->crtc_h)
12407 			return true;
12408 
12409 		/* Rotation / mirroring updates. */
12410 		if (old_other_state->rotation != new_other_state->rotation)
12411 			return true;
12412 
12413 		/* Blending updates. */
12414 		if (old_other_state->pixel_blend_mode !=
12415 		    new_other_state->pixel_blend_mode)
12416 			return true;
12417 
12418 		/* Alpha updates. */
12419 		if (old_other_state->alpha != new_other_state->alpha)
12420 			return true;
12421 
12422 		/* Colorspace changes. */
12423 		if (old_other_state->color_range != new_other_state->color_range ||
12424 		    old_other_state->color_encoding != new_other_state->color_encoding)
12425 			return true;
12426 
12427 		/* HDR/Transfer Function changes. */
12428 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
12429 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
12430 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
12431 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
12432 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
12433 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
12434 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
12435 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
12436 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
12437 			return true;
12438 
12439 		/* Framebuffer checks fall at the end. */
12440 		if (!old_other_state->fb || !new_other_state->fb)
12441 			continue;
12442 
12443 		/* Pixel format changes can require bandwidth updates. */
12444 		if (old_other_state->fb->format != new_other_state->fb->format)
12445 			return true;
12446 
12447 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
12448 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
12449 
12450 		/* Tiling and DCC changes also require bandwidth updates. */
12451 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
12452 		    old_afb->base.modifier != new_afb->base.modifier)
12453 			return true;
12454 	}
12455 
12456 	return false;
12457 }
12458 
12459 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
12460 			      struct drm_plane_state *new_plane_state,
12461 			      struct drm_framebuffer *fb)
12462 {
12463 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
12464 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
12465 	unsigned int pitch;
12466 	bool linear;
12467 
12468 	if (fb->width > new_acrtc->max_cursor_width ||
12469 	    fb->height > new_acrtc->max_cursor_height) {
12470 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB size %dx%d\n",
12471 				 new_plane_state->fb->width,
12472 				 new_plane_state->fb->height);
12473 		return -EINVAL;
12474 	}
12475 	if (new_plane_state->src_w != fb->width << 16 ||
12476 	    new_plane_state->src_h != fb->height << 16) {
12477 		drm_dbg_atomic(adev_to_drm(adev), "Cropping not supported for cursor plane\n");
12478 		return -EINVAL;
12479 	}
12480 
12481 	/* Pitch in pixels */
12482 	pitch = fb->pitches[0] / fb->format->cpp[0];
12483 
12484 	if (fb->width != pitch) {
12485 		drm_dbg_atomic(adev_to_drm(adev), "Cursor FB width %d doesn't match pitch %d",
12486 				 fb->width, pitch);
12487 		return -EINVAL;
12488 	}
12489 
12490 	switch (pitch) {
12491 	case 64:
12492 	case 128:
12493 	case 256:
12494 		/* FB pitch is supported by cursor plane */
12495 		break;
12496 	default:
12497 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB pitch %d px\n", pitch);
12498 		return -EINVAL;
12499 	}
12500 
12501 	/* Core DRM takes care of checking FB modifiers, so we only need to
12502 	 * check tiling flags when the FB doesn't have a modifier.
12503 	 */
12504 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
12505 		if (adev->family == AMDGPU_FAMILY_GC_12_0_0) {
12506 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
12507 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
12508 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
12509 		} else {
12510 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
12511 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
12512 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
12513 		}
12514 		if (!linear) {
12515 			drm_dbg_atomic(adev_to_drm(adev), "Cursor FB not linear");
12516 			return -EINVAL;
12517 		}
12518 	}
12519 
12520 	return 0;
12521 }
12522 
12523 /*
12524  * Helper function for checking the cursor in native mode
12525  */
12526 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
12527 					struct drm_plane *plane,
12528 					struct drm_plane_state *new_plane_state,
12529 					bool enable)
12530 {
12531 
12532 	struct amdgpu_crtc *new_acrtc;
12533 	int ret;
12534 
12535 	if (!enable || !new_plane_crtc ||
12536 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
12537 		return 0;
12538 
12539 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
12540 
12541 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
12542 		drm_dbg_atomic(new_plane_crtc->dev, "Cropping not supported for cursor plane\n");
12543 		return -EINVAL;
12544 	}
12545 
12546 	if (new_plane_state->fb) {
12547 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
12548 						new_plane_state->fb);
12549 		if (ret)
12550 			return ret;
12551 	}
12552 
12553 	return 0;
12554 }
12555 
12556 static bool dm_should_update_native_cursor(struct drm_atomic_commit *state,
12557 					   struct drm_crtc *old_plane_crtc,
12558 					   struct drm_crtc *new_plane_crtc,
12559 					   bool enable)
12560 {
12561 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12562 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12563 
12564 	if (!enable) {
12565 		if (old_plane_crtc == NULL)
12566 			return true;
12567 
12568 		old_crtc_state = drm_atomic_get_old_crtc_state(
12569 			state, old_plane_crtc);
12570 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12571 
12572 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12573 	} else {
12574 		if (new_plane_crtc == NULL)
12575 			return true;
12576 
12577 		new_crtc_state = drm_atomic_get_new_crtc_state(
12578 			state, new_plane_crtc);
12579 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12580 
12581 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12582 	}
12583 }
12584 
12585 static int dm_update_plane_state(struct dc *dc,
12586 				 struct drm_atomic_commit *state,
12587 				 struct drm_plane *plane,
12588 				 struct drm_plane_state *old_plane_state,
12589 				 struct drm_plane_state *new_plane_state,
12590 				 bool enable,
12591 				 bool *lock_and_validation_needed,
12592 				 bool *is_top_most_overlay)
12593 {
12594 
12595 	struct dm_atomic_state *dm_state = NULL;
12596 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
12597 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12598 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
12599 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
12600 	bool needs_reset, update_native_cursor;
12601 	int ret = 0;
12602 
12603 
12604 	new_plane_crtc = new_plane_state->crtc;
12605 	old_plane_crtc = old_plane_state->crtc;
12606 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
12607 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
12608 
12609 	update_native_cursor = dm_should_update_native_cursor(state,
12610 							      old_plane_crtc,
12611 							      new_plane_crtc,
12612 							      enable);
12613 
12614 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
12615 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12616 						    new_plane_state, enable);
12617 		if (ret)
12618 			return ret;
12619 
12620 		return 0;
12621 	}
12622 
12623 	needs_reset = should_reset_plane(state, plane, old_plane_state,
12624 					 new_plane_state);
12625 
12626 	/* Remove any changed/removed planes */
12627 	if (!enable) {
12628 		if (!needs_reset)
12629 			return 0;
12630 
12631 		if (!old_plane_crtc)
12632 			return 0;
12633 
12634 		old_crtc_state = drm_atomic_get_old_crtc_state(
12635 				state, old_plane_crtc);
12636 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12637 
12638 		if (!dm_old_crtc_state->stream)
12639 			return 0;
12640 
12641 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
12642 				plane->base.id, old_plane_crtc->base.id);
12643 
12644 		ret = dm_atomic_get_state(state, &dm_state);
12645 		if (ret)
12646 			return ret;
12647 
12648 		if (!dc_state_remove_plane(
12649 				dc,
12650 				dm_old_crtc_state->stream,
12651 				dm_old_plane_state->dc_state,
12652 				dm_state->context)) {
12653 
12654 			return -EINVAL;
12655 		}
12656 
12657 		if (dm_old_plane_state->dc_state)
12658 			dc_plane_state_release(dm_old_plane_state->dc_state);
12659 
12660 		dm_new_plane_state->dc_state = NULL;
12661 
12662 		*lock_and_validation_needed = true;
12663 
12664 	} else { /* Add new planes */
12665 		struct dc_plane_state *dc_new_plane_state;
12666 
12667 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
12668 			return 0;
12669 
12670 		if (!new_plane_crtc)
12671 			return 0;
12672 
12673 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
12674 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12675 
12676 		if (!dm_new_crtc_state->stream)
12677 			return 0;
12678 
12679 		if (!needs_reset)
12680 			return 0;
12681 
12682 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
12683 		if (ret)
12684 			goto out;
12685 
12686 		WARN_ON(dm_new_plane_state->dc_state);
12687 
12688 		dc_new_plane_state = dc_create_plane_state(dc);
12689 		if (!dc_new_plane_state) {
12690 			ret = -ENOMEM;
12691 			goto out;
12692 		}
12693 
12694 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
12695 				 plane->base.id, new_plane_crtc->base.id);
12696 
12697 		ret = fill_dc_plane_attributes(
12698 			drm_to_adev(new_plane_crtc->dev),
12699 			dc_new_plane_state,
12700 			new_plane_state,
12701 			new_crtc_state);
12702 		if (ret) {
12703 			dc_plane_state_release(dc_new_plane_state);
12704 			goto out;
12705 		}
12706 
12707 		ret = dm_atomic_get_state(state, &dm_state);
12708 		if (ret) {
12709 			dc_plane_state_release(dc_new_plane_state);
12710 			goto out;
12711 		}
12712 
12713 		/*
12714 		 * Any atomic check errors that occur after this will
12715 		 * not need a release. The plane state will be attached
12716 		 * to the stream, and therefore part of the atomic
12717 		 * state. It'll be released when the atomic state is
12718 		 * cleaned.
12719 		 */
12720 		if (!dc_state_add_plane(
12721 				dc,
12722 				dm_new_crtc_state->stream,
12723 				dc_new_plane_state,
12724 				dm_state->context)) {
12725 
12726 			dc_plane_state_release(dc_new_plane_state);
12727 			ret = -EINVAL;
12728 			goto out;
12729 		}
12730 
12731 		dm_new_plane_state->dc_state = dc_new_plane_state;
12732 
12733 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
12734 
12735 		/* Tell DC to do a full surface update every time there
12736 		 * is a plane change. Inefficient, but works for now.
12737 		 */
12738 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
12739 
12740 		*lock_and_validation_needed = true;
12741 	}
12742 
12743 out:
12744 	/* If enabling cursor overlay failed, attempt fallback to native mode */
12745 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
12746 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12747 						    new_plane_state, enable);
12748 		if (ret)
12749 			return ret;
12750 
12751 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
12752 	}
12753 
12754 	return ret;
12755 }
12756 
12757 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
12758 				       int *src_w, int *src_h)
12759 {
12760 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
12761 	case DRM_MODE_ROTATE_90:
12762 	case DRM_MODE_ROTATE_270:
12763 		*src_w = plane_state->src_h >> 16;
12764 		*src_h = plane_state->src_w >> 16;
12765 		break;
12766 	case DRM_MODE_ROTATE_0:
12767 	case DRM_MODE_ROTATE_180:
12768 	default:
12769 		*src_w = plane_state->src_w >> 16;
12770 		*src_h = plane_state->src_h >> 16;
12771 		break;
12772 	}
12773 }
12774 
12775 static void
12776 dm_get_plane_scale(struct drm_plane_state *plane_state,
12777 		   int *out_plane_scale_w, int *out_plane_scale_h)
12778 {
12779 	int plane_src_w, plane_src_h;
12780 
12781 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
12782 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
12783 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
12784 }
12785 
12786 /*
12787  * The normalized_zpos value cannot be used by this iterator directly. It's only
12788  * calculated for enabled planes, potentially causing normalized_zpos collisions
12789  * between enabled/disabled planes in the atomic state. We need a unique value
12790  * so that the iterator will not generate the same object twice, or loop
12791  * indefinitely.
12792  */
12793 static inline struct __drm_planes_state *__get_next_zpos(
12794 	struct drm_atomic_commit *state,
12795 	struct __drm_planes_state *prev)
12796 {
12797 	unsigned int highest_zpos = 0, prev_zpos = 256;
12798 	uint32_t highest_id = 0, prev_id = UINT_MAX;
12799 	struct drm_plane_state *new_plane_state;
12800 	struct drm_plane *plane;
12801 	int i, highest_i = -1;
12802 
12803 	if (prev != NULL) {
12804 		prev_zpos = prev->new_state->zpos;
12805 		prev_id = prev->ptr->base.id;
12806 	}
12807 
12808 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
12809 		/* Skip planes with higher zpos than the previously returned */
12810 		if (new_plane_state->zpos > prev_zpos ||
12811 		    (new_plane_state->zpos == prev_zpos &&
12812 		     plane->base.id >= prev_id))
12813 			continue;
12814 
12815 		/* Save the index of the plane with highest zpos */
12816 		if (new_plane_state->zpos > highest_zpos ||
12817 		    (new_plane_state->zpos == highest_zpos &&
12818 		     plane->base.id > highest_id)) {
12819 			highest_zpos = new_plane_state->zpos;
12820 			highest_id = plane->base.id;
12821 			highest_i = i;
12822 		}
12823 	}
12824 
12825 	if (highest_i < 0)
12826 		return NULL;
12827 
12828 	return &state->planes[highest_i];
12829 }
12830 
12831 /*
12832  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
12833  * by descending zpos, as read from the new plane state. This is the same
12834  * ordering as defined by drm_atomic_normalize_zpos().
12835  */
12836 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
12837 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
12838 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
12839 		for_each_if(((plane) = __i->ptr,				\
12840 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
12841 			     (old_plane_state) = __i->old_state,		\
12842 			     (new_plane_state) = __i->new_state, 1))
12843 
12844 static int add_affected_mst_dsc_crtcs(struct drm_atomic_commit *state, struct drm_crtc *crtc)
12845 {
12846 	struct drm_connector *connector;
12847 	struct drm_connector_state *conn_state, *old_conn_state;
12848 	struct amdgpu_dm_connector *aconnector = NULL;
12849 	int i;
12850 
12851 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
12852 		if (!conn_state->crtc)
12853 			conn_state = old_conn_state;
12854 
12855 		if (conn_state->crtc != crtc)
12856 			continue;
12857 
12858 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
12859 			continue;
12860 
12861 		aconnector = to_amdgpu_dm_connector(connector);
12862 		if (!aconnector->mst_output_port || !aconnector->mst_root)
12863 			aconnector = NULL;
12864 		else
12865 			break;
12866 	}
12867 
12868 	if (!aconnector)
12869 		return 0;
12870 
12871 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
12872 }
12873 
12874 /**
12875  * DOC: Cursor Modes - Native vs Overlay
12876  *
12877  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
12878  * plane. It does not require a dedicated hw plane to enable, but it is
12879  * subjected to the same z-order and scaling as the hw plane. It also has format
12880  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
12881  * hw plane.
12882  *
12883  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
12884  * own scaling and z-pos. It also has no blending restrictions. It lends to a
12885  * cursor behavior more akin to a DRM client's expectations. However, it does
12886  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
12887  * available.
12888  */
12889 
12890 /**
12891  * dm_plane_color_pipeline_active() - Check if a plane's color pipeline active.
12892  * @state: DRM atomic state
12893  * @plane: DRM plane to check
12894  * @use_old: if true, inspect the old colorop states; otherwise the new ones
12895  *
12896  * A color pipeline may be selected (color_pipeline != NULL) but still is
12897  * inactive if every colorop in the chain is bypassed.  Only return
12898  * true when at least one colorop has bypass == false, meaning the cursor
12899  * would be subjected to the transformation in native mode.
12900  *
12901  * Return: true if the pipeline modifies pixels, false otherwise.
12902  */
12903 static bool dm_plane_color_pipeline_active(struct drm_atomic_commit *state,
12904 					   struct drm_plane *plane,
12905 					   bool use_old)
12906 {
12907 	struct drm_colorop *colorop;
12908 	struct drm_colorop_state *old_colorop_state, *new_colorop_state;
12909 	int i;
12910 
12911 	for_each_oldnew_colorop_in_state(state, colorop, old_colorop_state, new_colorop_state, i) {
12912 		struct drm_colorop_state *cstate = use_old ? old_colorop_state : new_colorop_state;
12913 
12914 		if (cstate->colorop->plane != plane)
12915 			continue;
12916 		if (!cstate->bypass)
12917 			return true;
12918 	}
12919 	return false;
12920 }
12921 
12922 /**
12923  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
12924  * @adev: amdgpu device
12925  * @state: DRM atomic state
12926  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
12927  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
12928  *
12929  * Get whether the cursor should be enabled in native mode, or overlay mode, on
12930  * the dm_crtc_state.
12931  *
12932  * The cursor should be enabled in overlay mode if there exists an underlying
12933  * plane - on which the cursor may be blended - that is either YUV formatted,
12934  * scaled differently from the cursor, or has a color pipeline active.
12935  *
12936  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
12937  * calling this function.
12938  *
12939  * Return: 0 on success, or an error code if getting the cursor plane state
12940  * failed.
12941  */
12942 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
12943 				   struct drm_atomic_commit *state,
12944 				   struct dm_crtc_state *dm_crtc_state,
12945 				   enum amdgpu_dm_cursor_mode *cursor_mode)
12946 {
12947 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
12948 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
12949 	struct drm_plane *plane;
12950 	bool consider_mode_change = false;
12951 	bool entire_crtc_covered = false;
12952 	bool cursor_changed = false;
12953 	int underlying_scale_w, underlying_scale_h;
12954 	int cursor_scale_w, cursor_scale_h;
12955 	int i;
12956 
12957 	/* Overlay cursor not supported on HW before DCN
12958 	 * DCN401/420 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
12959 	 * as previous DCN generations, so enable native mode on DCN401/420
12960 	 *
12961 	 * Always set native cursor mode when the CRTC is disabled,
12962 	 * to make sure it doesn't cause atomic commits to fail when
12963 	 * they are trying to disable the CRTC.
12964 	 */
12965 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1) ||
12966 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
12967 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 1) ||
12968 	    !dm_crtc_state->base.enable) {
12969 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12970 		return 0;
12971 	}
12972 
12973 	/* Init cursor_mode to be the same as current */
12974 	*cursor_mode = dm_crtc_state->cursor_mode;
12975 
12976 	/*
12977 	 * Cursor mode can change if a plane's format changes, scale changes, is
12978 	 * enabled/disabled, z-order changes, or color management properties change.
12979 	 */
12980 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
12981 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
12982 
12983 		/* Only care about planes on this CRTC */
12984 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
12985 			continue;
12986 
12987 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
12988 			cursor_changed = true;
12989 
12990 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
12991 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
12992 		    old_plane_state->fb->format != plane_state->fb->format) {
12993 			consider_mode_change = true;
12994 			break;
12995 		}
12996 
12997 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
12998 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
12999 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
13000 			consider_mode_change = true;
13001 			break;
13002 		}
13003 
13004 		if (dm_plane_color_pipeline_active(state, plane, true) !=
13005 		    dm_plane_color_pipeline_active(state, plane, false)) {
13006 			consider_mode_change = true;
13007 			break;
13008 		}
13009 	}
13010 
13011 	if (!consider_mode_change && !crtc_state->zpos_changed)
13012 		return 0;
13013 
13014 	/*
13015 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
13016 	 * no need to set cursor mode. This avoids needlessly locking the cursor
13017 	 * state.
13018 	 */
13019 	if (!cursor_changed &&
13020 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
13021 		return 0;
13022 	}
13023 
13024 	cursor_state = drm_atomic_get_plane_state(state,
13025 						  crtc_state->crtc->cursor);
13026 	if (IS_ERR(cursor_state))
13027 		return PTR_ERR(cursor_state);
13028 
13029 	/* Cursor is disabled */
13030 	if (!cursor_state->fb)
13031 		return 0;
13032 
13033 	/* For all planes in descending z-order (all of which are below cursor
13034 	 * as per zpos definitions), check their scaling and format
13035 	 */
13036 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
13037 
13038 		/* Only care about non-cursor planes on this CRTC */
13039 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
13040 		    plane->type == DRM_PLANE_TYPE_CURSOR)
13041 			continue;
13042 
13043 		/* Underlying plane is YUV format - use overlay cursor */
13044 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
13045 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
13046 			return 0;
13047 		}
13048 
13049 		/* Underlying plane has an active color pipeline - cursor would be transformed */
13050 		if (dm_plane_color_pipeline_active(state, plane, false)) {
13051 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
13052 			return 0;
13053 		}
13054 
13055 		dm_get_plane_scale(plane_state,
13056 				   &underlying_scale_w, &underlying_scale_h);
13057 		dm_get_plane_scale(cursor_state,
13058 				   &cursor_scale_w, &cursor_scale_h);
13059 
13060 		/* Underlying plane has different scale - use overlay cursor */
13061 		if (cursor_scale_w != underlying_scale_w &&
13062 		    cursor_scale_h != underlying_scale_h) {
13063 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
13064 			return 0;
13065 		}
13066 
13067 		/* If this plane covers the whole CRTC, no need to check planes underneath */
13068 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
13069 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
13070 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
13071 			entire_crtc_covered = true;
13072 			break;
13073 		}
13074 	}
13075 
13076 	/* If planes do not cover the entire CRTC, use overlay mode to enable
13077 	 * cursor over holes
13078 	 */
13079 	if (entire_crtc_covered)
13080 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
13081 	else
13082 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
13083 
13084 	return 0;
13085 }
13086 
13087 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
13088 					    struct drm_atomic_commit *state,
13089 					    struct drm_crtc_state *crtc_state)
13090 {
13091 	struct drm_plane *plane;
13092 	struct drm_plane_state *new_plane_state, *old_plane_state;
13093 
13094 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
13095 		new_plane_state = drm_atomic_get_new_plane_state(state, plane);
13096 		old_plane_state = drm_atomic_get_old_plane_state(state, plane);
13097 
13098 		if (!old_plane_state || !new_plane_state)
13099 			continue;
13100 
13101 		if (old_plane_state->fb && new_plane_state->fb &&
13102 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
13103 			return true;
13104 	}
13105 
13106 	return false;
13107 }
13108 
13109 /**
13110  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
13111  *
13112  * @dev: The DRM device
13113  * @state: The atomic state to commit
13114  *
13115  * Validate that the given atomic state is programmable by DC into hardware.
13116  * This involves constructing a &struct dc_state reflecting the new hardware
13117  * state we wish to commit, then querying DC to see if it is programmable. It's
13118  * important not to modify the existing DC state. Otherwise, atomic_check
13119  * may unexpectedly commit hardware changes.
13120  *
13121  * When validating the DC state, it's important that the right locks are
13122  * acquired. For full updates case which removes/adds/updates streams on one
13123  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
13124  * that any such full update commit will wait for completion of any outstanding
13125  * flip using DRMs synchronization events.
13126  *
13127  * Note that DM adds the affected connectors for all CRTCs in state, when that
13128  * might not seem necessary. This is because DC stream creation requires the
13129  * DC sink, which is tied to the DRM connector state. Cleaning this up should
13130  * be possible but non-trivial - a possible TODO item.
13131  *
13132  * Return: -Error code if validation failed.
13133  */
13134 static int amdgpu_dm_atomic_check(struct drm_device *dev,
13135 				  struct drm_atomic_commit *state)
13136 {
13137 	struct amdgpu_device *adev = drm_to_adev(dev);
13138 	struct dm_atomic_state *dm_state = NULL;
13139 	struct dc *dc = adev->dm.dc;
13140 	struct drm_connector *connector;
13141 	struct drm_connector_state *old_con_state, *new_con_state;
13142 	struct drm_crtc *crtc;
13143 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13144 	struct drm_plane *plane;
13145 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
13146 	enum dc_status status;
13147 	int ret, i;
13148 	bool lock_and_validation_needed = false;
13149 	bool is_top_most_overlay = true;
13150 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
13151 	struct drm_dp_mst_topology_mgr *mgr;
13152 	struct drm_dp_mst_topology_state *mst_state;
13153 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
13154 
13155 	trace_amdgpu_dm_atomic_check_begin(state);
13156 
13157 	ret = drm_atomic_helper_check_modeset(dev, state);
13158 	if (ret) {
13159 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
13160 		goto fail;
13161 	}
13162 
13163 	/* Check connector changes */
13164 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
13165 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
13166 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
13167 
13168 		/* Skip connectors that are disabled or part of modeset already. */
13169 		if (!new_con_state->crtc)
13170 			continue;
13171 
13172 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
13173 		if (IS_ERR(new_crtc_state)) {
13174 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
13175 			ret = PTR_ERR(new_crtc_state);
13176 			goto fail;
13177 		}
13178 
13179 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
13180 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
13181 			new_crtc_state->connectors_changed = true;
13182 	}
13183 
13184 	if (dc_resource_is_dsc_encoding_supported(dc)) {
13185 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13186 			dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13187 			dm_new_crtc_state->mode_changed_independent_from_dsc = new_crtc_state->mode_changed;
13188 		}
13189 
13190 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13191 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
13192 				ret = add_affected_mst_dsc_crtcs(state, crtc);
13193 				if (ret) {
13194 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
13195 					goto fail;
13196 				}
13197 			}
13198 		}
13199 	}
13200 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13201 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
13202 
13203 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
13204 		    !new_crtc_state->color_mgmt_changed &&
13205 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
13206 			dm_old_crtc_state->dsc_force_changed == false)
13207 			continue;
13208 
13209 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
13210 		if (ret) {
13211 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
13212 			goto fail;
13213 		}
13214 
13215 		if (!new_crtc_state->enable)
13216 			continue;
13217 
13218 		ret = drm_atomic_add_affected_connectors(state, crtc);
13219 		if (ret) {
13220 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
13221 			goto fail;
13222 		}
13223 
13224 		ret = drm_atomic_add_affected_planes(state, crtc);
13225 		if (ret) {
13226 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
13227 			goto fail;
13228 		}
13229 
13230 		if (dm_old_crtc_state->dsc_force_changed)
13231 			new_crtc_state->mode_changed = true;
13232 	}
13233 
13234 	/*
13235 	 * Add all primary and overlay planes on the CRTC to the state
13236 	 * whenever a plane is enabled to maintain correct z-ordering
13237 	 * and to enable fast surface updates.
13238 	 */
13239 	drm_for_each_crtc(crtc, dev) {
13240 		bool modified = false;
13241 
13242 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
13243 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
13244 				continue;
13245 
13246 			if (new_plane_state->crtc == crtc ||
13247 			    old_plane_state->crtc == crtc) {
13248 				modified = true;
13249 				break;
13250 			}
13251 		}
13252 
13253 		if (!modified)
13254 			continue;
13255 
13256 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
13257 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
13258 				continue;
13259 
13260 			new_plane_state =
13261 				drm_atomic_get_plane_state(state, plane);
13262 
13263 			if (IS_ERR(new_plane_state)) {
13264 				ret = PTR_ERR(new_plane_state);
13265 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
13266 				goto fail;
13267 			}
13268 		}
13269 	}
13270 
13271 	/*
13272 	 * DC consults the zpos (layer_index in DC terminology) to determine the
13273 	 * hw plane on which to enable the hw cursor (see
13274 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
13275 	 * atomic state, so call drm helper to normalize zpos.
13276 	 */
13277 	ret = drm_atomic_normalize_zpos(dev, state);
13278 	if (ret) {
13279 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
13280 		goto fail;
13281 	}
13282 
13283 	/*
13284 	 * Determine whether cursors on each CRTC should be enabled in native or
13285 	 * overlay mode.
13286 	 */
13287 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13288 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13289 
13290 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
13291 					      &dm_new_crtc_state->cursor_mode);
13292 		if (ret) {
13293 			drm_dbg(dev, "Failed to determine cursor mode\n");
13294 			goto fail;
13295 		}
13296 
13297 		/*
13298 		 * If overlay cursor is needed, DC cannot go through the
13299 		 * native cursor update path. All enabled planes on the CRTC
13300 		 * need to be added for DC to not disable a plane by mistake
13301 		 */
13302 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
13303 			if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
13304 				drm_dbg(dev, "Overlay cursor not supported on DCE\n");
13305 				ret = -EINVAL;
13306 				goto fail;
13307 			}
13308 
13309 			ret = drm_atomic_add_affected_planes(state, crtc);
13310 			if (ret)
13311 				goto fail;
13312 		}
13313 	}
13314 
13315 	/* Remove exiting planes if they are modified */
13316 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13317 
13318 		ret = dm_update_plane_state(dc, state, plane,
13319 					    old_plane_state,
13320 					    new_plane_state,
13321 					    false,
13322 					    &lock_and_validation_needed,
13323 					    &is_top_most_overlay);
13324 		if (ret) {
13325 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13326 			goto fail;
13327 		}
13328 	}
13329 
13330 	/* Disable all crtcs which require disable */
13331 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13332 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
13333 					   old_crtc_state,
13334 					   new_crtc_state,
13335 					   false,
13336 					   &lock_and_validation_needed);
13337 		if (ret) {
13338 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
13339 			goto fail;
13340 		}
13341 	}
13342 
13343 	/* Enable all crtcs which require enable */
13344 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13345 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
13346 					   old_crtc_state,
13347 					   new_crtc_state,
13348 					   true,
13349 					   &lock_and_validation_needed);
13350 		if (ret) {
13351 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
13352 			goto fail;
13353 		}
13354 	}
13355 
13356 	/* Add new/modified planes */
13357 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13358 		ret = dm_update_plane_state(dc, state, plane,
13359 					    old_plane_state,
13360 					    new_plane_state,
13361 					    true,
13362 					    &lock_and_validation_needed,
13363 					    &is_top_most_overlay);
13364 		if (ret) {
13365 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13366 			goto fail;
13367 		}
13368 	}
13369 
13370 #if defined(CONFIG_DRM_AMD_DC_FP)
13371 	if (dc_resource_is_dsc_encoding_supported(dc)) {
13372 		ret = pre_validate_dsc(state, &dm_state, vars);
13373 		if (ret != 0)
13374 			goto fail;
13375 	}
13376 #endif
13377 
13378 	/* Run this here since we want to validate the streams we created */
13379 	ret = drm_atomic_helper_check_planes(dev, state);
13380 	if (ret) {
13381 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
13382 		goto fail;
13383 	}
13384 
13385 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13386 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13387 		if (dm_new_crtc_state->mpo_requested)
13388 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
13389 	}
13390 
13391 	/* Check cursor restrictions */
13392 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13393 		enum amdgpu_dm_cursor_mode required_cursor_mode;
13394 		int is_rotated, is_scaled;
13395 
13396 		/* Overlay cusor not subject to native cursor restrictions */
13397 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13398 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
13399 			continue;
13400 
13401 		/* Check if rotation or scaling is enabled on DCN401 */
13402 		if ((drm_plane_mask(crtc->cursor) &
13403 		     new_crtc_state->plane_mask) &&
13404 		    (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 1) ||
13405 		     amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
13406 		     amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1))) {
13407 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
13408 
13409 			is_rotated = new_cursor_state &&
13410 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
13411 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
13412 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
13413 
13414 			if (is_rotated || is_scaled) {
13415 				drm_dbg_driver(
13416 					crtc->dev,
13417 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
13418 					crtc->base.id, crtc->name);
13419 				ret = -EINVAL;
13420 				goto fail;
13421 			}
13422 		}
13423 
13424 		/* If HW can only do native cursor, check restrictions again */
13425 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
13426 					      &required_cursor_mode);
13427 		if (ret) {
13428 			drm_dbg_driver(crtc->dev,
13429 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
13430 				       crtc->base.id, crtc->name);
13431 			goto fail;
13432 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
13433 			drm_dbg_driver(crtc->dev,
13434 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling, YUV, or color pipeline restrictions\n",
13435 				       crtc->base.id, crtc->name);
13436 			ret = -EINVAL;
13437 			goto fail;
13438 		}
13439 	}
13440 
13441 	if (state->legacy_cursor_update) {
13442 		/*
13443 		 * This is a fast cursor update coming from the plane update
13444 		 * helper, check if it can be done asynchronously for better
13445 		 * performance.
13446 		 */
13447 		state->async_update =
13448 			!drm_atomic_helper_async_check(dev, state);
13449 
13450 		/*
13451 		 * Skip the remaining global validation if this is an async
13452 		 * update. Cursor updates can be done without affecting
13453 		 * state or bandwidth calcs and this avoids the performance
13454 		 * penalty of locking the private state object and
13455 		 * allocating a new dc_state.
13456 		 */
13457 		if (state->async_update)
13458 			return 0;
13459 	}
13460 
13461 	/* Check scaling and underscan changes*/
13462 	/* TODO Removed scaling changes validation due to inability to commit
13463 	 * new stream into context w\o causing full reset. Need to
13464 	 * decide how to handle.
13465 	 */
13466 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
13467 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
13468 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
13469 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
13470 
13471 		/* Skip any modesets/resets */
13472 		if (!acrtc || drm_atomic_crtc_needs_modeset(
13473 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
13474 			continue;
13475 
13476 		/* Skip any thing not scale or underscan changes */
13477 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
13478 			continue;
13479 
13480 		lock_and_validation_needed = true;
13481 	}
13482 
13483 	/* set the slot info for each mst_state based on the link encoding format */
13484 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
13485 		struct amdgpu_dm_connector *aconnector;
13486 		struct drm_connector *connector;
13487 		struct drm_connector_list_iter iter;
13488 		u8 link_coding_cap;
13489 
13490 		drm_connector_list_iter_begin(dev, &iter);
13491 		drm_for_each_connector_iter(connector, &iter) {
13492 			if (connector->index == mst_state->mgr->conn_base_id) {
13493 				aconnector = to_amdgpu_dm_connector(connector);
13494 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
13495 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
13496 
13497 				break;
13498 			}
13499 		}
13500 		drm_connector_list_iter_end(&iter);
13501 	}
13502 
13503 	/**
13504 	 * Streams and planes are reset when there are changes that affect
13505 	 * bandwidth. Anything that affects bandwidth needs to go through
13506 	 * DC global validation to ensure that the configuration can be applied
13507 	 * to hardware.
13508 	 *
13509 	 * We have to currently stall out here in atomic_check for outstanding
13510 	 * commits to finish in this case because our IRQ handlers reference
13511 	 * DRM state directly - we can end up disabling interrupts too early
13512 	 * if we don't.
13513 	 *
13514 	 * TODO: Remove this stall and drop DM state private objects.
13515 	 */
13516 	if (lock_and_validation_needed) {
13517 		ret = dm_atomic_get_state(state, &dm_state);
13518 		if (ret) {
13519 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
13520 			goto fail;
13521 		}
13522 
13523 		ret = do_aquire_global_lock(dev, state);
13524 		if (ret) {
13525 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
13526 			goto fail;
13527 		}
13528 
13529 #if defined(CONFIG_DRM_AMD_DC_FP)
13530 		if (dc_resource_is_dsc_encoding_supported(dc)) {
13531 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
13532 			if (ret) {
13533 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
13534 				ret = -EINVAL;
13535 				goto fail;
13536 			}
13537 		}
13538 #endif
13539 
13540 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
13541 		if (ret) {
13542 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
13543 			goto fail;
13544 		}
13545 
13546 		/*
13547 		 * Perform validation of MST topology in the state:
13548 		 * We need to perform MST atomic check before calling
13549 		 * dc_validate_global_state(), or there is a chance
13550 		 * to get stuck in an infinite loop and hang eventually.
13551 		 */
13552 		ret = drm_dp_mst_atomic_check(state);
13553 		if (ret) {
13554 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
13555 			goto fail;
13556 		}
13557 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
13558 		if (status != DC_OK) {
13559 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
13560 				       dc_status_to_str(status), status);
13561 			ret = -EINVAL;
13562 			goto fail;
13563 		}
13564 	} else {
13565 		/*
13566 		 * The commit is a fast update. Fast updates shouldn't change
13567 		 * the DC context, affect global validation, and can have their
13568 		 * commit work done in parallel with other commits not touching
13569 		 * the same resource. If we have a new DC context as part of
13570 		 * the DM atomic state from validation we need to free it and
13571 		 * retain the existing one instead.
13572 		 *
13573 		 * Furthermore, since the DM atomic state only contains the DC
13574 		 * context and can safely be annulled, we can free the state
13575 		 * and clear the associated private object now to free
13576 		 * some memory and avoid a possible use-after-free later.
13577 		 */
13578 
13579 		for (i = 0; i < state->num_private_objs; i++) {
13580 			struct drm_private_obj *obj = state->private_objs[i].ptr;
13581 
13582 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
13583 				int j = state->num_private_objs-1;
13584 
13585 				dm_atomic_destroy_state(obj,
13586 						state->private_objs[i].state_to_destroy);
13587 
13588 				/* If i is not at the end of the array then the
13589 				 * last element needs to be moved to where i was
13590 				 * before the array can safely be truncated.
13591 				 */
13592 				if (i != j)
13593 					state->private_objs[i] =
13594 						state->private_objs[j];
13595 
13596 				state->private_objs[j].ptr = NULL;
13597 				state->private_objs[j].state_to_destroy = NULL;
13598 				state->private_objs[j].old_state = NULL;
13599 				state->private_objs[j].new_state = NULL;
13600 
13601 				state->num_private_objs = j;
13602 				break;
13603 			}
13604 		}
13605 	}
13606 
13607 	/* Store the overall update type for use later in atomic check. */
13608 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13609 		struct dm_crtc_state *dm_new_crtc_state =
13610 			to_dm_crtc_state(new_crtc_state);
13611 
13612 		/*
13613 		 * Only allow async flips for fast updates that don't change
13614 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
13615 		 */
13616 		if (new_crtc_state->async_flip &&
13617 		    (lock_and_validation_needed ||
13618 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
13619 			drm_dbg_atomic(crtc->dev,
13620 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
13621 				       crtc->base.id, crtc->name);
13622 			ret = -EINVAL;
13623 			goto fail;
13624 		}
13625 
13626 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
13627 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
13628 	}
13629 
13630 	/* Must be success */
13631 	WARN_ON(ret);
13632 
13633 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13634 
13635 	return ret;
13636 
13637 fail:
13638 	if (ret == -EDEADLK)
13639 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
13640 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
13641 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
13642 	else
13643 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
13644 
13645 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13646 
13647 	return ret;
13648 }
13649 
13650 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
13651 		unsigned int offset,
13652 		unsigned int total_length,
13653 		u8 *data,
13654 		unsigned int length,
13655 		struct amdgpu_hdmi_vsdb_info *vsdb)
13656 {
13657 	bool res;
13658 	union dmub_rb_cmd cmd;
13659 	struct dmub_cmd_send_edid_cea *input;
13660 	struct dmub_cmd_edid_cea_output *output;
13661 
13662 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
13663 		return false;
13664 
13665 	memset(&cmd, 0, sizeof(cmd));
13666 
13667 	input = &cmd.edid_cea.data.input;
13668 
13669 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
13670 	cmd.edid_cea.header.sub_type = 0;
13671 	cmd.edid_cea.header.payload_bytes =
13672 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
13673 	input->offset = offset;
13674 	input->length = length;
13675 	input->cea_total_length = total_length;
13676 	memcpy(input->payload, data, length);
13677 
13678 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
13679 	if (!res) {
13680 		drm_err(adev_to_drm(dm->adev), "EDID CEA parser failed\n");
13681 		return false;
13682 	}
13683 
13684 	output = &cmd.edid_cea.data.output;
13685 
13686 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
13687 		if (!output->ack.success) {
13688 			drm_err(adev_to_drm(dm->adev), "EDID CEA ack failed at offset %d\n",
13689 					output->ack.offset);
13690 		}
13691 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
13692 		if (!output->amd_vsdb.vsdb_found)
13693 			return false;
13694 
13695 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
13696 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
13697 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
13698 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
13699 		vsdb->freesync_mccs_vcp_code = output->amd_vsdb.freesync_mccs_vcp_code;
13700 	} else {
13701 		drm_warn(adev_to_drm(dm->adev), "Unknown EDID CEA parser results\n");
13702 		return false;
13703 	}
13704 
13705 	return true;
13706 }
13707 
13708 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
13709 		u8 *edid_ext, int len,
13710 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13711 {
13712 	int i;
13713 
13714 	/* send extension block to DMCU for parsing */
13715 	for (i = 0; i < len; i += 8) {
13716 		bool res;
13717 		int offset;
13718 
13719 		/* send 8 bytes a time */
13720 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
13721 			return false;
13722 
13723 		if (i+8 == len) {
13724 			/* EDID block sent completed, expect result */
13725 			int version, min_rate, max_rate;
13726 
13727 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
13728 			if (res) {
13729 				/* amd vsdb found */
13730 				vsdb_info->freesync_supported = 1;
13731 				vsdb_info->amd_vsdb_version = version;
13732 				vsdb_info->min_refresh_rate_hz = min_rate;
13733 				vsdb_info->max_refresh_rate_hz = max_rate;
13734 				/* Not enabled on DMCU*/
13735 				vsdb_info->freesync_mccs_vcp_code = 0;
13736 				return true;
13737 			}
13738 			/* not amd vsdb */
13739 			return false;
13740 		}
13741 
13742 		/* check for ack*/
13743 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
13744 		if (!res)
13745 			return false;
13746 	}
13747 
13748 	return false;
13749 }
13750 
13751 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
13752 		u8 *edid_ext, int len,
13753 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13754 {
13755 	int i;
13756 
13757 	/* send extension block to DMCU for parsing */
13758 	for (i = 0; i < len; i += 8) {
13759 		/* send 8 bytes a time */
13760 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
13761 			return false;
13762 	}
13763 
13764 	return vsdb_info->freesync_supported;
13765 }
13766 
13767 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
13768 		u8 *edid_ext, int len,
13769 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13770 {
13771 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
13772 	bool ret;
13773 
13774 	mutex_lock(&adev->dm.dc_lock);
13775 	if (adev->dm.dmub_srv)
13776 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
13777 	else
13778 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
13779 	mutex_unlock(&adev->dm.dc_lock);
13780 	return ret;
13781 }
13782 
13783 static void parse_edid_displayid_vrr(struct drm_connector *connector,
13784 				     const struct edid *edid)
13785 {
13786 	u8 *edid_ext = NULL;
13787 	int i;
13788 	int j = 0;
13789 	u16 min_vfreq;
13790 	u16 max_vfreq;
13791 
13792 	if (!edid || !edid->extensions)
13793 		return;
13794 
13795 	/* Find DisplayID extension */
13796 	for (i = 0; i < edid->extensions; i++) {
13797 		edid_ext = (void *)(edid + (i + 1));
13798 		if (edid_ext[0] == DISPLAYID_EXT)
13799 			break;
13800 	}
13801 
13802 	if (i == edid->extensions)
13803 		return;
13804 
13805 	while (j < EDID_LENGTH) {
13806 		/* Get dynamic video timing range from DisplayID if available */
13807 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
13808 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
13809 			min_vfreq = edid_ext[j+9];
13810 			if (edid_ext[j+1] & 7)
13811 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
13812 			else
13813 				max_vfreq = edid_ext[j+10];
13814 
13815 			if (max_vfreq && min_vfreq) {
13816 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
13817 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
13818 
13819 				return;
13820 			}
13821 		}
13822 		j++;
13823 	}
13824 }
13825 
13826 static int get_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13827 			struct amdgpu_hdmi_vsdb_info *vsdb_info)
13828 {
13829 	struct drm_connector *connector = &aconnector->base;
13830 
13831 	vsdb_info->replay_mode = connector->display_info.amd_vsdb.replay_mode;
13832 	vsdb_info->amd_vsdb_version = connector->display_info.amd_vsdb.version;
13833 
13834 	return connector->display_info.amd_vsdb.version != 0;
13835 }
13836 
13837 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13838 			       const struct edid *edid,
13839 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
13840 {
13841 	u8 *edid_ext = NULL;
13842 	int i;
13843 	bool valid_vsdb_found = false;
13844 
13845 	/*----- drm_find_cea_extension() -----*/
13846 	/* No EDID or EDID extensions */
13847 	if (edid == NULL || edid->extensions == 0)
13848 		return -ENODEV;
13849 
13850 	/* Find CEA extension */
13851 	for (i = 0; i < edid->extensions; i++) {
13852 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
13853 		if (edid_ext[0] == CEA_EXT)
13854 			break;
13855 	}
13856 
13857 	if (i == edid->extensions)
13858 		return -ENODEV;
13859 
13860 	/*----- cea_db_offsets() -----*/
13861 	if (edid_ext[0] != CEA_EXT)
13862 		return -ENODEV;
13863 
13864 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
13865 
13866 	return valid_vsdb_found ? i : -ENODEV;
13867 }
13868 
13869 /**
13870  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
13871  *
13872  * @connector: Connector to query.
13873  * @drm_edid: DRM EDID from monitor
13874  * @do_mccs: Controls whether MCCS (Monitor Control Command Set) over
13875  *	      DDC (Display Data Channel) transactions are performed. When true,
13876  *	      the driver queries the monitor to get or update additional FreeSync
13877  *	      capability information. When false, these transactions are skipped.
13878  *
13879  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
13880  * track of some of the display information in the internal data struct used by
13881  * amdgpu_dm. This function checks which type of connector we need to set the
13882  * FreeSync parameters.
13883  */
13884 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
13885 				    const struct drm_edid *drm_edid, bool do_mccs)
13886 {
13887 	int i = 0;
13888 	struct amdgpu_dm_connector *amdgpu_dm_connector =
13889 			to_amdgpu_dm_connector(connector);
13890 	struct dm_connector_state *dm_con_state = NULL;
13891 	struct dc_sink *sink;
13892 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
13893 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
13894 	const struct edid *edid;
13895 	bool freesync_capable = false;
13896 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
13897 
13898 	if (!connector->state) {
13899 		drm_err(adev_to_drm(adev), "%s - Connector has no state", __func__);
13900 		goto update;
13901 	}
13902 
13903 	sink = amdgpu_dm_connector->dc_sink ?
13904 		amdgpu_dm_connector->dc_sink :
13905 		amdgpu_dm_connector->dc_em_sink;
13906 
13907 	drm_edid_connector_update(connector, drm_edid);
13908 
13909 	if (!drm_edid || !sink) {
13910 		dm_con_state = to_dm_connector_state(connector->state);
13911 
13912 		amdgpu_dm_connector->min_vfreq = 0;
13913 		amdgpu_dm_connector->max_vfreq = 0;
13914 		freesync_capable = false;
13915 
13916 		goto update;
13917 	}
13918 
13919 	dm_con_state = to_dm_connector_state(connector->state);
13920 
13921 	if (!adev->dm.freesync_module || !dc_supports_vrr(sink->ctx->dce_version))
13922 		goto update;
13923 
13924 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
13925 
13926 	/* Some eDP panels only have the refresh rate range info in DisplayID */
13927 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
13928 	     connector->display_info.monitor_range.max_vfreq == 0))
13929 		parse_edid_displayid_vrr(connector, edid);
13930 
13931 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
13932 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
13933 		if (amdgpu_dm_connector->dc_link &&
13934 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
13935 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
13936 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
13937 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13938 				freesync_capable = true;
13939 		}
13940 
13941 		get_amd_vsdb(amdgpu_dm_connector, &vsdb_info);
13942 
13943 		if (vsdb_info.replay_mode) {
13944 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
13945 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
13946 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
13947 		}
13948 
13949 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
13950 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13951 		if (i >= 0) {
13952 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13953 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13954 
13955 			if (vsdb_info.freesync_supported) {
13956 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13957 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13958 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13959 					freesync_capable = true;
13960 
13961 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13962 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13963 			}
13964 		}
13965 	}
13966 
13967 	if (amdgpu_dm_connector->dc_link)
13968 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
13969 
13970 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
13971 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13972 		if (i >= 0) {
13973 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13974 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13975 
13976 			if (vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
13977 				amdgpu_dm_connector->pack_sdp_v1_3 = true;
13978 				amdgpu_dm_connector->as_type = as_type;
13979 
13980 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13981 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13982 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13983 					freesync_capable = true;
13984 
13985 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13986 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13987 			}
13988 		}
13989 	}
13990 
13991 	/* Handle MCCS */
13992 	if (do_mccs) {
13993 		dm_helpers_read_mccs_caps(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13994 
13995 		if (sink->edid_caps.freesync_vcp_code && !sink->mccs_caps.freesync_supported)
13996 			freesync_capable = false;
13997 
13998 		if (sink->mccs_caps.freesync_supported && freesync_capable)
13999 			dm_helpers_mccs_vcp_set(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
14000 	}
14001 
14002 update:
14003 	if (dm_con_state)
14004 		dm_con_state->freesync_capable = freesync_capable;
14005 
14006 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
14007 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
14008 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
14009 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
14010 	}
14011 
14012 	if (connector->vrr_capable_property)
14013 		drm_connector_set_vrr_capable_property(connector,
14014 						       freesync_capable);
14015 }
14016 
14017 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
14018 {
14019 	struct amdgpu_device *adev = drm_to_adev(dev);
14020 	struct dc *dc = adev->dm.dc;
14021 	int i;
14022 
14023 	mutex_lock(&adev->dm.dc_lock);
14024 	if (dc->current_state) {
14025 		for (i = 0; i < dc->current_state->stream_count; ++i)
14026 			dc->current_state->streams[i]
14027 				->triggered_crtc_reset.enabled =
14028 				adev->dm.force_timing_sync;
14029 
14030 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
14031 		dc_trigger_sync(dc, dc->current_state);
14032 	}
14033 	mutex_unlock(&adev->dm.dc_lock);
14034 }
14035 
14036 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
14037 {
14038 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
14039 		dc_exit_ips_for_hw_access(dc);
14040 }
14041 
14042 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
14043 		       u32 value, const char *func_name)
14044 {
14045 #ifdef DM_CHECK_ADDR_0
14046 	if (address == 0) {
14047 		drm_err(adev_to_drm(ctx->driver_context),
14048 			"invalid register write. address = 0");
14049 		return;
14050 	}
14051 #endif
14052 
14053 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
14054 	cgs_write_register(ctx->cgs_device, address, value);
14055 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
14056 }
14057 
14058 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
14059 			  const char *func_name)
14060 {
14061 	u32 value;
14062 #ifdef DM_CHECK_ADDR_0
14063 	if (address == 0) {
14064 		drm_err(adev_to_drm(ctx->driver_context),
14065 			"invalid register read; address = 0\n");
14066 		return 0;
14067 	}
14068 #endif
14069 
14070 	if (ctx->dmub_srv &&
14071 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
14072 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
14073 		ASSERT(false);
14074 		return 0;
14075 	}
14076 
14077 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
14078 
14079 	value = cgs_read_register(ctx->cgs_device, address);
14080 
14081 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
14082 
14083 	return value;
14084 }
14085 
14086 int amdgpu_dm_process_dmub_aux_transfer_sync(
14087 		struct dc_context *ctx,
14088 		unsigned int link_index,
14089 		struct aux_payload *payload,
14090 		enum aux_return_code_type *operation_result)
14091 {
14092 	struct amdgpu_device *adev = ctx->driver_context;
14093 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
14094 	int ret = -1;
14095 
14096 	mutex_lock(&adev->dm.dpia_aux_lock);
14097 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
14098 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
14099 		goto out;
14100 	}
14101 
14102 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
14103 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
14104 		*operation_result = AUX_RET_ERROR_TIMEOUT;
14105 		goto out;
14106 	}
14107 
14108 	if (p_notify->result != AUX_RET_SUCCESS) {
14109 		/*
14110 		 * Transient states before tunneling is enabled could
14111 		 * lead to this error. We can ignore this for now.
14112 		 */
14113 		if (p_notify->result == AUX_RET_ERROR_PROTOCOL_ERROR) {
14114 			drm_warn(adev_to_drm(adev), "DPIA AUX failed on 0x%x(%d), error %d\n",
14115 					payload->address, payload->length,
14116 					p_notify->result);
14117 		}
14118 		*operation_result = p_notify->result;
14119 		goto out;
14120 	}
14121 
14122 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command & 0xF;
14123 	if (adev->dm.dmub_notify->aux_reply.command & 0xF0)
14124 		/* The reply is stored in the top nibble of the command. */
14125 		payload->reply[0] = (adev->dm.dmub_notify->aux_reply.command >> 4) & 0xF;
14126 
14127 	/*write req may receive a byte indicating partially written number as well*/
14128 	if (p_notify->aux_reply.length)
14129 		memcpy(payload->data, p_notify->aux_reply.data,
14130 				p_notify->aux_reply.length);
14131 
14132 	/* success */
14133 	ret = p_notify->aux_reply.length;
14134 	*operation_result = p_notify->result;
14135 out:
14136 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
14137 	mutex_unlock(&adev->dm.dpia_aux_lock);
14138 	return ret;
14139 }
14140 
14141 static void abort_fused_io(
14142 		struct dc_context *ctx,
14143 		const struct dmub_cmd_fused_request *request
14144 )
14145 {
14146 	union dmub_rb_cmd command = { 0 };
14147 	struct dmub_rb_cmd_fused_io *io = &command.fused_io;
14148 
14149 	io->header.type = DMUB_CMD__FUSED_IO;
14150 	io->header.sub_type = DMUB_CMD__FUSED_IO_ABORT;
14151 	io->header.payload_bytes = sizeof(*io) - sizeof(io->header);
14152 	io->request = *request;
14153 	dm_execute_dmub_cmd(ctx, &command, DM_DMUB_WAIT_TYPE_NO_WAIT);
14154 }
14155 
14156 static bool execute_fused_io(
14157 		struct amdgpu_device *dev,
14158 		struct dc_context *ctx,
14159 		union dmub_rb_cmd *commands,
14160 		uint8_t count,
14161 		uint32_t timeout_us
14162 )
14163 {
14164 	const uint8_t ddc_line = commands[0].fused_io.request.u.aux.ddc_line;
14165 
14166 	if (ddc_line >= ARRAY_SIZE(dev->dm.fused_io))
14167 		return false;
14168 
14169 	struct fused_io_sync *sync = &dev->dm.fused_io[ddc_line];
14170 	struct dmub_rb_cmd_fused_io *first = &commands[0].fused_io;
14171 	const bool result = dm_execute_dmub_cmd_list(ctx, count, commands, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY)
14172 			&& first->header.ret_status
14173 			&& first->request.status == FUSED_REQUEST_STATUS_SUCCESS;
14174 
14175 	if (!result)
14176 		return false;
14177 
14178 	while (wait_for_completion_timeout(&sync->replied, usecs_to_jiffies(timeout_us))) {
14179 		reinit_completion(&sync->replied);
14180 
14181 		struct dmub_cmd_fused_request *reply = (struct dmub_cmd_fused_request *) sync->reply_data;
14182 
14183 		static_assert(sizeof(*reply) <= sizeof(sync->reply_data), "Size mismatch");
14184 
14185 		if (reply->identifier == first->request.identifier) {
14186 			first->request = *reply;
14187 			return true;
14188 		}
14189 	}
14190 
14191 	reinit_completion(&sync->replied);
14192 	first->request.status = FUSED_REQUEST_STATUS_TIMEOUT;
14193 	abort_fused_io(ctx, &first->request);
14194 	return false;
14195 }
14196 
14197 bool amdgpu_dm_execute_fused_io(
14198 		struct amdgpu_device *dev,
14199 		struct dc_link *link,
14200 		union dmub_rb_cmd *commands,
14201 		uint8_t count,
14202 		uint32_t timeout_us)
14203 {
14204 	struct amdgpu_display_manager *dm = &dev->dm;
14205 
14206 	mutex_lock(&dm->dpia_aux_lock);
14207 
14208 	const bool result = execute_fused_io(dev, link->ctx, commands, count, timeout_us);
14209 
14210 	mutex_unlock(&dm->dpia_aux_lock);
14211 	return result;
14212 }
14213 
14214 int amdgpu_dm_process_dmub_set_config_sync(
14215 		struct dc_context *ctx,
14216 		unsigned int link_index,
14217 		struct set_config_cmd_payload *payload,
14218 		enum set_config_status *operation_result)
14219 {
14220 	struct amdgpu_device *adev = ctx->driver_context;
14221 	bool is_cmd_complete;
14222 	int ret;
14223 
14224 	mutex_lock(&adev->dm.dpia_aux_lock);
14225 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
14226 			link_index, payload, adev->dm.dmub_notify);
14227 
14228 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
14229 		ret = 0;
14230 		*operation_result = adev->dm.dmub_notify->sc_status;
14231 	} else {
14232 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
14233 		ret = -1;
14234 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
14235 	}
14236 
14237 	if (!is_cmd_complete)
14238 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
14239 	mutex_unlock(&adev->dm.dpia_aux_lock);
14240 	return ret;
14241 }
14242 
14243 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
14244 {
14245 	struct amdgpu_device *adev = ctx->driver_context;
14246 
14247 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
14248 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
14249 }
14250 
14251 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)
14252 {
14253 	struct amdgpu_device *adev = ctx->driver_context;
14254 
14255 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
14256 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
14257 }
14258 
14259 void dm_acpi_process_phy_transition_interlock(
14260 	const struct dc_context *ctx,
14261 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
14262 {
14263 	// Not yet implemented
14264 }
14265