xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision 26934ed848fab9978da089b84c1e78395ef343bb)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright 2015-2026 Advanced Micro Devices, Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  * Authors: AMD
24  *
25  */
26 
27 /* The caprices of the preprocessor require that this be declared right here */
28 #define CREATE_TRACE_POINTS
29 
30 #include "dm_services_types.h"
31 #include "dc.h"
32 #include "link_enc_cfg.h"
33 #include "dc/inc/core_types.h"
34 #include "dal_asic_id.h"
35 #include "dmub/dmub_srv.h"
36 #include "dc/inc/hw/dmcu.h"
37 #include "dc/inc/hw/abm.h"
38 #include "dc/dc_dmub_srv.h"
39 #include "dc/dc_edid_parser.h"
40 #include "dc/dc_stat.h"
41 #include "dc/dc_state.h"
42 #include "amdgpu_dm_trace.h"
43 #include "link/protocols/link_dpcd.h"
44 #include "link_service_types.h"
45 #include "link/protocols/link_dp_capability.h"
46 #include "link/protocols/link_ddc.h"
47 
48 #include "amdgpu.h"
49 #include "amdgpu_display.h"
50 #include "amdgpu_ucode.h"
51 #include "atom.h"
52 #include "amdgpu_dm.h"
53 #include "amdgpu_dm_plane.h"
54 #include "amdgpu_dm_crtc.h"
55 #include "amdgpu_dm_hdcp.h"
56 #include <drm/display/drm_hdcp_helper.h>
57 #include "amdgpu_dm_wb.h"
58 #include "amdgpu_atombios.h"
59 
60 #include "amd_shared.h"
61 #include "amdgpu_dm_irq.h"
62 #include "dm_helpers.h"
63 #include "amdgpu_dm_mst_types.h"
64 #if defined(CONFIG_DEBUG_FS)
65 #include "amdgpu_dm_debugfs.h"
66 #endif
67 #include "amdgpu_dm_psr.h"
68 #include "amdgpu_dm_replay.h"
69 
70 #include "ivsrcid/ivsrcid_vislands30.h"
71 
72 #include <linux/backlight.h>
73 #include <linux/module.h>
74 #include <linux/moduleparam.h>
75 #include <linux/types.h>
76 #include <linux/pm_runtime.h>
77 #include <linux/pci.h>
78 #include <linux/power_supply.h>
79 #include <linux/firmware.h>
80 #include <linux/component.h>
81 #include <linux/sort.h>
82 
83 #include <drm/drm_privacy_screen_consumer.h>
84 #include <drm/display/drm_dp_mst_helper.h>
85 #include <drm/display/drm_hdmi_helper.h>
86 #include <drm/drm_atomic.h>
87 #include <drm/drm_atomic_uapi.h>
88 #include <drm/drm_atomic_helper.h>
89 #include <drm/drm_blend.h>
90 #include <drm/drm_fixed.h>
91 #include <drm/drm_fourcc.h>
92 #include <drm/drm_edid.h>
93 #include <drm/drm_eld.h>
94 #include <drm/drm_mode.h>
95 #include <drm/drm_utils.h>
96 #include <drm/drm_vblank.h>
97 #include <drm/drm_audio_component.h>
98 #include <drm/drm_colorop.h>
99 #include <drm/drm_gem_atomic_helper.h>
100 
101 #include <media/cec-notifier.h>
102 #include <acpi/video.h>
103 
104 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
105 
106 #include "modules/inc/mod_freesync.h"
107 #include "modules/inc/mod_power.h"
108 #include "modules/power/power_helpers.h"
109 
110 static_assert(AMDGPU_DMUB_NOTIFICATION_MAX == DMUB_NOTIFICATION_MAX, "AMDGPU_DMUB_NOTIFICATION_MAX mismatch");
111 
112 #define FIRMWARE_RENOIR_DMUB "amdgpu/renoir_dmcub.bin"
113 MODULE_FIRMWARE(FIRMWARE_RENOIR_DMUB);
114 #define FIRMWARE_SIENNA_CICHLID_DMUB "amdgpu/sienna_cichlid_dmcub.bin"
115 MODULE_FIRMWARE(FIRMWARE_SIENNA_CICHLID_DMUB);
116 #define FIRMWARE_NAVY_FLOUNDER_DMUB "amdgpu/navy_flounder_dmcub.bin"
117 MODULE_FIRMWARE(FIRMWARE_NAVY_FLOUNDER_DMUB);
118 #define FIRMWARE_GREEN_SARDINE_DMUB "amdgpu/green_sardine_dmcub.bin"
119 MODULE_FIRMWARE(FIRMWARE_GREEN_SARDINE_DMUB);
120 #define FIRMWARE_VANGOGH_DMUB "amdgpu/vangogh_dmcub.bin"
121 MODULE_FIRMWARE(FIRMWARE_VANGOGH_DMUB);
122 #define FIRMWARE_DIMGREY_CAVEFISH_DMUB "amdgpu/dimgrey_cavefish_dmcub.bin"
123 MODULE_FIRMWARE(FIRMWARE_DIMGREY_CAVEFISH_DMUB);
124 #define FIRMWARE_BEIGE_GOBY_DMUB "amdgpu/beige_goby_dmcub.bin"
125 MODULE_FIRMWARE(FIRMWARE_BEIGE_GOBY_DMUB);
126 #define FIRMWARE_YELLOW_CARP_DMUB "amdgpu/yellow_carp_dmcub.bin"
127 MODULE_FIRMWARE(FIRMWARE_YELLOW_CARP_DMUB);
128 #define FIRMWARE_DCN_314_DMUB "amdgpu/dcn_3_1_4_dmcub.bin"
129 MODULE_FIRMWARE(FIRMWARE_DCN_314_DMUB);
130 #define FIRMWARE_DCN_315_DMUB "amdgpu/dcn_3_1_5_dmcub.bin"
131 MODULE_FIRMWARE(FIRMWARE_DCN_315_DMUB);
132 #define FIRMWARE_DCN316_DMUB "amdgpu/dcn_3_1_6_dmcub.bin"
133 MODULE_FIRMWARE(FIRMWARE_DCN316_DMUB);
134 
135 #define FIRMWARE_DCN_V3_2_0_DMCUB "amdgpu/dcn_3_2_0_dmcub.bin"
136 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_0_DMCUB);
137 #define FIRMWARE_DCN_V3_2_1_DMCUB "amdgpu/dcn_3_2_1_dmcub.bin"
138 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_1_DMCUB);
139 
140 #define FIRMWARE_RAVEN_DMCU		"amdgpu/raven_dmcu.bin"
141 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
142 
143 #define FIRMWARE_NAVI12_DMCU            "amdgpu/navi12_dmcu.bin"
144 MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
145 
146 #define FIRMWARE_DCN_35_DMUB "amdgpu/dcn_3_5_dmcub.bin"
147 MODULE_FIRMWARE(FIRMWARE_DCN_35_DMUB);
148 
149 #define FIRMWARE_DCN_351_DMUB "amdgpu/dcn_3_5_1_dmcub.bin"
150 MODULE_FIRMWARE(FIRMWARE_DCN_351_DMUB);
151 
152 #define FIRMWARE_DCN_36_DMUB "amdgpu/dcn_3_6_dmcub.bin"
153 MODULE_FIRMWARE(FIRMWARE_DCN_36_DMUB);
154 
155 #define FIRMWARE_DCN_401_DMUB "amdgpu/dcn_4_0_1_dmcub.bin"
156 MODULE_FIRMWARE(FIRMWARE_DCN_401_DMUB);
157 
158 #define FIRMWARE_DCN_42_DMUB "amdgpu/dcn_4_2_dmcub.bin"
159 MODULE_FIRMWARE(FIRMWARE_DCN_42_DMUB);
160 
161 #define FIRMWARE_DCN_42B_DMUB "amdgpu/dcn_4_2_1_dmcub.bin"
162 MODULE_FIRMWARE(FIRMWARE_DCN_42B_DMUB);
163 
164 /**
165  * DOC: overview
166  *
167  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
168  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
169  * requests into DC requests, and DC responses into DRM responses.
170  *
171  * The root control structure is &struct amdgpu_display_manager.
172  */
173 
174 /* basic init/fini API */
175 static int amdgpu_dm_init(struct amdgpu_device *adev);
176 static void amdgpu_dm_fini(struct amdgpu_device *adev);
177 static bool is_freesync_video_mode(const struct drm_display_mode *mode, struct amdgpu_dm_connector *aconnector);
178 static void reset_freesync_config_for_crtc(struct dm_crtc_state *new_crtc_state);
179 static struct amdgpu_i2c_adapter *
180 create_i2c(struct ddc_service *ddc_service, bool oem);
181 
182 static enum drm_mode_subconnector get_subconnector_type(struct dc_link *link)
183 {
184 	switch (link->dpcd_caps.dongle_type) {
185 	case DISPLAY_DONGLE_NONE:
186 		return DRM_MODE_SUBCONNECTOR_Native;
187 	case DISPLAY_DONGLE_DP_VGA_CONVERTER:
188 		return DRM_MODE_SUBCONNECTOR_VGA;
189 	case DISPLAY_DONGLE_DP_DVI_CONVERTER:
190 	case DISPLAY_DONGLE_DP_DVI_DONGLE:
191 		return DRM_MODE_SUBCONNECTOR_DVID;
192 	case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
193 	case DISPLAY_DONGLE_DP_HDMI_DONGLE:
194 		return DRM_MODE_SUBCONNECTOR_HDMIA;
195 	case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
196 	default:
197 		return DRM_MODE_SUBCONNECTOR_Unknown;
198 	}
199 }
200 
201 static void update_subconnector_property(struct amdgpu_dm_connector *aconnector)
202 {
203 	struct dc_link *link = aconnector->dc_link;
204 	struct drm_connector *connector = &aconnector->base;
205 	enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
206 
207 	if (connector->connector_type != DRM_MODE_CONNECTOR_DisplayPort)
208 		return;
209 
210 	if (aconnector->dc_sink)
211 		subconnector = get_subconnector_type(link);
212 
213 	drm_object_property_set_value(&connector->base,
214 			connector->dev->mode_config.dp_subconnector_property,
215 			subconnector);
216 }
217 
218 /*
219  * initializes drm_device display related structures, based on the information
220  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
221  * drm_encoder, drm_mode_config
222  *
223  * Returns 0 on success
224  */
225 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
226 /* removes and deallocates the drm structures, created by the above function */
227 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
228 
229 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
230 				    struct amdgpu_dm_connector *amdgpu_dm_connector,
231 				    u32 link_index,
232 				    struct amdgpu_encoder *amdgpu_encoder);
233 static int amdgpu_dm_encoder_init(struct drm_device *dev,
234 				  struct amdgpu_encoder *aencoder,
235 				  uint32_t link_index);
236 
237 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
238 
239 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state);
240 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state);
241 
242 static int amdgpu_dm_atomic_check(struct drm_device *dev,
243 				  struct drm_atomic_commit *state);
244 
245 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector);
246 static void handle_hpd_rx_irq(void *param);
247 
248 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
249 					 int bl_idx,
250 					 u32 user_brightness);
251 
252 static bool
253 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
254 				 struct drm_crtc_state *new_crtc_state);
255 /*
256  * dm_vblank_get_counter
257  *
258  * @brief
259  * Get counter for number of vertical blanks
260  *
261  * @param
262  * struct amdgpu_device *adev - [in] desired amdgpu device
263  * int disp_idx - [in] which CRTC to get the counter from
264  *
265  * @return
266  * Counter for vertical blanks
267  */
268 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
269 {
270 	struct amdgpu_crtc *acrtc = NULL;
271 
272 	if (crtc >= adev->mode_info.num_crtc)
273 		return 0;
274 
275 	acrtc = adev->mode_info.crtcs[crtc];
276 
277 	if (!acrtc->dm_irq_params.stream) {
278 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
279 			  crtc);
280 		return 0;
281 	}
282 
283 	return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
284 }
285 
286 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
287 				  u32 *vbl, u32 *position)
288 {
289 	u32 v_blank_start = 0, v_blank_end = 0, h_position = 0, v_position = 0;
290 	struct amdgpu_crtc *acrtc = NULL;
291 	struct dc *dc = adev->dm.dc;
292 
293 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
294 		return -EINVAL;
295 
296 	acrtc = adev->mode_info.crtcs[crtc];
297 
298 	if (!acrtc->dm_irq_params.stream) {
299 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
300 			  crtc);
301 		return 0;
302 	}
303 
304 	if (dc && dc->caps.ips_support && dc->idle_optimizations_allowed)
305 		dc_allow_idle_optimizations(dc, false);
306 
307 	/*
308 	 * TODO rework base driver to use values directly.
309 	 * for now parse it back into reg-format
310 	 */
311 	dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
312 				 &v_blank_start,
313 				 &v_blank_end,
314 				 &h_position,
315 				 &v_position);
316 
317 	*position = v_position | (h_position << 16);
318 	*vbl = v_blank_start | (v_blank_end << 16);
319 
320 	return 0;
321 }
322 
323 static bool dm_is_idle(struct amdgpu_ip_block *ip_block)
324 {
325 	/* XXX todo */
326 	return true;
327 }
328 
329 static int dm_wait_for_idle(struct amdgpu_ip_block *ip_block)
330 {
331 	/* XXX todo */
332 	return 0;
333 }
334 
335 static bool dm_check_soft_reset(struct amdgpu_ip_block *ip_block)
336 {
337 	return false;
338 }
339 
340 static int dm_soft_reset(struct amdgpu_ip_block *ip_block)
341 {
342 	/* XXX todo */
343 	return 0;
344 }
345 
346 static struct amdgpu_crtc *
347 get_crtc_by_otg_inst(struct amdgpu_device *adev,
348 		     int otg_inst)
349 {
350 	struct drm_device *dev = adev_to_drm(adev);
351 	struct drm_crtc *crtc;
352 	struct amdgpu_crtc *amdgpu_crtc;
353 
354 	if (WARN_ON(otg_inst == -1))
355 		return adev->mode_info.crtcs[0];
356 
357 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
358 		amdgpu_crtc = to_amdgpu_crtc(crtc);
359 
360 		if (amdgpu_crtc->otg_inst == otg_inst)
361 			return amdgpu_crtc;
362 	}
363 
364 	return NULL;
365 }
366 
367 static inline bool is_dc_timing_adjust_needed(struct dm_crtc_state *old_state,
368 					      struct dm_crtc_state *new_state)
369 {
370 	if (new_state->stream->adjust.timing_adjust_pending)
371 		return true;
372 	if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
373 		return true;
374 	else if (amdgpu_dm_crtc_vrr_active(old_state) != amdgpu_dm_crtc_vrr_active(new_state))
375 		return true;
376 	else
377 		return false;
378 }
379 
380 /*
381  * DC will program planes with their z-order determined by their ordering
382  * in the dc_surface_updates array. This comparator is used to sort them
383  * by descending zpos.
384  */
385 static int dm_plane_layer_index_cmp(const void *a, const void *b)
386 {
387 	const struct dc_surface_update *sa = (struct dc_surface_update *)a;
388 	const struct dc_surface_update *sb = (struct dc_surface_update *)b;
389 
390 	/* Sort by descending dc_plane layer_index (i.e. normalized_zpos) */
391 	return sb->surface->layer_index - sa->surface->layer_index;
392 }
393 
394 /**
395  * update_planes_and_stream_adapter() - Send planes to be updated in DC
396  *
397  * DC has a generic way to update planes and stream via
398  * dc_update_planes_and_stream function; however, DM might need some
399  * adjustments and preparation before calling it. This function is a wrapper
400  * for the dc_update_planes_and_stream that does any required configuration
401  * before passing control to DC.
402  *
403  * @dc: Display Core control structure
404  * @update_type: specify whether it is FULL/MEDIUM/FAST update
405  * @planes_count: planes count to update
406  * @stream: stream state
407  * @stream_update: stream update
408  * @array_of_surface_update: dc surface update pointer
409  *
410  */
411 static inline bool update_planes_and_stream_adapter(struct dc *dc,
412 						    int update_type,
413 						    int planes_count,
414 						    struct dc_stream_state *stream,
415 						    struct dc_stream_update *stream_update,
416 						    struct dc_surface_update *array_of_surface_update)
417 {
418 	sort(array_of_surface_update, planes_count,
419 	     sizeof(*array_of_surface_update), dm_plane_layer_index_cmp, NULL);
420 
421 	/*
422 	 * Previous frame finished and HW is ready for optimization.
423 	 */
424 	dc_post_update_surfaces_to_stream(dc);
425 
426 	return dc_update_planes_and_stream(dc,
427 					   array_of_surface_update,
428 					   planes_count,
429 					   stream,
430 					   stream_update);
431 }
432 
433 /**
434  * dm_pflip_high_irq() - Handle pageflip interrupt
435  * @interrupt_params: ignored
436  *
437  * Handles the pageflip interrupt by notifying all interested parties
438  * that the pageflip has been completed.
439  */
440 static void dm_pflip_high_irq(void *interrupt_params)
441 {
442 	struct amdgpu_crtc *amdgpu_crtc;
443 	struct common_irq_params *irq_params = interrupt_params;
444 	struct amdgpu_device *adev = irq_params->adev;
445 	struct drm_device *dev = adev_to_drm(adev);
446 	unsigned long flags;
447 	struct drm_pending_vblank_event *e;
448 	u32 vpos, hpos, v_blank_start, v_blank_end;
449 	bool vrr_active;
450 
451 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
452 
453 	/* IRQ could occur when in initial stage */
454 	/* TODO work and BO cleanup */
455 	if (amdgpu_crtc == NULL) {
456 		drm_dbg_state(dev, "CRTC is null, returning.\n");
457 		return;
458 	}
459 
460 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
461 
462 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED) {
463 		drm_dbg_state(dev,
464 			      "amdgpu_crtc->pflip_status = %d != AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p]\n",
465 			      amdgpu_crtc->pflip_status, AMDGPU_FLIP_SUBMITTED,
466 			      amdgpu_crtc->crtc_id, amdgpu_crtc);
467 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
468 		return;
469 	}
470 
471 	/* page flip completed. */
472 	e = amdgpu_crtc->event;
473 	amdgpu_crtc->event = NULL;
474 
475 	WARN_ON(!e);
476 
477 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(amdgpu_crtc);
478 
479 	/* Fixed refresh rate, or VRR scanout position outside front-porch? */
480 	if (!vrr_active ||
481 	    !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
482 				      &v_blank_end, &hpos, &vpos) ||
483 	    (vpos < v_blank_start)) {
484 		/* Update to correct count and vblank timestamp if racing with
485 		 * vblank irq. This also updates to the correct vblank timestamp
486 		 * even in VRR mode, as scanout is past the front-porch atm.
487 		 */
488 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
489 
490 		/* Wake up userspace by sending the pageflip event with proper
491 		 * count and timestamp of vblank of flip completion.
492 		 */
493 		if (e) {
494 			drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
495 
496 			/* Event sent, so done with vblank for this flip */
497 			drm_crtc_vblank_put(&amdgpu_crtc->base);
498 		}
499 	} else if (e) {
500 		/* VRR active and inside front-porch: vblank count and
501 		 * timestamp for pageflip event will only be up to date after
502 		 * drm_crtc_handle_vblank() has been executed from late vblank
503 		 * irq handler after start of back-porch (vline 0). We queue the
504 		 * pageflip event for send-out by drm_crtc_handle_vblank() with
505 		 * updated timestamp and count, once it runs after us.
506 		 *
507 		 * We need to open-code this instead of using the helper
508 		 * drm_crtc_arm_vblank_event(), as that helper would
509 		 * call drm_crtc_accurate_vblank_count(), which we must
510 		 * not call in VRR mode while we are in front-porch!
511 		 */
512 
513 		/* sequence will be replaced by real count during send-out. */
514 		e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
515 		e->pipe = amdgpu_crtc->crtc_id;
516 
517 		list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
518 		e = NULL;
519 	}
520 
521 	/* Keep track of vblank of this flip for flip throttling. We use the
522 	 * cooked hw counter, as that one incremented at start of this vblank
523 	 * of pageflip completion, so last_flip_vblank is the forbidden count
524 	 * for queueing new pageflips if vsync + VRR is enabled.
525 	 */
526 	amdgpu_crtc->dm_irq_params.last_flip_vblank =
527 		amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
528 
529 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
530 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
531 
532 	drm_dbg_state(dev,
533 		      "crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
534 		      amdgpu_crtc->crtc_id, amdgpu_crtc, vrr_active, (int)!e);
535 }
536 
537 static void dm_handle_vmin_vmax_update(struct work_struct *offload_work)
538 {
539 	struct vupdate_offload_work *work = container_of(offload_work, struct vupdate_offload_work, work);
540 	struct amdgpu_device *adev = work->adev;
541 	struct dc_stream_state *stream = work->stream;
542 	struct dc_crtc_timing_adjust *adjust = work->adjust;
543 
544 	mutex_lock(&adev->dm.dc_lock);
545 	dc_stream_adjust_vmin_vmax(adev->dm.dc, stream, adjust);
546 	mutex_unlock(&adev->dm.dc_lock);
547 
548 	dc_stream_release(stream);
549 	kfree(work->adjust);
550 	kfree(work);
551 }
552 
553 static void schedule_dc_vmin_vmax(struct amdgpu_device *adev,
554 	struct dc_stream_state *stream,
555 	struct dc_crtc_timing_adjust *adjust)
556 {
557 	struct vupdate_offload_work *offload_work = kzalloc_obj(*offload_work,
558 								GFP_NOWAIT);
559 	if (!offload_work) {
560 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate vupdate_offload_work\n");
561 		return;
562 	}
563 
564 	struct dc_crtc_timing_adjust *adjust_copy = kzalloc_obj(*adjust_copy,
565 								GFP_NOWAIT);
566 	if (!adjust_copy) {
567 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate adjust_copy\n");
568 		kfree(offload_work);
569 		return;
570 	}
571 
572 	dc_stream_retain(stream);
573 	memcpy(adjust_copy, adjust, sizeof(*adjust_copy));
574 
575 	INIT_WORK(&offload_work->work, dm_handle_vmin_vmax_update);
576 	offload_work->adev = adev;
577 	offload_work->stream = stream;
578 	offload_work->adjust = adjust_copy;
579 
580 	queue_work(system_percpu_wq, &offload_work->work);
581 }
582 
583 static void dm_vupdate_high_irq(void *interrupt_params)
584 {
585 	struct common_irq_params *irq_params = interrupt_params;
586 	struct amdgpu_device *adev = irq_params->adev;
587 	struct amdgpu_crtc *acrtc;
588 	struct drm_device *drm_dev;
589 	struct drm_vblank_crtc *vblank;
590 	ktime_t frame_duration_ns, previous_timestamp;
591 	unsigned long flags;
592 	int vrr_active;
593 
594 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
595 
596 	if (acrtc) {
597 		vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
598 		drm_dev = acrtc->base.dev;
599 		vblank = drm_crtc_vblank_crtc(&acrtc->base);
600 		previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
601 		frame_duration_ns = vblank->time - previous_timestamp;
602 
603 		if (frame_duration_ns > 0) {
604 			trace_amdgpu_refresh_rate_track(acrtc->base.index,
605 						frame_duration_ns,
606 						ktime_divns(NSEC_PER_SEC, frame_duration_ns));
607 			atomic64_set(&irq_params->previous_timestamp, vblank->time);
608 		}
609 
610 		drm_dbg_vbl(drm_dev,
611 			    "crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
612 			    vrr_active);
613 
614 		/* Core vblank handling is done here after end of front-porch in
615 		 * vrr mode, as vblank timestamping will give valid results
616 		 * while now done after front-porch. This will also deliver
617 		 * page-flip completion events that have been queued to us
618 		 * if a pageflip happened inside front-porch.
619 		 */
620 		if (vrr_active && acrtc->dm_irq_params.stream) {
621 			bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
622 			bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
623 			bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state
624 				== VRR_STATE_ACTIVE_VARIABLE;
625 
626 			amdgpu_dm_crtc_handle_vblank(acrtc);
627 
628 			/* BTR processing for pre-DCE12 ASICs */
629 			if (adev->family < AMDGPU_FAMILY_AI) {
630 				spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
631 				mod_freesync_handle_v_update(
632 				    adev->dm.freesync_module,
633 				    acrtc->dm_irq_params.stream,
634 				    &acrtc->dm_irq_params.vrr_params);
635 
636 				if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
637 					schedule_dc_vmin_vmax(adev,
638 						acrtc->dm_irq_params.stream,
639 						&acrtc->dm_irq_params.vrr_params.adjust);
640 				}
641 				spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
642 			}
643 		}
644 	}
645 }
646 
647 /**
648  * dm_crtc_high_irq() - Handles CRTC interrupt
649  * @interrupt_params: used for determining the CRTC instance
650  *
651  * Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
652  * event handler.
653  */
654 static void dm_crtc_high_irq(void *interrupt_params)
655 {
656 	struct common_irq_params *irq_params = interrupt_params;
657 	struct amdgpu_device *adev = irq_params->adev;
658 	struct drm_writeback_job *job;
659 	struct amdgpu_crtc *acrtc;
660 	unsigned long flags;
661 	int vrr_active;
662 
663 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
664 	if (!acrtc)
665 		return;
666 
667 	if (acrtc->wb_conn) {
668 		spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
669 
670 		if (acrtc->wb_pending) {
671 			job = list_first_entry_or_null(&acrtc->wb_conn->job_queue,
672 						       struct drm_writeback_job,
673 						       list_entry);
674 			acrtc->wb_pending = false;
675 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
676 
677 			if (job) {
678 				unsigned int v_total, refresh_hz;
679 				struct dc_stream_state *stream = acrtc->dm_irq_params.stream;
680 
681 				v_total = stream->adjust.v_total_max ?
682 					  stream->adjust.v_total_max : stream->timing.v_total;
683 				refresh_hz = div_u64((uint64_t) stream->timing.pix_clk_100hz *
684 					     100LL, (v_total * stream->timing.h_total));
685 				mdelay(1000 / refresh_hz);
686 
687 				drm_writeback_signal_completion(acrtc->wb_conn, 0);
688 				dc_stream_fc_disable_writeback(adev->dm.dc,
689 							       acrtc->dm_irq_params.stream, 0);
690 			}
691 		} else
692 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
693 	}
694 
695 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
696 
697 	drm_dbg_vbl(adev_to_drm(adev),
698 		    "crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
699 		    vrr_active, acrtc->dm_irq_params.active_planes);
700 
701 	/**
702 	 * Core vblank handling at start of front-porch is only possible
703 	 * in non-vrr mode, as only there vblank timestamping will give
704 	 * valid results while done in front-porch. Otherwise defer it
705 	 * to dm_vupdate_high_irq after end of front-porch.
706 	 */
707 	if (!vrr_active)
708 		amdgpu_dm_crtc_handle_vblank(acrtc);
709 
710 	/**
711 	 * Following stuff must happen at start of vblank, for crc
712 	 * computation and below-the-range btr support in vrr mode.
713 	 */
714 	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
715 
716 	/* BTR updates need to happen before VUPDATE on Vega and above. */
717 	if (adev->family < AMDGPU_FAMILY_AI)
718 		return;
719 
720 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
721 
722 	if (acrtc->dm_irq_params.stream &&
723 		acrtc->dm_irq_params.vrr_params.supported) {
724 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
725 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
726 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state == VRR_STATE_ACTIVE_VARIABLE;
727 
728 		mod_freesync_handle_v_update(adev->dm.freesync_module,
729 					     acrtc->dm_irq_params.stream,
730 					     &acrtc->dm_irq_params.vrr_params);
731 
732 		/* update vmin_vmax only if freesync is enabled, or only if PSR and REPLAY are disabled */
733 		if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
734 			schedule_dc_vmin_vmax(adev, acrtc->dm_irq_params.stream,
735 					&acrtc->dm_irq_params.vrr_params.adjust);
736 		}
737 	}
738 
739 	/*
740 	 * If there aren't any active_planes then DCH HUBP may be clock-gated.
741 	 * In that case, pageflip completion interrupts won't fire and pageflip
742 	 * completion events won't get delivered. Prevent this by sending
743 	 * pending pageflip events from here if a flip is still pending.
744 	 *
745 	 * If any planes are enabled, use dm_pflip_high_irq() instead, to
746 	 * avoid race conditions between flip programming and completion,
747 	 * which could cause too early flip completion events.
748 	 */
749 	if (adev->family >= AMDGPU_FAMILY_RV &&
750 	    acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
751 	    acrtc->dm_irq_params.active_planes == 0) {
752 		if (acrtc->event) {
753 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
754 			acrtc->event = NULL;
755 			drm_crtc_vblank_put(&acrtc->base);
756 		}
757 		acrtc->pflip_status = AMDGPU_FLIP_NONE;
758 	}
759 
760 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
761 }
762 
763 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
764 /**
765  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
766  * DCN generation ASICs
767  * @interrupt_params: interrupt parameters
768  *
769  * Used to set crc window/read out crc value at vertical line 0 position
770  */
771 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
772 {
773 	struct common_irq_params *irq_params = interrupt_params;
774 	struct amdgpu_device *adev = irq_params->adev;
775 	struct amdgpu_crtc *acrtc;
776 
777 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
778 
779 	if (!acrtc)
780 		return;
781 
782 	amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
783 }
784 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
785 
786 /**
787  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
788  * @adev: amdgpu_device pointer
789  * @notify: dmub notification structure
790  *
791  * Dmub AUX or SET_CONFIG command completion processing callback
792  * Copies dmub notification to DM which is to be read by AUX command.
793  * issuing thread and also signals the event to wake up the thread.
794  */
795 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
796 					struct dmub_notification *notify)
797 {
798 	if (adev->dm.dmub_notify)
799 		memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
800 	if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
801 		complete(&adev->dm.dmub_aux_transfer_done);
802 }
803 
804 static void dmub_aux_fused_io_callback(struct amdgpu_device *adev,
805 					struct dmub_notification *notify)
806 {
807 	if (!adev || !notify) {
808 		ASSERT(false);
809 		return;
810 	}
811 
812 	const struct dmub_cmd_fused_request *req = &notify->fused_request;
813 	const uint8_t ddc_line = req->u.aux.ddc_line;
814 
815 	if (ddc_line >= ARRAY_SIZE(adev->dm.fused_io)) {
816 		ASSERT(false);
817 		return;
818 	}
819 
820 	struct fused_io_sync *sync = &adev->dm.fused_io[ddc_line];
821 
822 	static_assert(sizeof(*req) <= sizeof(sync->reply_data), "Size mismatch");
823 	memcpy(sync->reply_data, req, sizeof(*req));
824 	complete(&sync->replied);
825 }
826 
827 /**
828  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
829  * @adev: amdgpu_device pointer
830  * @notify: dmub notification structure
831  *
832  * Dmub Hpd interrupt processing callback. Gets displayindex through the
833  * ink index and calls helper to do the processing.
834  */
835 static void dmub_hpd_callback(struct amdgpu_device *adev,
836 			      struct dmub_notification *notify)
837 {
838 	struct amdgpu_dm_connector *aconnector;
839 	struct amdgpu_dm_connector *hpd_aconnector = NULL;
840 	struct drm_connector *connector;
841 	struct drm_connector_list_iter iter;
842 	struct dc_link *link;
843 	u8 link_index = 0;
844 	struct drm_device *dev;
845 
846 	if (adev == NULL)
847 		return;
848 
849 	if (notify == NULL) {
850 		drm_err(adev_to_drm(adev), "DMUB HPD callback notification was NULL");
851 		return;
852 	}
853 
854 	if (notify->link_index > adev->dm.dc->link_count) {
855 		drm_err(adev_to_drm(adev), "DMUB HPD index (%u)is abnormal", notify->link_index);
856 		return;
857 	}
858 
859 	/* Skip DMUB HPD IRQ in suspend/resume. We will probe them later. */
860 	if (notify->type == DMUB_NOTIFICATION_HPD && adev->in_suspend) {
861 		drm_info(adev_to_drm(adev), "Skip DMUB HPD IRQ callback in suspend/resume\n");
862 		return;
863 	}
864 
865 	link_index = notify->link_index;
866 	link = adev->dm.dc->links[link_index];
867 	dev = adev->dm.ddev;
868 
869 	drm_connector_list_iter_begin(dev, &iter);
870 	drm_for_each_connector_iter(connector, &iter) {
871 
872 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
873 			continue;
874 
875 		aconnector = to_amdgpu_dm_connector(connector);
876 		if (link && aconnector->dc_link == link) {
877 			if (notify->type == DMUB_NOTIFICATION_HPD)
878 				drm_info(adev_to_drm(adev), "DMUB HPD IRQ callback: link_index=%u\n", link_index);
879 			else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
880 				drm_info(adev_to_drm(adev), "DMUB HPD RX IRQ callback: link_index=%u\n", link_index);
881 			else
882 				drm_warn(adev_to_drm(adev), "DMUB Unknown HPD callback type %d, link_index=%u\n",
883 						notify->type, link_index);
884 
885 			hpd_aconnector = aconnector;
886 			break;
887 		}
888 	}
889 	drm_connector_list_iter_end(&iter);
890 
891 	if (hpd_aconnector) {
892 		if (notify->type == DMUB_NOTIFICATION_HPD) {
893 			if (hpd_aconnector->dc_link->hpd_status == (notify->hpd_status == DP_HPD_PLUG))
894 				drm_warn(adev_to_drm(adev), "DMUB reported hpd status unchanged. link_index=%u\n", link_index);
895 			handle_hpd_irq_helper(hpd_aconnector);
896 		} else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ) {
897 			handle_hpd_rx_irq(hpd_aconnector);
898 		}
899 	}
900 }
901 
902 /**
903  * dmub_hpd_sense_callback - DMUB HPD sense processing callback.
904  * @adev: amdgpu_device pointer
905  * @notify: dmub notification structure
906  *
907  * HPD sense changes can occur during low power states and need to be
908  * notified from firmware to driver.
909  */
910 static void dmub_hpd_sense_callback(struct amdgpu_device *adev,
911 			      struct dmub_notification *notify)
912 {
913 	drm_dbg_driver(adev_to_drm(adev), "DMUB HPD SENSE callback.\n");
914 }
915 
916 /**
917  * register_dmub_notify_callback - Sets callback for DMUB notify
918  * @adev: amdgpu_device pointer
919  * @type: Type of dmub notification
920  * @callback: Dmub interrupt callback function
921  * @dmub_int_thread_offload: offload indicator
922  *
923  * API to register a dmub callback handler for a dmub notification
924  * Also sets indicator whether callback processing to be offloaded.
925  * to dmub interrupt handling thread
926  * Return: true if successfully registered, false if there is existing registration
927  */
928 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
929 					  enum dmub_notification_type type,
930 					  dmub_notify_interrupt_callback_t callback,
931 					  bool dmub_int_thread_offload)
932 {
933 	if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
934 		adev->dm.dmub_callback[type] = callback;
935 		adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
936 	} else
937 		return false;
938 
939 	return true;
940 }
941 
942 static void dm_handle_hpd_work(struct work_struct *work)
943 {
944 	struct dmub_hpd_work *dmub_hpd_wrk;
945 
946 	dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
947 
948 	if (!dmub_hpd_wrk->dmub_notify) {
949 		drm_err(adev_to_drm(dmub_hpd_wrk->adev), "dmub_hpd_wrk dmub_notify is NULL");
950 		return;
951 	}
952 
953 	if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
954 		dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
955 		dmub_hpd_wrk->dmub_notify);
956 	}
957 
958 	kfree(dmub_hpd_wrk->dmub_notify);
959 	kfree(dmub_hpd_wrk);
960 
961 }
962 
963 static const char *dmub_notification_type_str(enum dmub_notification_type e)
964 {
965 	switch (e) {
966 	case DMUB_NOTIFICATION_NO_DATA:
967 		return "NO_DATA";
968 	case DMUB_NOTIFICATION_AUX_REPLY:
969 		return "AUX_REPLY";
970 	case DMUB_NOTIFICATION_HPD:
971 		return "HPD";
972 	case DMUB_NOTIFICATION_HPD_IRQ:
973 		return "HPD_IRQ";
974 	case DMUB_NOTIFICATION_SET_CONFIG_REPLY:
975 		return "SET_CONFIG_REPLY";
976 	case DMUB_NOTIFICATION_DPIA_NOTIFICATION:
977 		return "DPIA_NOTIFICATION";
978 	case DMUB_NOTIFICATION_HPD_SENSE_NOTIFY:
979 		return "HPD_SENSE_NOTIFY";
980 	case DMUB_NOTIFICATION_FUSED_IO:
981 		return "FUSED_IO";
982 	default:
983 		return "<unknown>";
984 	}
985 }
986 
987 #define DMUB_TRACE_MAX_READ 64
988 /**
989  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
990  * @interrupt_params: used for determining the Outbox instance
991  *
992  * Handles the Outbox Interrupt
993  * event handler.
994  */
995 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
996 {
997 	struct dmub_notification notify = {0};
998 	struct common_irq_params *irq_params = interrupt_params;
999 	struct amdgpu_device *adev = irq_params->adev;
1000 	struct amdgpu_display_manager *dm = &adev->dm;
1001 	struct dmcub_trace_buf_entry entry = { 0 };
1002 	u32 count = 0;
1003 	struct dmub_hpd_work *dmub_hpd_wrk;
1004 
1005 	do {
1006 		if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
1007 			trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
1008 							entry.param0, entry.param1);
1009 
1010 			drm_dbg_driver(adev_to_drm(adev), "trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
1011 				 entry.trace_code, entry.tick_count, entry.param0, entry.param1);
1012 		} else
1013 			break;
1014 
1015 		count++;
1016 
1017 	} while (count <= DMUB_TRACE_MAX_READ);
1018 
1019 	if (count > DMUB_TRACE_MAX_READ)
1020 		drm_dbg_driver(adev_to_drm(adev), "Warning : count > DMUB_TRACE_MAX_READ");
1021 
1022 	if (dc_enable_dmub_notifications(adev->dm.dc) &&
1023 		irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
1024 
1025 		do {
1026 			dc_stat_get_dmub_notification(adev->dm.dc, &notify);
1027 			if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
1028 				drm_err(adev_to_drm(adev), "DM: notify type %d invalid!", notify.type);
1029 				continue;
1030 			}
1031 			if (!dm->dmub_callback[notify.type]) {
1032 				drm_warn(adev_to_drm(adev), "DMUB notification skipped due to no handler: type=%s\n",
1033 					dmub_notification_type_str(notify.type));
1034 				continue;
1035 			}
1036 			if (dm->dmub_thread_offload[notify.type] == true) {
1037 				dmub_hpd_wrk = kzalloc_obj(*dmub_hpd_wrk,
1038 							   GFP_ATOMIC);
1039 				if (!dmub_hpd_wrk) {
1040 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk");
1041 					return;
1042 				}
1043 				dmub_hpd_wrk->dmub_notify = kmemdup(&notify, sizeof(struct dmub_notification),
1044 								    GFP_ATOMIC);
1045 				if (!dmub_hpd_wrk->dmub_notify) {
1046 					kfree(dmub_hpd_wrk);
1047 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk->dmub_notify");
1048 					return;
1049 				}
1050 				INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
1051 				dmub_hpd_wrk->adev = adev;
1052 				queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
1053 			} else {
1054 				dm->dmub_callback[notify.type](adev, &notify);
1055 			}
1056 		} while (notify.pending_notification);
1057 	}
1058 }
1059 
1060 static int dm_set_clockgating_state(struct amdgpu_ip_block *ip_block,
1061 		  enum amd_clockgating_state state)
1062 {
1063 	return 0;
1064 }
1065 
1066 static int dm_set_powergating_state(struct amdgpu_ip_block *ip_block,
1067 		  enum amd_powergating_state state)
1068 {
1069 	return 0;
1070 }
1071 
1072 /* Prototypes of private functions */
1073 static int dm_early_init(struct amdgpu_ip_block *ip_block);
1074 
1075 /* Allocate memory for FBC compressed data  */
1076 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
1077 {
1078 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
1079 	struct dm_compressor_info *compressor = &adev->dm.compressor;
1080 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
1081 	struct drm_display_mode *mode;
1082 	unsigned long max_size = 0;
1083 
1084 	if (adev->dm.dc->fbc_compressor == NULL)
1085 		return;
1086 
1087 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
1088 		return;
1089 
1090 	if (compressor->bo_ptr)
1091 		return;
1092 
1093 
1094 	list_for_each_entry(mode, &connector->modes, head) {
1095 		if (max_size < (unsigned long) mode->htotal * mode->vtotal)
1096 			max_size = (unsigned long) mode->htotal * mode->vtotal;
1097 	}
1098 
1099 	if (max_size) {
1100 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
1101 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
1102 			    &compressor->gpu_addr, &compressor->cpu_addr);
1103 
1104 		if (r)
1105 			drm_err(adev_to_drm(adev), "DM: Failed to initialize FBC\n");
1106 		else {
1107 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
1108 			drm_info(adev_to_drm(adev), "DM: FBC alloc %lu\n", max_size*4);
1109 		}
1110 
1111 	}
1112 
1113 }
1114 
1115 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
1116 					  int pipe, bool *enabled,
1117 					  unsigned char *buf, int max_bytes)
1118 {
1119 	struct drm_device *dev = dev_get_drvdata(kdev);
1120 	struct amdgpu_device *adev = drm_to_adev(dev);
1121 	struct drm_connector *connector;
1122 	struct drm_connector_list_iter conn_iter;
1123 	struct amdgpu_dm_connector *aconnector;
1124 	int ret = 0;
1125 
1126 	*enabled = false;
1127 
1128 	mutex_lock(&adev->dm.audio_lock);
1129 
1130 	drm_connector_list_iter_begin(dev, &conn_iter);
1131 	drm_for_each_connector_iter(connector, &conn_iter) {
1132 
1133 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1134 			continue;
1135 
1136 		aconnector = to_amdgpu_dm_connector(connector);
1137 		if (aconnector->audio_inst != port)
1138 			continue;
1139 
1140 		*enabled = true;
1141 		mutex_lock(&connector->eld_mutex);
1142 		ret = drm_eld_size(connector->eld);
1143 		memcpy(buf, connector->eld, min(max_bytes, ret));
1144 		mutex_unlock(&connector->eld_mutex);
1145 
1146 		break;
1147 	}
1148 	drm_connector_list_iter_end(&conn_iter);
1149 
1150 	mutex_unlock(&adev->dm.audio_lock);
1151 
1152 	drm_dbg_kms(adev_to_drm(adev), "Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
1153 
1154 	return ret;
1155 }
1156 
1157 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
1158 	.get_eld = amdgpu_dm_audio_component_get_eld,
1159 };
1160 
1161 static int amdgpu_dm_audio_component_bind(struct device *kdev,
1162 				       struct device *hda_kdev, void *data)
1163 {
1164 	struct drm_device *dev = dev_get_drvdata(kdev);
1165 	struct amdgpu_device *adev = drm_to_adev(dev);
1166 	struct drm_audio_component *acomp = data;
1167 
1168 	acomp->ops = &amdgpu_dm_audio_component_ops;
1169 	acomp->dev = kdev;
1170 	adev->dm.audio_component = acomp;
1171 
1172 	return 0;
1173 }
1174 
1175 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
1176 					  struct device *hda_kdev, void *data)
1177 {
1178 	struct amdgpu_device *adev = drm_to_adev(dev_get_drvdata(kdev));
1179 	struct drm_audio_component *acomp = data;
1180 
1181 	acomp->ops = NULL;
1182 	acomp->dev = NULL;
1183 	adev->dm.audio_component = NULL;
1184 }
1185 
1186 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
1187 	.bind	= amdgpu_dm_audio_component_bind,
1188 	.unbind	= amdgpu_dm_audio_component_unbind,
1189 };
1190 
1191 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
1192 {
1193 	int i, ret;
1194 
1195 	if (!amdgpu_audio)
1196 		return 0;
1197 
1198 	adev->mode_info.audio.enabled = true;
1199 
1200 	adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
1201 
1202 	for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
1203 		adev->mode_info.audio.pin[i].channels = -1;
1204 		adev->mode_info.audio.pin[i].rate = -1;
1205 		adev->mode_info.audio.pin[i].bits_per_sample = -1;
1206 		adev->mode_info.audio.pin[i].status_bits = 0;
1207 		adev->mode_info.audio.pin[i].category_code = 0;
1208 		adev->mode_info.audio.pin[i].connected = false;
1209 		adev->mode_info.audio.pin[i].id =
1210 			adev->dm.dc->res_pool->audios[i]->inst;
1211 		adev->mode_info.audio.pin[i].offset = 0;
1212 	}
1213 
1214 	ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1215 	if (ret < 0)
1216 		return ret;
1217 
1218 	adev->dm.audio_registered = true;
1219 
1220 	return 0;
1221 }
1222 
1223 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
1224 {
1225 	if (!amdgpu_audio)
1226 		return;
1227 
1228 	if (!adev->mode_info.audio.enabled)
1229 		return;
1230 
1231 	if (adev->dm.audio_registered) {
1232 		component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1233 		adev->dm.audio_registered = false;
1234 	}
1235 
1236 	/* TODO: Disable audio? */
1237 
1238 	adev->mode_info.audio.enabled = false;
1239 }
1240 
1241 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
1242 {
1243 	struct drm_audio_component *acomp = adev->dm.audio_component;
1244 
1245 	if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
1246 		drm_dbg_kms(adev_to_drm(adev), "Notify ELD: %d\n", pin);
1247 
1248 		acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1249 						 pin, -1);
1250 	}
1251 }
1252 
1253 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1254 {
1255 	const struct dmcub_firmware_header_v1_0 *hdr;
1256 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1257 	struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1258 	const struct firmware *dmub_fw = adev->dm.dmub_fw;
1259 	struct dc *dc = adev->dm.dc;
1260 	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1261 	struct abm *abm = adev->dm.dc->res_pool->abm;
1262 	struct dc_context *ctx = adev->dm.dc->ctx;
1263 	struct dmub_srv_hw_params hw_params;
1264 	enum dmub_status status;
1265 	const unsigned char *fw_inst_const, *fw_bss_data;
1266 	u32 i, fw_inst_const_size, fw_bss_data_size;
1267 	bool has_hw_support;
1268 
1269 	if (!dmub_srv)
1270 		/* DMUB isn't supported on the ASIC. */
1271 		return 0;
1272 
1273 	if (!fb_info) {
1274 		drm_err(adev_to_drm(adev), "No framebuffer info for DMUB service.\n");
1275 		return -EINVAL;
1276 	}
1277 
1278 	if (!dmub_fw) {
1279 		/* Firmware required for DMUB support. */
1280 		drm_err(adev_to_drm(adev), "No firmware provided for DMUB.\n");
1281 		return -EINVAL;
1282 	}
1283 
1284 	/* initialize register offsets for ASICs with runtime initialization available */
1285 	if (dmub_srv->hw_funcs.init_reg_offsets)
1286 		dmub_srv->hw_funcs.init_reg_offsets(dmub_srv, ctx);
1287 
1288 	status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1289 	if (status != DMUB_STATUS_OK) {
1290 		drm_err(adev_to_drm(adev), "Error checking HW support for DMUB: %d\n", status);
1291 		return -EINVAL;
1292 	}
1293 
1294 	if (!has_hw_support) {
1295 		drm_info(adev_to_drm(adev), "DMUB unsupported on ASIC\n");
1296 		return 0;
1297 	}
1298 
1299 	/* Reset DMCUB if it was previously running - before we overwrite its memory. */
1300 	status = dmub_srv_hw_reset(dmub_srv);
1301 	if (status != DMUB_STATUS_OK)
1302 		drm_warn(adev_to_drm(adev), "Error resetting DMUB HW: %d\n", status);
1303 
1304 	hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1305 
1306 	fw_inst_const = dmub_fw->data +
1307 			le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1308 			PSP_HEADER_BYTES_256;
1309 
1310 	fw_bss_data = dmub_fw->data +
1311 		      le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1312 		      le32_to_cpu(hdr->inst_const_bytes);
1313 
1314 	/* Copy firmware and bios info into FB memory. */
1315 	fw_inst_const_size = adev->dm.fw_inst_size;
1316 
1317 	fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1318 
1319 	/* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1320 	 * amdgpu_ucode_init_single_fw will load dmub firmware
1321 	 * fw_inst_const part to cw0; otherwise, the firmware back door load
1322 	 * will be done by dm_dmub_hw_init
1323 	 */
1324 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1325 		memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1326 				fw_inst_const_size);
1327 	}
1328 
1329 	if (fw_bss_data_size)
1330 		memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1331 		       fw_bss_data, fw_bss_data_size);
1332 
1333 	/* Copy firmware bios info into FB memory. */
1334 	memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1335 	       adev->bios_size);
1336 
1337 	/* Reset regions that need to be reset. */
1338 	memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1339 	fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1340 
1341 	memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1342 	       fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1343 
1344 	memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1345 	       fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1346 
1347 	memset(fb_info->fb[DMUB_WINDOW_SHARED_STATE].cpu_addr, 0,
1348 	       fb_info->fb[DMUB_WINDOW_SHARED_STATE].size);
1349 
1350 	/* Initialize hardware. */
1351 	memset(&hw_params, 0, sizeof(hw_params));
1352 	hw_params.soc_fb_info.fb_base = adev->gmc.fb_start;
1353 	hw_params.soc_fb_info.fb_offset = adev->vm_manager.vram_base_offset;
1354 
1355 	/* backdoor load firmware and trigger dmub running */
1356 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1357 		hw_params.load_inst_const = true;
1358 
1359 	if (dmcu)
1360 		hw_params.psp_version = dmcu->psp_version;
1361 
1362 	for (i = 0; i < fb_info->num_fb; ++i)
1363 		hw_params.fb[i] = &fb_info->fb[i];
1364 
1365 	/* Enable usb4 dpia in the FW APU */
1366 	if (dc->caps.is_apu &&
1367 		dc->res_pool->usb4_dpia_count != 0 &&
1368 		!dc->debug.dpia_debug.bits.disable_dpia) {
1369 		hw_params.dpia_supported = true;
1370 		hw_params.disable_dpia = dc->debug.dpia_debug.bits.disable_dpia;
1371 		hw_params.dpia_hpd_int_enable_supported = false;
1372 		hw_params.enable_non_transparent_setconfig = dc->config.consolidated_dpia_dp_lt;
1373 		hw_params.disable_dpia_bw_allocation = !dc->config.usb4_bw_alloc_support;
1374 	}
1375 
1376 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1377 	case IP_VERSION(3, 5, 0):
1378 	case IP_VERSION(3, 5, 1):
1379 	case IP_VERSION(3, 6, 0):
1380 	case IP_VERSION(4, 2, 0):
1381 	case IP_VERSION(4, 2, 1):
1382 		hw_params.ips_sequential_ono = adev->external_rev_id > 0x10;
1383 		hw_params.lower_hbr3_phy_ssc = true;
1384 		break;
1385 	default:
1386 		break;
1387 	}
1388 
1389 	status = dmub_srv_hw_init(dmub_srv, &hw_params);
1390 	if (status != DMUB_STATUS_OK) {
1391 		drm_err(adev_to_drm(adev), "Error initializing DMUB HW: %d\n", status);
1392 		return -EINVAL;
1393 	}
1394 
1395 	/* Wait for firmware load to finish. */
1396 	status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1397 	if (status != DMUB_STATUS_OK)
1398 		drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1399 
1400 	/* Init DMCU and ABM if available. */
1401 	if (dmcu && abm) {
1402 		dmcu->funcs->dmcu_init(dmcu);
1403 		abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1404 	}
1405 
1406 	if (!adev->dm.dc->ctx->dmub_srv)
1407 		adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1408 	if (!adev->dm.dc->ctx->dmub_srv) {
1409 		drm_err(adev_to_drm(adev), "Couldn't allocate DC DMUB server!\n");
1410 		return -ENOMEM;
1411 	}
1412 
1413 	drm_info(adev_to_drm(adev), "DMUB hardware initialized: version=0x%08X\n",
1414 		 adev->dm.dmcub_fw_version);
1415 
1416 	/* Keeping sanity checks off if
1417 	 * DCN31 >= 4.0.59.0
1418 	 * DCN314 >= 8.0.16.0
1419 	 * Otherwise, turn on sanity checks
1420 	 */
1421 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1422 	case IP_VERSION(3, 1, 2):
1423 	case IP_VERSION(3, 1, 3):
1424 		if (adev->dm.dmcub_fw_version &&
1425 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1426 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(4, 0, 59))
1427 				adev->dm.dc->debug.sanity_checks = true;
1428 		break;
1429 	case IP_VERSION(3, 1, 4):
1430 		if (adev->dm.dmcub_fw_version &&
1431 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1432 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(8, 0, 16))
1433 				adev->dm.dc->debug.sanity_checks = true;
1434 		break;
1435 	default:
1436 		break;
1437 	}
1438 
1439 	return 0;
1440 }
1441 
1442 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1443 {
1444 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1445 	enum dmub_status status;
1446 	bool init;
1447 	int r;
1448 
1449 	if (!dmub_srv) {
1450 		/* DMUB isn't supported on the ASIC. */
1451 		return;
1452 	}
1453 
1454 	status = dmub_srv_is_hw_init(dmub_srv, &init);
1455 	if (status != DMUB_STATUS_OK)
1456 		drm_warn(adev_to_drm(adev), "DMUB hardware init check failed: %d\n", status);
1457 
1458 	if (status == DMUB_STATUS_OK && init) {
1459 		/* Wait for firmware load to finish. */
1460 		status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1461 		if (status != DMUB_STATUS_OK)
1462 			drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1463 	} else {
1464 		/* Perform the full hardware initialization. */
1465 		r = dm_dmub_hw_init(adev);
1466 		if (r)
1467 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
1468 	}
1469 }
1470 
1471 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1472 {
1473 	u64 pt_base;
1474 	u32 logical_addr_low;
1475 	u32 logical_addr_high;
1476 	u32 agp_base, agp_bot, agp_top;
1477 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1478 
1479 	memset(pa_config, 0, sizeof(*pa_config));
1480 
1481 	agp_base = 0;
1482 	agp_bot = adev->gmc.agp_start >> 24;
1483 	agp_top = adev->gmc.agp_end >> 24;
1484 
1485 	/* AGP aperture is disabled */
1486 	if (agp_bot > agp_top) {
1487 		logical_addr_low = adev->gmc.fb_start >> 18;
1488 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1489 				       AMD_APU_IS_RENOIR |
1490 				       AMD_APU_IS_GREEN_SARDINE))
1491 			/*
1492 			 * Raven2 has a HW issue that it is unable to use the vram which
1493 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1494 			 * workaround that increase system aperture high address (add 1)
1495 			 * to get rid of the VM fault and hardware hang.
1496 			 */
1497 			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
1498 		else
1499 			logical_addr_high = adev->gmc.fb_end >> 18;
1500 	} else {
1501 		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1502 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1503 				       AMD_APU_IS_RENOIR |
1504 				       AMD_APU_IS_GREEN_SARDINE))
1505 			/*
1506 			 * Raven2 has a HW issue that it is unable to use the vram which
1507 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1508 			 * workaround that increase system aperture high address (add 1)
1509 			 * to get rid of the VM fault and hardware hang.
1510 			 */
1511 			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1512 		else
1513 			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1514 	}
1515 
1516 	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1517 
1518 	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
1519 						   AMDGPU_GPU_PAGE_SHIFT);
1520 	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
1521 						  AMDGPU_GPU_PAGE_SHIFT);
1522 	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
1523 						 AMDGPU_GPU_PAGE_SHIFT);
1524 	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
1525 						AMDGPU_GPU_PAGE_SHIFT);
1526 	page_table_base.high_part = upper_32_bits(pt_base);
1527 	page_table_base.low_part = lower_32_bits(pt_base);
1528 
1529 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1530 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1531 
1532 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
1533 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1534 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1535 
1536 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1537 	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
1538 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1539 
1540 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1541 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1542 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1543 
1544 	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
1545 
1546 }
1547 
1548 static void force_connector_state(
1549 	struct amdgpu_dm_connector *aconnector,
1550 	enum drm_connector_force force_state)
1551 {
1552 	struct drm_connector *connector = &aconnector->base;
1553 
1554 	mutex_lock(&connector->dev->mode_config.mutex);
1555 	aconnector->base.force = force_state;
1556 	mutex_unlock(&connector->dev->mode_config.mutex);
1557 
1558 	mutex_lock(&aconnector->hpd_lock);
1559 	drm_kms_helper_connector_hotplug_event(connector);
1560 	mutex_unlock(&aconnector->hpd_lock);
1561 }
1562 
1563 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1564 {
1565 	struct hpd_rx_irq_offload_work *offload_work;
1566 	struct amdgpu_dm_connector *aconnector;
1567 	struct dc_link *dc_link;
1568 	struct amdgpu_device *adev;
1569 	enum dc_connection_type new_connection_type = dc_connection_none;
1570 	unsigned long flags;
1571 	union test_response test_response;
1572 
1573 	memset(&test_response, 0, sizeof(test_response));
1574 
1575 	offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1576 	aconnector = offload_work->offload_wq->aconnector;
1577 	adev = offload_work->adev;
1578 
1579 	if (!aconnector) {
1580 		drm_err(adev_to_drm(adev), "Can't retrieve aconnector in hpd_rx_irq_offload_work");
1581 		goto skip;
1582 	}
1583 
1584 	dc_link = aconnector->dc_link;
1585 
1586 	mutex_lock(&aconnector->hpd_lock);
1587 	if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
1588 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
1589 	mutex_unlock(&aconnector->hpd_lock);
1590 
1591 	if (new_connection_type == dc_connection_none)
1592 		goto skip;
1593 
1594 	if (amdgpu_in_reset(adev))
1595 		goto skip;
1596 
1597 	if (offload_work->data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
1598 		offload_work->data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
1599 		dm_handle_mst_sideband_msg_ready_event(&aconnector->mst_mgr, DOWN_OR_UP_MSG_RDY_EVENT);
1600 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1601 		offload_work->offload_wq->is_handling_mst_msg_rdy_event = false;
1602 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1603 		goto skip;
1604 	}
1605 
1606 	mutex_lock(&adev->dm.dc_lock);
1607 	if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
1608 		dc_link_dp_handle_automated_test(dc_link);
1609 
1610 		if (aconnector->timing_changed) {
1611 			/* force connector disconnect and reconnect */
1612 			force_connector_state(aconnector, DRM_FORCE_OFF);
1613 			msleep(100);
1614 			force_connector_state(aconnector, DRM_FORCE_UNSPECIFIED);
1615 		}
1616 
1617 		test_response.bits.ACK = 1;
1618 
1619 		core_link_write_dpcd(
1620 		dc_link,
1621 		DP_TEST_RESPONSE,
1622 		&test_response.raw,
1623 		sizeof(test_response));
1624 	} else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1625 			dc_link_check_link_loss_status(dc_link, &offload_work->data) &&
1626 			dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1627 		/* offload_work->data is from handle_hpd_rx_irq->
1628 		 * schedule_hpd_rx_offload_work.this is defer handle
1629 		 * for hpd short pulse. upon here, link status may be
1630 		 * changed, need get latest link status from dpcd
1631 		 * registers. if link status is good, skip run link
1632 		 * training again.
1633 		 */
1634 		union hpd_irq_data irq_data;
1635 
1636 		memset(&irq_data, 0, sizeof(irq_data));
1637 
1638 		/* before dc_link_dp_handle_link_loss, allow new link lost handle
1639 		 * request be added to work queue if link lost at end of dc_link_
1640 		 * dp_handle_link_loss
1641 		 */
1642 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1643 		offload_work->offload_wq->is_handling_link_loss = false;
1644 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1645 
1646 		if ((dc_link_dp_read_hpd_rx_irq_data(dc_link, &irq_data) == DC_OK) &&
1647 			dc_link_check_link_loss_status(dc_link, &irq_data))
1648 			dc_link_dp_handle_link_loss(dc_link);
1649 	}
1650 	mutex_unlock(&adev->dm.dc_lock);
1651 
1652 skip:
1653 	kfree(offload_work);
1654 
1655 }
1656 
1657 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct amdgpu_device *adev)
1658 {
1659 	struct dc *dc = adev->dm.dc;
1660 	int max_caps = dc->caps.max_links;
1661 	int i = 0;
1662 	struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1663 
1664 	hpd_rx_offload_wq = kzalloc_objs(*hpd_rx_offload_wq, max_caps);
1665 
1666 	if (!hpd_rx_offload_wq)
1667 		return NULL;
1668 
1669 
1670 	for (i = 0; i < max_caps; i++) {
1671 		hpd_rx_offload_wq[i].wq =
1672 				    create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1673 
1674 		if (hpd_rx_offload_wq[i].wq == NULL) {
1675 			drm_err(adev_to_drm(adev), "create amdgpu_dm_hpd_rx_offload_wq fail!");
1676 			goto out_err;
1677 		}
1678 
1679 		spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
1680 	}
1681 
1682 	return hpd_rx_offload_wq;
1683 
1684 out_err:
1685 	for (i = 0; i < max_caps; i++) {
1686 		if (hpd_rx_offload_wq[i].wq)
1687 			destroy_workqueue(hpd_rx_offload_wq[i].wq);
1688 	}
1689 	kfree(hpd_rx_offload_wq);
1690 	return NULL;
1691 }
1692 
1693 struct amdgpu_stutter_quirk {
1694 	u16 chip_vendor;
1695 	u16 chip_device;
1696 	u16 subsys_vendor;
1697 	u16 subsys_device;
1698 	u8 revision;
1699 };
1700 
1701 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1702 	/* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1703 	{ 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1704 	{ 0, 0, 0, 0, 0 },
1705 };
1706 
1707 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1708 {
1709 	const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1710 
1711 	while (p && p->chip_device != 0) {
1712 		if (pdev->vendor == p->chip_vendor &&
1713 		    pdev->device == p->chip_device &&
1714 		    pdev->subsystem_vendor == p->subsys_vendor &&
1715 		    pdev->subsystem_device == p->subsys_device &&
1716 		    pdev->revision == p->revision) {
1717 			return true;
1718 		}
1719 		++p;
1720 	}
1721 	return false;
1722 }
1723 
1724 
1725 void*
1726 dm_allocate_gpu_mem(
1727 		struct amdgpu_device *adev,
1728 		enum dc_gpu_mem_alloc_type type,
1729 		size_t size,
1730 		long long *addr)
1731 {
1732 	struct dal_allocation *da;
1733 	u32 domain = (type == DC_MEM_ALLOC_TYPE_GART) ?
1734 		AMDGPU_GEM_DOMAIN_GTT : AMDGPU_GEM_DOMAIN_VRAM;
1735 	int ret;
1736 
1737 	da = kzalloc_obj(struct dal_allocation);
1738 	if (!da)
1739 		return NULL;
1740 
1741 	ret = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
1742 				      domain, &da->bo,
1743 				      &da->gpu_addr, &da->cpu_ptr);
1744 
1745 	*addr = da->gpu_addr;
1746 
1747 	if (ret) {
1748 		kfree(da);
1749 		return NULL;
1750 	}
1751 
1752 	/* add da to list in dm */
1753 	list_add(&da->list, &adev->dm.da_list);
1754 
1755 	return da->cpu_ptr;
1756 }
1757 
1758 void
1759 dm_free_gpu_mem(
1760 		struct amdgpu_device *adev,
1761 		enum dc_gpu_mem_alloc_type type,
1762 		void *pvMem)
1763 {
1764 	struct dal_allocation *da;
1765 
1766 	/* walk the da list in DM */
1767 	list_for_each_entry(da, &adev->dm.da_list, list) {
1768 		if (pvMem == da->cpu_ptr) {
1769 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
1770 			list_del(&da->list);
1771 			kfree(da);
1772 			break;
1773 		}
1774 	}
1775 
1776 }
1777 
1778 static enum dmub_status
1779 dm_dmub_send_vbios_gpint_command(struct amdgpu_device *adev,
1780 				 enum dmub_gpint_command command_code,
1781 				 uint16_t param,
1782 				 uint32_t timeout_us)
1783 {
1784 	union dmub_gpint_data_register reg, test;
1785 	uint32_t i;
1786 
1787 	/* Assume that VBIOS DMUB is ready to take commands */
1788 
1789 	reg.bits.status = 1;
1790 	reg.bits.command_code = command_code;
1791 	reg.bits.param = param;
1792 
1793 	cgs_write_register(adev->dm.cgs_device, 0x34c0 + 0x01f8, reg.all);
1794 
1795 	for (i = 0; i < timeout_us; ++i) {
1796 		udelay(1);
1797 
1798 		/* Check if our GPINT got acked */
1799 		reg.bits.status = 0;
1800 		test = (union dmub_gpint_data_register)
1801 			cgs_read_register(adev->dm.cgs_device, 0x34c0 + 0x01f8);
1802 
1803 		if (test.all == reg.all)
1804 			return DMUB_STATUS_OK;
1805 	}
1806 
1807 	return DMUB_STATUS_TIMEOUT;
1808 }
1809 
1810 static void *dm_dmub_get_vbios_bounding_box(struct amdgpu_device *adev)
1811 {
1812 	void *bb;
1813 	long long addr;
1814 	unsigned int bb_size;
1815 	int i = 0;
1816 	uint16_t chunk;
1817 	enum dmub_gpint_command send_addrs[] = {
1818 		DMUB_GPINT__SET_BB_ADDR_WORD0,
1819 		DMUB_GPINT__SET_BB_ADDR_WORD1,
1820 		DMUB_GPINT__SET_BB_ADDR_WORD2,
1821 		DMUB_GPINT__SET_BB_ADDR_WORD3,
1822 	};
1823 	enum dmub_status ret;
1824 
1825 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1826 	case IP_VERSION(4, 0, 1):
1827 		bb_size = sizeof(struct dml2_soc_bb);
1828 		break;
1829 	case IP_VERSION(4, 2, 0):
1830 	case IP_VERSION(4, 2, 1):
1831 		bb_size = sizeof(struct dml2_soc_bb);
1832 		break;
1833 	default:
1834 		return NULL;
1835 	}
1836 
1837 	bb =  dm_allocate_gpu_mem(adev,
1838 				  DC_MEM_ALLOC_TYPE_GART,
1839 				  bb_size,
1840 				  &addr);
1841 	if (!bb)
1842 		return NULL;
1843 
1844 	for (i = 0; i < 4; i++) {
1845 		/* Extract 16-bit chunk */
1846 		chunk = ((uint64_t) addr >> (i * 16)) & 0xFFFF;
1847 		/* Send the chunk */
1848 		ret = dm_dmub_send_vbios_gpint_command(adev, send_addrs[i], chunk, 30000);
1849 		if (ret != DMUB_STATUS_OK)
1850 			goto free_bb;
1851 	}
1852 
1853 	/* Now ask DMUB to copy the bb */
1854 	ret = dm_dmub_send_vbios_gpint_command(adev, DMUB_GPINT__BB_COPY, 1, 200000);
1855 	if (ret != DMUB_STATUS_OK)
1856 		goto free_bb;
1857 
1858 	return bb;
1859 
1860 free_bb:
1861 	dm_free_gpu_mem(adev, DC_MEM_ALLOC_TYPE_GART, (void *) bb);
1862 	return NULL;
1863 
1864 }
1865 
1866 static enum dmub_ips_disable_type dm_get_default_ips_mode(
1867 	struct amdgpu_device *adev)
1868 {
1869 	enum dmub_ips_disable_type ret = DMUB_IPS_ENABLE;
1870 
1871 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1872 	case IP_VERSION(3, 5, 0):
1873 	case IP_VERSION(3, 6, 0):
1874 	case IP_VERSION(3, 5, 1):
1875 		ret =  DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
1876 		break;
1877 	case IP_VERSION(4, 2, 0):
1878 	case IP_VERSION(4, 2, 1):
1879 		ret =  DMUB_IPS_ENABLE;
1880 		break;
1881 	default:
1882 		/* ASICs older than DCN35 do not have IPSs */
1883 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 5, 0))
1884 			ret = DMUB_IPS_DISABLE_ALL;
1885 		break;
1886 	}
1887 
1888 	return ret;
1889 }
1890 
1891 static int amdgpu_dm_init_power_module(struct amdgpu_display_manager *dm)
1892 {
1893 	struct mod_power_init_params init_data[MAX_NUM_EDP];
1894 
1895 	if (dm->num_of_edps == 0) {
1896 		drm_dbg_driver(
1897 			dm->ddev,
1898 			"amdgpu: No eDP detected, skip initializing power module\n");
1899 		return 0;
1900 	}
1901 
1902 	/* Initialize all the power module parameters */
1903 	for (int i = 0; i < dm->num_of_edps; i++) {
1904 		init_data[i].allow_psr_smu_optimizations =
1905 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_SMU_OPT);
1906 		init_data[i].allow_psr_multi_disp_optimizations =
1907 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_MULTI_DISP_OPT);
1908 		/* See dm_late_init */
1909 		init_data[i].backlight_ramping_override = false;
1910 		init_data[i].backlight_ramping_start = 0xCCCC;
1911 		init_data[i].backlight_ramping_reduction = 0xCCCCCCCC;
1912 		init_data[i].def_varibright_level = 0;
1913 		init_data[i].abm_config_setting = 0;
1914 		init_data[i].num_backlight_levels = 101;
1915 		init_data[i].use_nits_based_brightness = false;
1916 		init_data[i].panel_max_millinits = 0;
1917 		init_data[i].panel_min_millinits = 0;
1918 		init_data[i].disable_fractional_pwm =
1919 			!(amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK);
1920 		init_data[i].use_custom_backlight_caps = false;
1921 		init_data[i].custom_backlight_caps_config_no = 0;
1922 		init_data[i].use_linear_backlight_curve = false;
1923 		init_data[i].def_varibright_enable = 0;
1924 		init_data[i].varibright_level = 0;
1925 		/*
1926 		 * Power module uses 16-bit backlight levels (0xFFFF max) rather
1927 		 * than 8-bit(0XFF max)
1928 		 */
1929 		init_data[i].min_backlight_pwm =
1930 			dm->backlight_caps[i].min_input_signal * 0x101;
1931 		init_data[i].max_backlight_pwm =
1932 			dm->backlight_caps[i].max_input_signal * 0x101;
1933 		init_data[i].min_abm_backlight =
1934 			dm->backlight_caps[i].min_input_signal * 0x101;
1935 
1936 		/* Min backlight level after ABM reduction,  Don't allow below 1%
1937 		 * 0xFFFF x 0.01 = 0x28F
1938 		 */
1939 		init_data[i].min_abm_backlight = (init_data[i].min_abm_backlight < 0x28F) ?
1940 			0x28F : init_data[i].min_abm_backlight;
1941 	}
1942 
1943 	dm->power_module = mod_power_create(dm->dc, init_data, dm->num_of_edps);
1944 	if (!dm->power_module) {
1945 		drm_err(dm->ddev, "amdgpu: Error allocating memory for power module\n");
1946 		return -ENOMEM;
1947 	}
1948 
1949 	mod_power_hw_init(dm->power_module);
1950 	drm_dbg_driver(dm->ddev, "amdgpu: Power module init done\n");
1951 
1952 	return 0;
1953 }
1954 
1955 static void hdmi_frl_status_polling_work(struct work_struct *work)
1956 {
1957 	struct amdgpu_display_manager *dm =
1958 		container_of(to_delayed_work(work), struct amdgpu_display_manager,
1959 				hdmi_frl_status_polling_work);
1960 	struct dc *dc = dm->dc;
1961 	struct dc_link *dc_link;
1962 	bool link_update = false;
1963 
1964 	for (int i = 0; i < MAX_LINKS; i++) {
1965 		dc_link = dc->links[i];
1966 
1967 		if (!dc_link || !dc_link->local_sink)
1968 			continue;
1969 
1970 		if (!dc_is_hdmi_signal(dc_link->connector_signal))
1971 			continue;
1972 
1973 		if (dc_link->connector_signal != SIGNAL_TYPE_HDMI_FRL)
1974 			continue;
1975 
1976 		link_update = dc_link_frl_poll_status_flag(dc_link);
1977 		if (link_update) {
1978 			mutex_lock(&dm->dc_lock);
1979 			dc_link_detect(dc_link, DETECT_REASON_RETRAIN);
1980 			mutex_unlock(&dm->dc_lock);
1981 		}
1982 	}
1983 
1984 	queue_delayed_work(dm->hdmi_frl_status_polling_wq,
1985 			   &dm->hdmi_frl_status_polling_work,
1986 			   msecs_to_jiffies(dm->hdmi_frl_status_polling_delay_ms));
1987 }
1988 
1989 static int amdgpu_dm_init(struct amdgpu_device *adev)
1990 {
1991 	struct dc_init_data init_data;
1992 	struct dc_callback_init init_params;
1993 	int r;
1994 
1995 	adev->dm.ddev = adev_to_drm(adev);
1996 	adev->dm.adev = adev;
1997 
1998 	/* Zero all the fields */
1999 	memset(&init_data, 0, sizeof(init_data));
2000 	memset(&init_params, 0, sizeof(init_params));
2001 
2002 	mutex_init(&adev->dm.dpia_aux_lock);
2003 	mutex_init(&adev->dm.dc_lock);
2004 	mutex_init(&adev->dm.audio_lock);
2005 
2006 	spin_lock_init(&adev->dm.dmub_lock);
2007 
2008 	if (amdgpu_dm_irq_init(adev)) {
2009 		drm_err(adev_to_drm(adev), "failed to initialize DM IRQ support.\n");
2010 		goto error;
2011 	}
2012 
2013 	/* special handling for early revisions of GC 11.5.4 */
2014 	if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(11, 5, 4))
2015 		init_data.asic_id.chip_family = AMDGPU_FAMILY_GC_11_5_4;
2016 	else
2017 		init_data.asic_id.chip_family = adev->family;
2018 
2019 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
2020 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
2021 	init_data.asic_id.chip_id = adev->pdev->device;
2022 
2023 	init_data.asic_id.vram_width = adev->gmc.vram_width;
2024 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
2025 	init_data.asic_id.atombios_base_address =
2026 		adev->mode_info.atom_context->bios;
2027 
2028 	init_data.driver = adev;
2029 
2030 	/* cgs_device was created in dm_sw_init() */
2031 	init_data.cgs_device = adev->dm.cgs_device;
2032 
2033 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
2034 
2035 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2036 	case IP_VERSION(2, 1, 0):
2037 		switch (adev->dm.dmcub_fw_version) {
2038 		case 0: /* development */
2039 		case 0x1: /* linux-firmware.git hash 6d9f399 */
2040 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
2041 			init_data.flags.disable_dmcu = false;
2042 			break;
2043 		default:
2044 			init_data.flags.disable_dmcu = true;
2045 		}
2046 		break;
2047 	case IP_VERSION(2, 0, 3):
2048 		init_data.flags.disable_dmcu = true;
2049 		break;
2050 	default:
2051 		break;
2052 	}
2053 
2054 	/* APU support S/G display by default except:
2055 	 * ASICs before Carrizo,
2056 	 * RAVEN1 (Users reported stability issue)
2057 	 */
2058 
2059 	if (adev->asic_type < CHIP_CARRIZO) {
2060 		init_data.flags.gpu_vm_support = false;
2061 	} else if (adev->asic_type == CHIP_RAVEN) {
2062 		if (adev->apu_flags & AMD_APU_IS_RAVEN)
2063 			init_data.flags.gpu_vm_support = false;
2064 		else
2065 			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
2066 	} else {
2067 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(2, 0, 3))
2068 			init_data.flags.gpu_vm_support = (amdgpu_sg_display == 1);
2069 		else
2070 			init_data.flags.gpu_vm_support =
2071 				(amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
2072 	}
2073 
2074 	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
2075 
2076 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
2077 		init_data.flags.fbc_support = true;
2078 
2079 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
2080 		init_data.flags.multi_mon_pp_mclk_switch = true;
2081 
2082 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
2083 		init_data.flags.disable_fractional_pwm = true;
2084 
2085 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
2086 		init_data.flags.edp_no_power_sequencing = true;
2087 
2088 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
2089 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
2090 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
2091 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
2092 
2093 	if (amdgpu_dc_feature_mask & DC_FRL_MASK)
2094 		init_data.flags.enable_frl = true;
2095 
2096 	init_data.flags.seamless_boot_edp_requested = false;
2097 
2098 	if (amdgpu_device_seamless_boot_supported(adev)) {
2099 		init_data.flags.seamless_boot_edp_requested = true;
2100 		init_data.flags.allow_seamless_boot_optimization = true;
2101 		drm_dbg(adev->dm.ddev, "Seamless boot requested\n");
2102 	}
2103 
2104 	init_data.flags.enable_mipi_converter_optimization = true;
2105 
2106 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
2107 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
2108 	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
2109 
2110 	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
2111 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
2112 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS_DYNAMIC)
2113 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_DYNAMIC;
2114 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS2_DYNAMIC)
2115 		init_data.flags.disable_ips = DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
2116 	else if (amdgpu_dc_debug_mask & DC_FORCE_IPS_ENABLE)
2117 		init_data.flags.disable_ips = DMUB_IPS_ENABLE;
2118 	else
2119 		init_data.flags.disable_ips = dm_get_default_ips_mode(adev);
2120 
2121 	init_data.flags.disable_ips_in_vpb = 0;
2122 
2123 	/* DCN35 and above supports dynamic DTBCLK switch */
2124 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 5, 0))
2125 		init_data.flags.allow_0_dtb_clk = true;
2126 
2127 	/* Enable DWB for tested platforms only */
2128 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
2129 		init_data.num_virtual_links = 1;
2130 
2131 	/* DCN42 and above dpia switch to unified link training path */
2132 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 2, 0)) {
2133 		init_data.flags.consolidated_dpia_dp_lt = true;
2134 		init_data.flags.enable_dpia_pre_training = true;
2135 		init_data.flags.unify_link_enc_assignment = true;
2136 		init_data.flags.usb4_bw_alloc_support = true;
2137 	}
2138 	retrieve_dmi_info(&adev->dm);
2139 	if (adev->dm.edp0_on_dp1_quirk)
2140 		init_data.flags.support_edp0_on_dp1 = true;
2141 
2142 	if (adev->dm.bb_from_dmub)
2143 		init_data.bb_from_dmub = adev->dm.bb_from_dmub;
2144 	else
2145 		init_data.bb_from_dmub = NULL;
2146 
2147 	/* Display Core create. */
2148 	adev->dm.dc = dc_create(&init_data);
2149 
2150 	if (adev->dm.dc) {
2151 		drm_info(adev_to_drm(adev), "Display Core v%s initialized on %s\n", DC_VER,
2152 			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
2153 	} else {
2154 		drm_info(adev_to_drm(adev), "Display Core failed to initialize with v%s!\n", DC_VER);
2155 		goto error;
2156 	}
2157 
2158 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
2159 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
2160 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
2161 	}
2162 
2163 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2164 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2165 	if (dm_should_disable_stutter(adev->pdev))
2166 		adev->dm.dc->debug.disable_stutter = true;
2167 
2168 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
2169 		adev->dm.dc->debug.disable_stutter = true;
2170 
2171 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
2172 		adev->dm.dc->debug.disable_dsc = true;
2173 
2174 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
2175 		adev->dm.dc->debug.disable_clock_gate = true;
2176 
2177 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
2178 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
2179 
2180 	if (amdgpu_dc_debug_mask & DC_DISABLE_SUBVP_FAMS) {
2181 		adev->dm.dc->debug.force_disable_subvp = true;
2182 		adev->dm.dc->debug.fams2_config.bits.enable = false;
2183 	}
2184 
2185 	if (amdgpu_dc_debug_mask & DC_ENABLE_DML2) {
2186 		adev->dm.dc->debug.using_dml2 = true;
2187 		adev->dm.dc->debug.using_dml21 = true;
2188 	}
2189 
2190 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_FORCE_FW_ENABLE)
2191 		adev->dm.dc->debug.hdcp_lc_force_fw_enable = true;
2192 
2193 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_ENABLE_SW_FALLBACK)
2194 		adev->dm.dc->debug.hdcp_lc_enable_sw_fallback = true;
2195 
2196 	if (amdgpu_dc_debug_mask & DC_SKIP_DETECTION_LT)
2197 		adev->dm.dc->debug.skip_detection_link_training = true;
2198 
2199 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
2200 
2201 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
2202 	adev->dm.dc->debug.ignore_cable_id = true;
2203 
2204 	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
2205 		drm_info(adev_to_drm(adev), "DP-HDMI FRL PCON supported\n");
2206 
2207 	r = dm_dmub_hw_init(adev);
2208 	if (r) {
2209 		drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
2210 		goto error;
2211 	}
2212 
2213 	dc_hardware_init(adev->dm.dc);
2214 
2215 	adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev);
2216 	if (!adev->dm.hpd_rx_offload_wq) {
2217 		drm_err(adev_to_drm(adev), "failed to create hpd rx offload workqueue.\n");
2218 		goto error;
2219 	}
2220 
2221 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
2222 		struct dc_phy_addr_space_config pa_config;
2223 
2224 		mmhub_read_system_context(adev, &pa_config);
2225 
2226 		// Call the DC init_memory func
2227 		dc_setup_system_context(adev->dm.dc, &pa_config);
2228 	}
2229 
2230 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
2231 	if (!adev->dm.freesync_module) {
2232 		drm_err(adev_to_drm(adev),
2233 		"failed to initialize freesync_module.\n");
2234 	} else
2235 		drm_dbg_driver(adev_to_drm(adev), "freesync_module init done %p.\n",
2236 				adev->dm.freesync_module);
2237 
2238 	amdgpu_dm_init_color_mod();
2239 
2240 	if (adev->dm.dc->caps.max_links > 0) {
2241 		adev->dm.vblank_control_workqueue =
2242 			create_singlethread_workqueue("dm_vblank_control_workqueue");
2243 		if (!adev->dm.vblank_control_workqueue)
2244 			drm_err(adev_to_drm(adev), "failed to initialize vblank_workqueue.\n");
2245 	}
2246 
2247 	if (adev->dm.dc->caps.ips_support &&
2248 	    adev->dm.dc->config.disable_ips != DMUB_IPS_DISABLE_ALL)
2249 		adev->dm.idle_workqueue = idle_create_workqueue(adev);
2250 
2251 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
2252 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
2253 
2254 		if (!adev->dm.hdcp_workqueue)
2255 			drm_err(adev_to_drm(adev), "failed to initialize hdcp_workqueue.\n");
2256 		else
2257 			drm_dbg_driver(adev_to_drm(adev),
2258 				       "hdcp_workqueue init done %p.\n",
2259 				       adev->dm.hdcp_workqueue);
2260 
2261 		dc_init_callbacks(adev->dm.dc, &init_params);
2262 	}
2263 	if (adev->dm.dc->caps.max_links > 0) {
2264 		adev->dm.hdmi_frl_status_polling_wq =
2265 			create_singlethread_workqueue("hdmi_frl_status_polling_workqueue");
2266 		if (!adev->dm.hdmi_frl_status_polling_wq)
2267 			drm_err(adev_to_drm(adev), "failed to initialize hdmi_frl_status_polling_workqueue\n");
2268 		adev->dm.hdmi_frl_status_polling_delay_ms = 200;
2269 		INIT_DELAYED_WORK(&adev->dm.hdmi_frl_status_polling_work, hdmi_frl_status_polling_work);
2270 	}
2271 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2272 		init_completion(&adev->dm.dmub_aux_transfer_done);
2273 		adev->dm.dmub_notify = kzalloc_obj(struct dmub_notification);
2274 		if (!adev->dm.dmub_notify) {
2275 			drm_info(adev_to_drm(adev), "fail to allocate adev->dm.dmub_notify");
2276 			goto error;
2277 		}
2278 
2279 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
2280 		if (!adev->dm.delayed_hpd_wq) {
2281 			drm_err(adev_to_drm(adev), "failed to create hpd offload workqueue.\n");
2282 			goto error;
2283 		}
2284 
2285 		amdgpu_dm_outbox_init(adev);
2286 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
2287 			dmub_aux_setconfig_callback, false)) {
2288 			drm_err(adev_to_drm(adev), "fail to register dmub aux callback");
2289 			goto error;
2290 		}
2291 
2292 		for (size_t i = 0; i < ARRAY_SIZE(adev->dm.fused_io); i++)
2293 			init_completion(&adev->dm.fused_io[i].replied);
2294 
2295 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_FUSED_IO,
2296 			dmub_aux_fused_io_callback, false)) {
2297 			drm_err(adev_to_drm(adev), "fail to register dmub fused io callback");
2298 			goto error;
2299 		}
2300 		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
2301 		 * It is expected that DMUB will resend any pending notifications at this point. Note
2302 		 * that hpd and hpd_irq handler registration are deferred to register_hpd_handlers() to
2303 		 * align legacy interface initialization sequence. Connection status will be proactivly
2304 		 * detected once in the amdgpu_dm_initialize_drm_device.
2305 		 */
2306 		dc_enable_dmub_outbox(adev->dm.dc);
2307 
2308 		/* DPIA trace goes to dmesg logs only if outbox is enabled */
2309 		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
2310 			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
2311 	}
2312 
2313 	if (amdgpu_dm_initialize_drm_device(adev)) {
2314 		drm_err(adev_to_drm(adev),
2315 		"failed to initialize sw for display support.\n");
2316 		goto error;
2317 	}
2318 
2319 	if (amdgpu_dm_init_power_module(&adev->dm))
2320 		goto error;
2321 
2322 	/* create fake encoders for MST */
2323 	dm_dp_create_fake_mst_encoders(adev);
2324 
2325 	/* TODO: Add_display_info? */
2326 
2327 	/* TODO use dynamic cursor width */
2328 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
2329 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
2330 
2331 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
2332 		drm_err(adev_to_drm(adev),
2333 		"failed to initialize vblank for display support.\n");
2334 		goto error;
2335 	}
2336 
2337 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2338 	amdgpu_dm_crtc_secure_display_create_contexts(adev);
2339 	if (!adev->dm.secure_display_ctx.crtc_ctx)
2340 		drm_err(adev_to_drm(adev), "failed to initialize secure display contexts.\n");
2341 
2342 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))
2343 		adev->dm.secure_display_ctx.support_mul_roi = true;
2344 
2345 #endif
2346 
2347 	drm_dbg_driver(adev_to_drm(adev), "KMS initialized.\n");
2348 
2349 	return 0;
2350 error:
2351 	amdgpu_dm_fini(adev);
2352 
2353 	return -EINVAL;
2354 }
2355 
2356 static int amdgpu_dm_early_fini(struct amdgpu_ip_block *ip_block)
2357 {
2358 	struct amdgpu_device *adev = ip_block->adev;
2359 
2360 	amdgpu_dm_audio_fini(adev);
2361 
2362 	return 0;
2363 }
2364 
2365 static void amdgpu_dm_fini(struct amdgpu_device *adev)
2366 {
2367 	int i;
2368 
2369 	if (adev->dm.vblank_control_workqueue) {
2370 		destroy_workqueue(adev->dm.vblank_control_workqueue);
2371 		adev->dm.vblank_control_workqueue = NULL;
2372 	}
2373 
2374 	if (adev->dm.idle_workqueue) {
2375 		if (adev->dm.idle_workqueue->running) {
2376 			adev->dm.idle_workqueue->enable = false;
2377 			flush_work(&adev->dm.idle_workqueue->work);
2378 		}
2379 
2380 		kfree(adev->dm.idle_workqueue);
2381 		adev->dm.idle_workqueue = NULL;
2382 	}
2383 
2384 	/*
2385 	 * Disable ISM before dc_destroy() invalidates dm->dc.
2386 	 *
2387 	 * Quiesce workers first without dc_lock (they take dc_lock
2388 	 * themselves, so syncing under it would deadlock), then drive the
2389 	 * FSM back to FULL_POWER_RUNNING under dc_lock.
2390 	 */
2391 	amdgpu_dm_ism_disable(&adev->dm);
2392 	scoped_guard(mutex, &adev->dm.dc_lock)
2393 		amdgpu_dm_ism_force_full_power(&adev->dm);
2394 
2395 	amdgpu_dm_destroy_drm_device(&adev->dm);
2396 
2397 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2398 	if (adev->dm.secure_display_ctx.crtc_ctx) {
2399 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
2400 			if (adev->dm.secure_display_ctx.crtc_ctx[i].crtc) {
2401 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].notify_ta_work);
2402 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].forward_roi_work);
2403 			}
2404 		}
2405 		kfree(adev->dm.secure_display_ctx.crtc_ctx);
2406 		adev->dm.secure_display_ctx.crtc_ctx = NULL;
2407 	}
2408 #endif
2409 	if (adev->dm.hdcp_workqueue) {
2410 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
2411 		adev->dm.hdcp_workqueue = NULL;
2412 	}
2413 
2414 	if (adev->dm.dc) {
2415 		dc_deinit_callbacks(adev->dm.dc);
2416 		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
2417 		if (dc_enable_dmub_notifications(adev->dm.dc)) {
2418 			kfree(adev->dm.dmub_notify);
2419 			adev->dm.dmub_notify = NULL;
2420 			destroy_workqueue(adev->dm.delayed_hpd_wq);
2421 			adev->dm.delayed_hpd_wq = NULL;
2422 		}
2423 	}
2424 
2425 	if (adev->dm.dmub_bo)
2426 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
2427 				      &adev->dm.dmub_bo_gpu_addr,
2428 				      &adev->dm.dmub_bo_cpu_addr);
2429 
2430 	if (adev->dm.boot_time_crc_info.bo_ptr)
2431 		amdgpu_bo_free_kernel(&adev->dm.boot_time_crc_info.bo_ptr,
2432 					&adev->dm.boot_time_crc_info.gpu_addr,
2433 					&adev->dm.boot_time_crc_info.cpu_addr);
2434 
2435 	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
2436 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
2437 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
2438 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
2439 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
2440 			}
2441 		}
2442 
2443 		kfree(adev->dm.hpd_rx_offload_wq);
2444 		adev->dm.hpd_rx_offload_wq = NULL;
2445 	}
2446 
2447 	/* DC Destroy TODO: Replace destroy DAL */
2448 	if (adev->dm.dc)
2449 		dc_destroy(&adev->dm.dc);
2450 	/*
2451 	 * TODO: pageflip, vlank interrupt
2452 	 *
2453 	 * amdgpu_dm_irq_fini(adev);
2454 	 */
2455 
2456 	if (adev->dm.cgs_device) {
2457 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
2458 		adev->dm.cgs_device = NULL;
2459 	}
2460 	if (adev->dm.freesync_module) {
2461 		mod_freesync_destroy(adev->dm.freesync_module);
2462 		adev->dm.freesync_module = NULL;
2463 	}
2464 
2465 	if (adev->dm.power_module) {
2466 		mod_power_destroy(adev->dm.power_module);
2467 		adev->dm.power_module = NULL;
2468 	}
2469 	mutex_destroy(&adev->dm.audio_lock);
2470 	mutex_destroy(&adev->dm.dc_lock);
2471 	mutex_destroy(&adev->dm.dpia_aux_lock);
2472 }
2473 
2474 static int load_dmcu_fw(struct amdgpu_device *adev)
2475 {
2476 	const char *fw_name_dmcu = NULL;
2477 	int r;
2478 	const struct dmcu_firmware_header_v1_0 *hdr;
2479 
2480 	switch (adev->asic_type) {
2481 #if defined(CONFIG_DRM_AMD_DC_SI)
2482 	case CHIP_TAHITI:
2483 	case CHIP_PITCAIRN:
2484 	case CHIP_VERDE:
2485 	case CHIP_OLAND:
2486 #endif
2487 	case CHIP_BONAIRE:
2488 	case CHIP_HAWAII:
2489 	case CHIP_KAVERI:
2490 	case CHIP_KABINI:
2491 	case CHIP_MULLINS:
2492 	case CHIP_TONGA:
2493 	case CHIP_FIJI:
2494 	case CHIP_CARRIZO:
2495 	case CHIP_STONEY:
2496 	case CHIP_POLARIS11:
2497 	case CHIP_POLARIS10:
2498 	case CHIP_POLARIS12:
2499 	case CHIP_VEGAM:
2500 	case CHIP_VEGA10:
2501 	case CHIP_VEGA12:
2502 	case CHIP_VEGA20:
2503 		return 0;
2504 	case CHIP_NAVI12:
2505 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
2506 		break;
2507 	case CHIP_RAVEN:
2508 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
2509 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2510 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
2511 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2512 		else
2513 			return 0;
2514 		break;
2515 	default:
2516 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2517 		case IP_VERSION(2, 0, 2):
2518 		case IP_VERSION(2, 0, 3):
2519 		case IP_VERSION(2, 0, 0):
2520 		case IP_VERSION(2, 1, 0):
2521 		case IP_VERSION(3, 0, 0):
2522 		case IP_VERSION(3, 0, 2):
2523 		case IP_VERSION(3, 0, 3):
2524 		case IP_VERSION(3, 0, 1):
2525 		case IP_VERSION(3, 1, 2):
2526 		case IP_VERSION(3, 1, 3):
2527 		case IP_VERSION(3, 1, 4):
2528 		case IP_VERSION(3, 1, 5):
2529 		case IP_VERSION(3, 1, 6):
2530 		case IP_VERSION(3, 2, 0):
2531 		case IP_VERSION(3, 2, 1):
2532 		case IP_VERSION(3, 5, 0):
2533 		case IP_VERSION(3, 5, 1):
2534 		case IP_VERSION(3, 6, 0):
2535 		case IP_VERSION(4, 0, 1):
2536 		case IP_VERSION(4, 2, 0):
2537 		case IP_VERSION(4, 2, 1):
2538 			return 0;
2539 		default:
2540 			break;
2541 		}
2542 		drm_err(adev_to_drm(adev), "Unsupported ASIC type: 0x%X\n", adev->asic_type);
2543 		return -EINVAL;
2544 	}
2545 
2546 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
2547 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not supported on direct or SMU loading\n");
2548 		return 0;
2549 	}
2550 
2551 	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, AMDGPU_UCODE_REQUIRED,
2552 				 "%s", fw_name_dmcu);
2553 	if (r == -ENODEV) {
2554 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
2555 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not found\n");
2556 		adev->dm.fw_dmcu = NULL;
2557 		return 0;
2558 	}
2559 	if (r) {
2560 		drm_err(adev_to_drm(adev), "amdgpu_dm: Can't validate firmware \"%s\"\n",
2561 			fw_name_dmcu);
2562 		amdgpu_ucode_release(&adev->dm.fw_dmcu);
2563 		return r;
2564 	}
2565 
2566 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
2567 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
2568 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
2569 	adev->firmware.fw_size +=
2570 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2571 
2572 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
2573 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
2574 	adev->firmware.fw_size +=
2575 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2576 
2577 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
2578 
2579 	drm_dbg_kms(adev_to_drm(adev), "PSP loading DMCU firmware\n");
2580 
2581 	return 0;
2582 }
2583 
2584 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
2585 {
2586 	struct amdgpu_device *adev = ctx;
2587 
2588 	return dm_read_reg(adev->dm.dc->ctx, address);
2589 }
2590 
2591 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
2592 				     uint32_t value)
2593 {
2594 	struct amdgpu_device *adev = ctx;
2595 
2596 	return dm_write_reg(adev->dm.dc->ctx, address, value);
2597 }
2598 
2599 static int dm_dmub_sw_init(struct amdgpu_device *adev)
2600 {
2601 	struct dmub_srv_create_params create_params;
2602 	struct dmub_srv_fw_meta_info_params fw_meta_info_params;
2603 	struct dmub_srv_region_params region_params;
2604 	struct dmub_srv_region_info region_info;
2605 	struct dmub_srv_memory_params memory_params;
2606 	struct dmub_fw_meta_info fw_info;
2607 	struct dmub_srv_fb_info *fb_info;
2608 	struct dmub_srv *dmub_srv;
2609 	const struct dmcub_firmware_header_v1_0 *hdr;
2610 	enum dmub_asic dmub_asic;
2611 	enum dmub_status status;
2612 	static enum dmub_window_memory_type window_memory_type[DMUB_WINDOW_TOTAL] = {
2613 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_0_INST_CONST
2614 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_1_STACK
2615 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_2_BSS_DATA
2616 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_3_VBIOS
2617 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_4_MAILBOX
2618 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_5_TRACEBUFF
2619 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_6_FW_STATE
2620 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_7_SCRATCH_MEM
2621 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_IB_MEM
2622 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_SHARED_STATE
2623 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_LSDMA_BUFFER
2624 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_CURSOR_OFFLOAD
2625 	};
2626 	int r;
2627 
2628 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2629 	case IP_VERSION(2, 1, 0):
2630 		dmub_asic = DMUB_ASIC_DCN21;
2631 		break;
2632 	case IP_VERSION(3, 0, 0):
2633 		dmub_asic = DMUB_ASIC_DCN30;
2634 		break;
2635 	case IP_VERSION(3, 0, 1):
2636 		dmub_asic = DMUB_ASIC_DCN301;
2637 		break;
2638 	case IP_VERSION(3, 0, 2):
2639 		dmub_asic = DMUB_ASIC_DCN302;
2640 		break;
2641 	case IP_VERSION(3, 0, 3):
2642 		dmub_asic = DMUB_ASIC_DCN303;
2643 		break;
2644 	case IP_VERSION(3, 1, 2):
2645 	case IP_VERSION(3, 1, 3):
2646 		dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
2647 		break;
2648 	case IP_VERSION(3, 1, 4):
2649 		dmub_asic = DMUB_ASIC_DCN314;
2650 		break;
2651 	case IP_VERSION(3, 1, 5):
2652 		dmub_asic = DMUB_ASIC_DCN315;
2653 		break;
2654 	case IP_VERSION(3, 1, 6):
2655 		dmub_asic = DMUB_ASIC_DCN316;
2656 		break;
2657 	case IP_VERSION(3, 2, 0):
2658 		dmub_asic = DMUB_ASIC_DCN32;
2659 		break;
2660 	case IP_VERSION(3, 2, 1):
2661 		dmub_asic = DMUB_ASIC_DCN321;
2662 		break;
2663 	case IP_VERSION(3, 5, 0):
2664 	case IP_VERSION(3, 5, 1):
2665 		dmub_asic = DMUB_ASIC_DCN35;
2666 		break;
2667 	case IP_VERSION(3, 6, 0):
2668 		dmub_asic = DMUB_ASIC_DCN36;
2669 		break;
2670 	case IP_VERSION(4, 0, 1):
2671 		dmub_asic = DMUB_ASIC_DCN401;
2672 		break;
2673 	case IP_VERSION(4, 2, 0):
2674 		dmub_asic = DMUB_ASIC_DCN42;
2675 		break;
2676 	case IP_VERSION(4, 2, 1):
2677 		dmub_asic = DMUB_ASIC_DCN42B;
2678 		break;
2679 	default:
2680 		/* ASIC doesn't support DMUB. */
2681 		return 0;
2682 	}
2683 
2684 	hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
2685 	adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
2686 
2687 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
2688 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
2689 			AMDGPU_UCODE_ID_DMCUB;
2690 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
2691 			adev->dm.dmub_fw;
2692 		adev->firmware.fw_size +=
2693 			ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
2694 
2695 		drm_info(adev_to_drm(adev), "Loading DMUB firmware via PSP: version=0x%08X\n",
2696 			 adev->dm.dmcub_fw_version);
2697 	}
2698 
2699 
2700 	adev->dm.dmub_srv = kzalloc_obj(*adev->dm.dmub_srv);
2701 	dmub_srv = adev->dm.dmub_srv;
2702 
2703 	if (!dmub_srv) {
2704 		drm_err(adev_to_drm(adev), "Failed to allocate DMUB service!\n");
2705 		return -ENOMEM;
2706 	}
2707 
2708 	memset(&create_params, 0, sizeof(create_params));
2709 	create_params.user_ctx = adev;
2710 	create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2711 	create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2712 	create_params.asic = dmub_asic;
2713 
2714 	/* Create the DMUB service. */
2715 	status = dmub_srv_create(dmub_srv, &create_params);
2716 	if (status != DMUB_STATUS_OK) {
2717 		drm_err(adev_to_drm(adev), "Error creating DMUB service: %d\n", status);
2718 		return -EINVAL;
2719 	}
2720 
2721 	/* Extract the FW meta info. */
2722 	memset(&fw_meta_info_params, 0, sizeof(fw_meta_info_params));
2723 
2724 	fw_meta_info_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2725 					      PSP_HEADER_BYTES_256;
2726 	fw_meta_info_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2727 	fw_meta_info_params.fw_inst_const = adev->dm.dmub_fw->data +
2728 					    le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2729 					    PSP_HEADER_BYTES_256;
2730 	fw_meta_info_params.fw_bss_data = fw_meta_info_params.bss_data_size ? adev->dm.dmub_fw->data +
2731 					  le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2732 					  le32_to_cpu(hdr->inst_const_bytes) : NULL;
2733 	fw_meta_info_params.custom_psp_footer_size = 0;
2734 
2735 	status = dmub_srv_get_fw_meta_info_from_raw_fw(&fw_meta_info_params, &fw_info);
2736 	if (status != DMUB_STATUS_OK) {
2737 		/* Skip returning early, just log the error. */
2738 		drm_err(adev_to_drm(adev), "Error getting DMUB FW meta info: %d\n", status);
2739 		// return -EINVAL;
2740 	}
2741 
2742 	/* Calculate the size of all the regions for the DMUB service. */
2743 	memset(&region_params, 0, sizeof(region_params));
2744 
2745 	region_params.inst_const_size = fw_meta_info_params.inst_const_size;
2746 	region_params.bss_data_size = fw_meta_info_params.bss_data_size;
2747 	region_params.vbios_size = adev->bios_size;
2748 	region_params.fw_bss_data = fw_meta_info_params.fw_bss_data;
2749 	region_params.fw_inst_const = fw_meta_info_params.fw_inst_const;
2750 	region_params.window_memory_type = window_memory_type;
2751 	region_params.fw_info = (status == DMUB_STATUS_OK) ? &fw_info : NULL;
2752 
2753 	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2754 					   &region_info);
2755 
2756 	if (status != DMUB_STATUS_OK) {
2757 		drm_err(adev_to_drm(adev), "Error calculating DMUB region info: %d\n", status);
2758 		return -EINVAL;
2759 	}
2760 
2761 	/*
2762 	 * Allocate a framebuffer based on the total size of all the regions.
2763 	 * TODO: Move this into GART.
2764 	 */
2765 	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2766 				    AMDGPU_GEM_DOMAIN_VRAM |
2767 				    AMDGPU_GEM_DOMAIN_GTT,
2768 				    &adev->dm.dmub_bo,
2769 				    &adev->dm.dmub_bo_gpu_addr,
2770 				    &adev->dm.dmub_bo_cpu_addr);
2771 	if (r)
2772 		return r;
2773 
2774 	/* Rebase the regions on the framebuffer address. */
2775 	memset(&memory_params, 0, sizeof(memory_params));
2776 	memory_params.cpu_fb_addr = adev->dm.dmub_bo_cpu_addr;
2777 	memory_params.gpu_fb_addr = adev->dm.dmub_bo_gpu_addr;
2778 	memory_params.region_info = &region_info;
2779 	memory_params.window_memory_type = window_memory_type;
2780 
2781 	adev->dm.dmub_fb_info = kzalloc_obj(*adev->dm.dmub_fb_info);
2782 	fb_info = adev->dm.dmub_fb_info;
2783 
2784 	if (!fb_info) {
2785 		drm_err(adev_to_drm(adev),
2786 			"Failed to allocate framebuffer info for DMUB service!\n");
2787 		return -ENOMEM;
2788 	}
2789 
2790 	status = dmub_srv_calc_mem_info(dmub_srv, &memory_params, fb_info);
2791 	if (status != DMUB_STATUS_OK) {
2792 		drm_err(adev_to_drm(adev), "Error calculating DMUB FB info: %d\n", status);
2793 		return -EINVAL;
2794 	}
2795 
2796 	adev->dm.bb_from_dmub = dm_dmub_get_vbios_bounding_box(adev);
2797 	adev->dm.fw_inst_size = fw_meta_info_params.inst_const_size;
2798 
2799 	return 0;
2800 }
2801 
2802 static int dm_sw_init(struct amdgpu_ip_block *ip_block)
2803 {
2804 	struct amdgpu_device *adev = ip_block->adev;
2805 	int r;
2806 
2807 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
2808 
2809 	if (!adev->dm.cgs_device) {
2810 		drm_err(adev_to_drm(adev), "failed to create cgs device.\n");
2811 		return -EINVAL;
2812 	}
2813 
2814 	/* Moved from dm init since we need to use allocations for storing bounding box data */
2815 	INIT_LIST_HEAD(&adev->dm.da_list);
2816 
2817 	r = dm_dmub_sw_init(adev);
2818 	if (r)
2819 		return r;
2820 
2821 	return load_dmcu_fw(adev);
2822 }
2823 
2824 static int dm_sw_fini(struct amdgpu_ip_block *ip_block)
2825 {
2826 	struct amdgpu_device *adev = ip_block->adev;
2827 	struct dal_allocation *da;
2828 
2829 	list_for_each_entry(da, &adev->dm.da_list, list) {
2830 		if (adev->dm.bb_from_dmub == (void *) da->cpu_ptr) {
2831 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
2832 			list_del(&da->list);
2833 			kfree(da);
2834 			adev->dm.bb_from_dmub = NULL;
2835 			break;
2836 		}
2837 	}
2838 
2839 
2840 	kfree(adev->dm.dmub_fb_info);
2841 	adev->dm.dmub_fb_info = NULL;
2842 
2843 	if (adev->dm.dmub_srv) {
2844 		dmub_srv_destroy(adev->dm.dmub_srv);
2845 		kfree(adev->dm.dmub_srv);
2846 		adev->dm.dmub_srv = NULL;
2847 	}
2848 
2849 	amdgpu_ucode_release(&adev->dm.dmub_fw);
2850 	amdgpu_ucode_release(&adev->dm.fw_dmcu);
2851 
2852 	return 0;
2853 }
2854 
2855 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2856 {
2857 	struct amdgpu_dm_connector *aconnector;
2858 	struct drm_connector *connector;
2859 	struct drm_connector_list_iter iter;
2860 	int ret = 0;
2861 
2862 	drm_connector_list_iter_begin(dev, &iter);
2863 	drm_for_each_connector_iter(connector, &iter) {
2864 
2865 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2866 			continue;
2867 
2868 		aconnector = to_amdgpu_dm_connector(connector);
2869 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
2870 		    aconnector->mst_mgr.aux) {
2871 			drm_dbg_kms(dev, "DM_MST: starting TM on aconnector: %p [id: %d]\n",
2872 					 aconnector,
2873 					 aconnector->base.base.id);
2874 
2875 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2876 			if (ret < 0) {
2877 				drm_err(dev, "DM_MST: Failed to start MST\n");
2878 				aconnector->dc_link->type =
2879 					dc_connection_single;
2880 				ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2881 								     aconnector->dc_link);
2882 				break;
2883 			}
2884 		}
2885 	}
2886 	drm_connector_list_iter_end(&iter);
2887 
2888 	return ret;
2889 }
2890 
2891 static void amdgpu_dm_boot_time_crc_init(struct amdgpu_device *adev)
2892 {
2893 	struct dm_boot_time_crc_info *bootcrc_info = NULL;
2894 	struct dmub_srv *dmub = NULL;
2895 	union dmub_fw_boot_options option = {0};
2896 	int ret = 0;
2897 	const uint32_t fb_size = 3 * 1024 * 1024;	/* 3MB for DCC pattern */
2898 
2899 	if (!adev || !adev->dm.dc || !adev->dm.dc->ctx ||
2900 		!adev->dm.dc->ctx->dmub_srv) {
2901 		return;
2902 	}
2903 
2904 	dmub = adev->dm.dc->ctx->dmub_srv->dmub;
2905 	bootcrc_info = &adev->dm.boot_time_crc_info;
2906 
2907 	if (!dmub || !dmub->hw_funcs.get_fw_boot_option) {
2908 		drm_dbg(adev_to_drm(adev), "failed to init boot time crc buffer\n");
2909 		return;
2910 	}
2911 
2912 	option = dmub->hw_funcs.get_fw_boot_option(dmub);
2913 
2914 	/* Return if boot time CRC is not enabled */
2915 	if (option.bits.bootcrc_en_at_S0i3 == 0)
2916 		return;
2917 
2918 	/* Create a buffer for boot time CRC */
2919 	ret = amdgpu_bo_create_kernel(adev, fb_size, PAGE_SIZE,
2920 		AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT,
2921 		&bootcrc_info->bo_ptr,
2922 		&bootcrc_info->gpu_addr,
2923 		&bootcrc_info->cpu_addr);
2924 
2925 	if (ret) {
2926 		drm_dbg(adev_to_drm(adev), "failed to create boot time crc buffer\n");
2927 	} else {
2928 		bootcrc_info->size = fb_size;
2929 
2930 		drm_dbg(adev_to_drm(adev), "boot time crc buffer created addr 0x%llx, size %u\n",
2931 			bootcrc_info->gpu_addr, bootcrc_info->size);
2932 
2933 		/* Send the buffer info to DMUB */
2934 		dc_dmub_srv_boot_time_crc_init(adev->dm.dc,
2935 			bootcrc_info->gpu_addr, bootcrc_info->size);
2936 	}
2937 }
2938 
2939 static int dm_late_init(struct amdgpu_ip_block *ip_block)
2940 {
2941 	struct amdgpu_device *adev = ip_block->adev;
2942 
2943 	struct dmcu_iram_parameters params;
2944 	unsigned int linear_lut[16];
2945 	int i;
2946 	struct dmcu *dmcu = NULL;
2947 
2948 	dmcu = adev->dm.dc->res_pool->dmcu;
2949 
2950 	/* Init the boot time CRC (skip in resume) */
2951 	if ((adev->in_suspend == 0) &&
2952 		(amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(3, 6, 0)))
2953 		amdgpu_dm_boot_time_crc_init(adev);
2954 
2955 	for (i = 0; i < 16; i++)
2956 		linear_lut[i] = 0xFFFF * i / 15;
2957 
2958 	params.set = 0;
2959 	params.backlight_ramping_override = false;
2960 	params.backlight_ramping_start = 0xCCCC;
2961 	params.backlight_ramping_reduction = 0xCCCCCCCC;
2962 	params.backlight_lut_array_size = 16;
2963 	params.backlight_lut_array = linear_lut;
2964 
2965 	/* Min backlight level after ABM reduction,  Don't allow below 1%
2966 	 * 0xFFFF x 0.01 = 0x28F
2967 	 */
2968 	params.min_abm_backlight = 0x28F;
2969 	/* In the case where abm is implemented on dmcub,
2970 	 * dmcu object will be null.
2971 	 * ABM 2.4 and up are implemented on dmcub.
2972 	 */
2973 	if (dmcu) {
2974 		if (!dmcu_load_iram(dmcu, params))
2975 			return -EINVAL;
2976 	} else if (adev->dm.dc->ctx->dmub_srv) {
2977 		struct dc_link *edp_links[MAX_NUM_EDP];
2978 		int edp_num;
2979 
2980 		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
2981 		for (i = 0; i < edp_num; i++) {
2982 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
2983 				return -EINVAL;
2984 		}
2985 	}
2986 
2987 	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
2988 }
2989 
2990 static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
2991 {
2992 	u8 buf[UUID_SIZE];
2993 	guid_t guid;
2994 	int ret;
2995 
2996 	mutex_lock(&mgr->lock);
2997 	if (!mgr->mst_primary)
2998 		goto out_fail;
2999 
3000 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
3001 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
3002 		goto out_fail;
3003 	}
3004 
3005 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
3006 				 DP_MST_EN |
3007 				 DP_UP_REQ_EN |
3008 				 DP_UPSTREAM_IS_SRC);
3009 	if (ret < 0) {
3010 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
3011 		goto out_fail;
3012 	}
3013 
3014 	/* Some hubs forget their guids after they resume */
3015 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, buf, sizeof(buf));
3016 	if (ret != sizeof(buf)) {
3017 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
3018 		goto out_fail;
3019 	}
3020 
3021 	import_guid(&guid, buf);
3022 
3023 	if (guid_is_null(&guid)) {
3024 		guid_gen(&guid);
3025 		export_guid(buf, &guid);
3026 
3027 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, buf, sizeof(buf));
3028 
3029 		if (ret != sizeof(buf)) {
3030 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
3031 			goto out_fail;
3032 		}
3033 	}
3034 
3035 	guid_copy(&mgr->mst_primary->guid, &guid);
3036 
3037 out_fail:
3038 	mutex_unlock(&mgr->lock);
3039 }
3040 
3041 void hdmi_cec_unset_edid(struct amdgpu_dm_connector *aconnector)
3042 {
3043 	struct cec_notifier *n = aconnector->notifier;
3044 
3045 	if (!n)
3046 		return;
3047 
3048 	cec_notifier_phys_addr_invalidate(n);
3049 }
3050 
3051 void hdmi_cec_set_edid(struct amdgpu_dm_connector *aconnector)
3052 {
3053 	struct drm_connector *connector = &aconnector->base;
3054 	struct cec_notifier *n = aconnector->notifier;
3055 
3056 	if (!n)
3057 		return;
3058 
3059 	cec_notifier_set_phys_addr(n,
3060 				   connector->display_info.source_physical_address);
3061 }
3062 
3063 static void s3_handle_hdmi_cec(struct drm_device *ddev, bool suspend)
3064 {
3065 	struct amdgpu_dm_connector *aconnector;
3066 	struct drm_connector *connector;
3067 	struct drm_connector_list_iter conn_iter;
3068 
3069 	drm_connector_list_iter_begin(ddev, &conn_iter);
3070 	drm_for_each_connector_iter(connector, &conn_iter) {
3071 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3072 			continue;
3073 
3074 		aconnector = to_amdgpu_dm_connector(connector);
3075 		if (suspend)
3076 			hdmi_cec_unset_edid(aconnector);
3077 		else
3078 			hdmi_cec_set_edid(aconnector);
3079 	}
3080 	drm_connector_list_iter_end(&conn_iter);
3081 }
3082 
3083 static void s3_handle_mst(struct drm_device *dev, bool suspend)
3084 {
3085 	struct amdgpu_dm_connector *aconnector;
3086 	struct drm_connector *connector;
3087 	struct drm_connector_list_iter iter;
3088 	struct drm_dp_mst_topology_mgr *mgr;
3089 
3090 	drm_connector_list_iter_begin(dev, &iter);
3091 	drm_for_each_connector_iter(connector, &iter) {
3092 
3093 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3094 			continue;
3095 
3096 		aconnector = to_amdgpu_dm_connector(connector);
3097 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3098 		    aconnector->mst_root)
3099 			continue;
3100 
3101 		mgr = &aconnector->mst_mgr;
3102 
3103 		if (suspend) {
3104 			drm_dp_mst_topology_mgr_suspend(mgr);
3105 		} else {
3106 			/* if extended timeout is supported in hardware,
3107 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
3108 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
3109 			 */
3110 			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
3111 			if (!dp_is_lttpr_present(aconnector->dc_link))
3112 				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
3113 
3114 			/* TODO: move resume_mst_branch_status() into drm mst resume again
3115 			 * once topology probing work is pulled out from mst resume into mst
3116 			 * resume 2nd step. mst resume 2nd step should be called after old
3117 			 * state getting restored (i.e. drm_atomic_helper_resume()).
3118 			 */
3119 			resume_mst_branch_status(mgr);
3120 		}
3121 	}
3122 	drm_connector_list_iter_end(&iter);
3123 }
3124 
3125 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
3126 {
3127 	int ret = 0;
3128 
3129 	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
3130 	 * on window driver dc implementation.
3131 	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
3132 	 * should be passed to smu during boot up and resume from s3.
3133 	 * boot up: dc calculate dcn watermark clock settings within dc_create,
3134 	 * dcn20_resource_construct
3135 	 * then call pplib functions below to pass the settings to smu:
3136 	 * smu_set_watermarks_for_clock_ranges
3137 	 * smu_set_watermarks_table
3138 	 * navi10_set_watermarks_table
3139 	 * smu_write_watermarks_table
3140 	 *
3141 	 * For Renoir, clock settings of dcn watermark are also fixed values.
3142 	 * dc has implemented different flow for window driver:
3143 	 * dc_hardware_init / dc_set_power_state
3144 	 * dcn10_init_hw
3145 	 * notify_wm_ranges
3146 	 * set_wm_ranges
3147 	 * -- Linux
3148 	 * smu_set_watermarks_for_clock_ranges
3149 	 * renoir_set_watermarks_table
3150 	 * smu_write_watermarks_table
3151 	 *
3152 	 * For Linux,
3153 	 * dc_hardware_init -> amdgpu_dm_init
3154 	 * dc_set_power_state --> dm_resume
3155 	 *
3156 	 * therefore, this function apply to navi10/12/14 but not Renoir
3157 	 * *
3158 	 */
3159 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
3160 	case IP_VERSION(2, 0, 2):
3161 	case IP_VERSION(2, 0, 0):
3162 		break;
3163 	default:
3164 		return 0;
3165 	}
3166 
3167 	ret = amdgpu_dpm_write_watermarks_table(adev);
3168 	if (ret) {
3169 		drm_err(adev_to_drm(adev), "Failed to update WMTABLE!\n");
3170 		return ret;
3171 	}
3172 
3173 	return 0;
3174 }
3175 
3176 static int dm_oem_i2c_hw_init(struct amdgpu_device *adev)
3177 {
3178 	struct amdgpu_display_manager *dm = &adev->dm;
3179 	struct amdgpu_i2c_adapter *oem_i2c;
3180 	struct ddc_service *oem_ddc_service;
3181 	int r;
3182 
3183 	oem_ddc_service = dc_get_oem_i2c_device(adev->dm.dc);
3184 	if (oem_ddc_service) {
3185 		oem_i2c = create_i2c(oem_ddc_service, true);
3186 		if (!oem_i2c) {
3187 			drm_info(adev_to_drm(adev), "Failed to create oem i2c adapter data\n");
3188 			return -ENOMEM;
3189 		}
3190 
3191 		r = devm_i2c_add_adapter(adev->dev, &oem_i2c->base);
3192 		if (r) {
3193 			drm_info(adev_to_drm(adev), "Failed to register oem i2c\n");
3194 			kfree(oem_i2c);
3195 			return r;
3196 		}
3197 		dm->oem_i2c = oem_i2c;
3198 	}
3199 
3200 	return 0;
3201 }
3202 
3203 /**
3204  * dm_hw_init() - Initialize DC device
3205  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3206  *
3207  * Initialize the &struct amdgpu_display_manager device. This involves calling
3208  * the initializers of each DM component, then populating the struct with them.
3209  *
3210  * Although the function implies hardware initialization, both hardware and
3211  * software are initialized here. Splitting them out to their relevant init
3212  * hooks is a future TODO item.
3213  *
3214  * Some notable things that are initialized here:
3215  *
3216  * - Display Core, both software and hardware
3217  * - DC modules that we need (freesync and color management)
3218  * - DRM software states
3219  * - Interrupt sources and handlers
3220  * - Vblank support
3221  * - Debug FS entries, if enabled
3222  */
3223 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
3224 {
3225 	struct amdgpu_device *adev = ip_block->adev;
3226 	int r;
3227 
3228 	/* Create DAL display manager */
3229 	r = amdgpu_dm_init(adev);
3230 	if (r)
3231 		return r;
3232 	amdgpu_dm_hpd_init(adev);
3233 
3234 	r = dm_oem_i2c_hw_init(adev);
3235 	if (r)
3236 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
3237 
3238 	return 0;
3239 }
3240 
3241 /**
3242  * dm_hw_fini() - Teardown DC device
3243  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3244  *
3245  * Teardown components within &struct amdgpu_display_manager that require
3246  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
3247  * were loaded. Also flush IRQ workqueues and disable them.
3248  */
3249 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
3250 {
3251 	struct amdgpu_device *adev = ip_block->adev;
3252 
3253 	amdgpu_dm_hpd_fini(adev);
3254 
3255 	amdgpu_dm_irq_fini(adev);
3256 	amdgpu_dm_fini(adev);
3257 	return 0;
3258 }
3259 
3260 
3261 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
3262 				 struct dc_state *state, bool enable)
3263 {
3264 	enum dc_irq_source irq_source;
3265 	struct amdgpu_crtc *acrtc;
3266 	int rc = -EBUSY;
3267 	int i = 0;
3268 
3269 	for (i = 0; i < state->stream_count; i++) {
3270 		acrtc = get_crtc_by_otg_inst(
3271 				adev, state->stream_status[i].primary_otg_inst);
3272 
3273 		if (acrtc && state->stream_status[i].plane_count != 0) {
3274 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
3275 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3276 			if (rc)
3277 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
3278 					 enable ? "enable" : "disable");
3279 
3280 			if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
3281 				if (enable) {
3282 					if (amdgpu_dm_crtc_vrr_active(
3283 							to_dm_crtc_state(acrtc->base.state)))
3284 						rc = amdgpu_dm_crtc_set_vupdate_irq(
3285 							&acrtc->base, true);
3286 				} else
3287 					rc = amdgpu_dm_crtc_set_vupdate_irq(
3288 							&acrtc->base, false);
3289 
3290 				if (rc)
3291 					drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
3292 						enable ? "en" : "dis");
3293 			}
3294 
3295 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3296 			/* During gpu-reset we disable and then enable vblank irq, so
3297 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
3298 			 */
3299 			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
3300 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
3301 		}
3302 	}
3303 
3304 }
3305 
3306 DEFINE_FREE(state_release, struct dc_state *, if (_T) dc_state_release(_T))
3307 
3308 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
3309 {
3310 	struct dc_state *context __free(state_release) = NULL;
3311 	int i;
3312 	struct dc_stream_state *del_streams[MAX_PIPES];
3313 	int del_streams_count = 0;
3314 	struct dc_commit_streams_params params = {};
3315 
3316 	memset(del_streams, 0, sizeof(del_streams));
3317 
3318 	context = dc_state_create_current_copy(dc);
3319 	if (context == NULL)
3320 		return DC_ERROR_UNEXPECTED;
3321 
3322 	/* First remove from context all streams */
3323 	for (i = 0; i < context->stream_count; i++) {
3324 		struct dc_stream_state *stream = context->streams[i];
3325 
3326 		del_streams[del_streams_count++] = stream;
3327 	}
3328 
3329 	/* Remove all planes for removed streams and then remove the streams */
3330 	for (i = 0; i < del_streams_count; i++) {
3331 		enum dc_status res;
3332 
3333 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
3334 			return DC_FAIL_DETACH_SURFACES;
3335 
3336 		res = dc_state_remove_stream(dc, context, del_streams[i]);
3337 		if (res != DC_OK)
3338 			return res;
3339 	}
3340 
3341 	params.streams = context->streams;
3342 	params.stream_count = context->stream_count;
3343 
3344 	return dc_commit_streams(dc, &params);
3345 }
3346 
3347 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
3348 {
3349 	int i;
3350 
3351 	if (dm->hpd_rx_offload_wq) {
3352 		for (i = 0; i < dm->dc->caps.max_links; i++)
3353 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
3354 	}
3355 }
3356 
3357 static int dm_cache_state(struct amdgpu_device *adev)
3358 {
3359 	int r;
3360 
3361 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
3362 	if (IS_ERR(adev->dm.cached_state)) {
3363 		r = PTR_ERR(adev->dm.cached_state);
3364 		adev->dm.cached_state = NULL;
3365 	}
3366 
3367 	return adev->dm.cached_state ? 0 : r;
3368 }
3369 
3370 static void dm_destroy_cached_state(struct amdgpu_device *adev)
3371 {
3372 	struct amdgpu_display_manager *dm = &adev->dm;
3373 	struct drm_device *ddev = adev_to_drm(adev);
3374 	struct dm_plane_state *dm_new_plane_state;
3375 	struct drm_plane_state *new_plane_state;
3376 	struct dm_crtc_state *dm_new_crtc_state;
3377 	struct drm_crtc_state *new_crtc_state;
3378 	struct drm_plane *plane;
3379 	struct drm_crtc *crtc;
3380 	int i;
3381 
3382 	if (!dm->cached_state)
3383 		return;
3384 
3385 	/* Force mode set in atomic commit */
3386 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3387 		new_crtc_state->active_changed = true;
3388 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3389 		reset_freesync_config_for_crtc(dm_new_crtc_state);
3390 	}
3391 
3392 	/*
3393 	 * atomic_check is expected to create the dc states. We need to release
3394 	 * them here, since they were duplicated as part of the suspend
3395 	 * procedure.
3396 	 */
3397 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3398 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3399 		if (dm_new_crtc_state->stream) {
3400 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
3401 			dc_stream_release(dm_new_crtc_state->stream);
3402 			dm_new_crtc_state->stream = NULL;
3403 		}
3404 		dm_new_crtc_state->base.color_mgmt_changed = true;
3405 	}
3406 
3407 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
3408 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
3409 		if (dm_new_plane_state->dc_state) {
3410 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
3411 			dc_plane_state_release(dm_new_plane_state->dc_state);
3412 			dm_new_plane_state->dc_state = NULL;
3413 		}
3414 	}
3415 
3416 	drm_atomic_helper_resume(ddev, dm->cached_state);
3417 
3418 	dm->cached_state = NULL;
3419 }
3420 
3421 static int dm_suspend(struct amdgpu_ip_block *ip_block)
3422 {
3423 	struct amdgpu_device *adev = ip_block->adev;
3424 	struct amdgpu_display_manager *dm = &adev->dm;
3425 
3426 	if (amdgpu_in_reset(adev)) {
3427 		enum dc_status res;
3428 
3429 		/* Quiesce ISM workers before taking dc_lock (workers take
3430 		 * dc_lock themselves; syncing under it would deadlock).
3431 		 */
3432 		amdgpu_dm_ism_disable(dm);
3433 
3434 		mutex_lock(&dm->dc_lock);
3435 
3436 		amdgpu_dm_ism_force_full_power(dm);
3437 		dc_allow_idle_optimizations(adev->dm.dc, false);
3438 
3439 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
3440 
3441 		if (dm->cached_dc_state)
3442 			dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
3443 
3444 		res = amdgpu_dm_commit_zero_streams(dm->dc);
3445 		if (res != DC_OK) {
3446 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
3447 			return -EINVAL;
3448 		}
3449 
3450 		amdgpu_dm_irq_suspend(adev);
3451 
3452 		hpd_rx_irq_work_suspend(dm);
3453 
3454 		return 0;
3455 	}
3456 
3457 	if (!adev->dm.cached_state) {
3458 		int r = dm_cache_state(adev);
3459 
3460 		if (r)
3461 			return r;
3462 	}
3463 
3464 	s3_handle_hdmi_cec(adev_to_drm(adev), true);
3465 
3466 	s3_handle_mst(adev_to_drm(adev), true);
3467 
3468 	amdgpu_dm_irq_suspend(adev);
3469 
3470 	/*
3471 	 * Quiesce ISM workers before taking dc_lock (workers take dc_lock
3472 	 * themselves; syncing under it would deadlock).
3473 	 */
3474 	amdgpu_dm_ism_disable(dm);
3475 	scoped_guard(mutex, &dm->dc_lock)
3476 		amdgpu_dm_ism_force_full_power(dm);
3477 
3478 	hpd_rx_irq_work_suspend(dm);
3479 
3480 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
3481 
3482 	if (dm->dc->caps.ips_support && adev->in_s0ix)
3483 		dc_allow_idle_optimizations(dm->dc, true);
3484 
3485 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
3486 
3487 	return 0;
3488 }
3489 
3490 struct drm_connector *
3491 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_commit *state,
3492 					     struct drm_crtc *crtc)
3493 {
3494 	u32 i;
3495 	struct drm_connector_state *new_con_state;
3496 	struct drm_connector *connector;
3497 	struct drm_crtc *crtc_from_state;
3498 
3499 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3500 		crtc_from_state = new_con_state->crtc;
3501 
3502 		if (crtc_from_state == crtc)
3503 			return connector;
3504 	}
3505 
3506 	return NULL;
3507 }
3508 
3509 static void emulated_link_detect(struct dc_link *link)
3510 {
3511 	struct dc_sink_init_data sink_init_data = { 0 };
3512 	struct display_sink_capability sink_caps = { 0 };
3513 	enum dc_edid_status edid_status;
3514 	struct dc_context *dc_ctx = link->ctx;
3515 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
3516 	struct dc_sink *sink = NULL;
3517 	struct dc_sink *prev_sink = NULL;
3518 
3519 	link->type = dc_connection_none;
3520 	prev_sink = link->local_sink;
3521 
3522 	if (prev_sink)
3523 		dc_sink_release(prev_sink);
3524 
3525 	switch (link->connector_signal) {
3526 	case SIGNAL_TYPE_HDMI_TYPE_A: {
3527 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3528 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
3529 		break;
3530 	}
3531 
3532 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
3533 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3534 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
3535 		break;
3536 	}
3537 
3538 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
3539 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3540 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
3541 		break;
3542 	}
3543 
3544 	case SIGNAL_TYPE_LVDS: {
3545 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3546 		sink_caps.signal = SIGNAL_TYPE_LVDS;
3547 		break;
3548 	}
3549 
3550 	case SIGNAL_TYPE_EDP: {
3551 		sink_caps.transaction_type =
3552 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3553 		sink_caps.signal = SIGNAL_TYPE_EDP;
3554 		break;
3555 	}
3556 
3557 	case SIGNAL_TYPE_DISPLAY_PORT: {
3558 		sink_caps.transaction_type =
3559 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3560 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
3561 		break;
3562 	}
3563 
3564 	default:
3565 		drm_err(dev, "Invalid connector type! signal:%d\n",
3566 			link->connector_signal);
3567 		return;
3568 	}
3569 
3570 	sink_init_data.link = link;
3571 	sink_init_data.sink_signal = sink_caps.signal;
3572 
3573 	sink = dc_sink_create(&sink_init_data);
3574 	if (!sink) {
3575 		drm_err(dev, "Failed to create sink!\n");
3576 		return;
3577 	}
3578 
3579 	/* dc_sink_create returns a new reference */
3580 	link->local_sink = sink;
3581 
3582 	edid_status = dm_helpers_read_local_edid(
3583 			link->ctx,
3584 			link,
3585 			sink);
3586 
3587 	if (edid_status != EDID_OK)
3588 		drm_err(dev, "Failed to read EDID\n");
3589 
3590 }
3591 
3592 static void dm_gpureset_commit_state(struct dc_state *dc_state,
3593 				     struct amdgpu_display_manager *dm)
3594 {
3595 	struct {
3596 		struct dc_surface_update surface_updates[MAX_SURFACES];
3597 		struct dc_plane_info plane_infos[MAX_SURFACES];
3598 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3599 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3600 		struct dc_stream_update stream_update;
3601 	} *bundle __free(kfree);
3602 	int k, m;
3603 
3604 	bundle = kzalloc_obj(*bundle);
3605 
3606 	if (!bundle) {
3607 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
3608 		return;
3609 	}
3610 
3611 	for (k = 0; k < dc_state->stream_count; k++) {
3612 		bundle->stream_update.stream = dc_state->streams[k];
3613 
3614 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
3615 			bundle->surface_updates[m].surface =
3616 				dc_state->stream_status[k].plane_states[m];
3617 			bundle->surface_updates[m].surface->force_full_update =
3618 				true;
3619 		}
3620 
3621 		update_planes_and_stream_adapter(dm->dc,
3622 					 UPDATE_TYPE_FULL,
3623 					 dc_state->stream_status[k].plane_count,
3624 					 dc_state->streams[k],
3625 					 &bundle->stream_update,
3626 					 bundle->surface_updates);
3627 	}
3628 }
3629 
3630 static void apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
3631 					    struct dc_sink *sink)
3632 {
3633 	struct dc_panel_patch *ppatch = NULL;
3634 
3635 	if (!sink)
3636 		return;
3637 
3638 	ppatch = &sink->edid_caps.panel_patch;
3639 	if (ppatch->wait_after_dpcd_poweroff_ms) {
3640 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
3641 		drm_dbg_driver(adev_to_drm(adev),
3642 			       "%s: adding a %ds delay as w/a for panel\n",
3643 			       __func__,
3644 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
3645 	}
3646 }
3647 
3648 /**
3649  * amdgpu_dm_dump_links_and_sinks - Debug dump of all DC links and their sinks
3650  * @adev: amdgpu device pointer
3651  *
3652  * Iterates through all DC links and dumps information about local and remote
3653  * (MST) sinks. Should be called after connector detection is complete to see
3654  * the final state of all links.
3655  */
3656 static void amdgpu_dm_dump_links_and_sinks(struct amdgpu_device *adev)
3657 {
3658 	struct dc *dc = adev->dm.dc;
3659 	struct drm_device *dev = adev_to_drm(adev);
3660 	int li;
3661 
3662 	if (!dc)
3663 		return;
3664 
3665 	for (li = 0; li < dc->link_count; li++) {
3666 		struct dc_link *l = dc->links[li];
3667 		const char *name = NULL;
3668 		int rs;
3669 
3670 		if (!l)
3671 			continue;
3672 		if (l->local_sink && l->local_sink->edid_caps.display_name[0])
3673 			name = l->local_sink->edid_caps.display_name;
3674 		else
3675 			name = "n/a";
3676 
3677 		drm_dbg_kms(dev,
3678 			"LINK_DUMP[%d]: local_sink=%p type=%d sink_signal=%d sink_count=%u edid_name=%s mst_capable=%d mst_alloc_streams=%d\n",
3679 			li,
3680 			l->local_sink,
3681 			l->type,
3682 			l->local_sink ? l->local_sink->sink_signal : SIGNAL_TYPE_NONE,
3683 			l->sink_count,
3684 			name,
3685 			l->dpcd_caps.is_mst_capable,
3686 			l->mst_stream_alloc_table.stream_count);
3687 
3688 		/* Dump remote (MST) sinks if any */
3689 		for (rs = 0; rs < l->sink_count; rs++) {
3690 			struct dc_sink *rsink = l->remote_sinks[rs];
3691 			const char *rname = NULL;
3692 
3693 			if (!rsink)
3694 				continue;
3695 			if (rsink->edid_caps.display_name[0])
3696 				rname = rsink->edid_caps.display_name;
3697 			else
3698 				rname = "n/a";
3699 			drm_dbg_kms(dev,
3700 				"  REMOTE_SINK[%d:%d]: sink=%p signal=%d edid_name=%s\n",
3701 				li, rs,
3702 				rsink,
3703 				rsink->sink_signal,
3704 				rname);
3705 		}
3706 	}
3707 }
3708 
3709 static int dm_resume(struct amdgpu_ip_block *ip_block)
3710 {
3711 	struct amdgpu_device *adev = ip_block->adev;
3712 	struct drm_device *ddev = adev_to_drm(adev);
3713 	struct amdgpu_display_manager *dm = &adev->dm;
3714 	struct amdgpu_dm_connector *aconnector;
3715 	struct drm_connector *connector;
3716 	struct drm_connector_list_iter iter;
3717 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
3718 	enum dc_connection_type new_connection_type = dc_connection_none;
3719 	struct dc_state *dc_state;
3720 	int i, r, j;
3721 	struct dc_commit_streams_params commit_params = {};
3722 
3723 	if (dm->dc->caps.ips_support) {
3724 		if (!amdgpu_in_reset(adev))
3725 			mutex_lock(&dm->dc_lock);
3726 
3727 		/* Need to set POWER_STATE_D0 first or it will not execute
3728 		 * idle_power_optimizations command to DMUB.
3729 		 */
3730 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3731 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
3732 
3733 		if (!amdgpu_in_reset(adev))
3734 			mutex_unlock(&dm->dc_lock);
3735 	}
3736 
3737 	if (amdgpu_in_reset(adev)) {
3738 		dc_state = dm->cached_dc_state;
3739 
3740 		/*
3741 		 * The dc->current_state is backed up into dm->cached_dc_state
3742 		 * before we commit 0 streams.
3743 		 *
3744 		 * DC will clear link encoder assignments on the real state
3745 		 * but the changes won't propagate over to the copy we made
3746 		 * before the 0 streams commit.
3747 		 *
3748 		 * DC expects that link encoder assignments are *not* valid
3749 		 * when committing a state, so as a workaround we can copy
3750 		 * off of the current state.
3751 		 *
3752 		 * We lose the previous assignments, but we had already
3753 		 * commit 0 streams anyway.
3754 		 */
3755 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
3756 
3757 		r = dm_dmub_hw_init(adev);
3758 		if (r) {
3759 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
3760 			return r;
3761 		}
3762 
3763 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3764 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3765 
3766 		dc_resume(dm->dc);
3767 
3768 		amdgpu_dm_ism_enable(dm);
3769 		amdgpu_dm_irq_resume_early(adev);
3770 
3771 		for (i = 0; i < dc_state->stream_count; i++) {
3772 			dc_state->streams[i]->mode_changed = true;
3773 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
3774 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
3775 					= 0xffffffff;
3776 			}
3777 		}
3778 
3779 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3780 			amdgpu_dm_outbox_init(adev);
3781 			dc_enable_dmub_outbox(adev->dm.dc);
3782 		}
3783 
3784 		commit_params.streams = dc_state->streams;
3785 		commit_params.stream_count = dc_state->stream_count;
3786 		dc_exit_ips_for_hw_access(dm->dc);
3787 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
3788 
3789 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
3790 
3791 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
3792 
3793 		dc_state_release(dm->cached_dc_state);
3794 		dm->cached_dc_state = NULL;
3795 
3796 		amdgpu_dm_irq_resume_late(adev);
3797 
3798 		mutex_unlock(&dm->dc_lock);
3799 
3800 		/* set the backlight after a reset */
3801 		for (i = 0; i < dm->num_of_edps; i++) {
3802 			if (dm->backlight_dev[i])
3803 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
3804 		}
3805 
3806 		return 0;
3807 	}
3808 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
3809 	dc_state_release(dm_state->context);
3810 	dm_state->context = dc_state_create(dm->dc, NULL);
3811 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
3812 
3813 	/* Before powering on DC we need to re-initialize DMUB. */
3814 	dm_dmub_hw_resume(adev);
3815 
3816 	/* Re-enable outbox interrupts for DPIA. */
3817 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3818 		amdgpu_dm_outbox_init(adev);
3819 		dc_enable_dmub_outbox(adev->dm.dc);
3820 	}
3821 
3822 	/* power on hardware */
3823 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3824 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3825 
3826 	/* program HPD filter */
3827 	dc_resume(dm->dc);
3828 
3829 	scoped_guard(mutex, &dm->dc_lock)
3830 		amdgpu_dm_ism_enable(dm);
3831 
3832 	/*
3833 	 * early enable HPD Rx IRQ, should be done before set mode as short
3834 	 * pulse interrupts are used for MST
3835 	 */
3836 	amdgpu_dm_irq_resume_early(adev);
3837 
3838 	s3_handle_hdmi_cec(ddev, false);
3839 
3840 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
3841 	s3_handle_mst(ddev, false);
3842 
3843 	/* Do detection*/
3844 	drm_connector_list_iter_begin(ddev, &iter);
3845 	drm_for_each_connector_iter(connector, &iter) {
3846 		bool ret;
3847 
3848 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3849 			continue;
3850 
3851 		aconnector = to_amdgpu_dm_connector(connector);
3852 
3853 		if (!aconnector->dc_link)
3854 			continue;
3855 
3856 		/*
3857 		 * this is the case when traversing through already created end sink
3858 		 * MST connectors, should be skipped
3859 		 */
3860 		if (aconnector->mst_root)
3861 			continue;
3862 
3863 		/* Skip eDP detection, when there is no sink present */
3864 		if (aconnector->dc_link->connector_signal == SIGNAL_TYPE_EDP &&
3865 		    !aconnector->dc_link->edp_sink_present)
3866 			continue;
3867 
3868 		guard(mutex)(&aconnector->hpd_lock);
3869 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3870 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3871 
3872 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3873 			emulated_link_detect(aconnector->dc_link);
3874 		} else {
3875 			guard(mutex)(&dm->dc_lock);
3876 			dc_exit_ips_for_hw_access(dm->dc);
3877 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
3878 			if (ret) {
3879 				/* w/a delay for certain panels */
3880 				apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3881 			}
3882 		}
3883 
3884 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
3885 			aconnector->fake_enable = false;
3886 
3887 		if (aconnector->dc_sink)
3888 			dc_sink_release(aconnector->dc_sink);
3889 		aconnector->dc_sink = NULL;
3890 		amdgpu_dm_update_connector_after_detect(aconnector);
3891 	}
3892 	drm_connector_list_iter_end(&iter);
3893 
3894 	dm_destroy_cached_state(adev);
3895 
3896 	/* Do mst topology probing after resuming cached state*/
3897 	drm_connector_list_iter_begin(ddev, &iter);
3898 	drm_for_each_connector_iter(connector, &iter) {
3899 		bool init = false;
3900 
3901 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3902 			continue;
3903 
3904 		aconnector = to_amdgpu_dm_connector(connector);
3905 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3906 		    aconnector->mst_root)
3907 			continue;
3908 
3909 		scoped_guard(mutex, &aconnector->mst_mgr.lock) {
3910 			init = !aconnector->mst_mgr.mst_primary;
3911 		}
3912 		if (init)
3913 			dm_helpers_dp_mst_start_top_mgr(aconnector->dc_link->ctx,
3914 				aconnector->dc_link, false);
3915 		else
3916 			drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
3917 	}
3918 	drm_connector_list_iter_end(&iter);
3919 
3920 	/* Debug dump: list all DC links and their associated sinks after detection
3921 	 * is complete for all connectors. This provides a comprehensive view of the
3922 	 * final state without repeating the dump for each connector.
3923 	 */
3924 	amdgpu_dm_dump_links_and_sinks(adev);
3925 
3926 	amdgpu_dm_irq_resume_late(adev);
3927 
3928 	amdgpu_dm_smu_write_watermarks_table(adev);
3929 
3930 	drm_kms_helper_hotplug_event(ddev);
3931 
3932 	return 0;
3933 }
3934 
3935 /**
3936  * DOC: DM Lifecycle
3937  *
3938  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
3939  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
3940  * the base driver's device list to be initialized and torn down accordingly.
3941  *
3942  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
3943  */
3944 
3945 static const struct amd_ip_funcs amdgpu_dm_funcs = {
3946 	.name = "dm",
3947 	.early_init = dm_early_init,
3948 	.late_init = dm_late_init,
3949 	.sw_init = dm_sw_init,
3950 	.sw_fini = dm_sw_fini,
3951 	.early_fini = amdgpu_dm_early_fini,
3952 	.hw_init = dm_hw_init,
3953 	.hw_fini = dm_hw_fini,
3954 	.suspend = dm_suspend,
3955 	.resume = dm_resume,
3956 	.is_idle = dm_is_idle,
3957 	.wait_for_idle = dm_wait_for_idle,
3958 	.check_soft_reset = dm_check_soft_reset,
3959 	.soft_reset = dm_soft_reset,
3960 	.set_clockgating_state = dm_set_clockgating_state,
3961 	.set_powergating_state = dm_set_powergating_state,
3962 };
3963 
3964 const struct amdgpu_ip_block_version dm_ip_block = {
3965 	.type = AMD_IP_BLOCK_TYPE_DCE,
3966 	.major = 1,
3967 	.minor = 0,
3968 	.rev = 0,
3969 	.funcs = &amdgpu_dm_funcs,
3970 };
3971 
3972 
3973 /**
3974  * DOC: atomic
3975  *
3976  * *WIP*
3977  */
3978 
3979 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
3980 	.fb_create = amdgpu_display_user_framebuffer_create,
3981 	.get_format_info = amdgpu_dm_plane_get_format_info,
3982 	.atomic_check = amdgpu_dm_atomic_check,
3983 	.atomic_commit = drm_atomic_helper_commit,
3984 };
3985 
3986 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
3987 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
3988 	.atomic_commit_setup = amdgpu_dm_atomic_setup_commit,
3989 };
3990 
3991 #define DDC_MANUFACTURERNAME_SAMSUNG 0x2D4C
3992 
3993 static void dm_set_panel_type(struct amdgpu_dm_connector *aconnector)
3994 {
3995 	struct drm_connector *connector = &aconnector->base;
3996 	struct drm_display_info *display_info = &connector->display_info;
3997 	struct dc_link *link = aconnector->dc_link;
3998 	struct amdgpu_device *adev;
3999 
4000 	adev = drm_to_adev(connector->dev);
4001 
4002 	link->panel_type = PANEL_TYPE_NONE;
4003 
4004 	switch (display_info->amd_vsdb.panel_type) {
4005 	case AMD_VSDB_PANEL_TYPE_OLED:
4006 		link->panel_type = PANEL_TYPE_OLED;
4007 		break;
4008 	case AMD_VSDB_PANEL_TYPE_MINILED:
4009 		link->panel_type = PANEL_TYPE_MINILED;
4010 		break;
4011 	}
4012 
4013 	/* If VSDB didn't determine panel type, check DPCD ext caps */
4014 	if (link->panel_type == PANEL_TYPE_NONE) {
4015 		if (link->dpcd_sink_ext_caps.bits.miniled == 1)
4016 			link->panel_type = PANEL_TYPE_MINILED;
4017 		if (link->dpcd_sink_ext_caps.bits.oled == 1)
4018 			link->panel_type = PANEL_TYPE_OLED;
4019 	}
4020 
4021 	/* If VSDB and DPCD didn't determine panel type, check DID */
4022 	if (link->panel_type == PANEL_TYPE_NONE) {
4023 		if (display_info->panel_type == DRM_MODE_PANEL_TYPE_LCD)
4024 			link->panel_type = PANEL_TYPE_LCD;
4025 		else if (display_info->panel_type == DRM_MODE_PANEL_TYPE_OLED)
4026 			link->panel_type = PANEL_TYPE_OLED;
4027 	}
4028 
4029 	if (link->panel_type == PANEL_TYPE_NONE) {
4030 		struct drm_amd_vsdb_info *vsdb = &display_info->amd_vsdb;
4031 		u32 lum1_max = vsdb->luminance_range1.max_luminance;
4032 		u32 lum2_max = vsdb->luminance_range2.max_luminance;
4033 
4034 		if (vsdb->version && link->local_sink &&
4035 		    link->local_sink->edid_caps.manufacturer_id ==
4036 		    DDC_MANUFACTURERNAME_SAMSUNG &&
4037 		    lum1_max >= ((lum2_max * 3) / 2))
4038 			link->panel_type = PANEL_TYPE_MINILED;
4039 	}
4040 
4041 	if (link->panel_type == PANEL_TYPE_OLED)
4042 		drm_object_property_set_value(&connector->base,
4043 		    adev_to_drm(adev)->mode_config.panel_type_property,
4044 		    DRM_MODE_PANEL_TYPE_OLED);
4045 	else if (link->panel_type == PANEL_TYPE_LCD)
4046 		drm_object_property_set_value(&connector->base,
4047 		    adev_to_drm(adev)->mode_config.panel_type_property,
4048 		    DRM_MODE_PANEL_TYPE_LCD);
4049 	else
4050 		drm_object_property_set_value(&connector->base,
4051 		    adev_to_drm(adev)->mode_config.panel_type_property,
4052 		    DRM_MODE_PANEL_TYPE_UNKNOWN);
4053 
4054 	drm_dbg_kms(aconnector->base.dev, "Panel type: %d\n", link->panel_type);
4055 }
4056 
4057 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
4058 {
4059 	const struct drm_panel_backlight_quirk *panel_backlight_quirk;
4060 	struct amdgpu_dm_backlight_caps *caps;
4061 	struct drm_connector *conn_base;
4062 	struct amdgpu_device *adev;
4063 	struct drm_luminance_range_info *luminance_range;
4064 	struct drm_device *drm;
4065 
4066 	if (aconnector->bl_idx == -1 ||
4067 	    aconnector->dc_link->connector_signal != SIGNAL_TYPE_EDP)
4068 		return;
4069 
4070 	conn_base = &aconnector->base;
4071 	drm = conn_base->dev;
4072 	adev = drm_to_adev(drm);
4073 
4074 	caps = &adev->dm.backlight_caps[aconnector->bl_idx];
4075 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
4076 	caps->aux_support = false;
4077 
4078 	if (caps->ext_caps->bits.oled == 1
4079 	    /*
4080 	     * ||
4081 	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
4082 	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
4083 	     */)
4084 		caps->aux_support = true;
4085 
4086 	if (amdgpu_backlight == 0)
4087 		caps->aux_support = false;
4088 	else if (amdgpu_backlight == 1)
4089 		caps->aux_support = true;
4090 	if (caps->aux_support)
4091 		aconnector->dc_link->backlight_control_type = BACKLIGHT_CONTROL_AMD_AUX;
4092 
4093 	luminance_range = &conn_base->display_info.luminance_range;
4094 
4095 	if (luminance_range->max_luminance)
4096 		caps->aux_max_input_signal = luminance_range->max_luminance;
4097 	else
4098 		caps->aux_max_input_signal = 512;
4099 
4100 	if (luminance_range->min_luminance)
4101 		caps->aux_min_input_signal = luminance_range->min_luminance;
4102 	else
4103 		caps->aux_min_input_signal = 1;
4104 
4105 	panel_backlight_quirk =
4106 		drm_get_panel_backlight_quirk(aconnector->drm_edid);
4107 	if (!IS_ERR_OR_NULL(panel_backlight_quirk)) {
4108 		if (panel_backlight_quirk->min_brightness) {
4109 			caps->min_input_signal =
4110 				panel_backlight_quirk->min_brightness - 1;
4111 			drm_info(drm,
4112 				 "Applying panel backlight quirk, min_brightness: %d\n",
4113 				 caps->min_input_signal);
4114 		}
4115 		if (panel_backlight_quirk->brightness_mask) {
4116 			drm_info(drm,
4117 				 "Applying panel backlight quirk, brightness_mask: 0x%X\n",
4118 				 panel_backlight_quirk->brightness_mask);
4119 			caps->brightness_mask =
4120 				panel_backlight_quirk->brightness_mask;
4121 		}
4122 	}
4123 }
4124 
4125 DEFINE_FREE(sink_release, struct dc_sink *, if (_T) dc_sink_release(_T))
4126 
4127 void amdgpu_dm_update_connector_after_detect(
4128 		struct amdgpu_dm_connector *aconnector)
4129 {
4130 	struct drm_connector *connector = &aconnector->base;
4131 	struct dc_sink *sink __free(sink_release) = NULL;
4132 	struct drm_device *dev = connector->dev;
4133 
4134 	/* MST handled by drm_mst framework */
4135 	if (aconnector->mst_mgr.mst_state == true)
4136 		return;
4137 
4138 	sink = aconnector->dc_link->local_sink;
4139 	if (sink)
4140 		dc_sink_retain(sink);
4141 
4142 	/*
4143 	 * Edid mgmt connector gets first update only in mode_valid hook and then
4144 	 * the connector sink is set to either fake or physical sink depends on link status.
4145 	 * Skip if already done during boot.
4146 	 */
4147 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
4148 			&& aconnector->dc_em_sink) {
4149 
4150 		/*
4151 		 * For S3 resume with headless use eml_sink to fake stream
4152 		 * because on resume connector->sink is set to NULL
4153 		 */
4154 		guard(mutex)(&dev->mode_config.mutex);
4155 
4156 		if (sink) {
4157 			if (aconnector->dc_sink) {
4158 				amdgpu_dm_update_freesync_caps(connector, NULL, true);
4159 				/*
4160 				 * retain and release below are used to
4161 				 * bump up refcount for sink because the link doesn't point
4162 				 * to it anymore after disconnect, so on next crtc to connector
4163 				 * reshuffle by UMD we will get into unwanted dc_sink release
4164 				 */
4165 				dc_sink_release(aconnector->dc_sink);
4166 			}
4167 			aconnector->dc_sink = sink;
4168 			dc_sink_retain(aconnector->dc_sink);
4169 			amdgpu_dm_update_freesync_caps(connector,
4170 					aconnector->drm_edid, true);
4171 		} else {
4172 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4173 			if (!aconnector->dc_sink) {
4174 				aconnector->dc_sink = aconnector->dc_em_sink;
4175 				dc_sink_retain(aconnector->dc_sink);
4176 			}
4177 		}
4178 
4179 		return;
4180 	}
4181 
4182 	/*
4183 	 * TODO: temporary guard to look for proper fix
4184 	 * if this sink is MST sink, we should not do anything
4185 	 */
4186 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
4187 		return;
4188 
4189 	if (aconnector->dc_sink == sink) {
4190 		/*
4191 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
4192 		 * Do nothing!!
4193 		 */
4194 		drm_dbg_kms(dev, "DCHPD: connector_id=%d: dc_sink didn't change.\n",
4195 				 aconnector->connector_id);
4196 		return;
4197 	}
4198 
4199 	drm_dbg_kms(dev, "DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
4200 		    aconnector->connector_id, aconnector->dc_sink, sink);
4201 
4202 	/* When polling, DRM has already locked the mutex for us. */
4203 	if (!drm_kms_helper_is_poll_worker())
4204 		mutex_lock(&dev->mode_config.mutex);
4205 
4206 	/*
4207 	 * 1. Update status of the drm connector
4208 	 * 2. Send an event and let userspace tell us what to do
4209 	 */
4210 	if (sink) {
4211 		/*
4212 		 * TODO: check if we still need the S3 mode update workaround.
4213 		 * If yes, put it here.
4214 		 */
4215 		if (aconnector->dc_sink) {
4216 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4217 			dc_sink_release(aconnector->dc_sink);
4218 		}
4219 
4220 		aconnector->dc_sink = sink;
4221 		dc_sink_retain(aconnector->dc_sink);
4222 		drm_edid_free(aconnector->drm_edid);
4223 		aconnector->drm_edid = NULL;
4224 		if (sink->dc_edid.length == 0) {
4225 			hdmi_cec_unset_edid(aconnector);
4226 			if (aconnector->dc_link->aux_mode) {
4227 				drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4228 			}
4229 		} else {
4230 			const struct edid *edid = (const struct edid *)sink->dc_edid.raw_edid;
4231 
4232 			aconnector->drm_edid = drm_edid_alloc(edid, sink->dc_edid.length);
4233 			drm_edid_connector_update(connector, aconnector->drm_edid);
4234 
4235 			hdmi_cec_set_edid(aconnector);
4236 			if (aconnector->dc_link->aux_mode)
4237 				drm_dp_cec_attach(&aconnector->dm_dp_aux.aux,
4238 						  connector->display_info.source_physical_address);
4239 		}
4240 
4241 		if (!aconnector->timing_requested) {
4242 			aconnector->timing_requested =
4243 				kzalloc_obj(struct dc_crtc_timing);
4244 			if (!aconnector->timing_requested)
4245 				drm_err(dev,
4246 					"failed to create aconnector->requested_timing\n");
4247 		}
4248 
4249 		amdgpu_dm_update_freesync_caps(connector, aconnector->drm_edid, true);
4250 		update_connector_ext_caps(aconnector);
4251 		dm_set_panel_type(aconnector);
4252 	} else {
4253 		hdmi_cec_unset_edid(aconnector);
4254 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4255 		amdgpu_dm_update_freesync_caps(connector, NULL, true);
4256 		aconnector->num_modes = 0;
4257 		dc_sink_release(aconnector->dc_sink);
4258 		aconnector->dc_sink = NULL;
4259 		drm_edid_free(aconnector->drm_edid);
4260 		aconnector->drm_edid = NULL;
4261 		kfree(aconnector->timing_requested);
4262 		aconnector->timing_requested = NULL;
4263 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
4264 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
4265 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
4266 	}
4267 
4268 	update_subconnector_property(aconnector);
4269 
4270 	/* When polling, the mutex will be unlocked for us by DRM. */
4271 	if (!drm_kms_helper_is_poll_worker())
4272 		mutex_unlock(&dev->mode_config.mutex);
4273 }
4274 
4275 static bool are_sinks_equal(const struct dc_sink *sink1, const struct dc_sink *sink2)
4276 {
4277 	if (!sink1 || !sink2)
4278 		return false;
4279 	if (sink1->sink_signal != sink2->sink_signal)
4280 		return false;
4281 
4282 	if (sink1->dc_edid.length != sink2->dc_edid.length)
4283 		return false;
4284 
4285 	if (memcmp(sink1->dc_edid.raw_edid, sink2->dc_edid.raw_edid,
4286 		   sink1->dc_edid.length) != 0)
4287 		return false;
4288 	return true;
4289 }
4290 
4291 
4292 /**
4293  * DOC: hdmi_hpd_debounce_work
4294  *
4295  * HDMI HPD debounce delay in milliseconds. When an HDMI display toggles HPD
4296  * (such as during power save transitions), this delay determines how long to
4297  * wait before processing the HPD event. This allows distinguishing between a
4298  * physical unplug (>hdmi_hpd_debounce_delay)
4299  * and a spontaneous RX HPD toggle (<hdmi_hpd_debounce_delay).
4300  *
4301  * If the toggle is less than this delay, the driver compares sink capabilities
4302  * and permits a hotplug event if they changed.
4303  *
4304  * The default value of 1500ms was chosen based on experimental testing with
4305  * various monitors that exhibit spontaneous HPD toggling behavior.
4306  */
4307 static void hdmi_hpd_debounce_work(struct work_struct *work)
4308 {
4309 	struct amdgpu_dm_connector *aconnector =
4310 		container_of(to_delayed_work(work), struct amdgpu_dm_connector,
4311 			     hdmi_hpd_debounce_work);
4312 	struct drm_connector *connector = &aconnector->base;
4313 	struct drm_device *dev = connector->dev;
4314 	struct amdgpu_device *adev = drm_to_adev(dev);
4315 	struct dc *dc = aconnector->dc_link->ctx->dc;
4316 	bool fake_reconnect = false;
4317 	bool reallow_idle = false;
4318 	bool ret = false;
4319 	guard(mutex)(&aconnector->hpd_lock);
4320 
4321 	/* Re-detect the display */
4322 	scoped_guard(mutex, &adev->dm.dc_lock) {
4323 		if (dc->caps.ips_support && dc->ctx->dmub_srv->idle_allowed) {
4324 			dc_allow_idle_optimizations(dc, false);
4325 			reallow_idle = true;
4326 		}
4327 		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4328 	}
4329 
4330 	if (ret) {
4331 		/* Apply workaround delay for certain panels */
4332 		apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4333 		/* Compare sinks to determine if this was a spontaneous HPD toggle */
4334 		if (are_sinks_equal(aconnector->dc_link->local_sink, aconnector->hdmi_prev_sink)) {
4335 			/*
4336 			* Sinks match - this was a spontaneous HDMI HPD toggle.
4337 			*/
4338 			drm_dbg_kms(dev, "HDMI HPD: Sink unchanged after debounce, internal re-enable\n");
4339 			fake_reconnect = true;
4340 		}
4341 
4342 		/* Update connector state */
4343 		amdgpu_dm_update_connector_after_detect(aconnector);
4344 
4345 		drm_modeset_lock_all(dev);
4346 		dm_restore_drm_connector_state(dev, connector);
4347 		drm_modeset_unlock_all(dev);
4348 
4349 		/* Only notify OS if sink actually changed */
4350 		if (!fake_reconnect && aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4351 			drm_kms_helper_hotplug_event(dev);
4352 	}
4353 
4354 	/* Release the cached sink reference */
4355 	if (aconnector->hdmi_prev_sink) {
4356 		dc_sink_release(aconnector->hdmi_prev_sink);
4357 		aconnector->hdmi_prev_sink = NULL;
4358 	}
4359 
4360 	scoped_guard(mutex, &adev->dm.dc_lock) {
4361 		if (reallow_idle && dc->caps.ips_support)
4362 			dc_allow_idle_optimizations(dc, true);
4363 	}
4364 }
4365 
4366 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
4367 {
4368 	struct drm_connector *connector = &aconnector->base;
4369 	struct drm_device *dev = connector->dev;
4370 	enum dc_connection_type new_connection_type = dc_connection_none;
4371 	struct amdgpu_device *adev = drm_to_adev(dev);
4372 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
4373 	struct dc *dc = aconnector->dc_link->ctx->dc;
4374 	bool ret = false;
4375 	bool debounce_required = false;
4376 
4377 	if (adev->dm.disable_hpd_irq)
4378 		return;
4379 
4380 	/*
4381 	 * In case of failure or MST no need to update connector status or notify the OS
4382 	 * since (for MST case) MST does this in its own context.
4383 	 */
4384 	guard(mutex)(&aconnector->hpd_lock);
4385 
4386 	if (adev->dm.hdcp_workqueue) {
4387 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
4388 		dm_con_state->update_hdcp = true;
4389 	}
4390 	if (aconnector->fake_enable)
4391 		aconnector->fake_enable = false;
4392 
4393 	aconnector->timing_changed = false;
4394 
4395 	if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
4396 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4397 
4398 	/*
4399 	 * Check for HDMI disconnect with debounce enabled.
4400 	 */
4401 	debounce_required = (aconnector->hdmi_hpd_debounce_delay_ms > 0 &&
4402 			      dc_is_hdmi_signal(aconnector->dc_link->connector_signal) &&
4403 			      new_connection_type == dc_connection_none &&
4404 			      aconnector->dc_link->local_sink != NULL);
4405 
4406 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
4407 		emulated_link_detect(aconnector->dc_link);
4408 
4409 		drm_modeset_lock_all(dev);
4410 		dm_restore_drm_connector_state(dev, connector);
4411 		drm_modeset_unlock_all(dev);
4412 
4413 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4414 			drm_kms_helper_connector_hotplug_event(connector);
4415 	} else if (debounce_required) {
4416 		/*
4417 		 * HDMI disconnect detected - schedule delayed work instead of
4418 		 * processing immediately. This allows us to coalesce spurious
4419 		 * HDMI signals from physical unplugs.
4420 		 */
4421 		drm_dbg_kms(dev, "HDMI HPD: Disconnect detected, scheduling debounce work (%u ms)\n",
4422 			    aconnector->hdmi_hpd_debounce_delay_ms);
4423 
4424 		/* Cache the current sink for later comparison */
4425 		if (aconnector->hdmi_prev_sink)
4426 			dc_sink_release(aconnector->hdmi_prev_sink);
4427 		aconnector->hdmi_prev_sink = aconnector->dc_link->local_sink;
4428 		if (aconnector->hdmi_prev_sink)
4429 			dc_sink_retain(aconnector->hdmi_prev_sink);
4430 
4431 		/* Schedule delayed detection. */
4432 		if (mod_delayed_work(system_percpu_wq,
4433 				 &aconnector->hdmi_hpd_debounce_work,
4434 				 msecs_to_jiffies(aconnector->hdmi_hpd_debounce_delay_ms)))
4435 			drm_dbg_kms(dev, "HDMI HPD: Re-scheduled debounce work\n");
4436 
4437 	} else {
4438 
4439 		/* If the aconnector->hdmi_hpd_debounce_work is scheduled, exit early */
4440 		if (delayed_work_pending(&aconnector->hdmi_hpd_debounce_work))
4441 			return;
4442 
4443 		scoped_guard(mutex, &adev->dm.dc_lock) {
4444 			dc_exit_ips_for_hw_access(dc);
4445 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4446 		}
4447 		if (ret) {
4448 			/* w/a delay for certain panels */
4449 			apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4450 			amdgpu_dm_update_connector_after_detect(aconnector);
4451 
4452 			drm_modeset_lock_all(dev);
4453 			dm_restore_drm_connector_state(dev, connector);
4454 			drm_modeset_unlock_all(dev);
4455 
4456 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4457 				drm_kms_helper_connector_hotplug_event(connector);
4458 		}
4459 	}
4460 }
4461 
4462 static void handle_hpd_irq(void *param)
4463 {
4464 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4465 
4466 	handle_hpd_irq_helper(aconnector);
4467 
4468 }
4469 
4470 static void schedule_hpd_rx_offload_work(struct amdgpu_device *adev, struct hpd_rx_irq_offload_work_queue *offload_wq,
4471 							union hpd_irq_data hpd_irq_data)
4472 {
4473 	struct hpd_rx_irq_offload_work *offload_work = kzalloc_obj(*offload_work);
4474 
4475 	if (!offload_work) {
4476 		drm_err(adev_to_drm(adev), "Failed to allocate hpd_rx_irq_offload_work.\n");
4477 		return;
4478 	}
4479 
4480 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
4481 	offload_work->data = hpd_irq_data;
4482 	offload_work->offload_wq = offload_wq;
4483 	offload_work->adev = adev;
4484 
4485 	queue_work(offload_wq->wq, &offload_work->work);
4486 	drm_dbg_kms(adev_to_drm(adev), "queue work to handle hpd_rx offload work");
4487 }
4488 
4489 static void handle_hpd_rx_irq(void *param)
4490 {
4491 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4492 	struct drm_connector *connector = &aconnector->base;
4493 	struct drm_device *dev = connector->dev;
4494 	struct dc_link *dc_link = aconnector->dc_link;
4495 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
4496 	bool result = false;
4497 	enum dc_connection_type new_connection_type = dc_connection_none;
4498 	struct amdgpu_device *adev = drm_to_adev(dev);
4499 	union hpd_irq_data hpd_irq_data;
4500 	bool link_loss = false;
4501 	bool has_left_work = false;
4502 	int idx = dc_link->link_index;
4503 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
4504 	struct dc *dc = aconnector->dc_link->ctx->dc;
4505 
4506 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
4507 
4508 	if (adev->dm.disable_hpd_irq)
4509 		return;
4510 
4511 	/*
4512 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
4513 	 * conflict, after implement i2c helper, this mutex should be
4514 	 * retired.
4515 	 */
4516 	mutex_lock(&aconnector->hpd_lock);
4517 
4518 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
4519 						&link_loss, true, &has_left_work);
4520 
4521 	if (!has_left_work)
4522 		goto out;
4523 
4524 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
4525 		schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4526 		goto out;
4527 	}
4528 
4529 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
4530 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
4531 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
4532 			bool skip = false;
4533 
4534 			/*
4535 			 * DOWN_REP_MSG_RDY is also handled by polling method
4536 			 * mgr->cbs->poll_hpd_irq()
4537 			 */
4538 			spin_lock(&offload_wq->offload_lock);
4539 			skip = offload_wq->is_handling_mst_msg_rdy_event;
4540 
4541 			if (!skip)
4542 				offload_wq->is_handling_mst_msg_rdy_event = true;
4543 
4544 			spin_unlock(&offload_wq->offload_lock);
4545 
4546 			if (!skip)
4547 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4548 
4549 			goto out;
4550 		}
4551 
4552 		if (link_loss) {
4553 			bool skip = false;
4554 
4555 			spin_lock(&offload_wq->offload_lock);
4556 			skip = offload_wq->is_handling_link_loss;
4557 
4558 			if (!skip)
4559 				offload_wq->is_handling_link_loss = true;
4560 
4561 			spin_unlock(&offload_wq->offload_lock);
4562 
4563 			if (!skip)
4564 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4565 
4566 			goto out;
4567 		}
4568 	}
4569 
4570 out:
4571 	if (result && !is_mst_root_connector) {
4572 		/* Downstream Port status changed. */
4573 		if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
4574 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4575 
4576 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4577 			emulated_link_detect(dc_link);
4578 
4579 			if (aconnector->fake_enable)
4580 				aconnector->fake_enable = false;
4581 
4582 			amdgpu_dm_update_connector_after_detect(aconnector);
4583 
4584 
4585 			drm_modeset_lock_all(dev);
4586 			dm_restore_drm_connector_state(dev, connector);
4587 			drm_modeset_unlock_all(dev);
4588 
4589 			drm_kms_helper_connector_hotplug_event(connector);
4590 		} else {
4591 			bool ret = false;
4592 
4593 			mutex_lock(&adev->dm.dc_lock);
4594 			dc_exit_ips_for_hw_access(dc);
4595 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
4596 			mutex_unlock(&adev->dm.dc_lock);
4597 
4598 			if (ret) {
4599 				if (aconnector->fake_enable)
4600 					aconnector->fake_enable = false;
4601 
4602 				amdgpu_dm_update_connector_after_detect(aconnector);
4603 
4604 				drm_modeset_lock_all(dev);
4605 				dm_restore_drm_connector_state(dev, connector);
4606 				drm_modeset_unlock_all(dev);
4607 
4608 				drm_kms_helper_connector_hotplug_event(connector);
4609 			}
4610 		}
4611 	}
4612 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
4613 		if (adev->dm.hdcp_workqueue)
4614 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
4615 	}
4616 
4617 	if (dc_link->type != dc_connection_mst_branch)
4618 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
4619 
4620 	mutex_unlock(&aconnector->hpd_lock);
4621 }
4622 
4623 static int register_hpd_handlers(struct amdgpu_device *adev)
4624 {
4625 	struct drm_device *dev = adev_to_drm(adev);
4626 	struct drm_connector *connector;
4627 	struct amdgpu_dm_connector *aconnector;
4628 	const struct dc_link *dc_link;
4629 	struct dc_interrupt_params int_params = {0};
4630 
4631 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4632 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4633 
4634 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
4635 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD,
4636 			dmub_hpd_callback, true)) {
4637 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4638 			return -EINVAL;
4639 		}
4640 
4641 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ,
4642 			dmub_hpd_callback, true)) {
4643 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4644 			return -EINVAL;
4645 		}
4646 
4647 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_SENSE_NOTIFY,
4648 			dmub_hpd_sense_callback, true)) {
4649 			drm_err(adev_to_drm(adev), "fail to register dmub hpd sense callback");
4650 			return -EINVAL;
4651 		}
4652 	}
4653 
4654 	list_for_each_entry(connector,
4655 			&dev->mode_config.connector_list, head)	{
4656 
4657 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
4658 			continue;
4659 
4660 		aconnector = to_amdgpu_dm_connector(connector);
4661 		dc_link = aconnector->dc_link;
4662 
4663 		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
4664 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4665 			int_params.irq_source = dc_link->irq_source_hpd;
4666 
4667 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4668 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1 ||
4669 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6) {
4670 				drm_err(adev_to_drm(adev), "Failed to register hpd irq!\n");
4671 				return -EINVAL;
4672 			}
4673 
4674 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4675 				handle_hpd_irq, (void *) aconnector))
4676 				return -ENOMEM;
4677 		}
4678 
4679 		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
4680 
4681 			/* Also register for DP short pulse (hpd_rx). */
4682 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4683 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
4684 
4685 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4686 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1RX ||
4687 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6RX) {
4688 				drm_err(adev_to_drm(adev), "Failed to register hpd rx irq!\n");
4689 				return -EINVAL;
4690 			}
4691 
4692 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4693 				handle_hpd_rx_irq, (void *) aconnector))
4694 				return -ENOMEM;
4695 		}
4696 	}
4697 	return 0;
4698 }
4699 
4700 /* Register IRQ sources and initialize IRQ callbacks */
4701 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
4702 {
4703 	struct dc *dc = adev->dm.dc;
4704 	struct common_irq_params *c_irq_params;
4705 	struct dc_interrupt_params int_params = {0};
4706 	int r;
4707 	int i;
4708 	unsigned int src_id;
4709 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4710 	/* Use different interrupts for VBLANK on DCE 6 vs. newer. */
4711 	const unsigned int vblank_d1 =
4712 		adev->dm.dc->ctx->dce_version >= DCE_VERSION_8_0
4713 		? VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0 : 1;
4714 
4715 	if (adev->family >= AMDGPU_FAMILY_AI)
4716 		client_id = SOC15_IH_CLIENTID_DCE;
4717 
4718 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4719 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4720 
4721 	/*
4722 	 * Actions of amdgpu_irq_add_id():
4723 	 * 1. Register a set() function with base driver.
4724 	 *    Base driver will call set() function to enable/disable an
4725 	 *    interrupt in DC hardware.
4726 	 * 2. Register amdgpu_dm_irq_handler().
4727 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4728 	 *    coming from DC hardware.
4729 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4730 	 *    for acknowledging and handling.
4731 	 */
4732 
4733 	/* Use VBLANK interrupt */
4734 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
4735 		src_id = vblank_d1 + i;
4736 		r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->crtc_irq);
4737 		if (r) {
4738 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4739 			return r;
4740 		}
4741 
4742 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4743 		int_params.irq_source =
4744 			dc_interrupt_to_irq_source(dc, src_id, 0);
4745 
4746 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4747 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4748 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4749 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4750 			return -EINVAL;
4751 		}
4752 
4753 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4754 
4755 		c_irq_params->adev = adev;
4756 		c_irq_params->irq_src = int_params.irq_source;
4757 
4758 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4759 			dm_crtc_high_irq, c_irq_params))
4760 			return -ENOMEM;
4761 	}
4762 
4763 	if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
4764 		/* Use VUPDATE interrupt */
4765 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
4766 			src_id = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT + i * 2;
4767 			r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->vupdate_irq);
4768 			if (r) {
4769 				drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4770 				return r;
4771 			}
4772 
4773 			int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4774 			int_params.irq_source =
4775 				dc_interrupt_to_irq_source(dc, src_id, 0);
4776 
4777 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4778 				int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4779 				int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4780 				drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4781 				return -EINVAL;
4782 			}
4783 
4784 			c_irq_params = &adev->dm.vupdate_params[
4785 				int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4786 			c_irq_params->adev = adev;
4787 			c_irq_params->irq_src = int_params.irq_source;
4788 
4789 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4790 				dm_vupdate_high_irq, c_irq_params))
4791 				return -ENOMEM;
4792 		}
4793 	}
4794 
4795 	/* Use GRPH_PFLIP interrupt */
4796 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4797 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4798 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4799 		if (r) {
4800 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4801 			return r;
4802 		}
4803 
4804 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4805 		int_params.irq_source =
4806 			dc_interrupt_to_irq_source(dc, i, 0);
4807 
4808 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4809 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4810 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4811 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4812 			return -EINVAL;
4813 		}
4814 
4815 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4816 
4817 		c_irq_params->adev = adev;
4818 		c_irq_params->irq_src = int_params.irq_source;
4819 
4820 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4821 			dm_pflip_high_irq, c_irq_params))
4822 			return -ENOMEM;
4823 	}
4824 
4825 	/* HPD */
4826 	r = amdgpu_irq_add_id(adev, client_id,
4827 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4828 	if (r) {
4829 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4830 		return r;
4831 	}
4832 
4833 	r = register_hpd_handlers(adev);
4834 
4835 	return r;
4836 }
4837 
4838 /* Register IRQ sources and initialize IRQ callbacks */
4839 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
4840 {
4841 	struct dc *dc = adev->dm.dc;
4842 	struct common_irq_params *c_irq_params;
4843 	struct dc_interrupt_params int_params = {0};
4844 	int r;
4845 	int i;
4846 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4847 	static const unsigned int vrtl_int_srcid[] = {
4848 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
4849 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
4850 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
4851 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
4852 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
4853 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
4854 	};
4855 #endif
4856 
4857 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4858 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4859 
4860 	/*
4861 	 * Actions of amdgpu_irq_add_id():
4862 	 * 1. Register a set() function with base driver.
4863 	 *    Base driver will call set() function to enable/disable an
4864 	 *    interrupt in DC hardware.
4865 	 * 2. Register amdgpu_dm_irq_handler().
4866 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4867 	 *    coming from DC hardware.
4868 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4869 	 *    for acknowledging and handling.
4870 	 */
4871 
4872 	/* Use VSTARTUP interrupt */
4873 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
4874 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
4875 			i++) {
4876 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
4877 
4878 		if (r) {
4879 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4880 			return r;
4881 		}
4882 
4883 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4884 		int_params.irq_source =
4885 			dc_interrupt_to_irq_source(dc, i, 0);
4886 
4887 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4888 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4889 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4890 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4891 			return -EINVAL;
4892 		}
4893 
4894 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4895 
4896 		c_irq_params->adev = adev;
4897 		c_irq_params->irq_src = int_params.irq_source;
4898 
4899 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4900 			dm_crtc_high_irq, c_irq_params))
4901 			return -ENOMEM;
4902 	}
4903 
4904 	/* Use otg vertical line interrupt */
4905 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4906 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
4907 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
4908 				vrtl_int_srcid[i], &adev->vline0_irq);
4909 
4910 		if (r) {
4911 			drm_err(adev_to_drm(adev), "Failed to add vline0 irq id!\n");
4912 			return r;
4913 		}
4914 
4915 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4916 		int_params.irq_source =
4917 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
4918 
4919 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4920 			int_params.irq_source < DC_IRQ_SOURCE_DC1_VLINE0 ||
4921 			int_params.irq_source > DC_IRQ_SOURCE_DC6_VLINE0) {
4922 			drm_err(adev_to_drm(adev), "Failed to register vline0 irq!\n");
4923 			return -EINVAL;
4924 		}
4925 
4926 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
4927 					- DC_IRQ_SOURCE_DC1_VLINE0];
4928 
4929 		c_irq_params->adev = adev;
4930 		c_irq_params->irq_src = int_params.irq_source;
4931 
4932 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4933 			dm_dcn_vertical_interrupt0_high_irq,
4934 			c_irq_params))
4935 			return -ENOMEM;
4936 	}
4937 #endif
4938 
4939 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
4940 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
4941 	 * to trigger at end of each vblank, regardless of state of the lock,
4942 	 * matching DCE behaviour.
4943 	 */
4944 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
4945 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
4946 	     i++) {
4947 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
4948 
4949 		if (r) {
4950 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4951 			return r;
4952 		}
4953 
4954 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4955 		int_params.irq_source =
4956 			dc_interrupt_to_irq_source(dc, i, 0);
4957 
4958 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4959 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4960 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4961 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4962 			return -EINVAL;
4963 		}
4964 
4965 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4966 
4967 		c_irq_params->adev = adev;
4968 		c_irq_params->irq_src = int_params.irq_source;
4969 
4970 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4971 			dm_vupdate_high_irq, c_irq_params))
4972 			return -ENOMEM;
4973 	}
4974 
4975 	/* Use GRPH_PFLIP interrupt */
4976 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
4977 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
4978 			i++) {
4979 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
4980 		if (r) {
4981 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4982 			return r;
4983 		}
4984 
4985 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4986 		int_params.irq_source =
4987 			dc_interrupt_to_irq_source(dc, i, 0);
4988 
4989 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4990 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4991 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4992 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4993 			return -EINVAL;
4994 		}
4995 
4996 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4997 
4998 		c_irq_params->adev = adev;
4999 		c_irq_params->irq_src = int_params.irq_source;
5000 
5001 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
5002 			dm_pflip_high_irq, c_irq_params))
5003 			return -ENOMEM;
5004 	}
5005 
5006 	/* HPD */
5007 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
5008 			&adev->hpd_irq);
5009 	if (r) {
5010 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
5011 		return r;
5012 	}
5013 
5014 	r = register_hpd_handlers(adev);
5015 
5016 	return r;
5017 }
5018 /* Register Outbox IRQ sources and initialize IRQ callbacks */
5019 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
5020 {
5021 	struct dc *dc = adev->dm.dc;
5022 	struct common_irq_params *c_irq_params;
5023 	struct dc_interrupt_params int_params = {0};
5024 	int r, i;
5025 
5026 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
5027 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
5028 
5029 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
5030 			&adev->dmub_outbox_irq);
5031 	if (r) {
5032 		drm_err(adev_to_drm(adev), "Failed to add outbox irq id!\n");
5033 		return r;
5034 	}
5035 
5036 	if (dc->ctx->dmub_srv) {
5037 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
5038 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
5039 		int_params.irq_source =
5040 		dc_interrupt_to_irq_source(dc, i, 0);
5041 
5042 		c_irq_params = &adev->dm.dmub_outbox_params[0];
5043 
5044 		c_irq_params->adev = adev;
5045 		c_irq_params->irq_src = int_params.irq_source;
5046 
5047 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
5048 			dm_dmub_outbox1_low_irq, c_irq_params))
5049 			return -ENOMEM;
5050 	}
5051 
5052 	return 0;
5053 }
5054 
5055 /*
5056  * Acquires the lock for the atomic state object and returns
5057  * the new atomic state.
5058  *
5059  * This should only be called during atomic check.
5060  */
5061 int dm_atomic_get_state(struct drm_atomic_commit *state,
5062 			struct dm_atomic_state **dm_state)
5063 {
5064 	struct drm_device *dev = state->dev;
5065 	struct amdgpu_device *adev = drm_to_adev(dev);
5066 	struct amdgpu_display_manager *dm = &adev->dm;
5067 	struct drm_private_state *priv_state;
5068 
5069 	if (*dm_state)
5070 		return 0;
5071 
5072 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
5073 	if (IS_ERR(priv_state))
5074 		return PTR_ERR(priv_state);
5075 
5076 	*dm_state = to_dm_atomic_state(priv_state);
5077 
5078 	return 0;
5079 }
5080 
5081 static struct dm_atomic_state *
5082 dm_atomic_get_new_state(struct drm_atomic_commit *state)
5083 {
5084 	struct drm_device *dev = state->dev;
5085 	struct amdgpu_device *adev = drm_to_adev(dev);
5086 	struct amdgpu_display_manager *dm = &adev->dm;
5087 	struct drm_private_obj *obj;
5088 	struct drm_private_state *new_obj_state;
5089 	int i;
5090 
5091 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
5092 		if (obj->funcs == dm->atomic_obj.funcs)
5093 			return to_dm_atomic_state(new_obj_state);
5094 	}
5095 
5096 	return NULL;
5097 }
5098 
5099 static struct drm_private_state *
5100 dm_atomic_duplicate_state(struct drm_private_obj *obj)
5101 {
5102 	struct dm_atomic_state *old_state, *new_state;
5103 
5104 	new_state = kzalloc_obj(*new_state);
5105 	if (!new_state)
5106 		return NULL;
5107 
5108 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
5109 
5110 	old_state = to_dm_atomic_state(obj->state);
5111 
5112 	if (old_state && old_state->context)
5113 		new_state->context = dc_state_create_copy(old_state->context);
5114 
5115 	if (!new_state->context) {
5116 		kfree(new_state);
5117 		return NULL;
5118 	}
5119 
5120 	return &new_state->base;
5121 }
5122 
5123 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
5124 				    struct drm_private_state *state)
5125 {
5126 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
5127 
5128 	if (dm_state && dm_state->context)
5129 		dc_state_release(dm_state->context);
5130 
5131 	kfree(dm_state);
5132 }
5133 
5134 static struct drm_private_state *
5135 dm_atomic_create_state(struct drm_private_obj *obj)
5136 {
5137 	struct amdgpu_device *adev = drm_to_adev(obj->dev);
5138 	struct dm_atomic_state *dm_state;
5139 	struct dc_state *context;
5140 
5141 	dm_state = kzalloc_obj(*dm_state);
5142 	if (!dm_state)
5143 		return ERR_PTR(-ENOMEM);
5144 
5145 	context = dc_state_create_current_copy(adev->dm.dc);
5146 	if (!context) {
5147 		kfree(dm_state);
5148 		return ERR_PTR(-ENOMEM);
5149 	}
5150 
5151 	__drm_atomic_helper_private_obj_create_state(obj, &dm_state->base);
5152 	dm_state->context = context;
5153 
5154 	return &dm_state->base;
5155 }
5156 
5157 static struct drm_private_state_funcs dm_atomic_state_funcs = {
5158 	.atomic_create_state = dm_atomic_create_state,
5159 	.atomic_duplicate_state = dm_atomic_duplicate_state,
5160 	.atomic_destroy_state = dm_atomic_destroy_state,
5161 };
5162 
5163 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
5164 {
5165 	int r;
5166 
5167 	adev->mode_info.mode_config_initialized = true;
5168 
5169 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
5170 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
5171 
5172 	adev_to_drm(adev)->mode_config.max_width = 16384;
5173 	adev_to_drm(adev)->mode_config.max_height = 16384;
5174 
5175 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
5176 	if (adev->asic_type == CHIP_HAWAII)
5177 		/* disable prefer shadow for now due to hibernation issues */
5178 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
5179 	else
5180 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
5181 	/* indicates support for immediate flip */
5182 	adev_to_drm(adev)->mode_config.async_page_flip = true;
5183 
5184 	drm_atomic_private_obj_init(adev_to_drm(adev),
5185 				    &adev->dm.atomic_obj,
5186 				    &dm_atomic_state_funcs);
5187 
5188 	r = amdgpu_display_modeset_create_props(adev);
5189 	if (r)
5190 		return r;
5191 
5192 #ifdef AMD_PRIVATE_COLOR
5193 	if (amdgpu_dm_create_color_properties(adev))
5194 		return -ENOMEM;
5195 #endif
5196 
5197 	r = amdgpu_dm_audio_init(adev);
5198 	if (r)
5199 		return r;
5200 
5201 	return 0;
5202 }
5203 
5204 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
5205 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
5206 #define AMDGPU_DM_MIN_SPREAD ((AMDGPU_DM_DEFAULT_MAX_BACKLIGHT - AMDGPU_DM_DEFAULT_MIN_BACKLIGHT) / 2)
5207 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
5208 
5209 void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
5210 				     int bl_idx)
5211 {
5212 	struct amdgpu_dm_backlight_caps *caps = &dm->backlight_caps[bl_idx];
5213 
5214 	if (caps->caps_valid)
5215 		return;
5216 
5217 #if defined(CONFIG_ACPI)
5218 	amdgpu_acpi_get_backlight_caps(caps);
5219 
5220 	/* validate the firmware value is sane */
5221 	if (caps->caps_valid) {
5222 		int spread = caps->max_input_signal - caps->min_input_signal;
5223 
5224 		if (caps->max_input_signal > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5225 		    caps->min_input_signal < 0 ||
5226 		    spread > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5227 		    spread < AMDGPU_DM_MIN_SPREAD) {
5228 			drm_dbg_kms(adev_to_drm(dm->adev), "DM: Invalid backlight caps: min=%d, max=%d\n",
5229 				      caps->min_input_signal, caps->max_input_signal);
5230 			caps->caps_valid = false;
5231 		}
5232 	}
5233 
5234 	if (!caps->caps_valid) {
5235 		caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5236 		caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5237 		caps->caps_valid = true;
5238 	}
5239 #else
5240 	if (caps->aux_support)
5241 		return;
5242 
5243 	caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5244 	caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5245 	caps->caps_valid = true;
5246 #endif
5247 }
5248 
5249 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
5250 				unsigned int *min, unsigned int *max)
5251 {
5252 	if (!caps)
5253 		return 0;
5254 
5255 	if (caps->aux_support) {
5256 		// Firmware limits are in nits, DC API wants millinits.
5257 		*max = 1000 * caps->aux_max_input_signal;
5258 		*min = 1000 * caps->aux_min_input_signal;
5259 	} else {
5260 		// Firmware limits are 8-bit, PWM control is 16-bit.
5261 		*max = 0x101 * caps->max_input_signal;
5262 		*min = 0x101 * caps->min_input_signal;
5263 	}
5264 	return 1;
5265 }
5266 
5267 /* Rescale from [min..max] to [0..AMDGPU_MAX_BL_LEVEL] */
5268 static inline u32 scale_input_to_fw(int min, int max, u64 input)
5269 {
5270 	return DIV_ROUND_CLOSEST_ULL(input * AMDGPU_MAX_BL_LEVEL, max - min);
5271 }
5272 
5273 /* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [min..max] */
5274 static inline u32 scale_fw_to_input(int min, int max, u64 input)
5275 {
5276 	return min + DIV_ROUND_CLOSEST_ULL(input * (max - min), AMDGPU_MAX_BL_LEVEL);
5277 }
5278 
5279 static void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps,
5280 				      unsigned int min, unsigned int max,
5281 				      uint32_t *user_brightness)
5282 {
5283 	u32 brightness = scale_input_to_fw(min, max, *user_brightness);
5284 	u8 lower_signal, upper_signal, upper_lum, lower_lum, lum;
5285 	int left, right;
5286 
5287 	if (amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)
5288 		return;
5289 
5290 	if (!caps->data_points)
5291 		return;
5292 
5293 	/*
5294 	 * Handle the case where brightness is below the first data point
5295 	 * Interpolate between (0,0) and (first_signal, first_lum)
5296 	 */
5297 	if (brightness < caps->luminance_data[0].input_signal) {
5298 		lum = DIV_ROUND_CLOSEST(caps->luminance_data[0].luminance * brightness,
5299 					caps->luminance_data[0].input_signal);
5300 		goto scale;
5301 	}
5302 
5303 	left = 0;
5304 	right = caps->data_points - 1;
5305 	while (left <= right) {
5306 		int mid = left + (right - left) / 2;
5307 		u8 signal = caps->luminance_data[mid].input_signal;
5308 
5309 		/* Exact match found */
5310 		if (signal == brightness) {
5311 			lum = caps->luminance_data[mid].luminance;
5312 			goto scale;
5313 		}
5314 
5315 		if (signal < brightness)
5316 			left = mid + 1;
5317 		else
5318 			right = mid - 1;
5319 	}
5320 
5321 	/* verify bound */
5322 	if (left >= caps->data_points)
5323 		left = caps->data_points - 1;
5324 
5325 	/* At this point, left > right */
5326 	lower_signal = caps->luminance_data[right].input_signal;
5327 	upper_signal = caps->luminance_data[left].input_signal;
5328 	lower_lum = caps->luminance_data[right].luminance;
5329 	upper_lum = caps->luminance_data[left].luminance;
5330 
5331 	/* interpolate */
5332 	if (right == left || !lower_lum)
5333 		lum = upper_lum;
5334 	else
5335 		lum = lower_lum + DIV_ROUND_CLOSEST((upper_lum - lower_lum) *
5336 						    (brightness - lower_signal),
5337 						    upper_signal - lower_signal);
5338 scale:
5339 	*user_brightness = scale_fw_to_input(min, max,
5340 					     DIV_ROUND_CLOSEST(lum * brightness, 101));
5341 }
5342 
5343 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
5344 					uint32_t brightness)
5345 {
5346 	unsigned int min, max;
5347 
5348 	if (!get_brightness_range(caps, &min, &max))
5349 		return brightness;
5350 
5351 	convert_custom_brightness(caps, min, max, &brightness);
5352 
5353 	// Rescale 0..max to min..max
5354 	return min + DIV_ROUND_CLOSEST_ULL((u64)(max - min) * brightness, max);
5355 }
5356 
5357 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
5358 				      uint32_t brightness)
5359 {
5360 	unsigned int min, max;
5361 
5362 	if (!get_brightness_range(caps, &min, &max))
5363 		return brightness;
5364 
5365 	if (brightness < min)
5366 		return 0;
5367 	// Rescale min..max to 0..max
5368 	return DIV_ROUND_CLOSEST_ULL((u64)max * (brightness - min),
5369 				 max - min);
5370 }
5371 
5372 static struct dc_stream_state *dm_find_stream_with_link(
5373 	struct amdgpu_display_manager *dm,
5374 	struct dc_link *link)
5375 {
5376 	struct dc_state *cur_dc_state = dm->dc->current_state;
5377 	struct dc_stream_state *stream = NULL;
5378 	int i;
5379 
5380 	for (i = 0; i < cur_dc_state->stream_count; i++) {
5381 		stream = cur_dc_state->streams[i];
5382 		if (stream->link == link)
5383 			return stream;
5384 	}
5385 
5386 	return NULL;
5387 }
5388 
5389 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
5390 					 int bl_idx,
5391 					 u32 user_brightness)
5392 {
5393 	struct amdgpu_dm_backlight_caps *caps;
5394 	struct dc_link *link;
5395 	u32 brightness = 0;
5396 	bool rc = false, reallow_idle = false;
5397 	struct drm_connector *connector;
5398 	struct dc_stream_state *stream;
5399 	unsigned int min, max;
5400 
5401 	list_for_each_entry(connector, &dm->ddev->mode_config.connector_list, head) {
5402 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5403 
5404 		if (aconnector->bl_idx != bl_idx)
5405 			continue;
5406 
5407 		/* if connector is off, save the brightness for next time it's on */
5408 		if (!aconnector->base.encoder) {
5409 			dm->brightness[bl_idx] = user_brightness;
5410 			dm->actual_brightness[bl_idx] = 0;
5411 			return;
5412 		}
5413 	}
5414 
5415 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5416 	caps = &dm->backlight_caps[bl_idx];
5417 
5418 	dm->brightness[bl_idx] = user_brightness;
5419 	/* update scratch register */
5420 	if (bl_idx == 0)
5421 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
5422 	brightness = convert_brightness_from_user(caps, dm->brightness[bl_idx]);
5423 	link = (struct dc_link *)dm->backlight_link[bl_idx];
5424 
5425 	/* Apply brightness quirk */
5426 	if (caps->brightness_mask)
5427 		brightness |= caps->brightness_mask;
5428 
5429 	if (trace_amdgpu_dm_brightness_enabled()) {
5430 		trace_amdgpu_dm_brightness(__builtin_return_address(0),
5431 					   user_brightness,
5432 					   brightness,
5433 					   caps->aux_support,
5434 					   power_supply_is_system_supplied() > 0);
5435 	}
5436 
5437 	stream = dm_find_stream_with_link(dm, link);
5438 	if (!stream)
5439 		return;
5440 
5441 	mutex_lock(&dm->dc_lock);
5442 	if (dm->dc->caps.ips_support && dm->dc->ctx->dmub_srv->idle_allowed) {
5443 		dc_allow_idle_optimizations(dm->dc, false);
5444 		reallow_idle = true;
5445 	}
5446 
5447 	if (caps->aux_support) {
5448 		rc = mod_power_set_backlight_nits(dm->power_module, stream, brightness,
5449 			AUX_BL_DEFAULT_TRANSITION_TIME_MS, false, true);
5450 	} else {
5451 		/* power module uses millipercent */
5452 		get_brightness_range(caps, &min, &max);
5453 		brightness = DIV_ROUND_CLOSEST(brightness * 100, (max - min)) * 1000;
5454 		rc = mod_power_set_backlight_percent(dm->power_module, stream,
5455 						     brightness, 0, false);
5456 	}
5457 
5458 	/*
5459 	 * Some kms clients create a ramped backlight transition effect
5460 	 * by rapidly changing the backlight. Yet we must wait on dmcub
5461 	 * fw to exit psr/replay before programming backlight. To
5462 	 * prevent lag, keep disable psr/replay and let the next atomic
5463 	 * flip clear the event.
5464 	 *
5465 	 * ToDo: use ISM to handle rapidly backlight change
5466 	 *
5467 	 * Rapidly backlight change is similar to rapidly cursor events,
5468 	 * which is now handled by ISM. ISM can delay the event until system
5469 	 * is really idle, so we may use ISM to handle backlight change as well.
5470 	 */
5471 	amdgpu_dm_psr_set_event(dm, stream, true,
5472 		psr_event_hw_programming, true);
5473 	amdgpu_dm_replay_set_event(dm, stream, true,
5474 		replay_event_hw_programming, true);
5475 
5476 	if (dm->dc->caps.ips_support && reallow_idle)
5477 		dc_allow_idle_optimizations(dm->dc, true);
5478 
5479 	mutex_unlock(&dm->dc_lock);
5480 
5481 	if (rc)
5482 		dm->actual_brightness[bl_idx] = user_brightness;
5483 }
5484 
5485 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
5486 {
5487 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5488 	int i;
5489 
5490 	for (i = 0; i < dm->num_of_edps; i++) {
5491 		if (bd == dm->backlight_dev[i])
5492 			break;
5493 	}
5494 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5495 		i = 0;
5496 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
5497 
5498 	return 0;
5499 }
5500 
5501 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
5502 					 int bl_idx)
5503 {
5504 	int ret;
5505 	struct amdgpu_dm_backlight_caps caps;
5506 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
5507 
5508 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5509 	caps = dm->backlight_caps[bl_idx];
5510 
5511 	if (caps.aux_support) {
5512 		u32 avg, peak;
5513 
5514 		if (!dc_link_get_backlight_level_nits(link, &avg, &peak))
5515 			return dm->brightness[bl_idx];
5516 		return convert_brightness_to_user(&caps, avg);
5517 	}
5518 
5519 	ret = dc_link_get_backlight_level(link);
5520 
5521 	if (ret == DC_ERROR_UNEXPECTED)
5522 		return dm->brightness[bl_idx];
5523 
5524 	return convert_brightness_to_user(&caps, ret);
5525 }
5526 
5527 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
5528 {
5529 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5530 	int i;
5531 
5532 	for (i = 0; i < dm->num_of_edps; i++) {
5533 		if (bd == dm->backlight_dev[i])
5534 			break;
5535 	}
5536 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5537 		i = 0;
5538 	return amdgpu_dm_backlight_get_level(dm, i);
5539 }
5540 
5541 static const struct backlight_ops amdgpu_dm_backlight_ops = {
5542 	.options = BL_CORE_SUSPENDRESUME,
5543 	.get_brightness = amdgpu_dm_backlight_get_brightness,
5544 	.update_status	= amdgpu_dm_backlight_update_status,
5545 };
5546 
5547 static void
5548 amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector *aconnector)
5549 {
5550 	struct drm_device *drm = aconnector->base.dev;
5551 	struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
5552 	struct backlight_properties props = { 0 };
5553 	struct amdgpu_dm_backlight_caps *caps;
5554 	char bl_name[16];
5555 	int min, max;
5556 	int real_brightness;
5557 	int init_brightness;
5558 
5559 	if (aconnector->bl_idx == -1)
5560 		return;
5561 
5562 	if (!acpi_video_backlight_use_native()) {
5563 		drm_info(drm, "Skipping amdgpu DM backlight registration\n");
5564 		/* Try registering an ACPI video backlight device instead. */
5565 		acpi_video_register_backlight();
5566 		return;
5567 	}
5568 
5569 	caps = &dm->backlight_caps[aconnector->bl_idx];
5570 	if (get_brightness_range(caps, &min, &max)) {
5571 		if (power_supply_is_system_supplied() > 0)
5572 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->ac_level, 100);
5573 		else
5574 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->dc_level, 100);
5575 		/* min is zero, so max needs to be adjusted */
5576 		props.max_brightness = max - min;
5577 		drm_dbg(drm, "Backlight caps: min: %d, max: %d, ac %d, dc %d\n", min, max,
5578 			caps->ac_level, caps->dc_level);
5579 	} else
5580 		props.brightness = props.max_brightness = MAX_BACKLIGHT_LEVEL;
5581 
5582 	init_brightness = props.brightness;
5583 
5584 	if (caps->data_points && !(amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)) {
5585 		drm_info(drm, "Using custom brightness curve\n");
5586 		props.scale = BACKLIGHT_SCALE_NON_LINEAR;
5587 	} else
5588 		props.scale = BACKLIGHT_SCALE_LINEAR;
5589 	props.type = BACKLIGHT_RAW;
5590 
5591 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
5592 		 drm->primary->index + aconnector->bl_idx);
5593 
5594 	dm->backlight_dev[aconnector->bl_idx] =
5595 		backlight_device_register(bl_name, aconnector->base.kdev, dm,
5596 					  &amdgpu_dm_backlight_ops, &props);
5597 	dm->brightness[aconnector->bl_idx] = props.brightness;
5598 
5599 	if (IS_ERR(dm->backlight_dev[aconnector->bl_idx])) {
5600 		drm_err(drm, "DM: Backlight registration failed!\n");
5601 		dm->backlight_dev[aconnector->bl_idx] = NULL;
5602 	} else {
5603 		/*
5604 		 * dm->brightness[x] can be inconsistent just after startup until
5605 		 * ops.get_brightness is called.
5606 		 */
5607 		real_brightness =
5608 			amdgpu_dm_backlight_ops.get_brightness(dm->backlight_dev[aconnector->bl_idx]);
5609 
5610 		if (real_brightness != init_brightness) {
5611 			dm->actual_brightness[aconnector->bl_idx] = real_brightness;
5612 			dm->brightness[aconnector->bl_idx] = real_brightness;
5613 		}
5614 		drm_dbg_driver(drm, "DM: Registered Backlight device: %s\n", bl_name);
5615 	}
5616 }
5617 
5618 static int initialize_plane(struct amdgpu_display_manager *dm,
5619 			    struct amdgpu_mode_info *mode_info, int plane_id,
5620 			    enum drm_plane_type plane_type,
5621 			    const struct dc_plane_cap *plane_cap)
5622 {
5623 	struct drm_plane *plane;
5624 	unsigned long possible_crtcs;
5625 	int ret = 0;
5626 
5627 	plane = kzalloc_obj(struct drm_plane);
5628 	if (!plane) {
5629 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
5630 		return -ENOMEM;
5631 	}
5632 	plane->type = plane_type;
5633 
5634 	/*
5635 	 * HACK: IGT tests expect that the primary plane for a CRTC
5636 	 * can only have one possible CRTC. Only expose support for
5637 	 * any CRTC if they're not going to be used as a primary plane
5638 	 * for a CRTC - like overlay or underlay planes.
5639 	 */
5640 	possible_crtcs = 1 << plane_id;
5641 	if (plane_id >= dm->dc->caps.max_streams)
5642 		possible_crtcs = 0xff;
5643 
5644 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
5645 
5646 	if (ret) {
5647 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
5648 		kfree(plane);
5649 		return ret;
5650 	}
5651 
5652 	if (mode_info)
5653 		mode_info->planes[plane_id] = plane;
5654 
5655 	return ret;
5656 }
5657 
5658 
5659 static void setup_backlight_device(struct amdgpu_display_manager *dm,
5660 				   struct amdgpu_dm_connector *aconnector)
5661 {
5662 	struct amdgpu_dm_backlight_caps *caps;
5663 	struct dc_link *link = aconnector->dc_link;
5664 	int bl_idx = dm->num_of_edps;
5665 
5666 	if (!(link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) ||
5667 	    link->type == dc_connection_none)
5668 		return;
5669 
5670 	if (dm->num_of_edps >= AMDGPU_DM_MAX_NUM_EDP) {
5671 		drm_warn(adev_to_drm(dm->adev), "Too much eDP connections, skipping backlight setup for additional eDPs\n");
5672 		return;
5673 	}
5674 
5675 	aconnector->bl_idx = bl_idx;
5676 
5677 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5678 	dm->backlight_link[bl_idx] = link;
5679 	dm->num_of_edps++;
5680 
5681 	update_connector_ext_caps(aconnector);
5682 	caps = &dm->backlight_caps[aconnector->bl_idx];
5683 
5684 	/* Only offer ABM property when non-OLED and user didn't turn off by module parameter */
5685 	if (caps->ext_caps && !caps->ext_caps->bits.oled && amdgpu_dm_abm_level < 0)
5686 		drm_object_attach_property(&aconnector->base.base,
5687 					   dm->adev->mode_info.abm_level_property,
5688 					   ABM_SYSFS_CONTROL);
5689 }
5690 
5691 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
5692 
5693 
5694 
5695 /*
5696  * In this architecture, the association
5697  * connector -> encoder -> crtc
5698  * id not really requried. The crtc and connector will hold the
5699  * display_index as an abstraction to use with DAL component
5700  *
5701  * Returns 0 on success
5702  */
5703 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
5704 {
5705 	struct amdgpu_display_manager *dm = &adev->dm;
5706 	s32 i;
5707 	struct amdgpu_dm_connector *aconnector = NULL;
5708 	struct amdgpu_encoder *aencoder = NULL;
5709 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5710 	u32 link_cnt;
5711 	s32 primary_planes;
5712 	enum dc_connection_type new_connection_type = dc_connection_none;
5713 	const struct dc_plane_cap *plane;
5714 	bool psr_feature_enabled = false;
5715 	bool replay_feature_enabled = false;
5716 	int max_overlay = dm->dc->caps.max_slave_planes;
5717 
5718 	dm->display_indexes_num = dm->dc->caps.max_streams;
5719 	/* Update the actual used number of crtc */
5720 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
5721 
5722 	amdgpu_dm_set_irq_funcs(adev);
5723 
5724 	link_cnt = dm->dc->caps.max_links;
5725 	if (amdgpu_dm_mode_config_init(dm->adev)) {
5726 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
5727 		return -EINVAL;
5728 	}
5729 
5730 	/* There is one primary plane per CRTC */
5731 	primary_planes = dm->dc->caps.max_streams;
5732 	if (primary_planes > AMDGPU_MAX_PLANES) {
5733 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
5734 		return -EINVAL;
5735 	}
5736 
5737 	/*
5738 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
5739 	 * Order is reversed to match iteration order in atomic check.
5740 	 */
5741 	for (i = (primary_planes - 1); i >= 0; i--) {
5742 		plane = &dm->dc->caps.planes[i];
5743 
5744 		if (initialize_plane(dm, mode_info, i,
5745 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
5746 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
5747 			goto fail;
5748 		}
5749 	}
5750 
5751 	/*
5752 	 * Initialize overlay planes, index starting after primary planes.
5753 	 * These planes have a higher DRM index than the primary planes since
5754 	 * they should be considered as having a higher z-order.
5755 	 * Order is reversed to match iteration order in atomic check.
5756 	 *
5757 	 * Only support DCN for now, and only expose one so we don't encourage
5758 	 * userspace to use up all the pipes.
5759 	 */
5760 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
5761 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
5762 
5763 		/* Do not create overlay if MPO disabled */
5764 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
5765 			break;
5766 
5767 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
5768 			continue;
5769 
5770 		if (!plane->pixel_format_support.argb8888)
5771 			continue;
5772 
5773 		if (max_overlay-- == 0)
5774 			break;
5775 
5776 		if (initialize_plane(dm, NULL, primary_planes + i,
5777 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
5778 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
5779 			goto fail;
5780 		}
5781 	}
5782 
5783 	for (i = 0; i < dm->dc->caps.max_streams; i++)
5784 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
5785 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
5786 			goto fail;
5787 		}
5788 
5789 	/* Use Outbox interrupt */
5790 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5791 	case IP_VERSION(3, 0, 0):
5792 	case IP_VERSION(3, 1, 2):
5793 	case IP_VERSION(3, 1, 3):
5794 	case IP_VERSION(3, 1, 4):
5795 	case IP_VERSION(3, 1, 5):
5796 	case IP_VERSION(3, 1, 6):
5797 	case IP_VERSION(3, 2, 0):
5798 	case IP_VERSION(3, 2, 1):
5799 	case IP_VERSION(2, 1, 0):
5800 	case IP_VERSION(3, 5, 0):
5801 	case IP_VERSION(3, 5, 1):
5802 	case IP_VERSION(3, 6, 0):
5803 	case IP_VERSION(4, 0, 1):
5804 	case IP_VERSION(4, 2, 0):
5805 	case IP_VERSION(4, 2, 1):
5806 		if (register_outbox_irq_handlers(dm->adev)) {
5807 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5808 			goto fail;
5809 		}
5810 		break;
5811 	default:
5812 		drm_dbg_kms(adev_to_drm(adev), "Unsupported DCN IP version for outbox: 0x%X\n",
5813 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
5814 	}
5815 
5816 	/* Determine whether to enable PSR support by default. */
5817 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
5818 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5819 		case IP_VERSION(3, 1, 2):
5820 		case IP_VERSION(3, 1, 3):
5821 		case IP_VERSION(3, 1, 4):
5822 		case IP_VERSION(3, 1, 5):
5823 		case IP_VERSION(3, 1, 6):
5824 		case IP_VERSION(3, 2, 0):
5825 		case IP_VERSION(3, 2, 1):
5826 		case IP_VERSION(3, 5, 0):
5827 		case IP_VERSION(3, 5, 1):
5828 		case IP_VERSION(3, 6, 0):
5829 		case IP_VERSION(4, 0, 1):
5830 		case IP_VERSION(4, 2, 0):
5831 		case IP_VERSION(4, 2, 1):
5832 			psr_feature_enabled = true;
5833 			break;
5834 		default:
5835 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
5836 			break;
5837 		}
5838 	}
5839 
5840 	/* Determine whether to enable Replay support by default. */
5841 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
5842 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5843 		case IP_VERSION(3, 1, 4):
5844 		case IP_VERSION(3, 2, 0):
5845 		case IP_VERSION(3, 2, 1):
5846 		case IP_VERSION(3, 5, 0):
5847 		case IP_VERSION(3, 5, 1):
5848 		case IP_VERSION(3, 6, 0):
5849 		case IP_VERSION(4, 2, 0):
5850 		case IP_VERSION(4, 2, 1):
5851 			replay_feature_enabled = true;
5852 			break;
5853 
5854 		default:
5855 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
5856 			break;
5857 		}
5858 	}
5859 
5860 	if (link_cnt > MAX_LINKS) {
5861 		drm_err(adev_to_drm(adev),
5862 			"KMS: Cannot support more than %d display indexes\n",
5863 				MAX_LINKS);
5864 		goto fail;
5865 	}
5866 
5867 	/* loops over all connectors on the board */
5868 	for (i = 0; i < link_cnt; i++) {
5869 		struct dc_link *link = NULL;
5870 
5871 		link = dc_get_link_at_index(dm->dc, i);
5872 
5873 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
5874 			struct amdgpu_dm_wb_connector *wbcon = kzalloc_obj(*wbcon);
5875 
5876 			if (!wbcon) {
5877 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
5878 				continue;
5879 			}
5880 
5881 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
5882 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
5883 				kfree(wbcon);
5884 				continue;
5885 			}
5886 
5887 			link->psr_settings.psr_feature_enabled = false;
5888 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
5889 
5890 			continue;
5891 		}
5892 
5893 		aconnector = kzalloc_obj(*aconnector);
5894 		if (!aconnector)
5895 			goto fail;
5896 
5897 		aencoder = kzalloc_obj(*aencoder);
5898 		if (!aencoder)
5899 			goto fail;
5900 
5901 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
5902 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
5903 			goto fail;
5904 		}
5905 
5906 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
5907 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
5908 			goto fail;
5909 		}
5910 
5911 		if (dm->hpd_rx_offload_wq)
5912 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
5913 				aconnector;
5914 
5915 		if (!dc_link_detect_connection_type(link, &new_connection_type))
5916 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
5917 
5918 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
5919 			emulated_link_detect(link);
5920 			amdgpu_dm_update_connector_after_detect(aconnector);
5921 		} else {
5922 			bool ret = false;
5923 
5924 			mutex_lock(&dm->dc_lock);
5925 			dc_exit_ips_for_hw_access(dm->dc);
5926 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
5927 			mutex_unlock(&dm->dc_lock);
5928 
5929 			if (ret) {
5930 				amdgpu_dm_update_connector_after_detect(aconnector);
5931 				setup_backlight_device(dm, aconnector);
5932 
5933 				/* Disable PSR if Replay can be enabled */
5934 				if (replay_feature_enabled)
5935 					if (amdgpu_dm_set_replay_caps(link, aconnector))
5936 						psr_feature_enabled = false;
5937 
5938 				if (psr_feature_enabled) {
5939 					amdgpu_dm_set_psr_caps(link, aconnector);
5940 					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",
5941 						 aconnector->base.name,
5942 						 link->psr_settings.psr_feature_enabled,
5943 						 link->psr_settings.psr_version,
5944 						 link->dpcd_caps.psr_info.psr_version,
5945 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
5946 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
5947 				}
5948 			}
5949 		}
5950 		amdgpu_set_panel_orientation(&aconnector->base);
5951 	}
5952 
5953 	/* Debug dump: list all DC links and their associated sinks after detection
5954 	 * is complete for all connectors. This provides a comprehensive view of the
5955 	 * final state without repeating the dump for each connector.
5956 	 */
5957 	amdgpu_dm_dump_links_and_sinks(adev);
5958 
5959 	/* Software is initialized. Now we can register interrupt handlers. */
5960 	switch (adev->asic_type) {
5961 #if defined(CONFIG_DRM_AMD_DC_SI)
5962 	case CHIP_TAHITI:
5963 	case CHIP_PITCAIRN:
5964 	case CHIP_VERDE:
5965 	case CHIP_OLAND:
5966 #endif
5967 	case CHIP_BONAIRE:
5968 	case CHIP_HAWAII:
5969 	case CHIP_KAVERI:
5970 	case CHIP_KABINI:
5971 	case CHIP_MULLINS:
5972 	case CHIP_TONGA:
5973 	case CHIP_FIJI:
5974 	case CHIP_CARRIZO:
5975 	case CHIP_STONEY:
5976 	case CHIP_POLARIS11:
5977 	case CHIP_POLARIS10:
5978 	case CHIP_POLARIS12:
5979 	case CHIP_VEGAM:
5980 	case CHIP_VEGA10:
5981 	case CHIP_VEGA12:
5982 	case CHIP_VEGA20:
5983 		if (dce110_register_irq_handlers(dm->adev)) {
5984 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5985 			goto fail;
5986 		}
5987 		break;
5988 	default:
5989 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5990 		case IP_VERSION(1, 0, 0):
5991 		case IP_VERSION(1, 0, 1):
5992 		case IP_VERSION(2, 0, 2):
5993 		case IP_VERSION(2, 0, 3):
5994 		case IP_VERSION(2, 0, 0):
5995 		case IP_VERSION(2, 1, 0):
5996 		case IP_VERSION(3, 0, 0):
5997 		case IP_VERSION(3, 0, 2):
5998 		case IP_VERSION(3, 0, 3):
5999 		case IP_VERSION(3, 0, 1):
6000 		case IP_VERSION(3, 1, 2):
6001 		case IP_VERSION(3, 1, 3):
6002 		case IP_VERSION(3, 1, 4):
6003 		case IP_VERSION(3, 1, 5):
6004 		case IP_VERSION(3, 1, 6):
6005 		case IP_VERSION(3, 2, 0):
6006 		case IP_VERSION(3, 2, 1):
6007 		case IP_VERSION(3, 5, 0):
6008 		case IP_VERSION(3, 5, 1):
6009 		case IP_VERSION(3, 6, 0):
6010 		case IP_VERSION(4, 0, 1):
6011 		case IP_VERSION(4, 2, 0):
6012 		case IP_VERSION(4, 2, 1):
6013 			if (dcn10_register_irq_handlers(dm->adev)) {
6014 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
6015 				goto fail;
6016 			}
6017 			break;
6018 		default:
6019 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
6020 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6021 			goto fail;
6022 		}
6023 		break;
6024 	}
6025 
6026 	return 0;
6027 fail:
6028 	kfree(aencoder);
6029 	kfree(aconnector);
6030 
6031 	return -EINVAL;
6032 }
6033 
6034 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
6035 {
6036 	if (dm->atomic_obj.state)
6037 		drm_atomic_private_obj_fini(&dm->atomic_obj);
6038 }
6039 
6040 /******************************************************************************
6041  * amdgpu_display_funcs functions
6042  *****************************************************************************/
6043 
6044 /*
6045  * dm_bandwidth_update - program display watermarks
6046  *
6047  * @adev: amdgpu_device pointer
6048  *
6049  * Calculate and program the display watermarks and line buffer allocation.
6050  */
6051 static void dm_bandwidth_update(struct amdgpu_device *adev)
6052 {
6053 	/* TODO: implement later */
6054 }
6055 
6056 static const struct amdgpu_display_funcs dm_display_funcs = {
6057 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
6058 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
6059 	.backlight_set_level = NULL, /* never called for DC */
6060 	.backlight_get_level = NULL, /* never called for DC */
6061 	.hpd_sense = NULL,/* called unconditionally */
6062 	.hpd_set_polarity = NULL, /* called unconditionally */
6063 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
6064 	.page_flip_get_scanoutpos =
6065 		dm_crtc_get_scanoutpos,/* called unconditionally */
6066 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
6067 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
6068 };
6069 
6070 #if defined(CONFIG_DEBUG_KERNEL_DC)
6071 
6072 static ssize_t s3_debug_store(struct device *device,
6073 			      struct device_attribute *attr,
6074 			      const char *buf,
6075 			      size_t count)
6076 {
6077 	int ret;
6078 	int s3_state;
6079 	struct drm_device *drm_dev = dev_get_drvdata(device);
6080 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
6081 	struct amdgpu_ip_block *ip_block;
6082 
6083 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
6084 	if (!ip_block)
6085 		return -EINVAL;
6086 
6087 	ret = kstrtoint(buf, 0, &s3_state);
6088 
6089 	if (ret == 0) {
6090 		if (s3_state) {
6091 			dm_resume(ip_block);
6092 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
6093 		} else
6094 			dm_suspend(ip_block);
6095 	}
6096 
6097 	return ret == 0 ? count : 0;
6098 }
6099 
6100 DEVICE_ATTR_WO(s3_debug);
6101 
6102 #endif
6103 
6104 static int dm_init_microcode(struct amdgpu_device *adev)
6105 {
6106 	char *fw_name_dmub;
6107 	int r;
6108 
6109 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6110 	case IP_VERSION(2, 1, 0):
6111 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
6112 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
6113 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
6114 		break;
6115 	case IP_VERSION(3, 0, 0):
6116 		if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(10, 3, 0))
6117 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
6118 		else
6119 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
6120 		break;
6121 	case IP_VERSION(3, 0, 1):
6122 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
6123 		break;
6124 	case IP_VERSION(3, 0, 2):
6125 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
6126 		break;
6127 	case IP_VERSION(3, 0, 3):
6128 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
6129 		break;
6130 	case IP_VERSION(3, 1, 2):
6131 	case IP_VERSION(3, 1, 3):
6132 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
6133 		break;
6134 	case IP_VERSION(3, 1, 4):
6135 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
6136 		break;
6137 	case IP_VERSION(3, 1, 5):
6138 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
6139 		break;
6140 	case IP_VERSION(3, 1, 6):
6141 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
6142 		break;
6143 	case IP_VERSION(3, 2, 0):
6144 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
6145 		break;
6146 	case IP_VERSION(3, 2, 1):
6147 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
6148 		break;
6149 	case IP_VERSION(3, 5, 0):
6150 		fw_name_dmub = FIRMWARE_DCN_35_DMUB;
6151 		break;
6152 	case IP_VERSION(3, 5, 1):
6153 		fw_name_dmub = FIRMWARE_DCN_351_DMUB;
6154 		break;
6155 	case IP_VERSION(3, 6, 0):
6156 		fw_name_dmub = FIRMWARE_DCN_36_DMUB;
6157 		break;
6158 	case IP_VERSION(4, 0, 1):
6159 		fw_name_dmub = FIRMWARE_DCN_401_DMUB;
6160 		break;
6161 	case IP_VERSION(4, 2, 0):
6162 		fw_name_dmub = FIRMWARE_DCN_42_DMUB;
6163 		break;
6164 	case IP_VERSION(4, 2, 1):
6165 		fw_name_dmub = FIRMWARE_DCN_42B_DMUB;
6166 		break;
6167 	default:
6168 		/* ASIC doesn't support DMUB. */
6169 		return 0;
6170 	}
6171 	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, AMDGPU_UCODE_REQUIRED,
6172 				 "%s", fw_name_dmub);
6173 	return r;
6174 }
6175 
6176 static int dm_early_init(struct amdgpu_ip_block *ip_block)
6177 {
6178 	struct amdgpu_device *adev = ip_block->adev;
6179 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
6180 	struct atom_context *ctx = mode_info->atom_context;
6181 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
6182 	u16 data_offset;
6183 
6184 	/* if there is no object header, skip DM */
6185 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
6186 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
6187 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
6188 		return -ENOENT;
6189 	}
6190 
6191 	switch (adev->asic_type) {
6192 #if defined(CONFIG_DRM_AMD_DC_SI)
6193 	case CHIP_TAHITI:
6194 	case CHIP_PITCAIRN:
6195 	case CHIP_VERDE:
6196 		adev->mode_info.num_crtc = 6;
6197 		adev->mode_info.num_hpd = 6;
6198 		adev->mode_info.num_dig = 6;
6199 		break;
6200 	case CHIP_OLAND:
6201 		adev->mode_info.num_crtc = 2;
6202 		adev->mode_info.num_hpd = 2;
6203 		adev->mode_info.num_dig = 2;
6204 		break;
6205 #endif
6206 	case CHIP_BONAIRE:
6207 	case CHIP_HAWAII:
6208 		adev->mode_info.num_crtc = 6;
6209 		adev->mode_info.num_hpd = 6;
6210 		adev->mode_info.num_dig = 6;
6211 		break;
6212 	case CHIP_KAVERI:
6213 		adev->mode_info.num_crtc = 4;
6214 		adev->mode_info.num_hpd = 6;
6215 		adev->mode_info.num_dig = 7;
6216 		break;
6217 	case CHIP_KABINI:
6218 	case CHIP_MULLINS:
6219 		adev->mode_info.num_crtc = 2;
6220 		adev->mode_info.num_hpd = 6;
6221 		adev->mode_info.num_dig = 6;
6222 		break;
6223 	case CHIP_FIJI:
6224 	case CHIP_TONGA:
6225 		adev->mode_info.num_crtc = 6;
6226 		adev->mode_info.num_hpd = 6;
6227 		adev->mode_info.num_dig = 7;
6228 		break;
6229 	case CHIP_CARRIZO:
6230 		adev->mode_info.num_crtc = 3;
6231 		adev->mode_info.num_hpd = 6;
6232 		adev->mode_info.num_dig = 9;
6233 		break;
6234 	case CHIP_STONEY:
6235 		adev->mode_info.num_crtc = 2;
6236 		adev->mode_info.num_hpd = 6;
6237 		adev->mode_info.num_dig = 9;
6238 		break;
6239 	case CHIP_POLARIS11:
6240 	case CHIP_POLARIS12:
6241 		adev->mode_info.num_crtc = 5;
6242 		adev->mode_info.num_hpd = 5;
6243 		adev->mode_info.num_dig = 5;
6244 		break;
6245 	case CHIP_POLARIS10:
6246 	case CHIP_VEGAM:
6247 		adev->mode_info.num_crtc = 6;
6248 		adev->mode_info.num_hpd = 6;
6249 		adev->mode_info.num_dig = 6;
6250 		break;
6251 	case CHIP_VEGA10:
6252 	case CHIP_VEGA12:
6253 	case CHIP_VEGA20:
6254 		adev->mode_info.num_crtc = 6;
6255 		adev->mode_info.num_hpd = 6;
6256 		adev->mode_info.num_dig = 6;
6257 		break;
6258 	default:
6259 
6260 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6261 		case IP_VERSION(2, 0, 2):
6262 		case IP_VERSION(3, 0, 0):
6263 			adev->mode_info.num_crtc = 6;
6264 			adev->mode_info.num_hpd = 6;
6265 			adev->mode_info.num_dig = 6;
6266 			break;
6267 		case IP_VERSION(2, 0, 0):
6268 		case IP_VERSION(3, 0, 2):
6269 			adev->mode_info.num_crtc = 5;
6270 			adev->mode_info.num_hpd = 5;
6271 			adev->mode_info.num_dig = 5;
6272 			break;
6273 		case IP_VERSION(2, 0, 3):
6274 		case IP_VERSION(3, 0, 3):
6275 			adev->mode_info.num_crtc = 2;
6276 			adev->mode_info.num_hpd = 2;
6277 			adev->mode_info.num_dig = 2;
6278 			break;
6279 		case IP_VERSION(1, 0, 0):
6280 		case IP_VERSION(1, 0, 1):
6281 		case IP_VERSION(3, 0, 1):
6282 		case IP_VERSION(2, 1, 0):
6283 		case IP_VERSION(3, 1, 2):
6284 		case IP_VERSION(3, 1, 3):
6285 		case IP_VERSION(3, 1, 4):
6286 		case IP_VERSION(3, 1, 5):
6287 		case IP_VERSION(3, 1, 6):
6288 		case IP_VERSION(3, 2, 0):
6289 		case IP_VERSION(3, 2, 1):
6290 		case IP_VERSION(3, 5, 0):
6291 		case IP_VERSION(3, 5, 1):
6292 		case IP_VERSION(3, 6, 0):
6293 		case IP_VERSION(4, 0, 1):
6294 		case IP_VERSION(4, 2, 0):
6295 		case IP_VERSION(4, 2, 1):
6296 			adev->mode_info.num_crtc = 4;
6297 			adev->mode_info.num_hpd = 4;
6298 			adev->mode_info.num_dig = 4;
6299 			break;
6300 		default:
6301 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
6302 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6303 			return -EINVAL;
6304 		}
6305 		break;
6306 	}
6307 
6308 	if (adev->mode_info.funcs == NULL)
6309 		adev->mode_info.funcs = &dm_display_funcs;
6310 
6311 	/*
6312 	 * Note: Do NOT change adev->reg.audio_endpt.rreg and
6313 	 * adev->reg.audio_endpt.wreg because they are initialised in
6314 	 * amdgpu_device_init()
6315 	 */
6316 #if defined(CONFIG_DEBUG_KERNEL_DC)
6317 	device_create_file(
6318 		adev_to_drm(adev)->dev,
6319 		&dev_attr_s3_debug);
6320 #endif
6321 	adev->dc_enabled = true;
6322 
6323 	return dm_init_microcode(adev);
6324 }
6325 
6326 static bool modereset_required(struct drm_crtc_state *crtc_state)
6327 {
6328 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
6329 }
6330 
6331 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
6332 {
6333 	drm_encoder_cleanup(encoder);
6334 	kfree(encoder);
6335 }
6336 
6337 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
6338 	.destroy = amdgpu_dm_encoder_destroy,
6339 };
6340 
6341 static int
6342 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
6343 			    const enum surface_pixel_format format,
6344 			    enum dc_color_space *color_space)
6345 {
6346 	bool full_range;
6347 
6348 	*color_space = COLOR_SPACE_SRGB;
6349 
6350 	/* Ignore properties when DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE is set */
6351 	if (plane_state->state && plane_state->state->plane_color_pipeline)
6352 		return 0;
6353 
6354 	/* DRM color properties only affect non-RGB formats. */
6355 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
6356 		return 0;
6357 
6358 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
6359 
6360 	switch (plane_state->color_encoding) {
6361 	case DRM_COLOR_YCBCR_BT601:
6362 		if (full_range)
6363 			*color_space = COLOR_SPACE_YCBCR601;
6364 		else
6365 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
6366 		break;
6367 
6368 	case DRM_COLOR_YCBCR_BT709:
6369 		if (full_range)
6370 			*color_space = COLOR_SPACE_YCBCR709;
6371 		else
6372 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
6373 		break;
6374 
6375 	case DRM_COLOR_YCBCR_BT2020:
6376 		if (full_range)
6377 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
6378 		else
6379 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6380 		break;
6381 
6382 	default:
6383 		return -EINVAL;
6384 	}
6385 
6386 	return 0;
6387 }
6388 
6389 static int
6390 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
6391 			    const struct drm_plane_state *plane_state,
6392 			    const u64 tiling_flags,
6393 			    struct dc_plane_info *plane_info,
6394 			    struct dc_plane_address *address,
6395 			    bool tmz_surface)
6396 {
6397 	const struct drm_framebuffer *fb = plane_state->fb;
6398 	const struct amdgpu_framebuffer *afb =
6399 		to_amdgpu_framebuffer(plane_state->fb);
6400 	int ret;
6401 
6402 	memset(plane_info, 0, sizeof(*plane_info));
6403 
6404 	switch (fb->format->format) {
6405 	case DRM_FORMAT_C8:
6406 		plane_info->format =
6407 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
6408 		break;
6409 	case DRM_FORMAT_RGB565:
6410 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
6411 		break;
6412 	case DRM_FORMAT_XRGB8888:
6413 	case DRM_FORMAT_ARGB8888:
6414 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6415 		break;
6416 	case DRM_FORMAT_XRGB2101010:
6417 	case DRM_FORMAT_ARGB2101010:
6418 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
6419 		break;
6420 	case DRM_FORMAT_XBGR2101010:
6421 	case DRM_FORMAT_ABGR2101010:
6422 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
6423 		break;
6424 	case DRM_FORMAT_XBGR8888:
6425 	case DRM_FORMAT_ABGR8888:
6426 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
6427 		break;
6428 	case DRM_FORMAT_NV21:
6429 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
6430 		break;
6431 	case DRM_FORMAT_NV12:
6432 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
6433 		break;
6434 	case DRM_FORMAT_P010:
6435 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
6436 		break;
6437 	case DRM_FORMAT_XRGB16161616F:
6438 	case DRM_FORMAT_ARGB16161616F:
6439 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
6440 		break;
6441 	case DRM_FORMAT_XBGR16161616F:
6442 	case DRM_FORMAT_ABGR16161616F:
6443 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
6444 		break;
6445 	case DRM_FORMAT_XRGB16161616:
6446 	case DRM_FORMAT_ARGB16161616:
6447 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
6448 		break;
6449 	case DRM_FORMAT_XBGR16161616:
6450 	case DRM_FORMAT_ABGR16161616:
6451 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
6452 		break;
6453 	default:
6454 		drm_err(adev_to_drm(adev),
6455 			"Unsupported screen format %p4cc\n",
6456 			&fb->format->format);
6457 		return -EINVAL;
6458 	}
6459 
6460 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
6461 	case DRM_MODE_ROTATE_0:
6462 		plane_info->rotation = ROTATION_ANGLE_0;
6463 		break;
6464 	case DRM_MODE_ROTATE_90:
6465 		plane_info->rotation = ROTATION_ANGLE_90;
6466 		break;
6467 	case DRM_MODE_ROTATE_180:
6468 		plane_info->rotation = ROTATION_ANGLE_180;
6469 		break;
6470 	case DRM_MODE_ROTATE_270:
6471 		plane_info->rotation = ROTATION_ANGLE_270;
6472 		break;
6473 	default:
6474 		plane_info->rotation = ROTATION_ANGLE_0;
6475 		break;
6476 	}
6477 
6478 
6479 	plane_info->visible = true;
6480 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
6481 
6482 	plane_info->layer_index = plane_state->normalized_zpos;
6483 
6484 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
6485 					  &plane_info->color_space);
6486 	if (ret)
6487 		return ret;
6488 
6489 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
6490 					   plane_info->rotation, tiling_flags,
6491 					   &plane_info->tiling_info,
6492 					   &plane_info->plane_size,
6493 					   &plane_info->dcc, address,
6494 					   tmz_surface);
6495 	if (ret)
6496 		return ret;
6497 
6498 	amdgpu_dm_plane_fill_blending_from_plane_state(
6499 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
6500 		&plane_info->global_alpha, &plane_info->global_alpha_value);
6501 
6502 	return 0;
6503 }
6504 
6505 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
6506 				    struct dc_plane_state *dc_plane_state,
6507 				    struct drm_plane_state *plane_state,
6508 				    struct drm_crtc_state *crtc_state)
6509 {
6510 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6511 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
6512 	struct dc_scaling_info scaling_info;
6513 	struct dc_plane_info plane_info;
6514 	int ret;
6515 
6516 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
6517 	if (ret)
6518 		return ret;
6519 
6520 	dc_plane_state->src_rect = scaling_info.src_rect;
6521 	dc_plane_state->dst_rect = scaling_info.dst_rect;
6522 	dc_plane_state->clip_rect = scaling_info.clip_rect;
6523 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
6524 
6525 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
6526 					  afb->tiling_flags,
6527 					  &plane_info,
6528 					  &dc_plane_state->address,
6529 					  afb->tmz_surface);
6530 	if (ret)
6531 		return ret;
6532 
6533 	dc_plane_state->format = plane_info.format;
6534 	dc_plane_state->color_space = plane_info.color_space;
6535 	dc_plane_state->format = plane_info.format;
6536 	dc_plane_state->plane_size = plane_info.plane_size;
6537 	dc_plane_state->rotation = plane_info.rotation;
6538 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
6539 	dc_plane_state->stereo_format = plane_info.stereo_format;
6540 	dc_plane_state->tiling_info = plane_info.tiling_info;
6541 	dc_plane_state->visible = plane_info.visible;
6542 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
6543 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
6544 	dc_plane_state->global_alpha = plane_info.global_alpha;
6545 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
6546 	dc_plane_state->dcc = plane_info.dcc;
6547 	dc_plane_state->layer_index = plane_info.layer_index;
6548 	dc_plane_state->flip_int_enabled = true;
6549 
6550 	/*
6551 	 * Always set input transfer function, since plane state is refreshed
6552 	 * every time.
6553 	 */
6554 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
6555 						plane_state,
6556 						dc_plane_state);
6557 	if (ret)
6558 		return ret;
6559 
6560 	return 0;
6561 }
6562 
6563 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
6564 				      struct rect *dirty_rect, int32_t x,
6565 				      s32 y, s32 width, s32 height,
6566 				      int *i, bool ffu)
6567 {
6568 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
6569 
6570 	dirty_rect->x = x;
6571 	dirty_rect->y = y;
6572 	dirty_rect->width = width;
6573 	dirty_rect->height = height;
6574 
6575 	if (ffu)
6576 		drm_dbg(plane->dev,
6577 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
6578 			plane->base.id, width, height);
6579 	else
6580 		drm_dbg(plane->dev,
6581 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
6582 			plane->base.id, x, y, width, height);
6583 
6584 	(*i)++;
6585 }
6586 
6587 /**
6588  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
6589  *
6590  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
6591  *         remote fb
6592  * @old_plane_state: Old state of @plane
6593  * @new_plane_state: New state of @plane
6594  * @crtc_state: New state of CRTC connected to the @plane
6595  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
6596  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
6597  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
6598  *             that have changed will be updated. If PSR SU is not enabled,
6599  *             or if damage clips are not available, the entire screen will be updated.
6600  * @dirty_regions_changed: dirty regions changed
6601  *
6602  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
6603  * (referred to as "damage clips" in DRM nomenclature) that require updating on
6604  * the eDP remote buffer. The responsibility of specifying the dirty regions is
6605  * amdgpu_dm's.
6606  *
6607  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
6608  * plane with regions that require flushing to the eDP remote buffer. In
6609  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
6610  * implicitly provide damage clips without any client support via the plane
6611  * bounds.
6612  */
6613 static void fill_dc_dirty_rects(struct drm_plane *plane,
6614 				struct drm_plane_state *old_plane_state,
6615 				struct drm_plane_state *new_plane_state,
6616 				struct drm_crtc_state *crtc_state,
6617 				struct dc_flip_addrs *flip_addrs,
6618 				bool is_psr_su,
6619 				bool *dirty_regions_changed)
6620 {
6621 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6622 	struct rect *dirty_rects = flip_addrs->dirty_rects;
6623 	u32 num_clips = 0;
6624 	struct drm_mode_rect *clips = NULL;
6625 	bool bb_changed;
6626 	bool fb_changed;
6627 	u32 i = 0;
6628 	*dirty_regions_changed = false;
6629 
6630 	/*
6631 	 * Cursor plane has it's own dirty rect update interface. See
6632 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
6633 	 */
6634 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
6635 		return;
6636 
6637 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
6638 		goto ffu;
6639 
6640 	if (!new_plane_state->ignore_damage_clips) {
6641 		num_clips = drm_plane_get_damage_clips_count(new_plane_state);
6642 		clips = drm_plane_get_damage_clips(new_plane_state);
6643 	}
6644 
6645 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
6646 						   is_psr_su)))
6647 		goto ffu;
6648 
6649 	if (!dm_crtc_state->mpo_requested) {
6650 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
6651 			goto ffu;
6652 
6653 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
6654 			fill_dc_dirty_rect(new_plane_state->plane,
6655 					   &dirty_rects[flip_addrs->dirty_rect_count],
6656 					   clips->x1, clips->y1,
6657 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
6658 					   &flip_addrs->dirty_rect_count,
6659 					   false);
6660 		return;
6661 	}
6662 
6663 	/*
6664 	 * MPO is requested. Add entire plane bounding box to dirty rects if
6665 	 * flipped to or damaged.
6666 	 *
6667 	 * If plane is moved or resized, also add old bounding box to dirty
6668 	 * rects.
6669 	 */
6670 	fb_changed = old_plane_state->fb->base.id !=
6671 		     new_plane_state->fb->base.id;
6672 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
6673 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
6674 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
6675 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
6676 
6677 	drm_dbg(plane->dev,
6678 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
6679 		new_plane_state->plane->base.id,
6680 		bb_changed, fb_changed, num_clips);
6681 
6682 	*dirty_regions_changed = bb_changed;
6683 
6684 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
6685 		goto ffu;
6686 
6687 	if (bb_changed) {
6688 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6689 				   new_plane_state->crtc_x,
6690 				   new_plane_state->crtc_y,
6691 				   new_plane_state->crtc_w,
6692 				   new_plane_state->crtc_h, &i, false);
6693 
6694 		/* Add old plane bounding-box if plane is moved or resized */
6695 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6696 				   old_plane_state->crtc_x,
6697 				   old_plane_state->crtc_y,
6698 				   old_plane_state->crtc_w,
6699 				   old_plane_state->crtc_h, &i, false);
6700 	}
6701 
6702 	if (num_clips) {
6703 		for (; i < num_clips; clips++)
6704 			fill_dc_dirty_rect(new_plane_state->plane,
6705 					   &dirty_rects[i], clips->x1,
6706 					   clips->y1, clips->x2 - clips->x1,
6707 					   clips->y2 - clips->y1, &i, false);
6708 	} else if (fb_changed && !bb_changed) {
6709 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6710 				   new_plane_state->crtc_x,
6711 				   new_plane_state->crtc_y,
6712 				   new_plane_state->crtc_w,
6713 				   new_plane_state->crtc_h, &i, false);
6714 	}
6715 
6716 	flip_addrs->dirty_rect_count = i;
6717 	return;
6718 
6719 ffu:
6720 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
6721 			   dm_crtc_state->base.mode.crtc_hdisplay,
6722 			   dm_crtc_state->base.mode.crtc_vdisplay,
6723 			   &flip_addrs->dirty_rect_count, true);
6724 }
6725 
6726 static void update_stream_scaling_settings(struct drm_device *dev,
6727 					   const struct drm_display_mode *mode,
6728 					   const struct dm_connector_state *dm_state,
6729 					   struct dc_stream_state *stream)
6730 {
6731 	enum amdgpu_rmx_type rmx_type;
6732 
6733 	struct rect src = { 0 }; /* viewport in composition space*/
6734 	struct rect dst = { 0 }; /* stream addressable area */
6735 
6736 	/* no mode. nothing to be done */
6737 	if (!mode)
6738 		return;
6739 
6740 	/* Full screen scaling by default */
6741 	src.width = mode->hdisplay;
6742 	src.height = mode->vdisplay;
6743 	dst.width = stream->timing.h_addressable;
6744 	dst.height = stream->timing.v_addressable;
6745 
6746 	if (dm_state) {
6747 		rmx_type = dm_state->scaling;
6748 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
6749 			if (src.width * dst.height <
6750 					src.height * dst.width) {
6751 				/* height needs less upscaling/more downscaling */
6752 				dst.width = src.width *
6753 						dst.height / src.height;
6754 			} else {
6755 				/* width needs less upscaling/more downscaling */
6756 				dst.height = src.height *
6757 						dst.width / src.width;
6758 			}
6759 		} else if (rmx_type == RMX_CENTER) {
6760 			dst = src;
6761 		}
6762 
6763 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
6764 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
6765 
6766 		if (dm_state->underscan_enable) {
6767 			dst.x += dm_state->underscan_hborder / 2;
6768 			dst.y += dm_state->underscan_vborder / 2;
6769 			dst.width -= dm_state->underscan_hborder;
6770 			dst.height -= dm_state->underscan_vborder;
6771 		}
6772 	}
6773 
6774 	stream->src = src;
6775 	stream->dst = dst;
6776 
6777 	drm_dbg_kms(dev, "Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
6778 		    dst.x, dst.y, dst.width, dst.height);
6779 
6780 }
6781 
6782 static enum dc_color_depth
6783 convert_color_depth_from_display_info(const struct drm_connector *connector,
6784 				      bool is_y420, int requested_bpc)
6785 {
6786 	u8 bpc;
6787 
6788 	if (is_y420) {
6789 		bpc = 8;
6790 
6791 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
6792 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
6793 			bpc = 16;
6794 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
6795 			bpc = 12;
6796 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
6797 			bpc = 10;
6798 	} else {
6799 		bpc = (uint8_t)connector->display_info.bpc;
6800 		/* Assume 8 bpc by default if no bpc is specified. */
6801 		bpc = bpc ? bpc : 8;
6802 	}
6803 
6804 	if (requested_bpc > 0) {
6805 		/*
6806 		 * Cap display bpc based on the user requested value.
6807 		 *
6808 		 * The value for state->max_bpc may not correctly updated
6809 		 * depending on when the connector gets added to the state
6810 		 * or if this was called outside of atomic check, so it
6811 		 * can't be used directly.
6812 		 */
6813 		bpc = min_t(u8, bpc, requested_bpc);
6814 
6815 		/* Round down to the nearest even number. */
6816 		bpc = bpc - (bpc & 1);
6817 	}
6818 
6819 	switch (bpc) {
6820 	case 0:
6821 		/*
6822 		 * Temporary Work around, DRM doesn't parse color depth for
6823 		 * EDID revision before 1.4
6824 		 * TODO: Fix edid parsing
6825 		 */
6826 		return COLOR_DEPTH_888;
6827 	case 6:
6828 		return COLOR_DEPTH_666;
6829 	case 8:
6830 		return COLOR_DEPTH_888;
6831 	case 10:
6832 		return COLOR_DEPTH_101010;
6833 	case 12:
6834 		return COLOR_DEPTH_121212;
6835 	case 14:
6836 		return COLOR_DEPTH_141414;
6837 	case 16:
6838 		return COLOR_DEPTH_161616;
6839 	default:
6840 		return COLOR_DEPTH_UNDEFINED;
6841 	}
6842 }
6843 
6844 static enum dc_aspect_ratio
6845 get_aspect_ratio(const struct drm_display_mode *mode_in)
6846 {
6847 	/* 1-1 mapping, since both enums follow the HDMI spec. */
6848 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
6849 }
6850 
6851 static enum dc_color_space
6852 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
6853 		       const struct drm_connector_state *connector_state)
6854 {
6855 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
6856 
6857 	switch (connector_state->colorspace) {
6858 	case DRM_MODE_COLORIMETRY_BT601_YCC:
6859 		if (dc_crtc_timing->flags.Y_ONLY)
6860 			color_space = COLOR_SPACE_YCBCR601_LIMITED;
6861 		else
6862 			color_space = COLOR_SPACE_YCBCR601;
6863 		break;
6864 	case DRM_MODE_COLORIMETRY_BT709_YCC:
6865 		if (dc_crtc_timing->flags.Y_ONLY)
6866 			color_space = COLOR_SPACE_YCBCR709_LIMITED;
6867 		else
6868 			color_space = COLOR_SPACE_YCBCR709;
6869 		break;
6870 	case DRM_MODE_COLORIMETRY_OPRGB:
6871 		color_space = COLOR_SPACE_ADOBERGB;
6872 		break;
6873 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
6874 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
6875 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
6876 			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
6877 		else
6878 			color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6879 		break;
6880 	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
6881 	default:
6882 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
6883 			color_space = COLOR_SPACE_SRGB;
6884 			if (connector_state->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_LIMITED)
6885 				color_space = COLOR_SPACE_SRGB_LIMITED;
6886 		/*
6887 		 * 27030khz is the separation point between HDTV and SDTV
6888 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
6889 		 * respectively
6890 		 */
6891 		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
6892 			if (dc_crtc_timing->flags.Y_ONLY)
6893 				color_space =
6894 					COLOR_SPACE_YCBCR709_LIMITED;
6895 			else
6896 				color_space = COLOR_SPACE_YCBCR709;
6897 		} else {
6898 			if (dc_crtc_timing->flags.Y_ONLY)
6899 				color_space =
6900 					COLOR_SPACE_YCBCR601_LIMITED;
6901 			else
6902 				color_space = COLOR_SPACE_YCBCR601;
6903 		}
6904 		break;
6905 	}
6906 
6907 	return color_space;
6908 }
6909 
6910 static enum display_content_type
6911 get_output_content_type(const struct drm_connector_state *connector_state)
6912 {
6913 	switch (connector_state->content_type) {
6914 	default:
6915 	case DRM_MODE_CONTENT_TYPE_NO_DATA:
6916 		return DISPLAY_CONTENT_TYPE_NO_DATA;
6917 	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
6918 		return DISPLAY_CONTENT_TYPE_GRAPHICS;
6919 	case DRM_MODE_CONTENT_TYPE_PHOTO:
6920 		return DISPLAY_CONTENT_TYPE_PHOTO;
6921 	case DRM_MODE_CONTENT_TYPE_CINEMA:
6922 		return DISPLAY_CONTENT_TYPE_CINEMA;
6923 	case DRM_MODE_CONTENT_TYPE_GAME:
6924 		return DISPLAY_CONTENT_TYPE_GAME;
6925 	}
6926 }
6927 
6928 static bool adjust_colour_depth_from_display_info(
6929 	struct dc_crtc_timing *timing_out,
6930 	const struct drm_display_info *info)
6931 {
6932 	enum dc_color_depth depth = timing_out->display_color_depth;
6933 	int normalized_clk;
6934 
6935 	do {
6936 		normalized_clk = timing_out->pix_clk_100hz / 10;
6937 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
6938 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
6939 			normalized_clk /= 2;
6940 		/* Adjusting pix clock following on HDMI spec based on colour depth */
6941 		switch (depth) {
6942 		case COLOR_DEPTH_888:
6943 			break;
6944 		case COLOR_DEPTH_101010:
6945 			normalized_clk = (normalized_clk * 30) / 24;
6946 			break;
6947 		case COLOR_DEPTH_121212:
6948 			normalized_clk = (normalized_clk * 36) / 24;
6949 			break;
6950 		case COLOR_DEPTH_161616:
6951 			normalized_clk = (normalized_clk * 48) / 24;
6952 			break;
6953 		default:
6954 			/* The above depths are the only ones valid for HDMI. */
6955 			return false;
6956 		}
6957 		if (normalized_clk <= info->max_tmds_clock) {
6958 			timing_out->display_color_depth = depth;
6959 			return true;
6960 		}
6961 	} while (--depth > COLOR_DEPTH_666);
6962 	return false;
6963 }
6964 
6965 static void fill_stream_properties_from_drm_display_mode(
6966 	struct dc_stream_state *stream,
6967 	const struct drm_display_mode *mode_in,
6968 	const struct drm_connector *connector,
6969 	const struct drm_connector_state *connector_state,
6970 	const struct dc_stream_state *old_stream,
6971 	int requested_bpc)
6972 {
6973 	bool is_dp_or_hdmi = dc_is_hdmi_signal(stream->signal) || dc_is_dp_signal(stream->signal);
6974 	struct dc_crtc_timing *timing_out = &stream->timing;
6975 	const struct drm_display_info *info = &connector->display_info;
6976 	struct amdgpu_dm_connector *aconnector = NULL;
6977 	struct hdmi_vendor_infoframe hv_frame;
6978 	struct hdmi_avi_infoframe avi_frame;
6979 	bool want_420;
6980 	bool want_422;
6981 	ssize_t err;
6982 
6983 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
6984 		aconnector = to_amdgpu_dm_connector(connector);
6985 
6986 	memset(&hv_frame, 0, sizeof(hv_frame));
6987 	memset(&avi_frame, 0, sizeof(avi_frame));
6988 
6989 	timing_out->h_border_left = 0;
6990 	timing_out->h_border_right = 0;
6991 	timing_out->v_border_top = 0;
6992 	timing_out->v_border_bottom = 0;
6993 
6994 	want_420 = (aconnector && aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR420) ||
6995 		   (connector_state->color_format == DRM_CONNECTOR_COLOR_FORMAT_YCBCR420);
6996 	want_422 = (aconnector && aconnector->force_yuv_pixel_format == PIXEL_ENCODING_YCBCR422) ||
6997 		   (connector_state->color_format == DRM_CONNECTOR_COLOR_FORMAT_YCBCR422);
6998 
6999 	if (drm_mode_is_420_only(info, mode_in) &&
7000 	    (want_420 || connector_state->color_format == DRM_CONNECTOR_COLOR_FORMAT_AUTO)) {
7001 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
7002 	} else if (drm_mode_is_420_also(info, mode_in) && want_420) {
7003 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
7004 	} else if ((info->color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR422)) &&
7005 		   want_422 && is_dp_or_hdmi) {
7006 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR422;
7007 	} else if (connector_state->color_format == DRM_CONNECTOR_COLOR_FORMAT_YCBCR444 &&
7008 		   (info->color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR444)) &&
7009 		   is_dp_or_hdmi) {
7010 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
7011 	} else if (connector_state->color_format == DRM_CONNECTOR_COLOR_FORMAT_RGB444 ||
7012 		   connector_state->color_format == DRM_CONNECTOR_COLOR_FORMAT_AUTO) {
7013 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
7014 	} else {
7015 		/*
7016 		 * If a format was explicitly requested but the requested format
7017 		 * can't be satisfied, set it to an invalid value so that an
7018 		 * error bubbles up to userspace. This way, userspace knows it
7019 		 * needs to make a better choice.
7020 		 */
7021 		if (connector_state->color_format != DRM_CONNECTOR_COLOR_FORMAT_AUTO)
7022 			timing_out->pixel_encoding = PIXEL_ENCODING_UNDEFINED;
7023 		else if (drm_mode_is_420_only(info, mode_in))
7024 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
7025 		else
7026 			timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
7027 	}
7028 
7029 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
7030 	timing_out->display_color_depth = convert_color_depth_from_display_info(
7031 		connector,
7032 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
7033 		requested_bpc);
7034 	timing_out->scan_type = SCANNING_TYPE_NODATA;
7035 	timing_out->hdmi_vic = 0;
7036 
7037 	if (old_stream) {
7038 		timing_out->vic = old_stream->timing.vic;
7039 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
7040 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
7041 	} else {
7042 		timing_out->vic = drm_match_cea_mode(mode_in);
7043 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
7044 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
7045 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
7046 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
7047 	}
7048 
7049 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7050 		stream->signal == SIGNAL_TYPE_HDMI_FRL) {
7051 		err = drm_hdmi_avi_infoframe_from_display_mode(&avi_frame,
7052 							       (struct drm_connector *)connector,
7053 							       mode_in);
7054 		if (err < 0)
7055 			drm_warn_once(connector->dev, "Failed to setup avi infoframe on connector %s: %zd\n",
7056 				      connector->name, err);
7057 		timing_out->vic = avi_frame.video_code;
7058 		err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame,
7059 								  (struct drm_connector *)connector,
7060 								  mode_in);
7061 		if (err < 0)
7062 			drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n",
7063 				      connector->name, err);
7064 		timing_out->hdmi_vic = hv_frame.vic;
7065 	}
7066 
7067 	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
7068 		timing_out->h_addressable = mode_in->hdisplay;
7069 		timing_out->h_total = mode_in->htotal;
7070 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
7071 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
7072 		timing_out->v_total = mode_in->vtotal;
7073 		timing_out->v_addressable = mode_in->vdisplay;
7074 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
7075 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
7076 		timing_out->pix_clk_100hz = mode_in->clock * 10;
7077 	} else {
7078 		timing_out->h_addressable = mode_in->crtc_hdisplay;
7079 		timing_out->h_total = mode_in->crtc_htotal;
7080 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
7081 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
7082 		timing_out->v_total = mode_in->crtc_vtotal;
7083 		timing_out->v_addressable = mode_in->crtc_vdisplay;
7084 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
7085 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
7086 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
7087 	}
7088 
7089 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
7090 
7091 	stream->out_transfer_func.type = TF_TYPE_PREDEFINED;
7092 	stream->out_transfer_func.tf = TRANSFER_FUNCTION_SRGB;
7093 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
7094 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
7095 		    drm_mode_is_420_also(info, mode_in) &&
7096 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
7097 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
7098 			adjust_colour_depth_from_display_info(timing_out, info);
7099 		}
7100 	}
7101 
7102 	stream->output_color_space = get_output_color_space(timing_out, connector_state);
7103 	stream->content_type = get_output_content_type(connector_state);
7104 }
7105 
7106 static void fill_audio_info(struct audio_info *audio_info,
7107 			    const struct drm_connector *drm_connector,
7108 			    const struct dc_sink *dc_sink)
7109 {
7110 	int i = 0;
7111 	int cea_revision = 0;
7112 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
7113 
7114 	audio_info->manufacture_id = edid_caps->manufacturer_id;
7115 	audio_info->product_id = edid_caps->product_id;
7116 
7117 	cea_revision = drm_connector->display_info.cea_rev;
7118 
7119 	strscpy(audio_info->display_name,
7120 		edid_caps->display_name,
7121 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
7122 
7123 	if (cea_revision >= 3) {
7124 		audio_info->mode_count = edid_caps->audio_mode_count;
7125 
7126 		for (i = 0; i < audio_info->mode_count; ++i) {
7127 			audio_info->modes[i].format_code =
7128 					(enum audio_format_code)
7129 					(edid_caps->audio_modes[i].format_code);
7130 			audio_info->modes[i].channel_count =
7131 					edid_caps->audio_modes[i].channel_count;
7132 			audio_info->modes[i].sample_rates.all =
7133 					edid_caps->audio_modes[i].sample_rate;
7134 			audio_info->modes[i].sample_size =
7135 					edid_caps->audio_modes[i].sample_size;
7136 		}
7137 	}
7138 
7139 	audio_info->flags.all = edid_caps->speaker_flags;
7140 
7141 	/* TODO: We only check for the progressive mode, check for interlace mode too */
7142 	if (drm_connector->latency_present[0]) {
7143 		audio_info->video_latency = drm_connector->video_latency[0];
7144 		audio_info->audio_latency = drm_connector->audio_latency[0];
7145 	}
7146 
7147 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
7148 
7149 }
7150 
7151 static void
7152 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
7153 				      struct drm_display_mode *dst_mode)
7154 {
7155 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
7156 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
7157 	dst_mode->crtc_clock = src_mode->crtc_clock;
7158 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
7159 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
7160 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
7161 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
7162 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
7163 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
7164 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
7165 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
7166 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
7167 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
7168 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
7169 }
7170 
7171 static void
7172 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
7173 					const struct drm_display_mode *native_mode,
7174 					bool scale_enabled)
7175 {
7176 	if (scale_enabled || (
7177 	    native_mode->clock == drm_mode->clock &&
7178 	    native_mode->htotal == drm_mode->htotal &&
7179 	    native_mode->vtotal == drm_mode->vtotal)) {
7180 		if (native_mode->crtc_clock)
7181 			copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
7182 	} else {
7183 		/* no scaling nor amdgpu inserted, no need to patch */
7184 	}
7185 }
7186 
7187 static struct dc_sink *
7188 create_fake_sink(struct drm_device *dev, struct dc_link *link)
7189 {
7190 	struct dc_sink_init_data sink_init_data = { 0 };
7191 	struct dc_sink *sink = NULL;
7192 
7193 	sink_init_data.link = link;
7194 	sink_init_data.sink_signal = link->connector_signal;
7195 
7196 	sink = dc_sink_create(&sink_init_data);
7197 	if (!sink) {
7198 		drm_err(dev, "Failed to create sink!\n");
7199 		return NULL;
7200 	}
7201 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
7202 
7203 	return sink;
7204 }
7205 
7206 static void set_multisync_trigger_params(
7207 		struct dc_stream_state *stream)
7208 {
7209 	struct dc_stream_state *master = NULL;
7210 
7211 	if (stream->triggered_crtc_reset.enabled) {
7212 		master = stream->triggered_crtc_reset.event_source;
7213 		stream->triggered_crtc_reset.event =
7214 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
7215 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
7216 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
7217 	}
7218 }
7219 
7220 static void set_master_stream(struct dc_stream_state *stream_set[],
7221 			      int stream_count)
7222 {
7223 	int j, highest_rfr = 0, master_stream = 0;
7224 
7225 	for (j = 0;  j < stream_count; j++) {
7226 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
7227 			int refresh_rate = 0;
7228 
7229 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
7230 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
7231 			if (refresh_rate > highest_rfr) {
7232 				highest_rfr = refresh_rate;
7233 				master_stream = j;
7234 			}
7235 		}
7236 	}
7237 	for (j = 0;  j < stream_count; j++) {
7238 		if (stream_set[j])
7239 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
7240 	}
7241 }
7242 
7243 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
7244 {
7245 	int i = 0;
7246 	struct dc_stream_state *stream;
7247 
7248 	if (context->stream_count < 2)
7249 		return;
7250 	for (i = 0; i < context->stream_count ; i++) {
7251 		if (!context->streams[i])
7252 			continue;
7253 		/*
7254 		 * TODO: add a function to read AMD VSDB bits and set
7255 		 * crtc_sync_master.multi_sync_enabled flag
7256 		 * For now it's set to false
7257 		 */
7258 	}
7259 
7260 	set_master_stream(context->streams, context->stream_count);
7261 
7262 	for (i = 0; i < context->stream_count ; i++) {
7263 		stream = context->streams[i];
7264 
7265 		if (!stream)
7266 			continue;
7267 
7268 		set_multisync_trigger_params(stream);
7269 	}
7270 }
7271 
7272 /**
7273  * DOC: FreeSync Video
7274  *
7275  * When a userspace application wants to play a video, the content follows a
7276  * standard format definition that usually specifies the FPS for that format.
7277  * The below list illustrates some video format and the expected FPS,
7278  * respectively:
7279  *
7280  * - TV/NTSC (23.976 FPS)
7281  * - Cinema (24 FPS)
7282  * - TV/PAL (25 FPS)
7283  * - TV/NTSC (29.97 FPS)
7284  * - TV/NTSC (30 FPS)
7285  * - Cinema HFR (48 FPS)
7286  * - TV/PAL (50 FPS)
7287  * - Commonly used (60 FPS)
7288  * - Multiples of 24 (48,72,96 FPS)
7289  *
7290  * The list of standards video format is not huge and can be added to the
7291  * connector modeset list beforehand. With that, userspace can leverage
7292  * FreeSync to extends the front porch in order to attain the target refresh
7293  * rate. Such a switch will happen seamlessly, without screen blanking or
7294  * reprogramming of the output in any other way. If the userspace requests a
7295  * modesetting change compatible with FreeSync modes that only differ in the
7296  * refresh rate, DC will skip the full update and avoid blink during the
7297  * transition. For example, the video player can change the modesetting from
7298  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
7299  * causing any display blink. This same concept can be applied to a mode
7300  * setting change.
7301  */
7302 static struct drm_display_mode *
7303 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
7304 		bool use_probed_modes)
7305 {
7306 	struct drm_display_mode *m, *m_pref = NULL;
7307 	u16 current_refresh, highest_refresh;
7308 	struct list_head *list_head = use_probed_modes ?
7309 		&aconnector->base.probed_modes :
7310 		&aconnector->base.modes;
7311 
7312 	if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
7313 		return NULL;
7314 
7315 	if (aconnector->freesync_vid_base.clock != 0)
7316 		return &aconnector->freesync_vid_base;
7317 
7318 	/* Find the preferred mode */
7319 	list_for_each_entry(m, list_head, head) {
7320 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
7321 			m_pref = m;
7322 			break;
7323 		}
7324 	}
7325 
7326 	if (!m_pref) {
7327 		/* Probably an EDID with no preferred mode. Fallback to first entry */
7328 		m_pref = list_first_entry_or_null(
7329 				&aconnector->base.modes, struct drm_display_mode, head);
7330 		if (!m_pref) {
7331 			drm_dbg_driver(aconnector->base.dev, "No preferred mode found in EDID\n");
7332 			return NULL;
7333 		}
7334 	}
7335 
7336 	highest_refresh = drm_mode_vrefresh(m_pref);
7337 
7338 	/*
7339 	 * Find the mode with highest refresh rate with same resolution.
7340 	 * For some monitors, preferred mode is not the mode with highest
7341 	 * supported refresh rate.
7342 	 */
7343 	list_for_each_entry(m, list_head, head) {
7344 		current_refresh  = drm_mode_vrefresh(m);
7345 
7346 		if (m->hdisplay == m_pref->hdisplay &&
7347 		    m->vdisplay == m_pref->vdisplay &&
7348 		    highest_refresh < current_refresh) {
7349 			highest_refresh = current_refresh;
7350 			m_pref = m;
7351 		}
7352 	}
7353 
7354 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
7355 	return m_pref;
7356 }
7357 
7358 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
7359 		struct amdgpu_dm_connector *aconnector)
7360 {
7361 	struct drm_display_mode *high_mode;
7362 	int timing_diff;
7363 
7364 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
7365 	if (!high_mode || !mode)
7366 		return false;
7367 
7368 	timing_diff = high_mode->vtotal - mode->vtotal;
7369 
7370 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
7371 	    high_mode->hdisplay != mode->hdisplay ||
7372 	    high_mode->vdisplay != mode->vdisplay ||
7373 	    high_mode->hsync_start != mode->hsync_start ||
7374 	    high_mode->hsync_end != mode->hsync_end ||
7375 	    high_mode->htotal != mode->htotal ||
7376 	    high_mode->hskew != mode->hskew ||
7377 	    high_mode->vscan != mode->vscan ||
7378 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
7379 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
7380 		return false;
7381 	else
7382 		return true;
7383 }
7384 
7385 #if defined(CONFIG_DRM_AMD_DC_FP)
7386 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
7387 			    struct dc_sink *sink, struct dc_stream_state *stream,
7388 			    struct dsc_dec_dpcd_caps *dsc_caps)
7389 {
7390 	stream->timing.flags.DSC = 0;
7391 	dsc_caps->is_dsc_supported = false;
7392 
7393 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
7394 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
7395 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE)
7396 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7397 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7398 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7399 				dsc_caps);
7400 		else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7401 			if (aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.fields.dsc_support.DSC_PASSTHROUGH_SUPPORT &&
7402 					!aconnector->dsc_settings.dsc_force_disable_passthrough &&
7403 					aconnector->dc_link->dpcd_caps.dongle_caps.dp_hdmi_frl_max_link_bw_in_kbps > 0 &&
7404 					sink->edid_caps.frl_dsc_support &&
7405 					sink->edid_caps.max_frl_rate > 0 &&
7406 					sink->edid_caps.frl_dsc_max_frl_rate > 0)
7407 				dc_dsc_parse_dsc_edid(aconnector->dc_link->ctx->dc, &sink->edid_caps, dsc_caps);
7408 			else
7409 				dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7410 				      aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7411 				      aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7412 				      dsc_caps);
7413 		}
7414 	} else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_HDMI_FRL) {
7415 		if (sink->edid_caps.frl_dsc_support &&
7416 				sink->edid_caps.max_frl_rate > 0 &&
7417 				sink->edid_caps.frl_dsc_max_frl_rate > 0)
7418 			dc_dsc_parse_dsc_edid(aconnector->dc_link->ctx->dc, &sink->edid_caps, dsc_caps);
7419 	}
7420 }
7421 
7422 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
7423 				    struct dc_sink *sink, struct dc_stream_state *stream,
7424 				    struct dsc_dec_dpcd_caps *dsc_caps,
7425 				    uint32_t max_dsc_target_bpp_limit_override)
7426 {
7427 	const struct dc_link_settings *verified_link_cap = NULL;
7428 	u32 link_bw_in_kbps;
7429 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
7430 	struct dc *dc = sink->ctx->dc;
7431 	struct dc_dsc_bw_range bw_range = {0};
7432 	struct dc_dsc_config dsc_cfg = {0};
7433 	struct dc_dsc_config_options dsc_options = {0};
7434 
7435 	dc_dsc_get_default_config_option(dc, &dsc_options);
7436 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7437 
7438 	verified_link_cap = dc_link_get_link_cap(stream->link);
7439 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
7440 	edp_min_bpp_x16 = 8 * 16;
7441 	edp_max_bpp_x16 = 8 * 16;
7442 
7443 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
7444 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
7445 
7446 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
7447 		edp_min_bpp_x16 = edp_max_bpp_x16;
7448 
7449 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
7450 				dc->debug.dsc_min_slice_height_override,
7451 				edp_min_bpp_x16, edp_max_bpp_x16,
7452 				dsc_caps,
7453 				&stream->timing,
7454 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7455 				&bw_range)) {
7456 
7457 		if (bw_range.max_kbps < link_bw_in_kbps) {
7458 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7459 					dsc_caps,
7460 					&dsc_options,
7461 					0,
7462 					&stream->timing,
7463 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7464 					&dsc_cfg)) {
7465 				stream->timing.dsc_cfg = dsc_cfg;
7466 				stream->timing.flags.DSC = 1;
7467 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
7468 			}
7469 			return;
7470 		}
7471 	}
7472 
7473 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7474 				dsc_caps,
7475 				&dsc_options,
7476 				link_bw_in_kbps,
7477 				&stream->timing,
7478 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7479 				&dsc_cfg)) {
7480 		stream->timing.dsc_cfg = dsc_cfg;
7481 		stream->timing.flags.DSC = 1;
7482 	}
7483 }
7484 
7485 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
7486 					struct dc_sink *sink, struct dc_stream_state *stream,
7487 					struct dsc_dec_dpcd_caps *dsc_caps)
7488 {
7489 	struct drm_connector *drm_connector = &aconnector->base;
7490 	u32 link_bandwidth_kbps;
7491 	struct dc *dc = sink->ctx->dc;
7492 	const struct dc_hdmi_frl_link_settings *frl_verified_link_cap = NULL;
7493 	u32 converter_bw_in_kbps;
7494 	u32 sink_bw_in_kbps;
7495 	u32 dsc_sink_bw_in_kbps;
7496 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
7497 	u32 dsc_max_supported_bw_in_kbps;
7498 	u32 max_dsc_target_bpp_limit_override =
7499 		drm_connector->display_info.max_dsc_bpp;
7500 	struct dc_dsc_config_options dsc_options = {0};
7501 
7502 	dc_dsc_get_default_config_option(dc, &dsc_options);
7503 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7504 
7505 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
7506 							dc_link_get_link_cap(aconnector->dc_link));
7507 
7508 	/* Set DSC policy according to dsc_clock_en */
7509 	dc_dsc_policy_set_enable_dsc_when_not_needed(
7510 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
7511 
7512 	if (sink->sink_signal == SIGNAL_TYPE_EDP &&
7513 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
7514 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
7515 
7516 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
7517 
7518 	} else if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
7519 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
7520 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7521 						dsc_caps,
7522 						&dsc_options,
7523 						link_bandwidth_kbps,
7524 						&stream->timing,
7525 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7526 						&stream->timing.dsc_cfg)) {
7527 				stream->timing.flags.DSC = 1;
7528 				drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from SST RX\n",
7529 							__func__, drm_connector->name);
7530 			}
7531 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7532 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
7533 					dc_link_get_highest_encoding_format(aconnector->dc_link));
7534 			converter_bw_in_kbps = aconnector->dc_link->dpcd_caps.dongle_caps.dp_hdmi_frl_max_link_bw_in_kbps;
7535 			sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.max_frl_rate);
7536 			dsc_sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.frl_dsc_max_frl_rate);
7537 
7538 			if (dsc_caps->is_frl) {
7539 				max_supported_bw_in_kbps = min(link_bandwidth_kbps, converter_bw_in_kbps);
7540 				max_supported_bw_in_kbps = min(max_supported_bw_in_kbps, sink_bw_in_kbps);
7541 				dsc_max_supported_bw_in_kbps = min(max_supported_bw_in_kbps, dsc_sink_bw_in_kbps);
7542 			} else {
7543 				max_supported_bw_in_kbps = link_bandwidth_kbps;
7544 				dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
7545 			}
7546 
7547 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
7548 					max_supported_bw_in_kbps > 0 &&
7549 					dsc_max_supported_bw_in_kbps > 0)
7550 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7551 						dsc_caps,
7552 						&dsc_options,
7553 						dsc_max_supported_bw_in_kbps,
7554 						&stream->timing,
7555 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7556 						&stream->timing.dsc_cfg)) {
7557 					stream->timing.flags.DSC = 1;
7558 					drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from %s\n",
7559 							__func__, drm_connector->name,
7560 							(dsc_caps->is_frl == 1) ? "HDMI FRL RX" : "DP-HDMI PCON");
7561 				}
7562 		}
7563 	}
7564 	else if (aconnector->dc_link && sink->sink_signal == SIGNAL_TYPE_HDMI_FRL) {
7565 		struct dc_dsc_policy dsc_policy = {0};
7566 
7567 		frl_verified_link_cap = dc_link_get_frl_link_cap(stream->link);
7568 		if (frl_verified_link_cap->frl_link_rate != HDMI_FRL_LINK_RATE_DISABLE &&
7569 			aconnector->dc_link->frl_flags.force_frl_dsc) {
7570 			dc_dsc_policy_set_enable_dsc_when_not_needed(true);
7571 			dc_dsc_get_policy_for_timing(&stream->timing, 0, &dsc_policy, dc_link_get_highest_encoding_format(stream->link));
7572 		}
7573 
7574 		timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing, DC_LINK_ENCODING_HDMI_FRL);
7575 		link_bandwidth_kbps = dc_link_frl_bandwidth_kbps(stream->link, frl_verified_link_cap->frl_link_rate);
7576 		dsc_sink_bw_in_kbps = dc_link_bw_kbps_from_raw_frl_link_rate_data(dc, sink->edid_caps.frl_dsc_max_frl_rate);
7577 
7578 		if ((timing_bw_in_kbps > link_bandwidth_kbps && dsc_sink_bw_in_kbps > 0) ||
7579 		    (dsc_policy.enable_dsc_when_not_needed || dsc_options.force_dsc_when_not_needed)) {
7580 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7581 					dsc_caps,
7582 					&dsc_options,
7583 					dsc_sink_bw_in_kbps,
7584 					&stream->timing,
7585 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7586 					&stream->timing.dsc_cfg)) {
7587 				stream->timing.flags.DSC = 1;
7588 				drm_dbg_driver(drm_connector->dev, "%s: HDMI_FRL_DSC [%s] DSC is selected from HDMI FRL RX\n",
7589 						__func__, drm_connector->name);
7590 			}
7591 		}
7592 	}
7593 
7594 	/* Overwrite the stream flag if DSC is enabled through debugfs */
7595 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
7596 		stream->timing.flags.DSC = 1;
7597 
7598 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
7599 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
7600 
7601 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
7602 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
7603 
7604 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
7605 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
7606 }
7607 #endif
7608 
7609 static struct dc_stream_state *
7610 create_stream_for_sink(struct drm_connector *connector,
7611 		       const struct drm_display_mode *drm_mode,
7612 		       const struct dm_connector_state *dm_state,
7613 		       const struct dc_stream_state *old_stream,
7614 		       int requested_bpc)
7615 {
7616 	struct drm_device *dev = connector->dev;
7617 	struct amdgpu_dm_connector *aconnector = NULL;
7618 	struct drm_display_mode *preferred_mode = NULL;
7619 	const struct drm_connector_state *con_state = &dm_state->base;
7620 	struct dc_stream_state *stream = NULL;
7621 	struct drm_display_mode mode;
7622 	struct drm_display_mode saved_mode;
7623 	struct drm_display_mode *freesync_mode = NULL;
7624 	bool native_mode_found = false;
7625 	bool recalculate_timing = false;
7626 	bool scale = dm_state->scaling != RMX_OFF;
7627 	int mode_refresh;
7628 	int preferred_refresh = 0;
7629 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
7630 #if defined(CONFIG_DRM_AMD_DC_FP)
7631 	struct dsc_dec_dpcd_caps dsc_caps = {0};
7632 #endif
7633 	struct dc_link *link = NULL;
7634 	struct dc_sink *sink = NULL;
7635 
7636 	drm_mode_init(&mode, drm_mode);
7637 	memset(&saved_mode, 0, sizeof(saved_mode));
7638 
7639 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK) {
7640 		aconnector = NULL;
7641 		aconnector = to_amdgpu_dm_connector(connector);
7642 		link = aconnector->dc_link;
7643 	} else {
7644 		struct drm_writeback_connector *wbcon = NULL;
7645 		struct amdgpu_dm_wb_connector *dm_wbcon = NULL;
7646 
7647 		wbcon = drm_connector_to_writeback(connector);
7648 		dm_wbcon = to_amdgpu_dm_wb_connector(wbcon);
7649 		link = dm_wbcon->link;
7650 	}
7651 
7652 	if (!aconnector || !aconnector->dc_sink) {
7653 		sink = create_fake_sink(dev, link);
7654 		if (!sink)
7655 			return stream;
7656 
7657 	} else {
7658 		sink = aconnector->dc_sink;
7659 		dc_sink_retain(sink);
7660 	}
7661 
7662 	stream = dc_create_stream_for_sink(sink);
7663 
7664 	if (stream == NULL) {
7665 		drm_err(dev, "Failed to create stream for sink!\n");
7666 		goto finish;
7667 	}
7668 
7669 	/* We leave this NULL for writeback connectors */
7670 	stream->dm_stream_context = aconnector;
7671 
7672 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
7673 		connector->display_info.hdmi.scdc.scrambling.low_rates;
7674 
7675 	list_for_each_entry(preferred_mode, &connector->modes, head) {
7676 		/* Search for preferred mode */
7677 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
7678 			native_mode_found = true;
7679 			break;
7680 		}
7681 	}
7682 	if (!native_mode_found)
7683 		preferred_mode = list_first_entry_or_null(
7684 				&connector->modes,
7685 				struct drm_display_mode,
7686 				head);
7687 
7688 	mode_refresh = drm_mode_vrefresh(&mode);
7689 
7690 	if (preferred_mode == NULL) {
7691 		/*
7692 		 * This may not be an error, the use case is when we have no
7693 		 * usermode calls to reset and set mode upon hotplug. In this
7694 		 * case, we call set mode ourselves to restore the previous mode
7695 		 * and the modelist may not be filled in time.
7696 		 */
7697 		drm_dbg_driver(dev, "No preferred mode found\n");
7698 	} else if (aconnector) {
7699 		recalculate_timing = amdgpu_freesync_vid_mode &&
7700 				 is_freesync_video_mode(&mode, aconnector);
7701 		if (recalculate_timing) {
7702 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
7703 			drm_mode_copy(&saved_mode, &mode);
7704 			saved_mode.picture_aspect_ratio = mode.picture_aspect_ratio;
7705 			drm_mode_copy(&mode, freesync_mode);
7706 			mode.picture_aspect_ratio = saved_mode.picture_aspect_ratio;
7707 		} else {
7708 			decide_crtc_timing_for_drm_display_mode(
7709 					&mode, preferred_mode, scale);
7710 
7711 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
7712 		}
7713 	}
7714 
7715 	if (recalculate_timing)
7716 		drm_mode_set_crtcinfo(&saved_mode, 0);
7717 
7718 	/*
7719 	 * If scaling is enabled and refresh rate didn't change
7720 	 * we copy the vic and polarities of the old timings
7721 	 */
7722 	if (!scale || mode_refresh != preferred_refresh)
7723 		fill_stream_properties_from_drm_display_mode(
7724 			stream, &mode, connector, con_state, NULL,
7725 			requested_bpc);
7726 	else
7727 		fill_stream_properties_from_drm_display_mode(
7728 			stream, &mode, connector, con_state, old_stream,
7729 			requested_bpc);
7730 
7731 	/* The rest isn't needed for writeback connectors */
7732 	if (!aconnector)
7733 		goto finish;
7734 
7735 	if (aconnector->timing_changed) {
7736 		drm_dbg(aconnector->base.dev,
7737 			"overriding timing for automated test, bpc %d, changing to %d\n",
7738 			stream->timing.display_color_depth,
7739 			aconnector->timing_requested->display_color_depth);
7740 		stream->timing = *aconnector->timing_requested;
7741 	}
7742 
7743 #if defined(CONFIG_DRM_AMD_DC_FP)
7744 	/* SST DSC determination policy */
7745 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
7746 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
7747 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
7748 #endif
7749 
7750 	update_stream_scaling_settings(dev, &mode, dm_state, stream);
7751 
7752 	fill_audio_info(
7753 		&stream->audio_info,
7754 		connector,
7755 		sink);
7756 
7757 	update_stream_signal(stream, sink);
7758 
7759 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A ||
7760 	    stream->signal == SIGNAL_TYPE_HDMI_FRL)
7761 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket, false, false);
7762 
7763 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT ||
7764 	    stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
7765 	    stream->signal == SIGNAL_TYPE_EDP) {
7766 		const struct dc_edid_caps *edid_caps;
7767 		unsigned int disable_colorimetry = 0;
7768 
7769 		if (aconnector->dc_sink) {
7770 			edid_caps = &aconnector->dc_sink->edid_caps;
7771 			disable_colorimetry = edid_caps->panel_patch.disable_colorimetry;
7772 		}
7773 
7774 		//
7775 		// should decide stream support vsc sdp colorimetry capability
7776 		// before building vsc info packet
7777 		//
7778 		stream->use_vsc_sdp_for_colorimetry = stream->link->dpcd_caps.dpcd_rev.raw >= 0x14 &&
7779 						      stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED &&
7780 						      !disable_colorimetry;
7781 
7782 		if (stream->out_transfer_func.tf == TRANSFER_FUNCTION_GAMMA22)
7783 			tf = TRANSFER_FUNC_GAMMA_22;
7784 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
7785 		aconnector->sr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
7786 
7787 	}
7788 finish:
7789 	dc_sink_release(sink);
7790 
7791 	return stream;
7792 }
7793 
7794 /**
7795  * amdgpu_dm_connector_poll - Poll a connector to see if it's connected to a display
7796  * @aconnector: DM connector to poll (owns @base drm_connector and @dc_link)
7797  * @force: if true, force polling even when DAC load detection was used
7798  *
7799  * Used for connectors that don't support HPD (hotplug detection) to
7800  * periodically check whether the connector is connected to a display.
7801  *
7802  * When connection was determined via DAC load detection, we avoid
7803  * re-running it on normal polls to prevent visible glitches, unless
7804  * @force is set.
7805  *
7806  * Return: The probed connector status (connected/disconnected/unknown).
7807  */
7808 static enum drm_connector_status
7809 amdgpu_dm_connector_poll(struct amdgpu_dm_connector *aconnector, bool force)
7810 {
7811 	struct drm_connector *connector = &aconnector->base;
7812 	struct drm_device *dev = connector->dev;
7813 	struct amdgpu_device *adev = drm_to_adev(dev);
7814 	struct dc_link *link = aconnector->dc_link;
7815 	enum dc_connection_type conn_type = dc_connection_none;
7816 	enum drm_connector_status status = connector_status_disconnected;
7817 
7818 	/* When we determined the connection using DAC load detection,
7819 	 * do NOT poll the connector do detect disconnect because
7820 	 * that would run DAC load detection again which can cause
7821 	 * visible visual glitches.
7822 	 *
7823 	 * Only allow to poll such a connector again when forcing.
7824 	 */
7825 	if (!force && link->local_sink && link->type == dc_connection_analog_load)
7826 		return connector->status;
7827 
7828 	mutex_lock(&aconnector->hpd_lock);
7829 
7830 	if (dc_link_detect_connection_type(aconnector->dc_link, &conn_type) &&
7831 	    conn_type != dc_connection_none) {
7832 		mutex_lock(&adev->dm.dc_lock);
7833 
7834 		/* Only call full link detection when a sink isn't created yet,
7835 		 * ie. just when the display is plugged in, otherwise we risk flickering.
7836 		 */
7837 		if (link->local_sink ||
7838 			dc_link_detect(link, DETECT_REASON_HPD))
7839 			status = connector_status_connected;
7840 
7841 		mutex_unlock(&adev->dm.dc_lock);
7842 	}
7843 
7844 	if (connector->status != status) {
7845 		if (status == connector_status_disconnected) {
7846 			if (link->local_sink)
7847 				dc_sink_release(link->local_sink);
7848 
7849 			link->local_sink = NULL;
7850 			link->dpcd_sink_count = 0;
7851 			link->type = dc_connection_none;
7852 		}
7853 
7854 		amdgpu_dm_update_connector_after_detect(aconnector);
7855 	}
7856 
7857 	mutex_unlock(&aconnector->hpd_lock);
7858 	return status;
7859 }
7860 
7861 /**
7862  * amdgpu_dm_connector_detect() - Detect whether a DRM connector is connected to a display
7863  *
7864  * A connector is considered connected when it has a sink that is not NULL.
7865  * For connectors that support HPD (hotplug detection), the connection is
7866  * handled in the HPD interrupt.
7867  * For connectors that may not support HPD, such as analog connectors,
7868  * DRM will call this function repeatedly to poll them.
7869  *
7870  * Notes:
7871  * 1. This interface is NOT called in context of HPD irq.
7872  * 2. This interface *is called* in context of user-mode ioctl. Which
7873  *    makes it a bad place for *any* MST-related activity.
7874  *
7875  * @connector: The DRM connector we are checking. We convert it to
7876  *             amdgpu_dm_connector so we can read the DC link and state.
7877  * @force:     If true, do a full detect again. This is used even when
7878  *             a lighter check would normally be used to avoid flicker.
7879  *
7880  * Return: The connector status (connected, disconnected, or unknown).
7881  *
7882  */
7883 static enum drm_connector_status
7884 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
7885 {
7886 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7887 
7888 	update_subconnector_property(aconnector);
7889 
7890 	if (aconnector->base.force == DRM_FORCE_ON ||
7891 		aconnector->base.force == DRM_FORCE_ON_DIGITAL)
7892 		return connector_status_connected;
7893 	else if (aconnector->base.force == DRM_FORCE_OFF)
7894 		return connector_status_disconnected;
7895 
7896 	/* Poll analog connectors and only when either
7897 	 * disconnected or connected to an analog display.
7898 	 */
7899 	if (drm_kms_helper_is_poll_worker() &&
7900 		dc_connector_supports_analog(aconnector->dc_link->link_id.id) &&
7901 		(!aconnector->dc_sink || aconnector->dc_sink->edid_caps.analog))
7902 		return amdgpu_dm_connector_poll(aconnector, force);
7903 
7904 	return (aconnector->dc_sink ? connector_status_connected :
7905 			connector_status_disconnected);
7906 }
7907 
7908 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
7909 					    struct drm_connector_state *connector_state,
7910 					    struct drm_property *property,
7911 					    uint64_t val)
7912 {
7913 	struct drm_device *dev = connector->dev;
7914 	struct amdgpu_device *adev = drm_to_adev(dev);
7915 	struct dm_connector_state *dm_old_state =
7916 		to_dm_connector_state(connector->state);
7917 	struct dm_connector_state *dm_new_state =
7918 		to_dm_connector_state(connector_state);
7919 
7920 	int ret = -EINVAL;
7921 
7922 	if (property == dev->mode_config.scaling_mode_property) {
7923 		enum amdgpu_rmx_type rmx_type;
7924 
7925 		switch (val) {
7926 		case DRM_MODE_SCALE_CENTER:
7927 			rmx_type = RMX_CENTER;
7928 			break;
7929 		case DRM_MODE_SCALE_ASPECT:
7930 			rmx_type = RMX_ASPECT;
7931 			break;
7932 		case DRM_MODE_SCALE_FULLSCREEN:
7933 			rmx_type = RMX_FULL;
7934 			break;
7935 		case DRM_MODE_SCALE_NONE:
7936 		default:
7937 			rmx_type = RMX_OFF;
7938 			break;
7939 		}
7940 
7941 		if (dm_old_state->scaling == rmx_type)
7942 			return 0;
7943 
7944 		dm_new_state->scaling = rmx_type;
7945 		ret = 0;
7946 	} else if (property == adev->mode_info.underscan_hborder_property) {
7947 		dm_new_state->underscan_hborder = val;
7948 		ret = 0;
7949 	} else if (property == adev->mode_info.underscan_vborder_property) {
7950 		dm_new_state->underscan_vborder = val;
7951 		ret = 0;
7952 	} else if (property == adev->mode_info.underscan_property) {
7953 		dm_new_state->underscan_enable = val;
7954 		ret = 0;
7955 	} else if (property == adev->mode_info.abm_level_property) {
7956 		switch (val) {
7957 		case ABM_SYSFS_CONTROL:
7958 			dm_new_state->abm_sysfs_forbidden = false;
7959 			break;
7960 		case ABM_LEVEL_OFF:
7961 			dm_new_state->abm_sysfs_forbidden = true;
7962 			dm_new_state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7963 			break;
7964 		default:
7965 			dm_new_state->abm_sysfs_forbidden = true;
7966 			dm_new_state->abm_level = val;
7967 		}
7968 		ret = 0;
7969 	}
7970 
7971 	return ret;
7972 }
7973 
7974 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
7975 					    const struct drm_connector_state *state,
7976 					    struct drm_property *property,
7977 					    uint64_t *val)
7978 {
7979 	struct drm_device *dev = connector->dev;
7980 	struct amdgpu_device *adev = drm_to_adev(dev);
7981 	struct dm_connector_state *dm_state =
7982 		to_dm_connector_state(state);
7983 	int ret = -EINVAL;
7984 
7985 	if (property == dev->mode_config.scaling_mode_property) {
7986 		switch (dm_state->scaling) {
7987 		case RMX_CENTER:
7988 			*val = DRM_MODE_SCALE_CENTER;
7989 			break;
7990 		case RMX_ASPECT:
7991 			*val = DRM_MODE_SCALE_ASPECT;
7992 			break;
7993 		case RMX_FULL:
7994 			*val = DRM_MODE_SCALE_FULLSCREEN;
7995 			break;
7996 		case RMX_OFF:
7997 		default:
7998 			*val = DRM_MODE_SCALE_NONE;
7999 			break;
8000 		}
8001 		ret = 0;
8002 	} else if (property == adev->mode_info.underscan_hborder_property) {
8003 		*val = dm_state->underscan_hborder;
8004 		ret = 0;
8005 	} else if (property == adev->mode_info.underscan_vborder_property) {
8006 		*val = dm_state->underscan_vborder;
8007 		ret = 0;
8008 	} else if (property == adev->mode_info.underscan_property) {
8009 		*val = dm_state->underscan_enable;
8010 		ret = 0;
8011 	} else if (property == adev->mode_info.abm_level_property) {
8012 		if (!dm_state->abm_sysfs_forbidden)
8013 			*val = ABM_SYSFS_CONTROL;
8014 		else
8015 			*val = (dm_state->abm_level != ABM_LEVEL_IMMEDIATE_DISABLE) ?
8016 				dm_state->abm_level : 0;
8017 		ret = 0;
8018 	}
8019 
8020 	return ret;
8021 }
8022 
8023 /**
8024  * DOC: panel power savings
8025  *
8026  * The display manager allows you to set your desired **panel power savings**
8027  * level (between 0-4, with 0 representing off), e.g. using the following::
8028  *
8029  *   # echo 3 > /sys/class/drm/card0-eDP-1/amdgpu/panel_power_savings
8030  *
8031  * Modifying this value can have implications on color accuracy, so tread
8032  * carefully.
8033  */
8034 
8035 static ssize_t panel_power_savings_show(struct device *device,
8036 					struct device_attribute *attr,
8037 					char *buf)
8038 {
8039 	struct drm_connector *connector = dev_get_drvdata(device);
8040 	struct drm_device *dev = connector->dev;
8041 	u8 val;
8042 
8043 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
8044 	val = to_dm_connector_state(connector->state)->abm_level ==
8045 		ABM_LEVEL_IMMEDIATE_DISABLE ? 0 :
8046 		to_dm_connector_state(connector->state)->abm_level;
8047 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
8048 
8049 	return sysfs_emit(buf, "%u\n", val);
8050 }
8051 
8052 static ssize_t panel_power_savings_store(struct device *device,
8053 					 struct device_attribute *attr,
8054 					 const char *buf, size_t count)
8055 {
8056 	struct drm_connector *connector = dev_get_drvdata(device);
8057 	struct drm_device *dev = connector->dev;
8058 	long val;
8059 	int ret;
8060 
8061 	ret = kstrtol(buf, 0, &val);
8062 
8063 	if (ret)
8064 		return ret;
8065 
8066 	if (val < 0 || val > 4)
8067 		return -EINVAL;
8068 
8069 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
8070 	if (to_dm_connector_state(connector->state)->abm_sysfs_forbidden)
8071 		ret = -EBUSY;
8072 	else
8073 		to_dm_connector_state(connector->state)->abm_level = val ?:
8074 			ABM_LEVEL_IMMEDIATE_DISABLE;
8075 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
8076 
8077 	if (ret)
8078 		return ret;
8079 
8080 	drm_kms_helper_hotplug_event(dev);
8081 
8082 	return count;
8083 }
8084 
8085 static DEVICE_ATTR_RW(panel_power_savings);
8086 
8087 static struct attribute *amdgpu_attrs[] = {
8088 	&dev_attr_panel_power_savings.attr,
8089 	NULL
8090 };
8091 
8092 static const struct attribute_group amdgpu_group = {
8093 	.name = "amdgpu",
8094 	.attrs = amdgpu_attrs
8095 };
8096 
8097 static bool
8098 amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector *amdgpu_dm_connector)
8099 {
8100 	if (amdgpu_dm_abm_level >= 0)
8101 		return false;
8102 
8103 	if (amdgpu_dm_connector->base.connector_type != DRM_MODE_CONNECTOR_eDP)
8104 		return false;
8105 
8106 	/* check for OLED panels */
8107 	if (amdgpu_dm_connector->bl_idx >= 0) {
8108 		struct drm_device *drm = amdgpu_dm_connector->base.dev;
8109 		struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
8110 		struct amdgpu_dm_backlight_caps *caps;
8111 
8112 		caps = &dm->backlight_caps[amdgpu_dm_connector->bl_idx];
8113 		if (caps->aux_support)
8114 			return false;
8115 	}
8116 
8117 	return true;
8118 }
8119 
8120 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
8121 {
8122 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
8123 
8124 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector))
8125 		sysfs_remove_group(&connector->kdev->kobj, &amdgpu_group);
8126 
8127 	cec_notifier_conn_unregister(amdgpu_dm_connector->notifier);
8128 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
8129 }
8130 
8131 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
8132 {
8133 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8134 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8135 	struct amdgpu_display_manager *dm = &adev->dm;
8136 
8137 	/*
8138 	 * Call only if mst_mgr was initialized before since it's not done
8139 	 * for all connector types.
8140 	 */
8141 	if (aconnector->mst_mgr.dev)
8142 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
8143 
8144 	/* Cancel and flush any pending HDMI HPD debounce work */
8145 	if (aconnector->hdmi_hpd_debounce_delay_ms) {
8146 		cancel_delayed_work_sync(&aconnector->hdmi_hpd_debounce_work);
8147 		if (aconnector->hdmi_prev_sink) {
8148 			dc_sink_release(aconnector->hdmi_prev_sink);
8149 			aconnector->hdmi_prev_sink = NULL;
8150 		}
8151 	}
8152 
8153 	if (aconnector->bl_idx != -1) {
8154 		backlight_device_unregister(dm->backlight_dev[aconnector->bl_idx]);
8155 		dm->backlight_dev[aconnector->bl_idx] = NULL;
8156 	}
8157 
8158 	if (aconnector->dc_em_sink)
8159 		dc_sink_release(aconnector->dc_em_sink);
8160 	aconnector->dc_em_sink = NULL;
8161 	if (aconnector->dc_sink)
8162 		dc_sink_release(aconnector->dc_sink);
8163 	aconnector->dc_sink = NULL;
8164 
8165 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
8166 	drm_connector_unregister(connector);
8167 	drm_connector_cleanup(connector);
8168 	kfree(aconnector->dm_dp_aux.aux.name);
8169 
8170 	kfree(connector);
8171 }
8172 
8173 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
8174 {
8175 	struct dm_connector_state *state =
8176 		to_dm_connector_state(connector->state);
8177 
8178 	if (connector->state)
8179 		__drm_atomic_helper_connector_destroy_state(connector->state);
8180 
8181 	kfree(state);
8182 
8183 	state = kzalloc_obj(*state);
8184 
8185 	if (state) {
8186 		state->scaling = RMX_OFF;
8187 		state->underscan_enable = false;
8188 		state->underscan_hborder = 0;
8189 		state->underscan_vborder = 0;
8190 		state->base.max_requested_bpc = 8;
8191 		state->vcpi_slots = 0;
8192 		state->pbn = 0;
8193 
8194 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) {
8195 			if (amdgpu_dm_abm_level <= 0)
8196 				state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
8197 			else
8198 				state->abm_level = amdgpu_dm_abm_level;
8199 		}
8200 
8201 		__drm_atomic_helper_connector_reset(connector, &state->base);
8202 	}
8203 }
8204 
8205 struct drm_connector_state *
8206 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
8207 {
8208 	struct dm_connector_state *state =
8209 		to_dm_connector_state(connector->state);
8210 
8211 	struct dm_connector_state *new_state =
8212 			kmemdup(state, sizeof(*state), GFP_KERNEL);
8213 
8214 	if (!new_state)
8215 		return NULL;
8216 
8217 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
8218 
8219 	new_state->freesync_capable = state->freesync_capable;
8220 	new_state->abm_level = state->abm_level;
8221 	new_state->scaling = state->scaling;
8222 	new_state->underscan_enable = state->underscan_enable;
8223 	new_state->underscan_hborder = state->underscan_hborder;
8224 	new_state->underscan_vborder = state->underscan_vborder;
8225 	new_state->vcpi_slots = state->vcpi_slots;
8226 	new_state->pbn = state->pbn;
8227 	return &new_state->base;
8228 }
8229 
8230 static int
8231 amdgpu_dm_connector_late_register(struct drm_connector *connector)
8232 {
8233 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8234 		to_amdgpu_dm_connector(connector);
8235 	int r;
8236 
8237 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector)) {
8238 		r = sysfs_create_group(&connector->kdev->kobj,
8239 				       &amdgpu_group);
8240 		if (r)
8241 			return r;
8242 	}
8243 
8244 	amdgpu_dm_register_backlight_device(amdgpu_dm_connector);
8245 
8246 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
8247 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
8248 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
8249 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
8250 		if (r)
8251 			return r;
8252 	}
8253 
8254 #if defined(CONFIG_DEBUG_FS)
8255 	connector_debugfs_init(amdgpu_dm_connector);
8256 #endif
8257 
8258 	return 0;
8259 }
8260 
8261 static void amdgpu_dm_connector_funcs_force(struct drm_connector *connector)
8262 {
8263 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8264 	struct dc_link *dc_link = aconnector->dc_link;
8265 	struct dc_sink *dc_em_sink = aconnector->dc_em_sink;
8266 	const struct drm_edid *drm_edid;
8267 	struct i2c_adapter *ddc;
8268 	struct drm_device *dev = connector->dev;
8269 
8270 	if (dc_link && dc_link->aux_mode)
8271 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8272 	else
8273 		ddc = &aconnector->i2c->base;
8274 
8275 	drm_edid = drm_edid_read_ddc(connector, ddc);
8276 	drm_edid_connector_update(connector, drm_edid);
8277 	if (!drm_edid) {
8278 		drm_err(dev, "No EDID found on connector: %s.\n", connector->name);
8279 		return;
8280 	}
8281 
8282 	aconnector->drm_edid = drm_edid;
8283 	/* Update emulated (virtual) sink's EDID */
8284 	if (dc_em_sink && dc_link) {
8285 		// FIXME: Get rid of drm_edid_raw()
8286 		const struct edid *edid = drm_edid_raw(drm_edid);
8287 
8288 		memset(&dc_em_sink->edid_caps, 0, sizeof(struct dc_edid_caps));
8289 		memmove(dc_em_sink->dc_edid.raw_edid, edid,
8290 			(edid->extensions + 1) * EDID_LENGTH);
8291 		dm_helpers_parse_edid_caps(
8292 			dc_link,
8293 			&dc_em_sink->dc_edid,
8294 			&dc_em_sink->edid_caps);
8295 	}
8296 }
8297 
8298 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
8299 	.reset = amdgpu_dm_connector_funcs_reset,
8300 	.detect = amdgpu_dm_connector_detect,
8301 	.fill_modes = drm_helper_probe_single_connector_modes,
8302 	.destroy = amdgpu_dm_connector_destroy,
8303 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
8304 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
8305 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
8306 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
8307 	.late_register = amdgpu_dm_connector_late_register,
8308 	.early_unregister = amdgpu_dm_connector_unregister,
8309 	.force = amdgpu_dm_connector_funcs_force
8310 };
8311 
8312 static int get_modes(struct drm_connector *connector)
8313 {
8314 	return amdgpu_dm_connector_get_modes(connector);
8315 }
8316 
8317 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
8318 {
8319 	struct drm_connector *connector = &aconnector->base;
8320 	struct dc_link *dc_link = aconnector->dc_link;
8321 	struct dc_sink_init_data init_params = {
8322 			.link = aconnector->dc_link,
8323 			.sink_signal = SIGNAL_TYPE_VIRTUAL
8324 	};
8325 	const struct drm_edid *drm_edid;
8326 	const struct edid *edid;
8327 	struct i2c_adapter *ddc;
8328 
8329 	if (dc_link && dc_link->aux_mode)
8330 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8331 	else
8332 		ddc = &aconnector->i2c->base;
8333 
8334 	drm_edid = drm_edid_read_ddc(connector, ddc);
8335 	drm_edid_connector_update(connector, drm_edid);
8336 	if (!drm_edid) {
8337 		drm_err(connector->dev, "No EDID found on connector: %s.\n", connector->name);
8338 		return;
8339 	}
8340 
8341 	if (connector->display_info.is_hdmi)
8342 		init_params.sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
8343 
8344 	aconnector->drm_edid = drm_edid;
8345 
8346 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
8347 	aconnector->dc_em_sink = dc_link_add_remote_sink(
8348 		aconnector->dc_link,
8349 		(uint8_t *)edid,
8350 		(edid->extensions + 1) * EDID_LENGTH,
8351 		&init_params);
8352 
8353 	if (aconnector->base.force == DRM_FORCE_ON) {
8354 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
8355 		aconnector->dc_link->local_sink :
8356 		aconnector->dc_em_sink;
8357 		if (aconnector->dc_sink)
8358 			dc_sink_retain(aconnector->dc_sink);
8359 	}
8360 }
8361 
8362 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
8363 {
8364 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
8365 
8366 	/*
8367 	 * In case of headless boot with force on for DP managed connector
8368 	 * Those settings have to be != 0 to get initial modeset
8369 	 */
8370 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
8371 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
8372 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
8373 	}
8374 
8375 	create_eml_sink(aconnector);
8376 }
8377 
8378 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
8379 						struct dc_stream_state *stream)
8380 {
8381 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
8382 	struct dc_plane_state *dc_plane_state = NULL;
8383 	struct dc_state *dc_state = NULL;
8384 
8385 	if (!stream)
8386 		goto cleanup;
8387 
8388 	dc_plane_state = dc_create_plane_state(dc);
8389 	if (!dc_plane_state)
8390 		goto cleanup;
8391 
8392 	dc_state = dc_state_create(dc, NULL);
8393 	if (!dc_state)
8394 		goto cleanup;
8395 
8396 	/* populate stream to plane */
8397 	dc_plane_state->src_rect.height  = stream->src.height;
8398 	dc_plane_state->src_rect.width   = stream->src.width;
8399 	dc_plane_state->dst_rect.height  = stream->src.height;
8400 	dc_plane_state->dst_rect.width   = stream->src.width;
8401 	dc_plane_state->clip_rect.height = stream->src.height;
8402 	dc_plane_state->clip_rect.width  = stream->src.width;
8403 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
8404 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
8405 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
8406 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
8407 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
8408 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
8409 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
8410 	dc_plane_state->rotation = ROTATION_ANGLE_0;
8411 	dc_plane_state->is_tiling_rotated = false;
8412 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
8413 
8414 	dc_result = dc_validate_stream(dc, stream);
8415 	if (dc_result == DC_OK)
8416 		dc_result = dc_validate_plane(dc, dc_plane_state);
8417 
8418 	if (dc_result == DC_OK)
8419 		dc_result = dc_state_add_stream(dc, dc_state, stream);
8420 
8421 	if (dc_result == DC_OK && !dc_state_add_plane(
8422 						dc,
8423 						stream,
8424 						dc_plane_state,
8425 						dc_state))
8426 		dc_result = DC_FAIL_ATTACH_SURFACES;
8427 
8428 	if (dc_result == DC_OK)
8429 		dc_result = dc_validate_global_state(dc, dc_state, DC_VALIDATE_MODE_ONLY);
8430 
8431 cleanup:
8432 	if (dc_state)
8433 		dc_state_release(dc_state);
8434 
8435 	if (dc_plane_state)
8436 		dc_plane_state_release(dc_plane_state);
8437 
8438 	return dc_result;
8439 }
8440 
8441 static enum dc_status
8442 dm_validate_stream_color_format(const struct drm_connector_state *drm_state,
8443 				const struct dc_stream_state *stream)
8444 {
8445 	enum dc_pixel_encoding encoding;
8446 
8447 	if (!drm_state->color_format)
8448 		return DC_OK;
8449 
8450 	switch (drm_state->color_format) {
8451 	case DRM_CONNECTOR_COLOR_FORMAT_AUTO:
8452 	case DRM_CONNECTOR_COLOR_FORMAT_RGB444:
8453 		encoding = PIXEL_ENCODING_RGB;
8454 		break;
8455 	case DRM_CONNECTOR_COLOR_FORMAT_YCBCR444:
8456 		encoding = PIXEL_ENCODING_YCBCR444;
8457 		break;
8458 	case DRM_CONNECTOR_COLOR_FORMAT_YCBCR422:
8459 		encoding = PIXEL_ENCODING_YCBCR422;
8460 		break;
8461 	case DRM_CONNECTOR_COLOR_FORMAT_YCBCR420:
8462 		encoding = PIXEL_ENCODING_YCBCR420;
8463 		break;
8464 	default:
8465 		encoding = PIXEL_ENCODING_UNDEFINED;
8466 		break;
8467 	}
8468 
8469 	return encoding == stream->timing.pixel_encoding ?
8470 		DC_OK : DC_UNSUPPORTED_VALUE;
8471 }
8472 
8473 struct dc_stream_state *
8474 create_validate_stream_for_sink(struct drm_connector *connector,
8475 				const struct drm_display_mode *drm_mode,
8476 				const struct dm_connector_state *dm_state,
8477 				const struct dc_stream_state *old_stream)
8478 {
8479 	struct amdgpu_dm_connector *aconnector = NULL;
8480 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8481 	struct dc_stream_state *stream;
8482 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
8483 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
8484 	enum dc_status dc_result = DC_OK;
8485 	uint8_t bpc_limit = 6;
8486 
8487 	if (!dm_state)
8488 		return NULL;
8489 
8490 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
8491 		aconnector = to_amdgpu_dm_connector(connector);
8492 
8493 	if (aconnector &&
8494 	    (aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
8495 	     aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_FRL ||
8496 	     aconnector->dc_link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER))
8497 		bpc_limit = 8;
8498 
8499 	do {
8500 		drm_dbg_kms(connector->dev, "Trying with %d bpc\n", requested_bpc);
8501 		stream = create_stream_for_sink(connector, drm_mode,
8502 						dm_state, old_stream,
8503 						requested_bpc);
8504 		if (stream == NULL) {
8505 			drm_err(adev_to_drm(adev), "Failed to create stream for sink!\n");
8506 			break;
8507 		}
8508 
8509 		dc_result = dc_validate_stream(adev->dm.dc, stream);
8510 
8511 		if (!aconnector) /* writeback connector */
8512 			return stream;
8513 
8514 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
8515 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
8516 
8517 		if (dc_result == DC_OK)
8518 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
8519 
8520 		if (dc_result == DC_OK)
8521 			dc_result = dm_validate_stream_color_format(drm_state, stream);
8522 
8523 		if (dc_result != DC_OK) {
8524 			drm_dbg_kms(connector->dev, "Pruned mode %d x %d (clk %d) %s %s -- %s\n",
8525 				      drm_mode->hdisplay,
8526 				      drm_mode->vdisplay,
8527 				      drm_mode->clock,
8528 				      dc_pixel_encoding_to_str(stream->timing.pixel_encoding),
8529 				      dc_color_depth_to_str(stream->timing.display_color_depth),
8530 				      dc_status_to_str(dc_result));
8531 
8532 			dc_stream_release(stream);
8533 			stream = NULL;
8534 			requested_bpc -= 2; /* lower bpc to retry validation */
8535 		}
8536 
8537 	} while (stream == NULL && requested_bpc >= bpc_limit);
8538 
8539 	switch (dc_result) {
8540 	/*
8541 	 * If we failed to validate DP bandwidth stream with the requested RGB color depth,
8542 	 * we try to fallback and configure in order:
8543 	 * YUV422 (8bpc, 6bpc)
8544 	 * YUV420 (8bpc, 6bpc)
8545 	 */
8546 	case DC_FAIL_ENC_VALIDATE:
8547 	case DC_EXCEED_DONGLE_CAP:
8548 	case DC_NO_DP_LINK_BANDWIDTH:
8549 		/* recursively entered twice and already tried both YUV422 and YUV420 */
8550 		if (aconnector->force_yuv422_output && aconnector->force_yuv420_output)
8551 			break;
8552 		/* first failure; try YUV422 */
8553 		if (!aconnector->force_yuv422_output) {
8554 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV422\n",
8555 				    __func__, __LINE__, dc_result);
8556 			aconnector->force_yuv422_output = true;
8557 		/* recursively entered and YUV422 failed, try YUV420 */
8558 		} else if (!aconnector->force_yuv420_output) {
8559 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV420\n",
8560 				    __func__, __LINE__, dc_result);
8561 			aconnector->force_yuv420_output = true;
8562 		}
8563 		stream = create_validate_stream_for_sink(connector, drm_mode,
8564 							 dm_state, old_stream);
8565 		aconnector->force_yuv422_output = false;
8566 		aconnector->force_yuv420_output = false;
8567 		break;
8568 	case DC_OK:
8569 		break;
8570 	default:
8571 		drm_dbg_kms(connector->dev, "%s:%d Unhandled validation failure %d\n",
8572 			    __func__, __LINE__, dc_result);
8573 		break;
8574 	}
8575 
8576 	return stream;
8577 }
8578 
8579 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
8580 				   const struct drm_display_mode *mode)
8581 {
8582 	int result = MODE_ERROR;
8583 	struct dc_sink *dc_sink;
8584 	struct drm_display_mode *test_mode;
8585 	/* TODO: Unhardcode stream count */
8586 	struct dc_stream_state *stream;
8587 	/* we always have an amdgpu_dm_connector here since we got
8588 	 * here via the amdgpu_dm_connector_helper_funcs
8589 	 */
8590 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8591 
8592 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
8593 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
8594 		return result;
8595 
8596 	/*
8597 	 * Only run this the first time mode_valid is called to initilialize
8598 	 * EDID mgmt
8599 	 */
8600 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
8601 		!aconnector->dc_em_sink)
8602 		handle_edid_mgmt(aconnector);
8603 
8604 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
8605 
8606 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
8607 				aconnector->base.force != DRM_FORCE_ON) {
8608 		drm_err(connector->dev, "dc_sink is NULL!\n");
8609 		goto fail;
8610 	}
8611 
8612 	test_mode = drm_mode_duplicate(connector->dev, mode);
8613 	if (!test_mode)
8614 		goto fail;
8615 
8616 	drm_mode_set_crtcinfo(test_mode, 0);
8617 
8618 	stream = create_validate_stream_for_sink(connector, test_mode,
8619 						 to_dm_connector_state(connector->state),
8620 						 NULL);
8621 	drm_mode_destroy(connector->dev, test_mode);
8622 	if (stream) {
8623 		dc_stream_release(stream);
8624 		result = MODE_OK;
8625 	}
8626 
8627 fail:
8628 	/* TODO: error handling*/
8629 	return result;
8630 }
8631 
8632 static int fill_hdr_info_packet(const struct drm_connector_state *state,
8633 				struct dc_info_packet *out)
8634 {
8635 	struct hdmi_drm_infoframe frame;
8636 	unsigned char buf[30]; /* 26 + 4 */
8637 	ssize_t len;
8638 	int ret, i;
8639 
8640 	memset(out, 0, sizeof(*out));
8641 
8642 	if (!state->hdr_output_metadata)
8643 		return 0;
8644 
8645 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
8646 	if (ret)
8647 		return ret;
8648 
8649 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
8650 	if (len < 0)
8651 		return (int)len;
8652 
8653 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
8654 	if (len != 30)
8655 		return -EINVAL;
8656 
8657 	/* Prepare the infopacket for DC. */
8658 	switch (state->connector->connector_type) {
8659 	case DRM_MODE_CONNECTOR_HDMIA:
8660 		out->hb0 = 0x87; /* type */
8661 		out->hb1 = 0x01; /* version */
8662 		out->hb2 = 0x1A; /* length */
8663 		out->sb[0] = buf[3]; /* checksum */
8664 		i = 1;
8665 		break;
8666 
8667 	case DRM_MODE_CONNECTOR_DisplayPort:
8668 	case DRM_MODE_CONNECTOR_eDP:
8669 		out->hb0 = 0x00; /* sdp id, zero */
8670 		out->hb1 = 0x87; /* type */
8671 		out->hb2 = 0x1D; /* payload len - 1 */
8672 		out->hb3 = (0x13 << 2); /* sdp version */
8673 		out->sb[0] = 0x01; /* version */
8674 		out->sb[1] = 0x1A; /* length */
8675 		i = 2;
8676 		break;
8677 
8678 	default:
8679 		return -EINVAL;
8680 	}
8681 
8682 	memcpy(&out->sb[i], &buf[4], 26);
8683 	out->valid = true;
8684 
8685 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
8686 		       sizeof(out->sb), false);
8687 
8688 	return 0;
8689 }
8690 
8691 static int
8692 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
8693 				 struct drm_atomic_commit *state)
8694 {
8695 	struct drm_connector_state *new_con_state =
8696 		drm_atomic_get_new_connector_state(state, conn);
8697 	struct drm_connector_state *old_con_state =
8698 		drm_atomic_get_old_connector_state(state, conn);
8699 	struct drm_crtc *crtc = new_con_state->crtc;
8700 	struct drm_crtc_state *new_crtc_state;
8701 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
8702 	int ret;
8703 
8704 	if (WARN_ON(unlikely(!old_con_state || !new_con_state)))
8705 		return -EINVAL;
8706 
8707 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
8708 
8709 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
8710 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
8711 		if (ret < 0)
8712 			return ret;
8713 	}
8714 
8715 	if (!crtc)
8716 		return 0;
8717 
8718 	if (new_con_state->privacy_screen_sw_state != old_con_state->privacy_screen_sw_state) {
8719 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8720 		if (IS_ERR(new_crtc_state))
8721 			return PTR_ERR(new_crtc_state);
8722 
8723 		new_crtc_state->mode_changed = true;
8724 	}
8725 
8726 	if (new_con_state->colorspace != old_con_state->colorspace) {
8727 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8728 		if (IS_ERR(new_crtc_state))
8729 			return PTR_ERR(new_crtc_state);
8730 
8731 		new_crtc_state->mode_changed = true;
8732 	}
8733 
8734 	if (new_con_state->content_type != old_con_state->content_type) {
8735 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8736 		if (IS_ERR(new_crtc_state))
8737 			return PTR_ERR(new_crtc_state);
8738 
8739 		new_crtc_state->mode_changed = true;
8740 	}
8741 
8742 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
8743 		struct dc_info_packet hdr_infopacket;
8744 
8745 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
8746 		if (ret)
8747 			return ret;
8748 
8749 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8750 		if (IS_ERR(new_crtc_state))
8751 			return PTR_ERR(new_crtc_state);
8752 
8753 		/*
8754 		 * DC considers the stream backends changed if the
8755 		 * static metadata changes. Forcing the modeset also
8756 		 * gives a simple way for userspace to switch from
8757 		 * 8bpc to 10bpc when setting the metadata to enter
8758 		 * or exit HDR.
8759 		 *
8760 		 * Changing the static metadata after it's been
8761 		 * set is permissible, however. So only force a
8762 		 * modeset if we're entering or exiting HDR.
8763 		 */
8764 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
8765 			!old_con_state->hdr_output_metadata ||
8766 			!new_con_state->hdr_output_metadata;
8767 	}
8768 
8769 	return 0;
8770 }
8771 
8772 static const struct drm_connector_helper_funcs
8773 amdgpu_dm_connector_helper_funcs = {
8774 	/*
8775 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
8776 	 * modes will be filtered by drm_mode_validate_size(), and those modes
8777 	 * are missing after user start lightdm. So we need to renew modes list.
8778 	 * in get_modes call back, not just return the modes count
8779 	 */
8780 	.get_modes = get_modes,
8781 	.mode_valid = amdgpu_dm_connector_mode_valid,
8782 	.atomic_check = amdgpu_dm_connector_atomic_check,
8783 };
8784 
8785 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
8786 {
8787 
8788 }
8789 
8790 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
8791 {
8792 	switch (display_color_depth) {
8793 	case COLOR_DEPTH_666:
8794 		return 6;
8795 	case COLOR_DEPTH_888:
8796 		return 8;
8797 	case COLOR_DEPTH_101010:
8798 		return 10;
8799 	case COLOR_DEPTH_121212:
8800 		return 12;
8801 	case COLOR_DEPTH_141414:
8802 		return 14;
8803 	case COLOR_DEPTH_161616:
8804 		return 16;
8805 	default:
8806 		break;
8807 	}
8808 	return 0;
8809 }
8810 
8811 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
8812 					  struct drm_crtc_state *crtc_state,
8813 					  struct drm_connector_state *conn_state)
8814 {
8815 	struct drm_atomic_commit *state = crtc_state->state;
8816 	struct drm_connector *connector = conn_state->connector;
8817 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8818 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
8819 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
8820 	struct drm_dp_mst_topology_mgr *mst_mgr;
8821 	struct drm_dp_mst_port *mst_port;
8822 	struct drm_dp_mst_topology_state *mst_state;
8823 	enum dc_color_depth color_depth;
8824 	int clock, bpp = 0;
8825 	bool is_y420 = false;
8826 
8827 	if ((connector->connector_type == DRM_MODE_CONNECTOR_eDP) ||
8828 	    (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)) {
8829 		struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8830 		struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8831 		enum drm_mode_status result;
8832 
8833 		result = drm_crtc_helper_mode_valid_fixed(encoder->crtc, adjusted_mode, native_mode);
8834 		if (result != MODE_OK && dm_new_connector_state->scaling == RMX_OFF) {
8835 			drm_dbg_driver(encoder->dev,
8836 				       "mode %dx%d@%dHz is not native, enabling scaling\n",
8837 				       adjusted_mode->hdisplay, adjusted_mode->vdisplay,
8838 				       drm_mode_vrefresh(adjusted_mode));
8839 			dm_new_connector_state->scaling = RMX_ASPECT;
8840 		}
8841 		return 0;
8842 	}
8843 
8844 	if (!aconnector->mst_output_port)
8845 		return 0;
8846 
8847 	mst_port = aconnector->mst_output_port;
8848 	mst_mgr = &aconnector->mst_root->mst_mgr;
8849 
8850 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
8851 		return 0;
8852 
8853 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
8854 	if (IS_ERR(mst_state))
8855 		return PTR_ERR(mst_state);
8856 
8857 	mst_state->pbn_div.full = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
8858 
8859 	if (!state->duplicated) {
8860 		int max_bpc = conn_state->max_requested_bpc;
8861 
8862 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
8863 			  aconnector->force_yuv420_output;
8864 		color_depth = convert_color_depth_from_display_info(connector,
8865 								    is_y420,
8866 								    max_bpc);
8867 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
8868 		clock = adjusted_mode->clock;
8869 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
8870 	}
8871 
8872 	dm_new_connector_state->vcpi_slots =
8873 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
8874 					      dm_new_connector_state->pbn);
8875 	if (dm_new_connector_state->vcpi_slots < 0) {
8876 		drm_dbg_atomic(connector->dev, "failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
8877 		return dm_new_connector_state->vcpi_slots;
8878 	}
8879 	return 0;
8880 }
8881 
8882 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
8883 	.disable = dm_encoder_helper_disable,
8884 	.atomic_check = dm_encoder_helper_atomic_check
8885 };
8886 
8887 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_commit *state,
8888 					    struct dc_state *dc_state,
8889 					    struct dsc_mst_fairness_vars *vars)
8890 {
8891 	struct dc_stream_state *stream = NULL;
8892 	struct drm_connector *connector;
8893 	struct drm_connector_state *new_con_state;
8894 	struct amdgpu_dm_connector *aconnector;
8895 	struct dm_connector_state *dm_conn_state;
8896 	int i, j, ret;
8897 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
8898 
8899 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8900 
8901 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
8902 			continue;
8903 
8904 		aconnector = to_amdgpu_dm_connector(connector);
8905 
8906 		if (!aconnector->mst_output_port)
8907 			continue;
8908 
8909 		if (!new_con_state || !new_con_state->crtc)
8910 			continue;
8911 
8912 		dm_conn_state = to_dm_connector_state(new_con_state);
8913 
8914 		for (j = 0; j < dc_state->stream_count; j++) {
8915 			stream = dc_state->streams[j];
8916 			if (!stream)
8917 				continue;
8918 
8919 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
8920 				break;
8921 
8922 			stream = NULL;
8923 		}
8924 
8925 		if (!stream)
8926 			continue;
8927 
8928 		pbn_div = dm_mst_get_pbn_divider(stream->link);
8929 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
8930 		for (j = 0; j < dc_state->stream_count; j++) {
8931 			if (vars[j].aconnector == aconnector) {
8932 				pbn = vars[j].pbn;
8933 				break;
8934 			}
8935 		}
8936 
8937 		if (j == dc_state->stream_count || pbn_div == 0)
8938 			continue;
8939 
8940 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
8941 
8942 		if (stream->timing.flags.DSC != 1) {
8943 			dm_conn_state->pbn = pbn;
8944 			dm_conn_state->vcpi_slots = slot_num;
8945 
8946 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
8947 							   dm_conn_state->pbn, false);
8948 			if (ret < 0)
8949 				return ret;
8950 
8951 			continue;
8952 		}
8953 
8954 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
8955 		if (vcpi < 0)
8956 			return vcpi;
8957 
8958 		dm_conn_state->pbn = pbn;
8959 		dm_conn_state->vcpi_slots = vcpi;
8960 	}
8961 	return 0;
8962 }
8963 
8964 static int to_drm_connector_type(enum signal_type st, uint32_t connector_id)
8965 {
8966 	switch (st) {
8967 	case SIGNAL_TYPE_HDMI_TYPE_A:
8968 		return DRM_MODE_CONNECTOR_HDMIA;
8969 	case SIGNAL_TYPE_EDP:
8970 		return DRM_MODE_CONNECTOR_eDP;
8971 	case SIGNAL_TYPE_LVDS:
8972 		return DRM_MODE_CONNECTOR_LVDS;
8973 	case SIGNAL_TYPE_RGB:
8974 		return DRM_MODE_CONNECTOR_VGA;
8975 	case SIGNAL_TYPE_DISPLAY_PORT:
8976 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
8977 		/* External DP bridges have a different connector type. */
8978 		if (connector_id == CONNECTOR_ID_VGA)
8979 			return DRM_MODE_CONNECTOR_VGA;
8980 		else if (connector_id == CONNECTOR_ID_LVDS)
8981 			return DRM_MODE_CONNECTOR_LVDS;
8982 
8983 		return DRM_MODE_CONNECTOR_DisplayPort;
8984 	case SIGNAL_TYPE_DVI_DUAL_LINK:
8985 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
8986 		if (connector_id == CONNECTOR_ID_SINGLE_LINK_DVII ||
8987 			connector_id == CONNECTOR_ID_DUAL_LINK_DVII)
8988 			return DRM_MODE_CONNECTOR_DVII;
8989 
8990 		return DRM_MODE_CONNECTOR_DVID;
8991 	case SIGNAL_TYPE_VIRTUAL:
8992 		return DRM_MODE_CONNECTOR_VIRTUAL;
8993 
8994 	default:
8995 		return DRM_MODE_CONNECTOR_Unknown;
8996 	}
8997 }
8998 
8999 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
9000 {
9001 	struct drm_encoder *encoder;
9002 
9003 	/* There is only one encoder per connector */
9004 	drm_connector_for_each_possible_encoder(connector, encoder)
9005 		return encoder;
9006 
9007 	return NULL;
9008 }
9009 
9010 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
9011 {
9012 	struct drm_encoder *encoder;
9013 	struct amdgpu_encoder *amdgpu_encoder;
9014 
9015 	encoder = amdgpu_dm_connector_to_encoder(connector);
9016 
9017 	if (encoder == NULL)
9018 		return;
9019 
9020 	amdgpu_encoder = to_amdgpu_encoder(encoder);
9021 
9022 	amdgpu_encoder->native_mode.clock = 0;
9023 
9024 	if (!list_empty(&connector->probed_modes)) {
9025 		struct drm_display_mode *preferred_mode = NULL;
9026 
9027 		list_for_each_entry(preferred_mode,
9028 				    &connector->probed_modes,
9029 				    head) {
9030 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
9031 				amdgpu_encoder->native_mode = *preferred_mode;
9032 
9033 			break;
9034 		}
9035 
9036 	}
9037 }
9038 
9039 static struct drm_display_mode *
9040 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
9041 			     const char *name,
9042 			     int hdisplay, int vdisplay)
9043 {
9044 	struct drm_device *dev = encoder->dev;
9045 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
9046 	struct drm_display_mode *mode = NULL;
9047 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
9048 
9049 	mode = drm_mode_duplicate(dev, native_mode);
9050 
9051 	if (mode == NULL)
9052 		return NULL;
9053 
9054 	mode->hdisplay = hdisplay;
9055 	mode->vdisplay = vdisplay;
9056 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
9057 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
9058 
9059 	return mode;
9060 
9061 }
9062 
9063 static const struct amdgpu_dm_mode_size {
9064 	char name[DRM_DISPLAY_MODE_LEN];
9065 	int w;
9066 	int h;
9067 } common_modes[] = {
9068 	{  "640x480",  640,  480},
9069 	{  "800x600",  800,  600},
9070 	{ "1024x768", 1024,  768},
9071 	{ "1280x720", 1280,  720},
9072 	{ "1280x800", 1280,  800},
9073 	{"1280x1024", 1280, 1024},
9074 	{ "1440x900", 1440,  900},
9075 	{"1680x1050", 1680, 1050},
9076 	{"1600x1200", 1600, 1200},
9077 	{"1920x1080", 1920, 1080},
9078 	{"1920x1200", 1920, 1200}
9079 };
9080 
9081 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
9082 						 struct drm_connector *connector)
9083 {
9084 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
9085 	struct drm_display_mode *mode = NULL;
9086 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
9087 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9088 				to_amdgpu_dm_connector(connector);
9089 	int i;
9090 	int n;
9091 
9092 	if ((connector->connector_type != DRM_MODE_CONNECTOR_eDP) &&
9093 	    (connector->connector_type != DRM_MODE_CONNECTOR_LVDS))
9094 		return;
9095 
9096 	n = ARRAY_SIZE(common_modes);
9097 
9098 	for (i = 0; i < n; i++) {
9099 		struct drm_display_mode *curmode = NULL;
9100 		bool mode_existed = false;
9101 
9102 		if (common_modes[i].w > native_mode->hdisplay ||
9103 		    common_modes[i].h > native_mode->vdisplay ||
9104 		   (common_modes[i].w == native_mode->hdisplay &&
9105 		    common_modes[i].h == native_mode->vdisplay))
9106 			continue;
9107 
9108 		list_for_each_entry(curmode, &connector->probed_modes, head) {
9109 			if (common_modes[i].w == curmode->hdisplay &&
9110 			    common_modes[i].h == curmode->vdisplay) {
9111 				mode_existed = true;
9112 				break;
9113 			}
9114 		}
9115 
9116 		if (mode_existed)
9117 			continue;
9118 
9119 		mode = amdgpu_dm_create_common_mode(encoder,
9120 				common_modes[i].name, common_modes[i].w,
9121 				common_modes[i].h);
9122 		if (!mode)
9123 			continue;
9124 
9125 		drm_mode_probed_add(connector, mode);
9126 		amdgpu_dm_connector->num_modes++;
9127 	}
9128 }
9129 
9130 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
9131 {
9132 	struct drm_encoder *encoder;
9133 	struct amdgpu_encoder *amdgpu_encoder;
9134 	const struct drm_display_mode *native_mode;
9135 
9136 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
9137 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
9138 		return;
9139 
9140 	mutex_lock(&connector->dev->mode_config.mutex);
9141 	amdgpu_dm_connector_get_modes(connector);
9142 	mutex_unlock(&connector->dev->mode_config.mutex);
9143 
9144 	encoder = amdgpu_dm_connector_to_encoder(connector);
9145 	if (!encoder)
9146 		return;
9147 
9148 	amdgpu_encoder = to_amdgpu_encoder(encoder);
9149 
9150 	native_mode = &amdgpu_encoder->native_mode;
9151 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
9152 		return;
9153 
9154 	drm_connector_set_panel_orientation_with_quirk(connector,
9155 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
9156 						       native_mode->hdisplay,
9157 						       native_mode->vdisplay);
9158 }
9159 
9160 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
9161 					      const struct drm_edid *drm_edid)
9162 {
9163 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9164 			to_amdgpu_dm_connector(connector);
9165 
9166 	if (drm_edid) {
9167 		/* empty probed_modes */
9168 		INIT_LIST_HEAD(&connector->probed_modes);
9169 		amdgpu_dm_connector->num_modes =
9170 				drm_edid_connector_add_modes(connector);
9171 
9172 		/* sorting the probed modes before calling function
9173 		 * amdgpu_dm_get_native_mode() since EDID can have
9174 		 * more than one preferred mode. The modes that are
9175 		 * later in the probed mode list could be of higher
9176 		 * and preferred resolution. For example, 3840x2160
9177 		 * resolution in base EDID preferred timing and 4096x2160
9178 		 * preferred resolution in DID extension block later.
9179 		 */
9180 		drm_mode_sort(&connector->probed_modes);
9181 		amdgpu_dm_get_native_mode(connector);
9182 
9183 		/* Freesync capabilities are reset by calling
9184 		 * drm_edid_connector_add_modes() and need to be
9185 		 * restored here.
9186 		 */
9187 		amdgpu_dm_update_freesync_caps(connector, drm_edid, false);
9188 	} else {
9189 		amdgpu_dm_connector->num_modes = 0;
9190 	}
9191 }
9192 
9193 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
9194 			      struct drm_display_mode *mode)
9195 {
9196 	struct drm_display_mode *m;
9197 
9198 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
9199 		if (drm_mode_equal(m, mode))
9200 			return true;
9201 	}
9202 
9203 	return false;
9204 }
9205 
9206 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
9207 {
9208 	const struct drm_display_mode *m;
9209 	struct drm_display_mode *new_mode;
9210 	uint i;
9211 	u32 new_modes_count = 0;
9212 
9213 	/* Standard FPS values
9214 	 *
9215 	 * 23.976       - TV/NTSC
9216 	 * 24           - Cinema
9217 	 * 25           - TV/PAL
9218 	 * 29.97        - TV/NTSC
9219 	 * 30           - TV/NTSC
9220 	 * 48           - Cinema HFR
9221 	 * 50           - TV/PAL
9222 	 * 60           - Commonly used
9223 	 * 48,72,96,120 - Multiples of 24
9224 	 */
9225 	static const u32 common_rates[] = {
9226 		23976, 24000, 25000, 29970, 30000,
9227 		48000, 50000, 60000, 72000, 96000, 120000
9228 	};
9229 
9230 	/*
9231 	 * Find mode with highest refresh rate with the same resolution
9232 	 * as the preferred mode. Some monitors report a preferred mode
9233 	 * with lower resolution than the highest refresh rate supported.
9234 	 */
9235 
9236 	m = get_highest_refresh_rate_mode(aconnector, true);
9237 	if (!m)
9238 		return 0;
9239 
9240 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
9241 		u64 target_vtotal, target_vtotal_diff;
9242 		u64 num, den;
9243 
9244 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
9245 			continue;
9246 
9247 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
9248 		    common_rates[i] > aconnector->max_vfreq * 1000)
9249 			continue;
9250 
9251 		num = (unsigned long long)m->clock * 1000 * 1000;
9252 		den = common_rates[i] * (unsigned long long)m->htotal;
9253 		target_vtotal = div_u64(num, den);
9254 		target_vtotal_diff = target_vtotal - m->vtotal;
9255 
9256 		/* Check for illegal modes */
9257 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
9258 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
9259 		    m->vtotal + target_vtotal_diff < m->vsync_end)
9260 			continue;
9261 
9262 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
9263 		if (!new_mode)
9264 			goto out;
9265 
9266 		new_mode->vtotal += (u16)target_vtotal_diff;
9267 		new_mode->vsync_start += (u16)target_vtotal_diff;
9268 		new_mode->vsync_end += (u16)target_vtotal_diff;
9269 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
9270 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
9271 
9272 		if (!is_duplicate_mode(aconnector, new_mode)) {
9273 			drm_mode_probed_add(&aconnector->base, new_mode);
9274 			new_modes_count += 1;
9275 		} else
9276 			drm_mode_destroy(aconnector->base.dev, new_mode);
9277 	}
9278  out:
9279 	return new_modes_count;
9280 }
9281 
9282 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
9283 						   const struct drm_edid *drm_edid)
9284 {
9285 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9286 		to_amdgpu_dm_connector(connector);
9287 
9288 	if (!(amdgpu_freesync_vid_mode && drm_edid))
9289 		return;
9290 
9291 	if (!amdgpu_dm_connector->dc_sink || !amdgpu_dm_connector->dc_link)
9292 		return;
9293 
9294 	if (!dc_supports_vrr(amdgpu_dm_connector->dc_sink->ctx->dce_version))
9295 		return;
9296 
9297 	if (dc_connector_supports_analog(amdgpu_dm_connector->dc_link->link_id.id) &&
9298 	    amdgpu_dm_connector->dc_sink->edid_caps.analog)
9299 		return;
9300 
9301 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
9302 		amdgpu_dm_connector->num_modes +=
9303 			add_fs_modes(amdgpu_dm_connector);
9304 }
9305 
9306 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
9307 {
9308 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9309 			to_amdgpu_dm_connector(connector);
9310 	struct dc_link *dc_link = amdgpu_dm_connector->dc_link;
9311 	struct drm_encoder *encoder;
9312 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
9313 	struct dc_link_settings *verified_link_cap = &dc_link->verified_link_cap;
9314 	const struct dc *dc = dc_link->dc;
9315 
9316 	encoder = amdgpu_dm_connector_to_encoder(connector);
9317 
9318 	if (!drm_edid) {
9319 		amdgpu_dm_connector->num_modes =
9320 				drm_add_modes_noedid(connector, 640, 480);
9321 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
9322 			amdgpu_dm_connector->num_modes +=
9323 				drm_add_modes_noedid(connector, 1920, 1080);
9324 
9325 		if (amdgpu_dm_connector->dc_sink &&
9326 		    amdgpu_dm_connector->dc_sink->edid_caps.analog &&
9327 		    dc_connector_supports_analog(dc_link->link_id.id)) {
9328 			/* Analog monitor connected by DAC load detection.
9329 			 * Add common modes. It will be up to the user to select one that works.
9330 			 */
9331 			for (int i = 0; i < ARRAY_SIZE(common_modes); i++)
9332 				amdgpu_dm_connector->num_modes += drm_add_modes_noedid(
9333 					connector, common_modes[i].w, common_modes[i].h);
9334 		}
9335 	} else {
9336 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
9337 		if (encoder)
9338 			amdgpu_dm_connector_add_common_modes(encoder, connector);
9339 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
9340 	}
9341 	amdgpu_dm_fbc_init(connector);
9342 
9343 	return amdgpu_dm_connector->num_modes;
9344 }
9345 
9346 static const u32 supported_colorspaces =
9347 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
9348 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
9349 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
9350 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
9351 
9352 static const u32 supported_colorformats =
9353 	BIT(DRM_OUTPUT_COLOR_FORMAT_RGB444) |
9354 	BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR444) |
9355 	BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR422) |
9356 	BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR420);
9357 
9358 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
9359 				     struct amdgpu_dm_connector *aconnector,
9360 				     int connector_type,
9361 				     struct dc_link *link,
9362 				     int link_index)
9363 {
9364 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
9365 
9366 	/*
9367 	 * Some of the properties below require access to state, like bpc.
9368 	 * Allocate some default initial connector state with our reset helper.
9369 	 */
9370 	if (aconnector->base.funcs->reset)
9371 		aconnector->base.funcs->reset(&aconnector->base);
9372 
9373 	aconnector->connector_id = link_index;
9374 	aconnector->bl_idx = -1;
9375 	aconnector->dc_link = link;
9376 	aconnector->base.interlace_allowed = false;
9377 	aconnector->base.doublescan_allowed = false;
9378 	aconnector->base.stereo_allowed = false;
9379 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
9380 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
9381 	aconnector->audio_inst = -1;
9382 	aconnector->pack_sdp_v1_3 = false;
9383 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
9384 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
9385 	mutex_init(&aconnector->hpd_lock);
9386 	mutex_init(&aconnector->handle_mst_msg_ready);
9387 
9388 	/*
9389 	 * If HDMI HPD debounce delay is set, use the minimum between selected
9390 	 * value and AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS
9391 	 */
9392 	if (amdgpu_hdmi_hpd_debounce_delay_ms) {
9393 		aconnector->hdmi_hpd_debounce_delay_ms = min(amdgpu_hdmi_hpd_debounce_delay_ms,
9394 							     AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS);
9395 		INIT_DELAYED_WORK(&aconnector->hdmi_hpd_debounce_work, hdmi_hpd_debounce_work);
9396 		aconnector->hdmi_prev_sink = NULL;
9397 	} else {
9398 		aconnector->hdmi_hpd_debounce_delay_ms = 0;
9399 	}
9400 
9401 	/*
9402 	 * configure support HPD hot plug connector_>polled default value is 0
9403 	 * which means HPD hot plug not supported
9404 	 */
9405 	switch (connector_type) {
9406 	case DRM_MODE_CONNECTOR_HDMIA:
9407 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9408 		aconnector->base.ycbcr_420_allowed =
9409 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
9410 		break;
9411 	case DRM_MODE_CONNECTOR_DisplayPort:
9412 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9413 		link->link_enc = link_enc_cfg_get_link_enc(link);
9414 		ASSERT(link->link_enc);
9415 		if (link->link_enc)
9416 			aconnector->base.ycbcr_420_allowed =
9417 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
9418 		break;
9419 	case DRM_MODE_CONNECTOR_DVID:
9420 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9421 		break;
9422 	case DRM_MODE_CONNECTOR_DVII:
9423 	case DRM_MODE_CONNECTOR_VGA:
9424 		aconnector->base.polled =
9425 			DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT;
9426 		break;
9427 	default:
9428 		break;
9429 	}
9430 
9431 	drm_object_attach_property(&aconnector->base.base,
9432 				dm->ddev->mode_config.scaling_mode_property,
9433 				DRM_MODE_SCALE_NONE);
9434 
9435 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA
9436 		|| (connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root))
9437 		drm_connector_attach_broadcast_rgb_property(&aconnector->base);
9438 
9439 	drm_object_attach_property(&aconnector->base.base,
9440 				adev->mode_info.underscan_property,
9441 				UNDERSCAN_OFF);
9442 	drm_object_attach_property(&aconnector->base.base,
9443 				adev->mode_info.underscan_hborder_property,
9444 				0);
9445 	drm_object_attach_property(&aconnector->base.base,
9446 				adev->mode_info.underscan_vborder_property,
9447 				0);
9448 
9449 	if (!aconnector->mst_root)
9450 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
9451 
9452 	aconnector->base.state->max_bpc = 16;
9453 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
9454 
9455 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9456 		/* Content Type is currently only implemented for HDMI. */
9457 		drm_connector_attach_content_type_property(&aconnector->base);
9458 	}
9459 
9460 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9461 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
9462 			drm_connector_attach_colorspace_property(&aconnector->base);
9463 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
9464 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
9465 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
9466 			drm_connector_attach_colorspace_property(&aconnector->base);
9467 	}
9468 
9469 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9470 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
9471 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
9472 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
9473 
9474 		if (!aconnector->mst_root) {
9475 			drm_connector_attach_vrr_capable_property(&aconnector->base);
9476 			drm_connector_attach_color_format_property(&aconnector->base,
9477 								   supported_colorformats);
9478 		}
9479 
9480 		if (adev->dm.hdcp_workqueue)
9481 			drm_connector_attach_content_protection_property(&aconnector->base, true);
9482 	}
9483 
9484 	if (connector_type == DRM_MODE_CONNECTOR_eDP) {
9485 		struct drm_privacy_screen *privacy_screen;
9486 
9487 		drm_connector_attach_panel_type_property(&aconnector->base);
9488 
9489 		privacy_screen = drm_privacy_screen_get(adev_to_drm(adev)->dev, NULL);
9490 		if (!IS_ERR(privacy_screen)) {
9491 			drm_connector_attach_privacy_screen_provider(&aconnector->base,
9492 								     privacy_screen);
9493 		} else if (PTR_ERR(privacy_screen) != -ENODEV) {
9494 			drm_warn(adev_to_drm(adev), "Error getting privacy-screen\n");
9495 		}
9496 	}
9497 }
9498 
9499 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
9500 			      struct i2c_msg *msgs, int num)
9501 {
9502 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
9503 	struct ddc_service *ddc_service = i2c->ddc_service;
9504 	struct i2c_command cmd;
9505 	int i;
9506 	int result = -EIO;
9507 
9508 	if (!ddc_service->ddc_pin)
9509 		return result;
9510 
9511 	cmd.payloads = kzalloc_objs(struct i2c_payload, num);
9512 
9513 	if (!cmd.payloads)
9514 		return result;
9515 
9516 	cmd.number_of_payloads = num;
9517 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
9518 	cmd.speed = 100;
9519 
9520 	for (i = 0; i < num; i++) {
9521 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
9522 		cmd.payloads[i].address = msgs[i].addr;
9523 		cmd.payloads[i].length = msgs[i].len;
9524 		cmd.payloads[i].data = msgs[i].buf;
9525 	}
9526 
9527 	if (i2c->oem) {
9528 		if (dc_submit_i2c_oem(
9529 			    ddc_service->ctx->dc,
9530 			    &cmd))
9531 			result = num;
9532 	} else {
9533 		if (dc_submit_i2c(
9534 			    ddc_service->ctx->dc,
9535 			    ddc_service->link->link_index,
9536 			    &cmd))
9537 			result = num;
9538 	}
9539 
9540 	kfree(cmd.payloads);
9541 	return result;
9542 }
9543 
9544 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
9545 {
9546 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
9547 }
9548 
9549 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
9550 	.master_xfer = amdgpu_dm_i2c_xfer,
9551 	.functionality = amdgpu_dm_i2c_func,
9552 };
9553 
9554 static struct amdgpu_i2c_adapter *
9555 create_i2c(struct ddc_service *ddc_service, bool oem)
9556 {
9557 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
9558 	struct amdgpu_i2c_adapter *i2c;
9559 
9560 	i2c = kzalloc_obj(struct amdgpu_i2c_adapter);
9561 	if (!i2c)
9562 		return NULL;
9563 	i2c->base.owner = THIS_MODULE;
9564 	i2c->base.dev.parent = &adev->pdev->dev;
9565 	i2c->base.algo = &amdgpu_dm_i2c_algo;
9566 	if (oem)
9567 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c OEM bus");
9568 	else
9569 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d",
9570 			 ddc_service->link->link_index);
9571 	i2c_set_adapdata(&i2c->base, i2c);
9572 	i2c->ddc_service = ddc_service;
9573 	i2c->oem = oem;
9574 
9575 	return i2c;
9576 }
9577 
9578 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
9579 {
9580 	struct cec_connector_info conn_info;
9581 	struct drm_device *ddev = aconnector->base.dev;
9582 	struct device *hdmi_dev = ddev->dev;
9583 
9584 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
9585 		drm_info(ddev, "HDMI-CEC feature masked\n");
9586 		return -EINVAL;
9587 	}
9588 
9589 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
9590 	aconnector->notifier =
9591 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
9592 	if (!aconnector->notifier) {
9593 		drm_err(ddev, "Failed to create cec notifier\n");
9594 		return -ENOMEM;
9595 	}
9596 
9597 	return 0;
9598 }
9599 
9600 /*
9601  * Note: this function assumes that dc_link_detect() was called for the
9602  * dc_link which will be represented by this aconnector.
9603  */
9604 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
9605 				    struct amdgpu_dm_connector *aconnector,
9606 				    u32 link_index,
9607 				    struct amdgpu_encoder *aencoder)
9608 {
9609 	int res = 0;
9610 	int connector_type;
9611 	struct dc *dc = dm->dc;
9612 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
9613 	struct amdgpu_i2c_adapter *i2c;
9614 
9615 	/* Not needed for writeback connector */
9616 	link->priv = aconnector;
9617 
9618 
9619 	i2c = create_i2c(link->ddc, false);
9620 	if (!i2c) {
9621 		drm_err(adev_to_drm(dm->adev), "Failed to create i2c adapter data\n");
9622 		return -ENOMEM;
9623 	}
9624 
9625 	aconnector->i2c = i2c;
9626 	res = devm_i2c_add_adapter(dm->adev->dev, &i2c->base);
9627 
9628 	if (res) {
9629 		drm_err(adev_to_drm(dm->adev), "Failed to register hw i2c %d\n", link->link_index);
9630 		goto out_free;
9631 	}
9632 
9633 	connector_type = to_drm_connector_type(link->connector_signal, link->link_id.id);
9634 
9635 	res = drm_connector_init_with_ddc(
9636 			dm->ddev,
9637 			&aconnector->base,
9638 			&amdgpu_dm_connector_funcs,
9639 			connector_type,
9640 			&i2c->base);
9641 
9642 	if (res) {
9643 		drm_err(adev_to_drm(dm->adev), "connector_init failed\n");
9644 		aconnector->connector_id = -1;
9645 		goto out_free;
9646 	}
9647 
9648 	drm_connector_helper_add(
9649 			&aconnector->base,
9650 			&amdgpu_dm_connector_helper_funcs);
9651 
9652 	amdgpu_dm_connector_init_helper(
9653 		dm,
9654 		aconnector,
9655 		connector_type,
9656 		link,
9657 		link_index);
9658 
9659 	drm_connector_attach_encoder(
9660 		&aconnector->base, &aencoder->base);
9661 
9662 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9663 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
9664 		amdgpu_dm_initialize_hdmi_connector(aconnector);
9665 
9666 	if (dc_is_dp_signal(link->connector_signal))
9667 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
9668 
9669 out_free:
9670 	if (res) {
9671 		kfree(i2c);
9672 		aconnector->i2c = NULL;
9673 	}
9674 	return res;
9675 }
9676 
9677 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
9678 {
9679 	switch (adev->mode_info.num_crtc) {
9680 	case 1:
9681 		return 0x1;
9682 	case 2:
9683 		return 0x3;
9684 	case 3:
9685 		return 0x7;
9686 	case 4:
9687 		return 0xf;
9688 	case 5:
9689 		return 0x1f;
9690 	case 6:
9691 	default:
9692 		return 0x3f;
9693 	}
9694 }
9695 
9696 static int amdgpu_dm_encoder_init(struct drm_device *dev,
9697 				  struct amdgpu_encoder *aencoder,
9698 				  uint32_t link_index)
9699 {
9700 	struct amdgpu_device *adev = drm_to_adev(dev);
9701 
9702 	int res = drm_encoder_init(dev,
9703 				   &aencoder->base,
9704 				   &amdgpu_dm_encoder_funcs,
9705 				   DRM_MODE_ENCODER_TMDS,
9706 				   NULL);
9707 
9708 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
9709 
9710 	if (!res)
9711 		aencoder->encoder_id = link_index;
9712 	else
9713 		aencoder->encoder_id = -1;
9714 
9715 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
9716 
9717 	return res;
9718 }
9719 
9720 static void manage_dm_interrupts(struct amdgpu_device *adev,
9721 				 struct amdgpu_crtc *acrtc,
9722 				 struct dm_crtc_state *acrtc_state)
9723 {	/*
9724 	 * We cannot be sure that the frontend index maps to the same
9725 	 * backend index - some even map to more than one.
9726 	 * So we have to go through the CRTC to find the right IRQ.
9727 	 */
9728 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
9729 			adev,
9730 			acrtc->crtc_id);
9731 	struct drm_device *dev = adev_to_drm(adev);
9732 
9733 	struct drm_vblank_crtc_config config = {0};
9734 	struct dc_crtc_timing *timing;
9735 	int offdelay;
9736 
9737 	if (acrtc_state) {
9738 		timing = &acrtc_state->stream->timing;
9739 
9740 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) >=
9741 		      IP_VERSION(3, 2, 0) &&
9742 		      !(adev->flags & AMD_IS_APU)) {
9743 			/*
9744 			 * DGPUs NV3x and newer that support idle optimizations
9745 			 * experience intermittent flip-done timeouts on cursor
9746 			 * updates. Restore 5s offdelay behavior for now.
9747 			 *
9748 			 * Discussion on the issue:
9749 			 * https://lore.kernel.org/amd-gfx/20260217191632.1243826-1-sysdadmin@m1k.cloud/
9750 			 */
9751 			config.offdelay_ms = 5000;
9752 			config.disable_immediate = false;
9753 		} else if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
9754 			     IP_VERSION(3, 5, 0)) {
9755 			/*
9756 			 * Older HW and DGPU have issues with instant off;
9757 			 * use a 2 frame offdelay.
9758 			 */
9759 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
9760 						      timing->v_total *
9761 						      timing->h_total,
9762 						      timing->pix_clk_100hz);
9763 
9764 			config.offdelay_ms = offdelay ?: 30;
9765 		} else {
9766 			/* offdelay_ms = 0 will never disable vblank */
9767 			config.offdelay_ms = 1;
9768 			config.disable_immediate = true;
9769 		}
9770 
9771 		drm_crtc_vblank_on_config(&acrtc->base,
9772 					  &config);
9773 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_get.*/
9774 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9775 		case IP_VERSION(3, 0, 0):
9776 		case IP_VERSION(3, 0, 2):
9777 		case IP_VERSION(3, 0, 3):
9778 		case IP_VERSION(3, 2, 0):
9779 			if (amdgpu_irq_get(adev, &adev->pageflip_irq, irq_type))
9780 				drm_err(dev, "DM_IRQ: Cannot get pageflip irq!\n");
9781 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9782 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
9783 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
9784 #endif
9785 		}
9786 
9787 	} else {
9788 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
9789 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9790 		case IP_VERSION(3, 0, 0):
9791 		case IP_VERSION(3, 0, 2):
9792 		case IP_VERSION(3, 0, 3):
9793 		case IP_VERSION(3, 2, 0):
9794 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9795 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
9796 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
9797 #endif
9798 			if (amdgpu_irq_put(adev, &adev->pageflip_irq, irq_type))
9799 				drm_err(dev, "DM_IRQ: Cannot put pageflip irq!\n");
9800 		}
9801 
9802 		drm_crtc_vblank_off(&acrtc->base);
9803 	}
9804 }
9805 
9806 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
9807 				      struct amdgpu_crtc *acrtc)
9808 {
9809 	int irq_type =
9810 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
9811 
9812 	/**
9813 	 * This reads the current state for the IRQ and force reapplies
9814 	 * the setting to hardware.
9815 	 */
9816 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
9817 }
9818 
9819 static bool
9820 is_scaling_state_different(const struct dm_connector_state *dm_state,
9821 			   const struct dm_connector_state *old_dm_state)
9822 {
9823 	if (dm_state->scaling != old_dm_state->scaling)
9824 		return true;
9825 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
9826 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
9827 			return true;
9828 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
9829 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
9830 			return true;
9831 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
9832 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
9833 		return true;
9834 	return false;
9835 }
9836 
9837 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
9838 					    struct drm_crtc_state *old_crtc_state,
9839 					    struct drm_connector_state *new_conn_state,
9840 					    struct drm_connector_state *old_conn_state,
9841 					    const struct drm_connector *connector,
9842 					    struct hdcp_workqueue *hdcp_w)
9843 {
9844 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
9845 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
9846 
9847 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
9848 		connector->index, connector->status, connector->dpms);
9849 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
9850 		old_conn_state->content_protection, new_conn_state->content_protection);
9851 
9852 	if (old_crtc_state)
9853 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9854 		old_crtc_state->enable,
9855 		old_crtc_state->active,
9856 		old_crtc_state->mode_changed,
9857 		old_crtc_state->active_changed,
9858 		old_crtc_state->connectors_changed);
9859 
9860 	if (new_crtc_state)
9861 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9862 		new_crtc_state->enable,
9863 		new_crtc_state->active,
9864 		new_crtc_state->mode_changed,
9865 		new_crtc_state->active_changed,
9866 		new_crtc_state->connectors_changed);
9867 
9868 	/* hdcp content type change */
9869 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
9870 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
9871 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9872 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
9873 		return true;
9874 	}
9875 
9876 	/* CP is being re enabled, ignore this */
9877 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
9878 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9879 		if (new_crtc_state && new_crtc_state->mode_changed) {
9880 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9881 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
9882 			return true;
9883 		}
9884 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
9885 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
9886 		return false;
9887 	}
9888 
9889 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
9890 	 *
9891 	 * Handles:	UNDESIRED -> ENABLED
9892 	 */
9893 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
9894 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
9895 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9896 
9897 	/* Stream removed and re-enabled
9898 	 *
9899 	 * Can sometimes overlap with the HPD case,
9900 	 * thus set update_hdcp to false to avoid
9901 	 * setting HDCP multiple times.
9902 	 *
9903 	 * Handles:	DESIRED -> DESIRED (Special case)
9904 	 */
9905 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
9906 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
9907 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9908 		dm_con_state->update_hdcp = false;
9909 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
9910 			__func__);
9911 		return true;
9912 	}
9913 
9914 	/* Hot-plug, headless s3, dpms
9915 	 *
9916 	 * Only start HDCP if the display is connected/enabled.
9917 	 * update_hdcp flag will be set to false until the next
9918 	 * HPD comes in.
9919 	 *
9920 	 * Handles:	DESIRED -> DESIRED (Special case)
9921 	 */
9922 	if (dm_con_state->update_hdcp &&
9923 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
9924 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
9925 		dm_con_state->update_hdcp = false;
9926 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
9927 			__func__);
9928 		return true;
9929 	}
9930 
9931 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
9932 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9933 			if (new_crtc_state && new_crtc_state->mode_changed) {
9934 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
9935 					__func__);
9936 				return true;
9937 			}
9938 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
9939 				__func__);
9940 			return false;
9941 		}
9942 
9943 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
9944 		return false;
9945 	}
9946 
9947 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9948 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
9949 			__func__);
9950 		return true;
9951 	}
9952 
9953 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
9954 	return false;
9955 }
9956 
9957 static void remove_stream(struct amdgpu_device *adev,
9958 			  struct amdgpu_crtc *acrtc,
9959 			  struct dc_stream_state *stream)
9960 {
9961 	/* this is the update mode case */
9962 
9963 	acrtc->otg_inst = -1;
9964 	acrtc->enabled = false;
9965 }
9966 
9967 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
9968 {
9969 
9970 	assert_spin_locked(&acrtc->base.dev->event_lock);
9971 	WARN_ON(acrtc->event);
9972 
9973 	acrtc->event = acrtc->base.state->event;
9974 
9975 	/* Set the flip status */
9976 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
9977 
9978 	/* Mark this event as consumed */
9979 	acrtc->base.state->event = NULL;
9980 
9981 	drm_dbg_state(acrtc->base.dev,
9982 		      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
9983 		      acrtc->crtc_id);
9984 }
9985 
9986 static void update_freesync_state_on_stream(
9987 	struct amdgpu_display_manager *dm,
9988 	struct dm_crtc_state *new_crtc_state,
9989 	struct dc_stream_state *new_stream,
9990 	struct dc_plane_state *surface,
9991 	u32 flip_timestamp_in_us)
9992 {
9993 	struct mod_vrr_params vrr_params;
9994 	struct dc_info_packet vrr_infopacket = {0};
9995 	struct amdgpu_device *adev = dm->adev;
9996 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9997 	unsigned long flags;
9998 	bool pack_sdp_v1_3 = false;
9999 	struct amdgpu_dm_connector *aconn;
10000 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
10001 
10002 	if (!new_stream)
10003 		return;
10004 
10005 	/*
10006 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
10007 	 * For now it's sufficient to just guard against these conditions.
10008 	 */
10009 
10010 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
10011 		return;
10012 
10013 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
10014 	vrr_params = acrtc->dm_irq_params.vrr_params;
10015 
10016 	if (surface) {
10017 		mod_freesync_handle_preflip(
10018 			dm->freesync_module,
10019 			surface,
10020 			new_stream,
10021 			flip_timestamp_in_us,
10022 			&vrr_params);
10023 
10024 		if (adev->family < AMDGPU_FAMILY_AI &&
10025 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
10026 			mod_freesync_handle_v_update(dm->freesync_module,
10027 						     new_stream, &vrr_params);
10028 
10029 			/* Need to call this before the frame ends. */
10030 			dc_stream_adjust_vmin_vmax(dm->dc,
10031 						   new_crtc_state->stream,
10032 						   &vrr_params.adjust);
10033 		}
10034 	}
10035 
10036 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
10037 
10038 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
10039 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
10040 
10041 		if (aconn->vsdb_info.amd_vsdb_version == 1)
10042 			packet_type = PACKET_TYPE_FS_V1;
10043 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
10044 			packet_type = PACKET_TYPE_FS_V2;
10045 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
10046 			packet_type = PACKET_TYPE_FS_V3;
10047 
10048 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
10049 					&new_stream->adaptive_sync_infopacket);
10050 	}
10051 
10052 	mod_freesync_build_vrr_infopacket(
10053 		dm->freesync_module,
10054 		new_stream,
10055 		&vrr_params,
10056 		packet_type,
10057 		TRANSFER_FUNC_UNKNOWN,
10058 		&vrr_infopacket,
10059 		pack_sdp_v1_3);
10060 
10061 	new_crtc_state->freesync_vrr_info_changed |=
10062 		(memcmp(&new_crtc_state->vrr_infopacket,
10063 			&vrr_infopacket,
10064 			sizeof(vrr_infopacket)) != 0);
10065 
10066 	acrtc->dm_irq_params.vrr_params = vrr_params;
10067 	new_crtc_state->vrr_infopacket = vrr_infopacket;
10068 
10069 	new_stream->vrr_infopacket = vrr_infopacket;
10070 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
10071 
10072 	if (new_crtc_state->freesync_vrr_info_changed)
10073 		drm_dbg_kms(adev_to_drm(adev), "VRR packet update: crtc=%u enabled=%d state=%d",
10074 			      new_crtc_state->base.crtc->base.id,
10075 			      (int)new_crtc_state->base.vrr_enabled,
10076 			      (int)vrr_params.state);
10077 
10078 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10079 }
10080 
10081 static void update_stream_irq_parameters(
10082 	struct amdgpu_display_manager *dm,
10083 	struct dm_crtc_state *new_crtc_state)
10084 {
10085 	struct dc_stream_state *new_stream = new_crtc_state->stream;
10086 	struct mod_vrr_params vrr_params;
10087 	struct mod_freesync_config config = new_crtc_state->freesync_config;
10088 	struct amdgpu_device *adev = dm->adev;
10089 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
10090 	unsigned long flags;
10091 
10092 	if (!new_stream)
10093 		return;
10094 
10095 	/*
10096 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
10097 	 * For now it's sufficient to just guard against these conditions.
10098 	 */
10099 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
10100 		return;
10101 
10102 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
10103 	vrr_params = acrtc->dm_irq_params.vrr_params;
10104 
10105 	if (new_crtc_state->vrr_supported &&
10106 	    config.min_refresh_in_uhz &&
10107 	    config.max_refresh_in_uhz) {
10108 		/*
10109 		 * if freesync compatible mode was set, config.state will be set
10110 		 * in atomic check
10111 		 */
10112 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
10113 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
10114 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
10115 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
10116 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
10117 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
10118 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
10119 		} else {
10120 			config.state = new_crtc_state->base.vrr_enabled ?
10121 						     VRR_STATE_ACTIVE_VARIABLE :
10122 						     VRR_STATE_INACTIVE;
10123 		}
10124 	} else {
10125 		config.state = VRR_STATE_UNSUPPORTED;
10126 	}
10127 
10128 	mod_freesync_build_vrr_params(dm->freesync_module,
10129 				      new_stream,
10130 				      &config, &vrr_params);
10131 
10132 	new_crtc_state->freesync_config = config;
10133 	/* Copy state for access from DM IRQ handler */
10134 	acrtc->dm_irq_params.freesync_config = config;
10135 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
10136 	acrtc->dm_irq_params.vrr_params = vrr_params;
10137 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
10138 }
10139 
10140 static void amdgpu_dm_handle_vrr_transition(struct amdgpu_display_manager *dm,
10141 					    struct dm_crtc_state *old_state,
10142 					    struct dm_crtc_state *new_state)
10143 {
10144 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
10145 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
10146 
10147 	if (!old_vrr_active && new_vrr_active) {
10148 		/* Transition VRR inactive -> active:
10149 		 * While VRR is active, we must not disable vblank irq, as a
10150 		 * reenable after disable would compute bogus vblank/pflip
10151 		 * timestamps if it likely happened inside display front-porch.
10152 		 *
10153 		 * We also need vupdate irq for the actual core vblank handling
10154 		 * at end of vblank.
10155 		 */
10156 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
10157 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
10158 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR off->on: Get vblank ref\n",
10159 				 __func__, new_state->base.crtc->base.id);
10160 
10161 		scoped_guard(mutex, &dm->dc_lock) {
10162 			dc_exit_ips_for_hw_access(dm->dc);
10163 			amdgpu_dm_psr_set_event(dm, new_state->stream, true,
10164 				psr_event_vrr_transition, true);
10165 			amdgpu_dm_replay_set_event(dm, new_state->stream, true,
10166 				replay_event_vrr, true);
10167 		}
10168 	} else if (old_vrr_active && !new_vrr_active) {
10169 		/* Transition VRR active -> inactive:
10170 		 * Allow vblank irq disable again for fixed refresh rate.
10171 		 */
10172 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
10173 		drm_crtc_vblank_put(new_state->base.crtc);
10174 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR on->off: Drop vblank ref\n",
10175 				 __func__, new_state->base.crtc->base.id);
10176 
10177 		scoped_guard(mutex, &dm->dc_lock) {
10178 			dc_exit_ips_for_hw_access(dm->dc);
10179 			amdgpu_dm_psr_set_event(dm, new_state->stream, false,
10180 				psr_event_vrr_transition, false);
10181 			amdgpu_dm_replay_set_event(dm, new_state->stream, false,
10182 				replay_event_vrr, false);
10183 		}
10184 	}
10185 }
10186 
10187 static void amdgpu_dm_commit_cursors(struct drm_atomic_commit *state)
10188 {
10189 	struct drm_plane *plane;
10190 	struct drm_plane_state *old_plane_state;
10191 	int i;
10192 
10193 	/*
10194 	 * TODO: Make this per-stream so we don't issue redundant updates for
10195 	 * commits with multiple streams.
10196 	 */
10197 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
10198 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
10199 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
10200 }
10201 
10202 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
10203 {
10204 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
10205 
10206 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
10207 }
10208 
10209 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
10210 				    struct drm_plane_state *old_plane_state,
10211 				    struct dc_stream_update *update)
10212 {
10213 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
10214 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
10215 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
10216 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
10217 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
10218 	uint64_t address = afb ? afb->address : 0;
10219 	struct dc_cursor_position position = {0};
10220 	struct dc_cursor_attributes attributes;
10221 	int ret;
10222 
10223 	if (!plane->state->fb && !old_plane_state->fb)
10224 		return;
10225 
10226 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
10227 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
10228 		       plane->state->crtc_h);
10229 
10230 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
10231 	if (ret)
10232 		return;
10233 
10234 	if (!position.enable) {
10235 		/* turn off cursor */
10236 		if (crtc_state && crtc_state->stream) {
10237 			dc_stream_set_cursor_position(crtc_state->stream,
10238 						      &position);
10239 			update->cursor_position = &crtc_state->stream->cursor_position;
10240 		}
10241 		return;
10242 	}
10243 
10244 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
10245 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
10246 
10247 	memset(&attributes, 0, sizeof(attributes));
10248 	attributes.address.high_part = upper_32_bits(address);
10249 	attributes.address.low_part  = lower_32_bits(address);
10250 	attributes.width             = plane->state->crtc_w;
10251 	attributes.height            = plane->state->crtc_h;
10252 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
10253 	attributes.rotation_angle    = 0;
10254 	attributes.attribute_flags.value = 0;
10255 
10256 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
10257 	 * legacy gamma setup.
10258 	 */
10259 	if (crtc_state->cm_is_degamma_srgb &&
10260 	    adev->dm.dc->caps.color.dpp.gamma_corr)
10261 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
10262 
10263 	if (afb)
10264 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
10265 
10266 	if (crtc_state->stream) {
10267 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
10268 						     &attributes))
10269 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
10270 
10271 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
10272 
10273 		if (!dc_stream_set_cursor_position(crtc_state->stream,
10274 						   &position))
10275 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
10276 
10277 		update->cursor_position = &crtc_state->stream->cursor_position;
10278 	}
10279 }
10280 
10281 static void amdgpu_dm_enable_self_refresh(struct amdgpu_display_manager *dm,
10282 					  struct amdgpu_crtc *acrtc_attach,
10283 					  const struct dm_crtc_state *acrtc_state,
10284 					  const u64 current_ts)
10285 {
10286 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
10287 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
10288 	struct amdgpu_dm_connector *aconn =
10289 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
10290 
10291 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
10292 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
10293 	    (psr->psr_feature_enabled || pr->replay_feature_enabled)) {
10294 		if (aconn->sr_skip_count > 0)
10295 			aconn->sr_skip_count--;
10296 
10297 		/* Allow SR when skip count is 0. */
10298 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
10299 
10300 		/*
10301 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
10302 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
10303 		 * can be enabled immediately once OS demonstrates an
10304 		 * adequate number of fast atomic commits to notify KMD
10305 		 * of update events.
10306 		 * See `amdgpu_dm_crtc_vblank_control_worker()`.
10307 		 */
10308 		if (acrtc_attach->dm_irq_params.allow_sr_entry &&
10309 			(current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
10310 			amdgpu_dm_psr_set_event(dm, acrtc_state->stream, false,
10311 				psr_event_hw_programming, false);
10312 
10313 			amdgpu_dm_replay_set_event(dm, acrtc_state->stream, false,
10314 				replay_event_hw_programming, false);
10315 		}
10316 	} else {
10317 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
10318 	}
10319 }
10320 
10321 static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state,
10322 				    struct drm_device *dev,
10323 				    struct amdgpu_display_manager *dm,
10324 				    struct drm_crtc *pcrtc,
10325 				    bool wait_for_vblank)
10326 {
10327 	u32 i;
10328 	u64 timestamp_ns = ktime_get_ns();
10329 	struct drm_plane *plane;
10330 	struct drm_plane_state *old_plane_state, *new_plane_state;
10331 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
10332 	struct drm_crtc_state *new_pcrtc_state =
10333 			drm_atomic_get_new_crtc_state(state, pcrtc);
10334 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
10335 	struct dm_crtc_state *dm_old_crtc_state =
10336 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
10337 	int planes_count = 0, vpos, hpos;
10338 	unsigned long flags;
10339 	u32 target_vblank, last_flip_vblank;
10340 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
10341 	bool cursor_update = false;
10342 	bool pflip_present = false;
10343 	bool dirty_rects_changed = false;
10344 	bool updated_planes_and_streams = false;
10345 	struct {
10346 		struct dc_surface_update surface_updates[MAX_SURFACES];
10347 		struct dc_plane_info plane_infos[MAX_SURFACES];
10348 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
10349 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
10350 		struct dc_stream_update stream_update;
10351 	} *bundle;
10352 
10353 	bundle = kzalloc_obj(*bundle);
10354 
10355 	if (!bundle) {
10356 		drm_err(dev, "Failed to allocate update bundle\n");
10357 		goto cleanup;
10358 	}
10359 
10360 	/*
10361 	 * Disable the cursor first if we're disabling all the planes.
10362 	 * It'll remain on the screen after the planes are re-enabled
10363 	 * if we don't.
10364 	 *
10365 	 * If the cursor is transitioning from native to overlay mode, the
10366 	 * native cursor needs to be disabled first.
10367 	 */
10368 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
10369 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10370 		struct dc_cursor_position cursor_position = {0};
10371 
10372 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
10373 						   &cursor_position))
10374 			drm_err(dev, "DC failed to disable native cursor\n");
10375 
10376 		bundle->stream_update.cursor_position =
10377 				&acrtc_state->stream->cursor_position;
10378 	}
10379 
10380 	if (acrtc_state->active_planes == 0 &&
10381 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10382 		amdgpu_dm_commit_cursors(state);
10383 
10384 	/* update planes when needed */
10385 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
10386 		struct drm_crtc *crtc = new_plane_state->crtc;
10387 		struct drm_crtc_state *new_crtc_state;
10388 		struct drm_framebuffer *fb = new_plane_state->fb;
10389 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
10390 		bool plane_needs_flip;
10391 		struct dc_plane_state *dc_plane;
10392 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
10393 
10394 		/* Cursor plane is handled after stream updates */
10395 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
10396 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10397 			if ((fb && crtc == pcrtc) ||
10398 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
10399 				cursor_update = true;
10400 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
10401 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
10402 			}
10403 
10404 			continue;
10405 		}
10406 
10407 		if (!fb || !crtc || pcrtc != crtc)
10408 			continue;
10409 
10410 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
10411 		if (!new_crtc_state->active)
10412 			continue;
10413 
10414 		dc_plane = dm_new_plane_state->dc_state;
10415 		if (!dc_plane)
10416 			continue;
10417 
10418 		bundle->surface_updates[planes_count].surface = dc_plane;
10419 		if (new_pcrtc_state->color_mgmt_changed || new_plane_state->color_mgmt_changed) {
10420 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
10421 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
10422 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
10423 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
10424 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
10425 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
10426 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
10427 		}
10428 
10429 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
10430 				     &bundle->scaling_infos[planes_count]);
10431 
10432 		bundle->surface_updates[planes_count].scaling_info =
10433 			&bundle->scaling_infos[planes_count];
10434 
10435 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
10436 
10437 		pflip_present = pflip_present || plane_needs_flip;
10438 
10439 		if (!plane_needs_flip) {
10440 			planes_count += 1;
10441 			continue;
10442 		}
10443 
10444 		fill_dc_plane_info_and_addr(
10445 			dm->adev, new_plane_state,
10446 			afb->tiling_flags,
10447 			&bundle->plane_infos[planes_count],
10448 			&bundle->flip_addrs[planes_count].address,
10449 			afb->tmz_surface);
10450 
10451 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
10452 				 new_plane_state->plane->index,
10453 				 bundle->plane_infos[planes_count].dcc.enable);
10454 
10455 		bundle->surface_updates[planes_count].plane_info =
10456 			&bundle->plane_infos[planes_count];
10457 
10458 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
10459 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
10460 			fill_dc_dirty_rects(plane, old_plane_state,
10461 					    new_plane_state, new_crtc_state,
10462 					    &bundle->flip_addrs[planes_count],
10463 					    acrtc_state->stream->link->psr_settings.psr_version ==
10464 					    DC_PSR_VERSION_SU_1,
10465 					    &dirty_rects_changed);
10466 
10467 			/*
10468 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
10469 			 * and enabled it again after dirty regions are stable to avoid video glitch.
10470 			 * PSR-SU will be enabled in
10471 			 * amdgpu_dm_crtc_vblank_control_worker() if user
10472 			 * pause the video during the PSR-SU was disabled.
10473 			 */
10474 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
10475 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
10476 			    dirty_rects_changed) {
10477 				mutex_lock(&dm->dc_lock);
10478 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
10479 				timestamp_ns;
10480 				dc_exit_ips_for_hw_access(dm->dc);
10481 				amdgpu_dm_psr_set_event(dm, acrtc_state->stream, true,
10482 					psr_event_hw_programming, true);
10483 				mutex_unlock(&dm->dc_lock);
10484 			}
10485 		}
10486 
10487 		/*
10488 		 * Only allow immediate flips for fast updates that don't
10489 		 * change memory domain, FB pitch, DCC state, rotation or
10490 		 * mirroring.
10491 		 *
10492 		 * dm_crtc_helper_atomic_check() only accepts async flips with
10493 		 * fast updates.
10494 		 */
10495 		if (crtc->state->async_flip &&
10496 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
10497 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
10498 			drm_warn_once(state->dev,
10499 				      "[PLANE:%d:%s] async flip with non-fast update\n",
10500 				      plane->base.id, plane->name);
10501 
10502 		bundle->flip_addrs[planes_count].flip_immediate =
10503 			crtc->state->async_flip &&
10504 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
10505 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
10506 
10507 		timestamp_ns = ktime_get_ns();
10508 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
10509 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
10510 		bundle->surface_updates[planes_count].surface = dc_plane;
10511 
10512 		if (!bundle->surface_updates[planes_count].surface) {
10513 			drm_err(dev, "No surface for CRTC: id=%d\n",
10514 					acrtc_attach->crtc_id);
10515 			continue;
10516 		}
10517 
10518 		if (plane == pcrtc->primary)
10519 			update_freesync_state_on_stream(
10520 				dm,
10521 				acrtc_state,
10522 				acrtc_state->stream,
10523 				dc_plane,
10524 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
10525 
10526 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
10527 				 __func__,
10528 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
10529 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
10530 
10531 		planes_count += 1;
10532 
10533 	}
10534 
10535 	if (pflip_present) {
10536 		if (!vrr_active) {
10537 			/* Use old throttling in non-vrr fixed refresh rate mode
10538 			 * to keep flip scheduling based on target vblank counts
10539 			 * working in a backwards compatible way, e.g., for
10540 			 * clients using the GLX_OML_sync_control extension or
10541 			 * DRI3/Present extension with defined target_msc.
10542 			 */
10543 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
10544 		} else {
10545 			/* For variable refresh rate mode only:
10546 			 * Get vblank of last completed flip to avoid > 1 vrr
10547 			 * flips per video frame by use of throttling, but allow
10548 			 * flip programming anywhere in the possibly large
10549 			 * variable vrr vblank interval for fine-grained flip
10550 			 * timing control and more opportunity to avoid stutter
10551 			 * on late submission of flips.
10552 			 */
10553 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10554 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
10555 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10556 		}
10557 
10558 		target_vblank = last_flip_vblank + wait_for_vblank;
10559 
10560 		/*
10561 		 * Wait until we're out of the vertical blank period before the one
10562 		 * targeted by the flip
10563 		 */
10564 		while ((acrtc_attach->enabled &&
10565 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
10566 							    0, &vpos, &hpos, NULL,
10567 							    NULL, &pcrtc->hwmode)
10568 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
10569 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
10570 			(int)(target_vblank -
10571 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
10572 			usleep_range(1000, 1100);
10573 		}
10574 
10575 		/**
10576 		 * Prepare the flip event for the pageflip interrupt to handle.
10577 		 *
10578 		 * This only works in the case where we've already turned on the
10579 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
10580 		 * from 0 -> n planes we have to skip a hardware generated event
10581 		 * and rely on sending it from software.
10582 		 */
10583 		if (acrtc_attach->base.state->event &&
10584 		    acrtc_state->active_planes > 0) {
10585 			drm_crtc_vblank_get(pcrtc);
10586 
10587 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10588 
10589 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
10590 			prepare_flip_isr(acrtc_attach);
10591 
10592 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10593 		}
10594 
10595 		if (acrtc_state->stream) {
10596 			if (acrtc_state->freesync_vrr_info_changed)
10597 				bundle->stream_update.vrr_infopacket =
10598 					&acrtc_state->stream->vrr_infopacket;
10599 		}
10600 	} else if (cursor_update && acrtc_state->active_planes > 0) {
10601 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10602 		if (acrtc_attach->base.state->event) {
10603 			drm_crtc_vblank_get(pcrtc);
10604 			acrtc_attach->event = acrtc_attach->base.state->event;
10605 			acrtc_attach->base.state->event = NULL;
10606 		}
10607 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10608 	}
10609 
10610 	/* Update the planes if changed or disable if we don't have any. */
10611 	if ((planes_count || acrtc_state->active_planes == 0) &&
10612 		acrtc_state->stream) {
10613 		/*
10614 		 * If PSR or idle optimizations are enabled then flush out
10615 		 * any pending work before hardware programming.
10616 		 */
10617 		if (dm->vblank_control_workqueue)
10618 			flush_workqueue(dm->vblank_control_workqueue);
10619 
10620 		bundle->stream_update.stream = acrtc_state->stream;
10621 		if (new_pcrtc_state->mode_changed) {
10622 			bundle->stream_update.src = acrtc_state->stream->src;
10623 			bundle->stream_update.dst = acrtc_state->stream->dst;
10624 		}
10625 
10626 		if (new_pcrtc_state->color_mgmt_changed) {
10627 			/*
10628 			 * TODO: This isn't fully correct since we've actually
10629 			 * already modified the stream in place.
10630 			 */
10631 			bundle->stream_update.gamut_remap =
10632 				&acrtc_state->stream->gamut_remap_matrix;
10633 			bundle->stream_update.output_csc_transform =
10634 				&acrtc_state->stream->csc_color_matrix;
10635 			bundle->stream_update.out_transfer_func =
10636 				&acrtc_state->stream->out_transfer_func;
10637 			bundle->stream_update.lut3d_func =
10638 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
10639 			bundle->stream_update.func_shaper =
10640 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
10641 		}
10642 
10643 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
10644 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
10645 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
10646 
10647 		/*
10648 		 * If FreeSync state on the stream has changed then we need to
10649 		 * re-adjust the min/max bounds now that DC doesn't handle this
10650 		 * as part of commit.
10651 		 */
10652 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
10653 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10654 			dc_stream_adjust_vmin_vmax(
10655 				dm->dc, acrtc_state->stream,
10656 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
10657 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10658 		}
10659 		mutex_lock(&dm->dc_lock);
10660 		update_planes_and_stream_adapter(dm->dc,
10661 					 acrtc_state->update_type,
10662 					 planes_count,
10663 					 acrtc_state->stream,
10664 					 &bundle->stream_update,
10665 					 bundle->surface_updates);
10666 		updated_planes_and_streams = true;
10667 
10668 		/**
10669 		 * Enable or disable the interrupts on the backend.
10670 		 *
10671 		 * Most pipes are put into power gating when unused.
10672 		 *
10673 		 * When power gating is enabled on a pipe we lose the
10674 		 * interrupt enablement state when power gating is disabled.
10675 		 *
10676 		 * So we need to update the IRQ control state in hardware
10677 		 * whenever the pipe turns on (since it could be previously
10678 		 * power gated) or off (since some pipes can't be power gated
10679 		 * on some ASICs).
10680 		 */
10681 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
10682 			dm_update_pflip_irq_state(drm_to_adev(dev),
10683 						  acrtc_attach);
10684 		amdgpu_dm_enable_self_refresh(dm, acrtc_attach, acrtc_state,
10685 					      timestamp_ns);
10686 		mutex_unlock(&dm->dc_lock);
10687 	}
10688 
10689 	/*
10690 	 * Update cursor state *after* programming all the planes.
10691 	 * This avoids redundant programming in the case where we're going
10692 	 * to be disabling a single plane - those pipes are being disabled.
10693 	 */
10694 	if (acrtc_state->active_planes &&
10695 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
10696 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10697 		amdgpu_dm_commit_cursors(state);
10698 
10699 cleanup:
10700 	kfree(bundle);
10701 }
10702 
10703 static void amdgpu_dm_commit_audio(struct drm_device *dev,
10704 				   struct drm_atomic_commit *state)
10705 {
10706 	struct amdgpu_device *adev = drm_to_adev(dev);
10707 	struct amdgpu_dm_connector *aconnector;
10708 	struct drm_connector *connector;
10709 	struct drm_connector_state *old_con_state, *new_con_state;
10710 	struct drm_crtc_state *new_crtc_state;
10711 	struct dm_crtc_state *new_dm_crtc_state;
10712 	const struct dc_stream_status *status;
10713 	int i, inst;
10714 
10715 	/* Notify device removals. */
10716 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10717 		if (old_con_state->crtc != new_con_state->crtc) {
10718 			/* CRTC changes require notification. */
10719 			goto notify;
10720 		}
10721 
10722 		if (!new_con_state->crtc)
10723 			continue;
10724 
10725 		new_crtc_state = drm_atomic_get_new_crtc_state(
10726 			state, new_con_state->crtc);
10727 
10728 		if (!new_crtc_state)
10729 			continue;
10730 
10731 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10732 			continue;
10733 
10734 notify:
10735 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10736 			continue;
10737 
10738 		aconnector = to_amdgpu_dm_connector(connector);
10739 
10740 		mutex_lock(&adev->dm.audio_lock);
10741 		inst = aconnector->audio_inst;
10742 		aconnector->audio_inst = -1;
10743 		mutex_unlock(&adev->dm.audio_lock);
10744 
10745 		amdgpu_dm_audio_eld_notify(adev, inst);
10746 	}
10747 
10748 	/* Notify audio device additions. */
10749 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10750 		if (!new_con_state->crtc)
10751 			continue;
10752 
10753 		new_crtc_state = drm_atomic_get_new_crtc_state(
10754 			state, new_con_state->crtc);
10755 
10756 		if (!new_crtc_state)
10757 			continue;
10758 
10759 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10760 			continue;
10761 
10762 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
10763 		if (!new_dm_crtc_state->stream)
10764 			continue;
10765 
10766 		status = dc_stream_get_status(new_dm_crtc_state->stream);
10767 		if (!status)
10768 			continue;
10769 
10770 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10771 			continue;
10772 
10773 		aconnector = to_amdgpu_dm_connector(connector);
10774 
10775 		mutex_lock(&adev->dm.audio_lock);
10776 		inst = status->audio_inst;
10777 		aconnector->audio_inst = inst;
10778 		mutex_unlock(&adev->dm.audio_lock);
10779 
10780 		amdgpu_dm_audio_eld_notify(adev, inst);
10781 	}
10782 }
10783 
10784 /*
10785  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
10786  * @crtc_state: the DRM CRTC state
10787  * @stream_state: the DC stream state.
10788  *
10789  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
10790  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
10791  */
10792 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
10793 						struct dc_stream_state *stream_state)
10794 {
10795 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
10796 }
10797 
10798 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
10799 			      struct dm_crtc_state *crtc_state)
10800 {
10801 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
10802 }
10803 
10804 /**
10805  * amdgpu_dm_mod_power_update_streams - update mod_power stream state on modeset
10806  * @state: the drm atomic state
10807  * @dm: the display manager to update mod_power on
10808  *
10809  * Notify mod_power of stream changes on modeset events, and disable PSR/Replay
10810  * in preparation for hardware programming. See also
10811  * amdgpu_dm_mod_power_setup_streams() for post-modeset mod_power setup.
10812  */
10813 static void amdgpu_dm_mod_power_update_streams(struct drm_atomic_commit *state,
10814 					       struct amdgpu_display_manager *dm)
10815 {
10816 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10817 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10818 	struct amdgpu_dm_connector *aconnector;
10819 	struct drm_crtc *crtc;
10820 	int i = 0;
10821 
10822 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10823 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10824 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10825 
10826 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10827 			continue;
10828 
10829 		/*
10830 		 * Update mod_power on modeset event in preparation for hw
10831 		 * programming. Always use the old stream, since it would have
10832 		 * been previously added to mod_power. If old stream is null (on
10833 		 * crtc enable, for example), mod_power will no-op, which is the
10834 		 * desried behavior.
10835 		 */
10836 		if (old_crtc_state->active) {
10837 			scoped_guard(mutex, &dm->dc_lock) {
10838 				dc_exit_ips_for_hw_access(dm->dc);
10839 				amdgpu_dm_psr_set_event(dm, dm_old_crtc_state->stream, true,
10840 					psr_event_hw_programming, true);
10841 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, true,
10842 					replay_event_hw_programming, true);
10843 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, false,
10844 					replay_event_general_ui, false);
10845 			}
10846 		}
10847 
10848 		if (new_crtc_state->active) {
10849 			aconnector = (struct amdgpu_dm_connector *)
10850 				dm_new_crtc_state->stream->dm_stream_context;
10851 			if (old_crtc_state->active) {
10852 				mod_power_replace_stream(dm->power_module,
10853 					dm_old_crtc_state->stream,
10854 					dm_new_crtc_state->stream,
10855 					&aconnector->psr_caps);
10856 			} else {
10857 				mod_power_add_stream(dm->power_module,
10858 					dm_new_crtc_state->stream,
10859 					&aconnector->psr_caps);
10860 			}
10861 		} else if (old_crtc_state->active) {
10862 			mod_power_remove_stream(dm->power_module,
10863 				dm_old_crtc_state->stream);
10864 		}
10865 	}
10866 }
10867 
10868 /**
10869  * amdgpu_dm_mod_power_setup_streams - setup mod_power stream state post modeset
10870  * @state: the drm atomic state
10871  * @dm: the display manager to update mod_power on
10872  *
10873  * Notify mod_power of mode_change. This needs to be done after dc_stream
10874  * updates have been committed, and VRR parameters have been updated.
10875  */
10876 static void amdgpu_dm_mod_power_setup_streams(struct drm_atomic_commit *state,
10877 					      struct amdgpu_display_manager *dm)
10878 {
10879 	struct dm_crtc_state *dm_new_crtc_state;
10880 	struct drm_crtc_state *new_crtc_state;
10881 	struct amdgpu_crtc *acrtc;
10882 	struct drm_crtc *crtc;
10883 	int i = 0;
10884 
10885 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10886 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10887 		acrtc = to_amdgpu_crtc(crtc);
10888 
10889 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10890 			continue;
10891 
10892 		if (new_crtc_state->active) {
10893 			amdgpu_dm_link_setup_replay(dm_new_crtc_state->stream,
10894 					&acrtc->dm_irq_params.vrr_params);
10895 			mod_power_notify_mode_change(dm->power_module,
10896 						dm_new_crtc_state->stream,
10897 						false);
10898 
10899 			/*
10900 			 * Block PSR / Replay on the new stream until display settles post-modeset.
10901 			 * These events will be cleared by amdgpu_dm_enable_self_refresh() once
10902 			 * allow_sr_entry becomes true.
10903 			 */
10904 			amdgpu_dm_psr_set_event(dm, dm_new_crtc_state->stream, true,
10905 				psr_event_hw_programming, true);
10906 
10907 			amdgpu_dm_replay_set_event(dm, dm_new_crtc_state->stream, true,
10908 				replay_event_hw_programming | replay_event_general_ui,
10909 				true);
10910 		}
10911 	}
10912 
10913 }
10914 
10915 static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state,
10916 					struct dc_state *dc_state)
10917 {
10918 	struct drm_device *dev = state->dev;
10919 	struct amdgpu_device *adev = drm_to_adev(dev);
10920 	struct amdgpu_display_manager *dm = &adev->dm;
10921 	struct drm_crtc *crtc;
10922 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10923 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10924 	struct drm_connector_state *old_con_state;
10925 	struct drm_connector *connector;
10926 	bool mode_set_reset_required = false;
10927 	u32 i;
10928 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
10929 	bool set_backlight_level = false;
10930 
10931 	/* Disable writeback */
10932 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
10933 		struct dm_connector_state *dm_old_con_state;
10934 		struct amdgpu_crtc *acrtc;
10935 
10936 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
10937 			continue;
10938 
10939 		old_crtc_state = NULL;
10940 
10941 		dm_old_con_state = to_dm_connector_state(old_con_state);
10942 		if (!dm_old_con_state->base.crtc)
10943 			continue;
10944 
10945 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
10946 		if (acrtc)
10947 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10948 
10949 		if (!acrtc || !acrtc->wb_enabled)
10950 			continue;
10951 
10952 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10953 
10954 		dm_clear_writeback(dm, dm_old_crtc_state);
10955 		acrtc->wb_enabled = false;
10956 	}
10957 
10958 	amdgpu_dm_mod_power_update_streams(state, dm);
10959 
10960 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
10961 				      new_crtc_state, i) {
10962 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10963 
10964 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10965 
10966 		if (old_crtc_state->active &&
10967 		    (!new_crtc_state->active ||
10968 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10969 			manage_dm_interrupts(adev, acrtc, NULL);
10970 			dc_stream_release(dm_old_crtc_state->stream);
10971 		}
10972 	}
10973 
10974 	drm_atomic_helper_calc_timestamping_constants(state);
10975 
10976 	/* update changed items */
10977 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10978 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10979 
10980 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10981 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10982 
10983 		drm_dbg_state(state->dev,
10984 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
10985 			acrtc->crtc_id,
10986 			new_crtc_state->enable,
10987 			new_crtc_state->active,
10988 			new_crtc_state->planes_changed,
10989 			new_crtc_state->mode_changed,
10990 			new_crtc_state->active_changed,
10991 			new_crtc_state->connectors_changed);
10992 
10993 		/* Disable cursor if disabling crtc */
10994 		if (old_crtc_state->active && !new_crtc_state->active) {
10995 			struct dc_cursor_position position;
10996 
10997 			memset(&position, 0, sizeof(position));
10998 			mutex_lock(&dm->dc_lock);
10999 			dc_exit_ips_for_hw_access(dm->dc);
11000 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
11001 			mutex_unlock(&dm->dc_lock);
11002 		}
11003 
11004 		/* Copy all transient state flags into dc state */
11005 		if (dm_new_crtc_state->stream) {
11006 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
11007 							    dm_new_crtc_state->stream);
11008 		}
11009 
11010 		/* handles headless hotplug case, updating new_state and
11011 		 * aconnector as needed
11012 		 */
11013 
11014 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
11015 
11016 			drm_dbg_atomic(dev,
11017 				       "Atomic commit: SET crtc id %d: [%p]\n",
11018 				       acrtc->crtc_id, acrtc);
11019 
11020 			if (!dm_new_crtc_state->stream) {
11021 				/*
11022 				 * this could happen because of issues with
11023 				 * userspace notifications delivery.
11024 				 * In this case userspace tries to set mode on
11025 				 * display which is disconnected in fact.
11026 				 * dc_sink is NULL in this case on aconnector.
11027 				 * We expect reset mode will come soon.
11028 				 *
11029 				 * This can also happen when unplug is done
11030 				 * during resume sequence ended
11031 				 *
11032 				 * In this case, we want to pretend we still
11033 				 * have a sink to keep the pipe running so that
11034 				 * hw state is consistent with the sw state
11035 				 */
11036 				drm_dbg_atomic(dev,
11037 					       "Failed to create new stream for crtc %d\n",
11038 						acrtc->base.base.id);
11039 				continue;
11040 			}
11041 
11042 			if (dm_old_crtc_state->stream)
11043 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
11044 
11045 			pm_runtime_get_noresume(dev->dev);
11046 
11047 			acrtc->enabled = true;
11048 			acrtc->hw_mode = new_crtc_state->mode;
11049 			crtc->hwmode = new_crtc_state->mode;
11050 			mode_set_reset_required = true;
11051 			set_backlight_level = true;
11052 		} else if (modereset_required(new_crtc_state)) {
11053 			drm_dbg_atomic(dev,
11054 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
11055 				       acrtc->crtc_id, acrtc);
11056 			/* i.e. reset mode */
11057 			if (dm_old_crtc_state->stream)
11058 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
11059 
11060 			mode_set_reset_required = true;
11061 		}
11062 	} /* for_each_crtc_in_state() */
11063 
11064 	/* if there mode set or reset, flush vblank work queue */
11065 	if (mode_set_reset_required) {
11066 		if (dm->vblank_control_workqueue)
11067 			flush_workqueue(dm->vblank_control_workqueue);
11068 	}
11069 
11070 	dm_enable_per_frame_crtc_master_sync(dc_state);
11071 	mutex_lock(&dm->dc_lock);
11072 	dc_exit_ips_for_hw_access(dm->dc);
11073 	WARN_ON(!dc_commit_streams(dm->dc, &params));
11074 
11075 	bool frl_stream_found = false;
11076 
11077 	for (i = 0; i < params.stream_count; i++) {
11078 		struct dc_stream_state *stream = params.streams[i];
11079 
11080 		if (stream->signal == SIGNAL_TYPE_HDMI_FRL) {
11081 			frl_stream_found = true;
11082 			break;
11083 		}
11084 	}
11085 	if (frl_stream_found) {
11086 		if (queue_delayed_work(dm->hdmi_frl_status_polling_wq,
11087 				       &dm->hdmi_frl_status_polling_work,
11088 				       msecs_to_jiffies(dm->hdmi_frl_status_polling_delay_ms)))
11089 			drm_dbg_kms(dev, "200ms frl status polling starts ...\n");
11090 	} else {
11091 		if (cancel_delayed_work_sync(&dm->hdmi_frl_status_polling_work))
11092 			drm_dbg_kms(dev, "200ms frl status polling stops ...\n");
11093 	}
11094 	/* Allow idle optimization when vblank count is 0 for display off */
11095 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
11096 		dc_allow_idle_optimizations(dm->dc, true);
11097 	mutex_unlock(&dm->dc_lock);
11098 
11099 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11100 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11101 
11102 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11103 
11104 		if (dm_new_crtc_state->stream != NULL) {
11105 			const struct dc_stream_status *status =
11106 					dc_stream_get_status(dm_new_crtc_state->stream);
11107 
11108 			if (!status)
11109 				status = dc_state_get_stream_status(dc_state,
11110 									 dm_new_crtc_state->stream);
11111 			if (!status)
11112 				drm_err(dev,
11113 					"got no status for stream %p on acrtc%p\n",
11114 					dm_new_crtc_state->stream, acrtc);
11115 			else
11116 				acrtc->otg_inst = status->primary_otg_inst;
11117 		}
11118 	}
11119 
11120 	/* During boot up and resume the DC layer will reset the panel brightness
11121 	 * to fix a flicker issue.
11122 	 * It will cause the dm->actual_brightness is not the current panel brightness
11123 	 * level. (the dm->brightness is the correct panel level)
11124 	 * So we set the backlight level with dm->brightness value after set mode
11125 	 */
11126 	if (set_backlight_level) {
11127 		for (i = 0; i < dm->num_of_edps; i++) {
11128 			if (dm->backlight_dev[i])
11129 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11130 		}
11131 	}
11132 }
11133 
11134 static void dm_set_writeback(struct amdgpu_display_manager *dm,
11135 			      struct dm_crtc_state *crtc_state,
11136 			      struct drm_connector *connector,
11137 			      struct drm_connector_state *new_con_state)
11138 {
11139 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
11140 	struct amdgpu_device *adev = dm->adev;
11141 	struct amdgpu_crtc *acrtc;
11142 	struct dc_writeback_info *wb_info;
11143 	struct pipe_ctx *pipe = NULL;
11144 	struct amdgpu_framebuffer *afb;
11145 	int i = 0;
11146 
11147 	wb_info = kzalloc_obj(*wb_info);
11148 	if (!wb_info) {
11149 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
11150 		return;
11151 	}
11152 
11153 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
11154 	if (!acrtc) {
11155 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
11156 		kfree(wb_info);
11157 		return;
11158 	}
11159 
11160 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
11161 	if (!afb) {
11162 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
11163 		kfree(wb_info);
11164 		return;
11165 	}
11166 
11167 	for (i = 0; i < MAX_PIPES; i++) {
11168 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
11169 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
11170 			break;
11171 		}
11172 	}
11173 
11174 	/* fill in wb_info */
11175 	wb_info->wb_enabled = true;
11176 
11177 	wb_info->dwb_pipe_inst = 0;
11178 	wb_info->dwb_params.dwbscl_black_color = 0;
11179 	wb_info->dwb_params.hdr_mult = 0x1F000;
11180 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
11181 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
11182 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
11183 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
11184 
11185 	/* width & height from crtc */
11186 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
11187 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
11188 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
11189 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
11190 
11191 	wb_info->dwb_params.cnv_params.crop_en = false;
11192 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
11193 
11194 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
11195 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
11196 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
11197 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
11198 
11199 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
11200 
11201 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
11202 
11203 	wb_info->dwb_params.scaler_taps.h_taps = 1;
11204 	wb_info->dwb_params.scaler_taps.v_taps = 1;
11205 	wb_info->dwb_params.scaler_taps.h_taps_c = 1;
11206 	wb_info->dwb_params.scaler_taps.v_taps_c = 1;
11207 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
11208 
11209 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
11210 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
11211 
11212 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
11213 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
11214 		wb_info->mcif_buf_params.chroma_address[i] = 0;
11215 	}
11216 
11217 	wb_info->mcif_buf_params.p_vmid = 1;
11218 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
11219 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
11220 		wb_info->mcif_warmup_params.region_size =
11221 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
11222 	}
11223 	wb_info->mcif_warmup_params.p_vmid = 1;
11224 	wb_info->writeback_source_plane = pipe->plane_state;
11225 
11226 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
11227 
11228 	acrtc->wb_pending = true;
11229 	acrtc->wb_conn = wb_conn;
11230 	drm_writeback_queue_job(wb_conn, new_con_state);
11231 }
11232 
11233 static void amdgpu_dm_update_hdcp(struct drm_atomic_commit *state)
11234 {
11235 	struct drm_connector_state *old_con_state, *new_con_state;
11236 	struct drm_device *dev = state->dev;
11237 	struct drm_connector *connector;
11238 	struct amdgpu_device *adev = drm_to_adev(dev);
11239 	int i;
11240 
11241 	if (!adev->dm.hdcp_workqueue)
11242 		return;
11243 
11244 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11245 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11246 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11247 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11248 		struct dm_crtc_state *dm_new_crtc_state;
11249 		struct amdgpu_dm_connector *aconnector;
11250 
11251 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11252 			continue;
11253 
11254 		aconnector = to_amdgpu_dm_connector(connector);
11255 
11256 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
11257 
11258 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
11259 			connector->index, connector->status, connector->dpms);
11260 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
11261 			old_con_state->content_protection, new_con_state->content_protection);
11262 
11263 		if (aconnector->dc_sink) {
11264 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
11265 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
11266 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
11267 				aconnector->dc_sink->edid_caps.display_name);
11268 			}
11269 		}
11270 
11271 		new_crtc_state = NULL;
11272 		old_crtc_state = NULL;
11273 
11274 		if (acrtc) {
11275 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11276 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11277 		}
11278 
11279 		if (old_crtc_state)
11280 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11281 			old_crtc_state->enable,
11282 			old_crtc_state->active,
11283 			old_crtc_state->mode_changed,
11284 			old_crtc_state->active_changed,
11285 			old_crtc_state->connectors_changed);
11286 
11287 		if (new_crtc_state)
11288 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11289 			new_crtc_state->enable,
11290 			new_crtc_state->active,
11291 			new_crtc_state->mode_changed,
11292 			new_crtc_state->active_changed,
11293 			new_crtc_state->connectors_changed);
11294 
11295 
11296 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11297 
11298 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
11299 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
11300 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
11301 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
11302 			dm_new_con_state->update_hdcp = true;
11303 			continue;
11304 		}
11305 
11306 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
11307 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
11308 			/* when display is unplugged from mst hub, connctor will
11309 			 * be destroyed within dm_dp_mst_connector_destroy. connector
11310 			 * hdcp perperties, like type, undesired, desired, enabled,
11311 			 * will be lost. So, save hdcp properties into hdcp_work within
11312 			 * amdgpu_dm_atomic_commit_tail. if the same display is
11313 			 * plugged back with same display index, its hdcp properties
11314 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
11315 			 */
11316 
11317 			bool enable_encryption = false;
11318 
11319 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
11320 				enable_encryption = true;
11321 
11322 			if (aconnector->dc_link && aconnector->dc_sink &&
11323 				aconnector->dc_link->type == dc_connection_mst_branch) {
11324 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
11325 				struct hdcp_workqueue *hdcp_w =
11326 					&hdcp_work[aconnector->dc_link->link_index];
11327 
11328 				hdcp_w->hdcp_content_type[connector->index] =
11329 					new_con_state->hdcp_content_type;
11330 				hdcp_w->content_protection[connector->index] =
11331 					new_con_state->content_protection;
11332 			}
11333 
11334 			if (new_crtc_state && new_crtc_state->mode_changed &&
11335 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
11336 				enable_encryption = true;
11337 
11338 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
11339 
11340 			if (aconnector->dc_link)
11341 				hdcp_update_display(
11342 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
11343 					new_con_state->hdcp_content_type, enable_encryption);
11344 		}
11345 	}
11346 }
11347 
11348 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state)
11349 {
11350 	struct drm_crtc *crtc;
11351 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11352 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11353 	int i, ret;
11354 
11355 	ret = drm_dp_mst_atomic_setup_commit(state);
11356 	if (ret)
11357 		return ret;
11358 
11359 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11360 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11361 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11362 		/*
11363 		 * Color management settings. We also update color properties
11364 		 * when a modeset is needed, to ensure it gets reprogrammed.
11365 		 */
11366 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
11367 		    (dm_new_crtc_state->base.color_mgmt_changed ||
11368 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11369 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11370 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
11371 			if (ret) {
11372 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
11373 				return ret;
11374 			}
11375 		}
11376 	}
11377 
11378 	return 0;
11379 }
11380 
11381 /**
11382  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
11383  * @state: The atomic state to commit
11384  *
11385  * This will tell DC to commit the constructed DC state from atomic_check,
11386  * programming the hardware. Any failures here implies a hardware failure, since
11387  * atomic check should have filtered anything non-kosher.
11388  */
11389 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state)
11390 {
11391 	struct drm_device *dev = state->dev;
11392 	struct amdgpu_device *adev = drm_to_adev(dev);
11393 	struct amdgpu_display_manager *dm = &adev->dm;
11394 	struct dm_atomic_state *dm_state;
11395 	struct dc_state *dc_state = NULL;
11396 	u32 i, j;
11397 	struct drm_crtc *crtc;
11398 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11399 	unsigned long flags;
11400 	bool wait_for_vblank = true;
11401 	struct drm_connector *connector;
11402 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
11403 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11404 	int crtc_disable_count = 0;
11405 
11406 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
11407 
11408 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
11409 	drm_dp_mst_atomic_wait_for_dependencies(state);
11410 
11411 	dm_state = dm_atomic_get_new_state(state);
11412 	if (dm_state && dm_state->context) {
11413 		dc_state = dm_state->context;
11414 		amdgpu_dm_commit_streams(state, dc_state);
11415 	}
11416 
11417 	amdgpu_dm_update_hdcp(state);
11418 
11419 	/* Handle connector state changes */
11420 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11421 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11422 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
11423 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11424 		struct dc_surface_update *dummy_updates;
11425 		struct dc_stream_update stream_update;
11426 		struct dc_info_packet hdr_packet;
11427 		struct dc_stream_status *status = NULL;
11428 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
11429 
11430 		memset(&stream_update, 0, sizeof(stream_update));
11431 
11432 		if (acrtc) {
11433 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11434 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11435 		}
11436 
11437 		/* Skip any modesets/resets */
11438 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
11439 			continue;
11440 
11441 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11442 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11443 
11444 		scaling_changed = is_scaling_state_different(dm_new_con_state,
11445 							     dm_old_con_state);
11446 
11447 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
11448 			(dm_old_crtc_state->stream->output_color_space !=
11449 				get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
11450 			output_color_space_changed = true;
11451 
11452 		abm_changed = dm_new_crtc_state->abm_level !=
11453 			      dm_old_crtc_state->abm_level;
11454 
11455 		hdr_changed =
11456 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
11457 
11458 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
11459 			continue;
11460 
11461 		stream_update.stream = dm_new_crtc_state->stream;
11462 		if (scaling_changed) {
11463 			update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
11464 					dm_new_con_state, dm_new_crtc_state->stream);
11465 
11466 			stream_update.src = dm_new_crtc_state->stream->src;
11467 			stream_update.dst = dm_new_crtc_state->stream->dst;
11468 		}
11469 
11470 		if (output_color_space_changed) {
11471 			dm_new_crtc_state->stream->output_color_space
11472 				= get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
11473 
11474 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
11475 		}
11476 
11477 		if (abm_changed) {
11478 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
11479 
11480 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
11481 		}
11482 
11483 		if (hdr_changed) {
11484 			fill_hdr_info_packet(new_con_state, &hdr_packet);
11485 			stream_update.hdr_static_metadata = &hdr_packet;
11486 		}
11487 
11488 		status = dc_stream_get_status(dm_new_crtc_state->stream);
11489 
11490 		if (WARN_ON(!status))
11491 			continue;
11492 
11493 		WARN_ON(!status->plane_count);
11494 
11495 		/*
11496 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
11497 		 * Here we create an empty update on each plane.
11498 		 * To fix this, DC should permit updating only stream properties.
11499 		 */
11500 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
11501 		if (!dummy_updates) {
11502 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
11503 			continue;
11504 		}
11505 		for (j = 0; j < status->plane_count; j++)
11506 			dummy_updates[j].surface = status->plane_states[j];
11507 
11508 		sort(dummy_updates, status->plane_count,
11509 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
11510 
11511 		mutex_lock(&dm->dc_lock);
11512 		dc_exit_ips_for_hw_access(dm->dc);
11513 		dc_update_planes_and_stream(dm->dc,
11514 					    dummy_updates,
11515 					    status->plane_count,
11516 					    dm_new_crtc_state->stream,
11517 					    &stream_update);
11518 		mutex_unlock(&dm->dc_lock);
11519 		kfree(dummy_updates);
11520 
11521 		drm_connector_update_privacy_screen(new_con_state);
11522 	}
11523 
11524 	/**
11525 	 * Enable interrupts for CRTCs that are newly enabled or went through
11526 	 * a modeset. It was intentionally deferred until after the front end
11527 	 * state was modified to wait until the OTG was on and so the IRQ
11528 	 * handlers didn't access stale or invalid state.
11529 	 */
11530 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11531 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11532 #ifdef CONFIG_DEBUG_FS
11533 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
11534 #endif
11535 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
11536 		if (old_crtc_state->active && !new_crtc_state->active)
11537 			crtc_disable_count++;
11538 
11539 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11540 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11541 
11542 		/* For freesync config update on crtc state and params for irq */
11543 		update_stream_irq_parameters(dm, dm_new_crtc_state);
11544 
11545 #ifdef CONFIG_DEBUG_FS
11546 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11547 		cur_crc_src = acrtc->dm_irq_params.crc_src;
11548 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11549 #endif
11550 
11551 		if (new_crtc_state->active &&
11552 		    (!old_crtc_state->active ||
11553 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11554 			dc_stream_retain(dm_new_crtc_state->stream);
11555 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
11556 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
11557 		}
11558 		/* Handle vrr on->off / off->on transitions */
11559 		amdgpu_dm_handle_vrr_transition(dm, dm_old_crtc_state, dm_new_crtc_state);
11560 
11561 #ifdef CONFIG_DEBUG_FS
11562 		if (new_crtc_state->active &&
11563 		    (!old_crtc_state->active ||
11564 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11565 			/**
11566 			 * Frontend may have changed so reapply the CRC capture
11567 			 * settings for the stream.
11568 			 */
11569 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
11570 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
11571 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
11572 					uint8_t cnt;
11573 
11574 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11575 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
11576 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
11577 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
11578 
11579 							/**
11580 							 * It takes 2 frames for HW to stably generate CRC when
11581 							 * resuming from suspend, so we set skip_frame_cnt 2.
11582 							 */
11583 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
11584 						}
11585 					}
11586 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11587 				}
11588 #endif
11589 				if (amdgpu_dm_crtc_configure_crc_source(
11590 					crtc, dm_new_crtc_state, cur_crc_src))
11591 					drm_dbg_atomic(dev, "Failed to configure crc source");
11592 			}
11593 		}
11594 #endif
11595 	}
11596 
11597 	amdgpu_dm_mod_power_setup_streams(state, dm);
11598 
11599 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
11600 		if (new_crtc_state->async_flip)
11601 			wait_for_vblank = false;
11602 
11603 	/* update planes when needed per crtc*/
11604 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
11605 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11606 
11607 		if (dm_new_crtc_state->stream)
11608 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
11609 	}
11610 
11611 	/* Enable writeback */
11612 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11613 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11614 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11615 
11616 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11617 			continue;
11618 
11619 		if (!new_con_state->writeback_job)
11620 			continue;
11621 
11622 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11623 
11624 		if (!new_crtc_state)
11625 			continue;
11626 
11627 		if (acrtc->wb_enabled)
11628 			continue;
11629 
11630 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11631 
11632 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
11633 		acrtc->wb_enabled = true;
11634 	}
11635 
11636 	/* Update audio instances for each connector. */
11637 	amdgpu_dm_commit_audio(dev, state);
11638 
11639 	/* restore the backlight level */
11640 	for (i = 0; i < dm->num_of_edps; i++) {
11641 		if (dm->backlight_dev[i] &&
11642 		    (dm->actual_brightness[i] != dm->brightness[i]))
11643 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11644 	}
11645 
11646 	/*
11647 	 * send vblank event on all events not handled in flip and
11648 	 * mark consumed event for drm_atomic_helper_commit_hw_done
11649 	 */
11650 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11651 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11652 
11653 		if (new_crtc_state->event)
11654 			drm_send_event_locked(dev, &new_crtc_state->event->base);
11655 
11656 		new_crtc_state->event = NULL;
11657 	}
11658 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11659 
11660 	/* Signal HW programming completion */
11661 	drm_atomic_helper_commit_hw_done(state);
11662 
11663 	if (wait_for_vblank)
11664 		drm_atomic_helper_wait_for_flip_done(dev, state);
11665 
11666 	drm_atomic_helper_cleanup_planes(dev, state);
11667 
11668 	/* Don't free the memory if we are hitting this as part of suspend.
11669 	 * This way we don't free any memory during suspend; see
11670 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
11671 	 * non-suspend modeset or when the driver is torn down.
11672 	 */
11673 	if (!adev->in_suspend) {
11674 		/* return the stolen vga memory back to VRAM */
11675 		if (!adev->mman.keep_stolen_vga_memory)
11676 			amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_VGA);
11677 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_EXTENDED);
11678 	}
11679 
11680 	/*
11681 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
11682 	 * so we can put the GPU into runtime suspend if we're not driving any
11683 	 * displays anymore
11684 	 */
11685 	for (i = 0; i < crtc_disable_count; i++)
11686 		pm_runtime_put_autosuspend(dev->dev);
11687 	pm_runtime_mark_last_busy(dev->dev);
11688 
11689 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
11690 }
11691 
11692 static int dm_force_atomic_commit(struct drm_connector *connector)
11693 {
11694 	int ret = 0;
11695 	struct drm_device *ddev = connector->dev;
11696 	struct drm_atomic_commit *state = drm_atomic_commit_alloc(ddev);
11697 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11698 	struct drm_plane *plane = disconnected_acrtc->base.primary;
11699 	struct drm_connector_state *conn_state;
11700 	struct drm_crtc_state *crtc_state;
11701 	struct drm_plane_state *plane_state;
11702 
11703 	if (!state)
11704 		return -ENOMEM;
11705 
11706 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
11707 
11708 	/* Construct an atomic state to restore previous display setting */
11709 
11710 	/*
11711 	 * Attach connectors to drm_atomic_commit
11712 	 */
11713 	conn_state = drm_atomic_get_connector_state(state, connector);
11714 
11715 	/* Check for error in getting connector state */
11716 	if (IS_ERR(conn_state)) {
11717 		ret = PTR_ERR(conn_state);
11718 		goto out;
11719 	}
11720 
11721 	/* Attach crtc to drm_atomic_commit*/
11722 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
11723 
11724 	/* Check for error in getting crtc state */
11725 	if (IS_ERR(crtc_state)) {
11726 		ret = PTR_ERR(crtc_state);
11727 		goto out;
11728 	}
11729 
11730 	/* force a restore */
11731 	crtc_state->mode_changed = true;
11732 
11733 	/* Attach plane to drm_atomic_commit */
11734 	plane_state = drm_atomic_get_plane_state(state, plane);
11735 
11736 	/* Check for error in getting plane state */
11737 	if (IS_ERR(plane_state)) {
11738 		ret = PTR_ERR(plane_state);
11739 		goto out;
11740 	}
11741 
11742 	/* Call commit internally with the state we just constructed */
11743 	ret = drm_atomic_commit(state);
11744 
11745 out:
11746 	drm_atomic_commit_put(state);
11747 	if (ret)
11748 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
11749 
11750 	return ret;
11751 }
11752 
11753 /*
11754  * This function handles all cases when set mode does not come upon hotplug.
11755  * This includes when a display is unplugged then plugged back into the
11756  * same port and when running without usermode desktop manager supprot
11757  */
11758 void dm_restore_drm_connector_state(struct drm_device *dev,
11759 				    struct drm_connector *connector)
11760 {
11761 	struct amdgpu_dm_connector *aconnector;
11762 	struct amdgpu_crtc *disconnected_acrtc;
11763 	struct dm_crtc_state *acrtc_state;
11764 
11765 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11766 		return;
11767 
11768 	aconnector = to_amdgpu_dm_connector(connector);
11769 
11770 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
11771 		return;
11772 
11773 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11774 	if (!disconnected_acrtc)
11775 		return;
11776 
11777 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
11778 	if (!acrtc_state->stream)
11779 		return;
11780 
11781 	/*
11782 	 * If the previous sink is not released and different from the current,
11783 	 * we deduce we are in a state where we can not rely on usermode call
11784 	 * to turn on the display, so we do it here
11785 	 */
11786 	if (acrtc_state->stream->sink != aconnector->dc_sink)
11787 		dm_force_atomic_commit(&aconnector->base);
11788 }
11789 
11790 /*
11791  * Grabs all modesetting locks to serialize against any blocking commits,
11792  * Waits for completion of all non blocking commits.
11793  */
11794 static int do_aquire_global_lock(struct drm_device *dev,
11795 				 struct drm_atomic_commit *state)
11796 {
11797 	struct drm_crtc *crtc;
11798 	struct drm_crtc_commit *commit;
11799 	long ret;
11800 
11801 	/*
11802 	 * Adding all modeset locks to aquire_ctx will
11803 	 * ensure that when the framework release it the
11804 	 * extra locks we are locking here will get released to
11805 	 */
11806 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
11807 	if (ret)
11808 		return ret;
11809 
11810 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
11811 		spin_lock(&crtc->commit_lock);
11812 		commit = list_first_entry_or_null(&crtc->commit_list,
11813 				struct drm_crtc_commit, commit_entry);
11814 		if (commit)
11815 			drm_crtc_commit_get(commit);
11816 		spin_unlock(&crtc->commit_lock);
11817 
11818 		if (!commit)
11819 			continue;
11820 
11821 		/*
11822 		 * Make sure all pending HW programming completed and
11823 		 * page flips done
11824 		 */
11825 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
11826 
11827 		if (ret > 0)
11828 			ret = wait_for_completion_interruptible_timeout(
11829 					&commit->flip_done, 10*HZ);
11830 
11831 		if (ret == 0)
11832 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
11833 				  crtc->base.id, crtc->name);
11834 
11835 		drm_crtc_commit_put(commit);
11836 	}
11837 
11838 	return ret < 0 ? ret : 0;
11839 }
11840 
11841 static void get_freesync_config_for_crtc(
11842 	struct dm_crtc_state *new_crtc_state,
11843 	struct dm_connector_state *new_con_state)
11844 {
11845 	struct mod_freesync_config config = {0};
11846 	struct amdgpu_dm_connector *aconnector;
11847 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
11848 	int vrefresh = drm_mode_vrefresh(mode);
11849 	bool fs_vid_mode = false;
11850 
11851 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11852 		return;
11853 
11854 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
11855 
11856 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
11857 					vrefresh >= aconnector->min_vfreq &&
11858 					vrefresh <= aconnector->max_vfreq;
11859 
11860 	if (new_crtc_state->vrr_supported) {
11861 		new_crtc_state->stream->ignore_msa_timing_param = true;
11862 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
11863 
11864 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
11865 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
11866 		config.vsif_supported = true;
11867 		config.btr = true;
11868 
11869 		if (fs_vid_mode) {
11870 			config.state = VRR_STATE_ACTIVE_FIXED;
11871 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
11872 			goto out;
11873 		} else if (new_crtc_state->base.vrr_enabled) {
11874 			config.state = VRR_STATE_ACTIVE_VARIABLE;
11875 		} else {
11876 			config.state = VRR_STATE_INACTIVE;
11877 		}
11878 	} else {
11879 		config.state = VRR_STATE_UNSUPPORTED;
11880 	}
11881 out:
11882 	new_crtc_state->freesync_config = config;
11883 }
11884 
11885 static void reset_freesync_config_for_crtc(
11886 	struct dm_crtc_state *new_crtc_state)
11887 {
11888 	new_crtc_state->vrr_supported = false;
11889 
11890 	memset(&new_crtc_state->vrr_infopacket, 0,
11891 	       sizeof(new_crtc_state->vrr_infopacket));
11892 }
11893 
11894 static bool
11895 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
11896 				 struct drm_crtc_state *new_crtc_state)
11897 {
11898 	const struct drm_display_mode *old_mode, *new_mode;
11899 
11900 	if (!old_crtc_state || !new_crtc_state)
11901 		return false;
11902 
11903 	old_mode = &old_crtc_state->mode;
11904 	new_mode = &new_crtc_state->mode;
11905 
11906 	if (old_mode->clock       == new_mode->clock &&
11907 	    old_mode->hdisplay    == new_mode->hdisplay &&
11908 	    old_mode->vdisplay    == new_mode->vdisplay &&
11909 	    old_mode->htotal      == new_mode->htotal &&
11910 	    old_mode->vtotal      != new_mode->vtotal &&
11911 	    old_mode->hsync_start == new_mode->hsync_start &&
11912 	    old_mode->vsync_start != new_mode->vsync_start &&
11913 	    old_mode->hsync_end   == new_mode->hsync_end &&
11914 	    old_mode->vsync_end   != new_mode->vsync_end &&
11915 	    old_mode->hskew       == new_mode->hskew &&
11916 	    old_mode->vscan       == new_mode->vscan &&
11917 	    (old_mode->vsync_end - old_mode->vsync_start) ==
11918 	    (new_mode->vsync_end - new_mode->vsync_start))
11919 		return true;
11920 
11921 	return false;
11922 }
11923 
11924 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
11925 {
11926 	u64 num, den, res;
11927 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
11928 
11929 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
11930 
11931 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
11932 	den = (unsigned long long)new_crtc_state->mode.htotal *
11933 	      (unsigned long long)new_crtc_state->mode.vtotal;
11934 
11935 	res = div_u64(num, den);
11936 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
11937 }
11938 
11939 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
11940 			 struct drm_atomic_commit *state,
11941 			 struct drm_crtc *crtc,
11942 			 struct drm_crtc_state *old_crtc_state,
11943 			 struct drm_crtc_state *new_crtc_state,
11944 			 bool enable,
11945 			 bool *lock_and_validation_needed)
11946 {
11947 	struct dm_atomic_state *dm_state = NULL;
11948 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11949 	struct dc_stream_state *new_stream;
11950 	struct amdgpu_device *adev = dm->adev;
11951 	int ret = 0;
11952 
11953 	/*
11954 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
11955 	 * update changed items
11956 	 */
11957 	struct amdgpu_crtc *acrtc = NULL;
11958 	struct drm_connector *connector = NULL;
11959 	struct amdgpu_dm_connector *aconnector = NULL;
11960 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
11961 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
11962 
11963 	new_stream = NULL;
11964 
11965 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11966 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11967 	acrtc = to_amdgpu_crtc(crtc);
11968 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
11969 	if (connector)
11970 		aconnector = to_amdgpu_dm_connector(connector);
11971 
11972 	/* TODO This hack should go away */
11973 	if (connector && enable) {
11974 		/* Make sure fake sink is created in plug-in scenario */
11975 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
11976 									connector);
11977 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
11978 									connector);
11979 
11980 		if (WARN_ON(!drm_new_conn_state)) {
11981 			ret = -EINVAL;
11982 			goto fail;
11983 		}
11984 
11985 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
11986 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
11987 
11988 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11989 			goto skip_modeset;
11990 
11991 		new_stream = create_validate_stream_for_sink(connector,
11992 							     &new_crtc_state->mode,
11993 							     dm_new_conn_state,
11994 							     dm_old_crtc_state->stream);
11995 
11996 		/*
11997 		 * we can have no stream on ACTION_SET if a display
11998 		 * was disconnected during S3, in this case it is not an
11999 		 * error, the OS will be updated after detection, and
12000 		 * will do the right thing on next atomic commit
12001 		 */
12002 
12003 		if (!new_stream) {
12004 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
12005 					__func__, acrtc->base.base.id);
12006 			ret = -ENOMEM;
12007 			goto fail;
12008 		}
12009 
12010 		/*
12011 		 * TODO: Check VSDB bits to decide whether this should
12012 		 * be enabled or not.
12013 		 */
12014 		new_stream->triggered_crtc_reset.enabled =
12015 			dm->force_timing_sync;
12016 
12017 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
12018 
12019 		ret = fill_hdr_info_packet(drm_new_conn_state,
12020 					   &new_stream->hdr_static_metadata);
12021 		if (ret)
12022 			goto fail;
12023 
12024 		/*
12025 		 * If we already removed the old stream from the context
12026 		 * (and set the new stream to NULL) then we can't reuse
12027 		 * the old stream even if the stream and scaling are unchanged.
12028 		 * We'll hit the BUG_ON and black screen.
12029 		 *
12030 		 * TODO: Refactor this function to allow this check to work
12031 		 * in all conditions.
12032 		 */
12033 		if (amdgpu_freesync_vid_mode &&
12034 		    dm_new_crtc_state->stream &&
12035 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
12036 			goto skip_modeset;
12037 
12038 		if (dm_new_crtc_state->stream &&
12039 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
12040 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
12041 			new_crtc_state->mode_changed = false;
12042 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
12043 					 new_crtc_state->mode_changed);
12044 		}
12045 	}
12046 
12047 	/* mode_changed flag may get updated above, need to check again */
12048 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
12049 		goto skip_modeset;
12050 
12051 	drm_dbg_state(state->dev,
12052 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
12053 		acrtc->crtc_id,
12054 		new_crtc_state->enable,
12055 		new_crtc_state->active,
12056 		new_crtc_state->planes_changed,
12057 		new_crtc_state->mode_changed,
12058 		new_crtc_state->active_changed,
12059 		new_crtc_state->connectors_changed);
12060 
12061 	/* Remove stream for any changed/disabled CRTC */
12062 	if (!enable) {
12063 
12064 		if (!dm_old_crtc_state->stream)
12065 			goto skip_modeset;
12066 
12067 		/* Unset freesync video if it was active before */
12068 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
12069 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
12070 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
12071 		}
12072 
12073 		/* Now check if we should set freesync video mode */
12074 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
12075 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
12076 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
12077 		    is_timing_unchanged_for_freesync(new_crtc_state,
12078 						     old_crtc_state)) {
12079 			new_crtc_state->mode_changed = false;
12080 			drm_dbg_driver(adev_to_drm(adev),
12081 				"Mode change not required for front porch change, setting mode_changed to %d",
12082 				new_crtc_state->mode_changed);
12083 
12084 			set_freesync_fixed_config(dm_new_crtc_state);
12085 
12086 			goto skip_modeset;
12087 		} else if (amdgpu_freesync_vid_mode && aconnector &&
12088 			   is_freesync_video_mode(&new_crtc_state->mode,
12089 						  aconnector)) {
12090 			struct drm_display_mode *high_mode;
12091 
12092 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
12093 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
12094 				set_freesync_fixed_config(dm_new_crtc_state);
12095 		}
12096 
12097 		ret = dm_atomic_get_state(state, &dm_state);
12098 		if (ret)
12099 			goto fail;
12100 
12101 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
12102 				crtc->base.id);
12103 
12104 		/* i.e. reset mode */
12105 		if (dc_state_remove_stream(
12106 				dm->dc,
12107 				dm_state->context,
12108 				dm_old_crtc_state->stream) != DC_OK) {
12109 			ret = -EINVAL;
12110 			goto fail;
12111 		}
12112 
12113 		dc_stream_release(dm_old_crtc_state->stream);
12114 		dm_new_crtc_state->stream = NULL;
12115 
12116 		reset_freesync_config_for_crtc(dm_new_crtc_state);
12117 
12118 		*lock_and_validation_needed = true;
12119 
12120 	} else {/* Add stream for any updated/enabled CRTC */
12121 		/*
12122 		 * Quick fix to prevent NULL pointer on new_stream when
12123 		 * added MST connectors not found in existing crtc_state in the chained mode
12124 		 * TODO: need to dig out the root cause of that
12125 		 */
12126 		if (!connector)
12127 			goto skip_modeset;
12128 
12129 		if (modereset_required(new_crtc_state))
12130 			goto skip_modeset;
12131 
12132 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
12133 				     dm_old_crtc_state->stream)) {
12134 
12135 			WARN_ON(dm_new_crtc_state->stream);
12136 
12137 			ret = dm_atomic_get_state(state, &dm_state);
12138 			if (ret)
12139 				goto fail;
12140 
12141 			dm_new_crtc_state->stream = new_stream;
12142 
12143 			dc_stream_retain(new_stream);
12144 
12145 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
12146 					 crtc->base.id);
12147 
12148 			if (dc_state_add_stream(
12149 					dm->dc,
12150 					dm_state->context,
12151 					dm_new_crtc_state->stream) != DC_OK) {
12152 				ret = -EINVAL;
12153 				goto fail;
12154 			}
12155 
12156 			*lock_and_validation_needed = true;
12157 		}
12158 	}
12159 
12160 skip_modeset:
12161 	/* Release extra reference */
12162 	if (new_stream)
12163 		dc_stream_release(new_stream);
12164 
12165 	/*
12166 	 * We want to do dc stream updates that do not require a
12167 	 * full modeset below.
12168 	 */
12169 	if (!(enable && connector && new_crtc_state->active))
12170 		return 0;
12171 	/*
12172 	 * Given above conditions, the dc state cannot be NULL because:
12173 	 * 1. We're in the process of enabling CRTCs (just been added
12174 	 *    to the dc context, or already is on the context)
12175 	 * 2. Has a valid connector attached, and
12176 	 * 3. Is currently active and enabled.
12177 	 * => The dc stream state currently exists.
12178 	 */
12179 	BUG_ON(dm_new_crtc_state->stream == NULL);
12180 
12181 	/* Scaling or underscan settings */
12182 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
12183 				drm_atomic_crtc_needs_modeset(new_crtc_state))
12184 		update_stream_scaling_settings(adev_to_drm(adev),
12185 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
12186 
12187 	/* ABM settings */
12188 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
12189 
12190 	/*
12191 	 * Color management settings. We also update color properties
12192 	 * when a modeset is needed, to ensure it gets reprogrammed.
12193 	 */
12194 	if (dm_new_crtc_state->base.color_mgmt_changed ||
12195 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
12196 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
12197 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
12198 		if (ret)
12199 			goto fail;
12200 	}
12201 
12202 	/* Update Freesync settings. */
12203 	get_freesync_config_for_crtc(dm_new_crtc_state,
12204 				     dm_new_conn_state);
12205 
12206 	return ret;
12207 
12208 fail:
12209 	if (new_stream)
12210 		dc_stream_release(new_stream);
12211 	return ret;
12212 }
12213 
12214 static bool should_reset_plane(struct drm_atomic_commit *state,
12215 			       struct drm_plane *plane,
12216 			       struct drm_plane_state *old_plane_state,
12217 			       struct drm_plane_state *new_plane_state)
12218 {
12219 	struct drm_plane *other;
12220 	struct drm_plane_state *old_other_state, *new_other_state;
12221 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12222 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
12223 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
12224 	struct drm_connector_state *new_con_state;
12225 	struct drm_connector *connector;
12226 	int i;
12227 
12228 	/*
12229 	 * TODO: Remove this hack for all asics once it proves that the
12230 	 * fast updates works fine on DCN3.2+.
12231 	 */
12232 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
12233 	    state->allow_modeset)
12234 		return true;
12235 
12236 	/* Check for writeback commit */
12237 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
12238 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
12239 			continue;
12240 
12241 		if (new_con_state->writeback_job)
12242 			return true;
12243 	}
12244 
12245 	if (amdgpu_in_reset(adev) && state->allow_modeset)
12246 		return true;
12247 
12248 	/* Exit early if we know that we're adding or removing the plane. */
12249 	if (old_plane_state->crtc != new_plane_state->crtc)
12250 		return true;
12251 
12252 	/* old crtc == new_crtc == NULL, plane not in context. */
12253 	if (!new_plane_state->crtc)
12254 		return false;
12255 
12256 	new_crtc_state =
12257 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
12258 	old_crtc_state =
12259 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
12260 
12261 	if (!new_crtc_state)
12262 		return true;
12263 
12264 	/*
12265 	 * A change in cursor mode means a new dc pipe needs to be acquired or
12266 	 * released from the state
12267 	 */
12268 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
12269 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
12270 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
12271 	    old_dm_crtc_state != NULL &&
12272 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
12273 		return true;
12274 	}
12275 
12276 	/* CRTC Degamma changes currently require us to recreate planes. */
12277 	if (new_crtc_state->color_mgmt_changed)
12278 		return true;
12279 
12280 	/* Plane color pipeline or its colorop changes. */
12281 	if (new_plane_state->color_mgmt_changed)
12282 		return true;
12283 
12284 	/*
12285 	 * On zpos change, planes need to be reordered by removing and re-adding
12286 	 * them one by one to the dc state, in order of descending zpos.
12287 	 *
12288 	 * TODO: We can likely skip bandwidth validation if the only thing that
12289 	 * changed about the plane was it'z z-ordering.
12290 	 */
12291 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
12292 		return true;
12293 
12294 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
12295 		return true;
12296 
12297 	/*
12298 	 * If there are any new primary or overlay planes being added or
12299 	 * removed then the z-order can potentially change. To ensure
12300 	 * correct z-order and pipe acquisition the current DC architecture
12301 	 * requires us to remove and recreate all existing planes.
12302 	 *
12303 	 * TODO: Come up with a more elegant solution for this.
12304 	 */
12305 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
12306 		struct amdgpu_framebuffer *old_afb, *new_afb;
12307 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
12308 
12309 		dm_new_other_state = to_dm_plane_state(new_other_state);
12310 		dm_old_other_state = to_dm_plane_state(old_other_state);
12311 
12312 		if (other->type == DRM_PLANE_TYPE_CURSOR)
12313 			continue;
12314 
12315 		if (old_other_state->crtc != new_plane_state->crtc &&
12316 		    new_other_state->crtc != new_plane_state->crtc)
12317 			continue;
12318 
12319 		if (old_other_state->crtc != new_other_state->crtc)
12320 			return true;
12321 
12322 		/* Src/dst size and scaling updates. */
12323 		if (old_other_state->src_w != new_other_state->src_w ||
12324 		    old_other_state->src_h != new_other_state->src_h ||
12325 		    old_other_state->crtc_w != new_other_state->crtc_w ||
12326 		    old_other_state->crtc_h != new_other_state->crtc_h)
12327 			return true;
12328 
12329 		/* Rotation / mirroring updates. */
12330 		if (old_other_state->rotation != new_other_state->rotation)
12331 			return true;
12332 
12333 		/* Blending updates. */
12334 		if (old_other_state->pixel_blend_mode !=
12335 		    new_other_state->pixel_blend_mode)
12336 			return true;
12337 
12338 		/* Alpha updates. */
12339 		if (old_other_state->alpha != new_other_state->alpha)
12340 			return true;
12341 
12342 		/* Colorspace changes. */
12343 		if (old_other_state->color_range != new_other_state->color_range ||
12344 		    old_other_state->color_encoding != new_other_state->color_encoding)
12345 			return true;
12346 
12347 		/* HDR/Transfer Function changes. */
12348 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
12349 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
12350 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
12351 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
12352 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
12353 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
12354 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
12355 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
12356 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
12357 			return true;
12358 
12359 		/* Framebuffer checks fall at the end. */
12360 		if (!old_other_state->fb || !new_other_state->fb)
12361 			continue;
12362 
12363 		/* Pixel format changes can require bandwidth updates. */
12364 		if (old_other_state->fb->format != new_other_state->fb->format)
12365 			return true;
12366 
12367 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
12368 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
12369 
12370 		/* Tiling and DCC changes also require bandwidth updates. */
12371 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
12372 		    old_afb->base.modifier != new_afb->base.modifier)
12373 			return true;
12374 	}
12375 
12376 	return false;
12377 }
12378 
12379 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
12380 			      struct drm_plane_state *new_plane_state,
12381 			      struct drm_framebuffer *fb)
12382 {
12383 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
12384 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
12385 	unsigned int pitch;
12386 	bool linear;
12387 
12388 	if (fb->width > new_acrtc->max_cursor_width ||
12389 	    fb->height > new_acrtc->max_cursor_height) {
12390 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB size %dx%d\n",
12391 				 new_plane_state->fb->width,
12392 				 new_plane_state->fb->height);
12393 		return -EINVAL;
12394 	}
12395 	if (new_plane_state->src_w != fb->width << 16 ||
12396 	    new_plane_state->src_h != fb->height << 16) {
12397 		drm_dbg_atomic(adev_to_drm(adev), "Cropping not supported for cursor plane\n");
12398 		return -EINVAL;
12399 	}
12400 
12401 	/* Pitch in pixels */
12402 	pitch = fb->pitches[0] / fb->format->cpp[0];
12403 
12404 	if (fb->width != pitch) {
12405 		drm_dbg_atomic(adev_to_drm(adev), "Cursor FB width %d doesn't match pitch %d",
12406 				 fb->width, pitch);
12407 		return -EINVAL;
12408 	}
12409 
12410 	switch (pitch) {
12411 	case 64:
12412 	case 128:
12413 	case 256:
12414 		/* FB pitch is supported by cursor plane */
12415 		break;
12416 	default:
12417 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB pitch %d px\n", pitch);
12418 		return -EINVAL;
12419 	}
12420 
12421 	/* Core DRM takes care of checking FB modifiers, so we only need to
12422 	 * check tiling flags when the FB doesn't have a modifier.
12423 	 */
12424 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
12425 		if (adev->family == AMDGPU_FAMILY_GC_12_0_0) {
12426 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
12427 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
12428 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
12429 		} else {
12430 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
12431 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
12432 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
12433 		}
12434 		if (!linear) {
12435 			drm_dbg_atomic(adev_to_drm(adev), "Cursor FB not linear");
12436 			return -EINVAL;
12437 		}
12438 	}
12439 
12440 	return 0;
12441 }
12442 
12443 /*
12444  * Helper function for checking the cursor in native mode
12445  */
12446 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
12447 					struct drm_plane *plane,
12448 					struct drm_plane_state *new_plane_state,
12449 					bool enable)
12450 {
12451 
12452 	struct amdgpu_crtc *new_acrtc;
12453 	int ret;
12454 
12455 	if (!enable || !new_plane_crtc ||
12456 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
12457 		return 0;
12458 
12459 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
12460 
12461 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
12462 		drm_dbg_atomic(new_plane_crtc->dev, "Cropping not supported for cursor plane\n");
12463 		return -EINVAL;
12464 	}
12465 
12466 	if (new_plane_state->fb) {
12467 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
12468 						new_plane_state->fb);
12469 		if (ret)
12470 			return ret;
12471 	}
12472 
12473 	return 0;
12474 }
12475 
12476 static bool dm_should_update_native_cursor(struct drm_atomic_commit *state,
12477 					   struct drm_crtc *old_plane_crtc,
12478 					   struct drm_crtc *new_plane_crtc,
12479 					   bool enable)
12480 {
12481 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12482 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12483 
12484 	if (!enable) {
12485 		if (old_plane_crtc == NULL)
12486 			return true;
12487 
12488 		old_crtc_state = drm_atomic_get_old_crtc_state(
12489 			state, old_plane_crtc);
12490 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12491 
12492 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12493 	} else {
12494 		if (new_plane_crtc == NULL)
12495 			return true;
12496 
12497 		new_crtc_state = drm_atomic_get_new_crtc_state(
12498 			state, new_plane_crtc);
12499 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12500 
12501 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12502 	}
12503 }
12504 
12505 static int dm_update_plane_state(struct dc *dc,
12506 				 struct drm_atomic_commit *state,
12507 				 struct drm_plane *plane,
12508 				 struct drm_plane_state *old_plane_state,
12509 				 struct drm_plane_state *new_plane_state,
12510 				 bool enable,
12511 				 bool *lock_and_validation_needed,
12512 				 bool *is_top_most_overlay)
12513 {
12514 
12515 	struct dm_atomic_state *dm_state = NULL;
12516 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
12517 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12518 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
12519 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
12520 	bool needs_reset, update_native_cursor;
12521 	int ret = 0;
12522 
12523 
12524 	new_plane_crtc = new_plane_state->crtc;
12525 	old_plane_crtc = old_plane_state->crtc;
12526 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
12527 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
12528 
12529 	update_native_cursor = dm_should_update_native_cursor(state,
12530 							      old_plane_crtc,
12531 							      new_plane_crtc,
12532 							      enable);
12533 
12534 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
12535 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12536 						    new_plane_state, enable);
12537 		if (ret)
12538 			return ret;
12539 
12540 		return 0;
12541 	}
12542 
12543 	needs_reset = should_reset_plane(state, plane, old_plane_state,
12544 					 new_plane_state);
12545 
12546 	/* Remove any changed/removed planes */
12547 	if (!enable) {
12548 		if (!needs_reset)
12549 			return 0;
12550 
12551 		if (!old_plane_crtc)
12552 			return 0;
12553 
12554 		old_crtc_state = drm_atomic_get_old_crtc_state(
12555 				state, old_plane_crtc);
12556 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12557 
12558 		if (!dm_old_crtc_state->stream)
12559 			return 0;
12560 
12561 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
12562 				plane->base.id, old_plane_crtc->base.id);
12563 
12564 		ret = dm_atomic_get_state(state, &dm_state);
12565 		if (ret)
12566 			return ret;
12567 
12568 		if (!dc_state_remove_plane(
12569 				dc,
12570 				dm_old_crtc_state->stream,
12571 				dm_old_plane_state->dc_state,
12572 				dm_state->context)) {
12573 
12574 			return -EINVAL;
12575 		}
12576 
12577 		if (dm_old_plane_state->dc_state)
12578 			dc_plane_state_release(dm_old_plane_state->dc_state);
12579 
12580 		dm_new_plane_state->dc_state = NULL;
12581 
12582 		*lock_and_validation_needed = true;
12583 
12584 	} else { /* Add new planes */
12585 		struct dc_plane_state *dc_new_plane_state;
12586 
12587 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
12588 			return 0;
12589 
12590 		if (!new_plane_crtc)
12591 			return 0;
12592 
12593 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
12594 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12595 
12596 		if (!dm_new_crtc_state->stream)
12597 			return 0;
12598 
12599 		if (!needs_reset)
12600 			return 0;
12601 
12602 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
12603 		if (ret)
12604 			goto out;
12605 
12606 		WARN_ON(dm_new_plane_state->dc_state);
12607 
12608 		dc_new_plane_state = dc_create_plane_state(dc);
12609 		if (!dc_new_plane_state) {
12610 			ret = -ENOMEM;
12611 			goto out;
12612 		}
12613 
12614 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
12615 				 plane->base.id, new_plane_crtc->base.id);
12616 
12617 		ret = fill_dc_plane_attributes(
12618 			drm_to_adev(new_plane_crtc->dev),
12619 			dc_new_plane_state,
12620 			new_plane_state,
12621 			new_crtc_state);
12622 		if (ret) {
12623 			dc_plane_state_release(dc_new_plane_state);
12624 			goto out;
12625 		}
12626 
12627 		ret = dm_atomic_get_state(state, &dm_state);
12628 		if (ret) {
12629 			dc_plane_state_release(dc_new_plane_state);
12630 			goto out;
12631 		}
12632 
12633 		/*
12634 		 * Any atomic check errors that occur after this will
12635 		 * not need a release. The plane state will be attached
12636 		 * to the stream, and therefore part of the atomic
12637 		 * state. It'll be released when the atomic state is
12638 		 * cleaned.
12639 		 */
12640 		if (!dc_state_add_plane(
12641 				dc,
12642 				dm_new_crtc_state->stream,
12643 				dc_new_plane_state,
12644 				dm_state->context)) {
12645 
12646 			dc_plane_state_release(dc_new_plane_state);
12647 			ret = -EINVAL;
12648 			goto out;
12649 		}
12650 
12651 		dm_new_plane_state->dc_state = dc_new_plane_state;
12652 
12653 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
12654 
12655 		/* Tell DC to do a full surface update every time there
12656 		 * is a plane change. Inefficient, but works for now.
12657 		 */
12658 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
12659 
12660 		*lock_and_validation_needed = true;
12661 	}
12662 
12663 out:
12664 	/* If enabling cursor overlay failed, attempt fallback to native mode */
12665 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
12666 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12667 						    new_plane_state, enable);
12668 		if (ret)
12669 			return ret;
12670 
12671 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
12672 	}
12673 
12674 	return ret;
12675 }
12676 
12677 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
12678 				       int *src_w, int *src_h)
12679 {
12680 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
12681 	case DRM_MODE_ROTATE_90:
12682 	case DRM_MODE_ROTATE_270:
12683 		*src_w = plane_state->src_h >> 16;
12684 		*src_h = plane_state->src_w >> 16;
12685 		break;
12686 	case DRM_MODE_ROTATE_0:
12687 	case DRM_MODE_ROTATE_180:
12688 	default:
12689 		*src_w = plane_state->src_w >> 16;
12690 		*src_h = plane_state->src_h >> 16;
12691 		break;
12692 	}
12693 }
12694 
12695 static void
12696 dm_get_plane_scale(struct drm_plane_state *plane_state,
12697 		   int *out_plane_scale_w, int *out_plane_scale_h)
12698 {
12699 	int plane_src_w, plane_src_h;
12700 
12701 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
12702 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
12703 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
12704 }
12705 
12706 /*
12707  * The normalized_zpos value cannot be used by this iterator directly. It's only
12708  * calculated for enabled planes, potentially causing normalized_zpos collisions
12709  * between enabled/disabled planes in the atomic state. We need a unique value
12710  * so that the iterator will not generate the same object twice, or loop
12711  * indefinitely.
12712  */
12713 static inline struct __drm_planes_state *__get_next_zpos(
12714 	struct drm_atomic_commit *state,
12715 	struct __drm_planes_state *prev)
12716 {
12717 	unsigned int highest_zpos = 0, prev_zpos = 256;
12718 	uint32_t highest_id = 0, prev_id = UINT_MAX;
12719 	struct drm_plane_state *new_plane_state;
12720 	struct drm_plane *plane;
12721 	int i, highest_i = -1;
12722 
12723 	if (prev != NULL) {
12724 		prev_zpos = prev->new_state->zpos;
12725 		prev_id = prev->ptr->base.id;
12726 	}
12727 
12728 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
12729 		/* Skip planes with higher zpos than the previously returned */
12730 		if (new_plane_state->zpos > prev_zpos ||
12731 		    (new_plane_state->zpos == prev_zpos &&
12732 		     plane->base.id >= prev_id))
12733 			continue;
12734 
12735 		/* Save the index of the plane with highest zpos */
12736 		if (new_plane_state->zpos > highest_zpos ||
12737 		    (new_plane_state->zpos == highest_zpos &&
12738 		     plane->base.id > highest_id)) {
12739 			highest_zpos = new_plane_state->zpos;
12740 			highest_id = plane->base.id;
12741 			highest_i = i;
12742 		}
12743 	}
12744 
12745 	if (highest_i < 0)
12746 		return NULL;
12747 
12748 	return &state->planes[highest_i];
12749 }
12750 
12751 /*
12752  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
12753  * by descending zpos, as read from the new plane state. This is the same
12754  * ordering as defined by drm_atomic_normalize_zpos().
12755  */
12756 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
12757 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
12758 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
12759 		for_each_if(((plane) = __i->ptr,				\
12760 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
12761 			     (old_plane_state) = __i->old_state,		\
12762 			     (new_plane_state) = __i->new_state, 1))
12763 
12764 static int add_affected_mst_dsc_crtcs(struct drm_atomic_commit *state, struct drm_crtc *crtc)
12765 {
12766 	struct drm_connector *connector;
12767 	struct drm_connector_state *conn_state, *old_conn_state;
12768 	struct amdgpu_dm_connector *aconnector = NULL;
12769 	int i;
12770 
12771 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
12772 		if (!conn_state->crtc)
12773 			conn_state = old_conn_state;
12774 
12775 		if (conn_state->crtc != crtc)
12776 			continue;
12777 
12778 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
12779 			continue;
12780 
12781 		aconnector = to_amdgpu_dm_connector(connector);
12782 		if (!aconnector->mst_output_port || !aconnector->mst_root)
12783 			aconnector = NULL;
12784 		else
12785 			break;
12786 	}
12787 
12788 	if (!aconnector)
12789 		return 0;
12790 
12791 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
12792 }
12793 
12794 /**
12795  * DOC: Cursor Modes - Native vs Overlay
12796  *
12797  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
12798  * plane. It does not require a dedicated hw plane to enable, but it is
12799  * subjected to the same z-order and scaling as the hw plane. It also has format
12800  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
12801  * hw plane.
12802  *
12803  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
12804  * own scaling and z-pos. It also has no blending restrictions. It lends to a
12805  * cursor behavior more akin to a DRM client's expectations. However, it does
12806  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
12807  * available.
12808  */
12809 
12810 /**
12811  * dm_plane_color_pipeline_active() - Check if a plane's color pipeline active.
12812  * @state: DRM atomic state
12813  * @plane: DRM plane to check
12814  * @use_old: if true, inspect the old colorop states; otherwise the new ones
12815  *
12816  * A color pipeline may be selected (color_pipeline != NULL) but still is
12817  * inactive if every colorop in the chain is bypassed.  Only return
12818  * true when at least one colorop has bypass == false, meaning the cursor
12819  * would be subjected to the transformation in native mode.
12820  *
12821  * Return: true if the pipeline modifies pixels, false otherwise.
12822  */
12823 static bool dm_plane_color_pipeline_active(struct drm_atomic_commit *state,
12824 					   struct drm_plane *plane,
12825 					   bool use_old)
12826 {
12827 	struct drm_colorop *colorop;
12828 	struct drm_colorop_state *old_colorop_state, *new_colorop_state;
12829 	int i;
12830 
12831 	for_each_oldnew_colorop_in_state(state, colorop, old_colorop_state, new_colorop_state, i) {
12832 		struct drm_colorop_state *cstate = use_old ? old_colorop_state : new_colorop_state;
12833 
12834 		if (cstate->colorop->plane != plane)
12835 			continue;
12836 		if (!cstate->bypass)
12837 			return true;
12838 	}
12839 	return false;
12840 }
12841 
12842 /**
12843  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
12844  * @adev: amdgpu device
12845  * @state: DRM atomic state
12846  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
12847  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
12848  *
12849  * Get whether the cursor should be enabled in native mode, or overlay mode, on
12850  * the dm_crtc_state.
12851  *
12852  * The cursor should be enabled in overlay mode if there exists an underlying
12853  * plane - on which the cursor may be blended - that is either YUV formatted,
12854  * scaled differently from the cursor, or has a color pipeline active.
12855  *
12856  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
12857  * calling this function.
12858  *
12859  * Return: 0 on success, or an error code if getting the cursor plane state
12860  * failed.
12861  */
12862 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
12863 				   struct drm_atomic_commit *state,
12864 				   struct dm_crtc_state *dm_crtc_state,
12865 				   enum amdgpu_dm_cursor_mode *cursor_mode)
12866 {
12867 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
12868 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
12869 	struct drm_plane *plane;
12870 	bool consider_mode_change = false;
12871 	bool entire_crtc_covered = false;
12872 	bool cursor_changed = false;
12873 	int underlying_scale_w, underlying_scale_h;
12874 	int cursor_scale_w, cursor_scale_h;
12875 	int i;
12876 
12877 	/* Overlay cursor not supported on HW before DCN
12878 	 * DCN401/420 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
12879 	 * as previous DCN generations, so enable native mode on DCN401/420
12880 	 */
12881 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1) ||
12882 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
12883 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 1)) {
12884 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12885 		return 0;
12886 	}
12887 
12888 	/* Init cursor_mode to be the same as current */
12889 	*cursor_mode = dm_crtc_state->cursor_mode;
12890 
12891 	/*
12892 	 * Cursor mode can change if a plane's format changes, scale changes, is
12893 	 * enabled/disabled, z-order changes, or color management properties change.
12894 	 */
12895 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
12896 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
12897 
12898 		/* Only care about planes on this CRTC */
12899 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
12900 			continue;
12901 
12902 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
12903 			cursor_changed = true;
12904 
12905 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
12906 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
12907 		    old_plane_state->fb->format != plane_state->fb->format) {
12908 			consider_mode_change = true;
12909 			break;
12910 		}
12911 
12912 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
12913 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
12914 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
12915 			consider_mode_change = true;
12916 			break;
12917 		}
12918 
12919 		if (dm_plane_color_pipeline_active(state, plane, true) !=
12920 		    dm_plane_color_pipeline_active(state, plane, false)) {
12921 			consider_mode_change = true;
12922 			break;
12923 		}
12924 	}
12925 
12926 	if (!consider_mode_change && !crtc_state->zpos_changed)
12927 		return 0;
12928 
12929 	/*
12930 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
12931 	 * no need to set cursor mode. This avoids needlessly locking the cursor
12932 	 * state.
12933 	 */
12934 	if (!cursor_changed &&
12935 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
12936 		return 0;
12937 	}
12938 
12939 	cursor_state = drm_atomic_get_plane_state(state,
12940 						  crtc_state->crtc->cursor);
12941 	if (IS_ERR(cursor_state))
12942 		return PTR_ERR(cursor_state);
12943 
12944 	/* Cursor is disabled */
12945 	if (!cursor_state->fb)
12946 		return 0;
12947 
12948 	/* For all planes in descending z-order (all of which are below cursor
12949 	 * as per zpos definitions), check their scaling and format
12950 	 */
12951 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
12952 
12953 		/* Only care about non-cursor planes on this CRTC */
12954 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
12955 		    plane->type == DRM_PLANE_TYPE_CURSOR)
12956 			continue;
12957 
12958 		/* Underlying plane is YUV format - use overlay cursor */
12959 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
12960 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12961 			return 0;
12962 		}
12963 
12964 		/* Underlying plane has an active color pipeline - cursor would be transformed */
12965 		if (dm_plane_color_pipeline_active(state, plane, false)) {
12966 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12967 			return 0;
12968 		}
12969 
12970 		dm_get_plane_scale(plane_state,
12971 				   &underlying_scale_w, &underlying_scale_h);
12972 		dm_get_plane_scale(cursor_state,
12973 				   &cursor_scale_w, &cursor_scale_h);
12974 
12975 		/* Underlying plane has different scale - use overlay cursor */
12976 		if (cursor_scale_w != underlying_scale_w &&
12977 		    cursor_scale_h != underlying_scale_h) {
12978 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12979 			return 0;
12980 		}
12981 
12982 		/* If this plane covers the whole CRTC, no need to check planes underneath */
12983 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
12984 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
12985 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
12986 			entire_crtc_covered = true;
12987 			break;
12988 		}
12989 	}
12990 
12991 	/* If planes do not cover the entire CRTC, use overlay mode to enable
12992 	 * cursor over holes
12993 	 */
12994 	if (entire_crtc_covered)
12995 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12996 	else
12997 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12998 
12999 	return 0;
13000 }
13001 
13002 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
13003 					    struct drm_atomic_commit *state,
13004 					    struct drm_crtc_state *crtc_state)
13005 {
13006 	struct drm_plane *plane;
13007 	struct drm_plane_state *new_plane_state, *old_plane_state;
13008 
13009 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
13010 		new_plane_state = drm_atomic_get_new_plane_state(state, plane);
13011 		old_plane_state = drm_atomic_get_old_plane_state(state, plane);
13012 
13013 		if (!old_plane_state || !new_plane_state)
13014 			continue;
13015 
13016 		if (old_plane_state->fb && new_plane_state->fb &&
13017 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
13018 			return true;
13019 	}
13020 
13021 	return false;
13022 }
13023 
13024 /**
13025  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
13026  *
13027  * @dev: The DRM device
13028  * @state: The atomic state to commit
13029  *
13030  * Validate that the given atomic state is programmable by DC into hardware.
13031  * This involves constructing a &struct dc_state reflecting the new hardware
13032  * state we wish to commit, then querying DC to see if it is programmable. It's
13033  * important not to modify the existing DC state. Otherwise, atomic_check
13034  * may unexpectedly commit hardware changes.
13035  *
13036  * When validating the DC state, it's important that the right locks are
13037  * acquired. For full updates case which removes/adds/updates streams on one
13038  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
13039  * that any such full update commit will wait for completion of any outstanding
13040  * flip using DRMs synchronization events.
13041  *
13042  * Note that DM adds the affected connectors for all CRTCs in state, when that
13043  * might not seem necessary. This is because DC stream creation requires the
13044  * DC sink, which is tied to the DRM connector state. Cleaning this up should
13045  * be possible but non-trivial - a possible TODO item.
13046  *
13047  * Return: -Error code if validation failed.
13048  */
13049 static int amdgpu_dm_atomic_check(struct drm_device *dev,
13050 				  struct drm_atomic_commit *state)
13051 {
13052 	struct amdgpu_device *adev = drm_to_adev(dev);
13053 	struct dm_atomic_state *dm_state = NULL;
13054 	struct dc *dc = adev->dm.dc;
13055 	struct drm_connector *connector;
13056 	struct drm_connector_state *old_con_state, *new_con_state;
13057 	struct drm_crtc *crtc;
13058 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
13059 	struct drm_plane *plane;
13060 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
13061 	enum dc_status status;
13062 	int ret, i;
13063 	bool lock_and_validation_needed = false;
13064 	bool is_top_most_overlay = true;
13065 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
13066 	struct drm_dp_mst_topology_mgr *mgr;
13067 	struct drm_dp_mst_topology_state *mst_state;
13068 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
13069 
13070 	trace_amdgpu_dm_atomic_check_begin(state);
13071 
13072 	ret = drm_atomic_helper_check_modeset(dev, state);
13073 	if (ret) {
13074 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
13075 		goto fail;
13076 	}
13077 
13078 	/* Check connector changes */
13079 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
13080 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
13081 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
13082 
13083 		/* Skip connectors that are disabled or part of modeset already. */
13084 		if (!new_con_state->crtc)
13085 			continue;
13086 
13087 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
13088 		if (IS_ERR(new_crtc_state)) {
13089 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
13090 			ret = PTR_ERR(new_crtc_state);
13091 			goto fail;
13092 		}
13093 
13094 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
13095 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
13096 			new_crtc_state->connectors_changed = true;
13097 	}
13098 
13099 	if (dc_resource_is_dsc_encoding_supported(dc)) {
13100 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13101 			dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13102 			dm_new_crtc_state->mode_changed_independent_from_dsc = new_crtc_state->mode_changed;
13103 		}
13104 
13105 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13106 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
13107 				ret = add_affected_mst_dsc_crtcs(state, crtc);
13108 				if (ret) {
13109 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
13110 					goto fail;
13111 				}
13112 			}
13113 		}
13114 	}
13115 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13116 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
13117 
13118 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
13119 		    !new_crtc_state->color_mgmt_changed &&
13120 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
13121 			dm_old_crtc_state->dsc_force_changed == false)
13122 			continue;
13123 
13124 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
13125 		if (ret) {
13126 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
13127 			goto fail;
13128 		}
13129 
13130 		if (!new_crtc_state->enable)
13131 			continue;
13132 
13133 		ret = drm_atomic_add_affected_connectors(state, crtc);
13134 		if (ret) {
13135 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
13136 			goto fail;
13137 		}
13138 
13139 		ret = drm_atomic_add_affected_planes(state, crtc);
13140 		if (ret) {
13141 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
13142 			goto fail;
13143 		}
13144 
13145 		if (dm_old_crtc_state->dsc_force_changed)
13146 			new_crtc_state->mode_changed = true;
13147 	}
13148 
13149 	/*
13150 	 * Add all primary and overlay planes on the CRTC to the state
13151 	 * whenever a plane is enabled to maintain correct z-ordering
13152 	 * and to enable fast surface updates.
13153 	 */
13154 	drm_for_each_crtc(crtc, dev) {
13155 		bool modified = false;
13156 
13157 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
13158 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
13159 				continue;
13160 
13161 			if (new_plane_state->crtc == crtc ||
13162 			    old_plane_state->crtc == crtc) {
13163 				modified = true;
13164 				break;
13165 			}
13166 		}
13167 
13168 		if (!modified)
13169 			continue;
13170 
13171 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
13172 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
13173 				continue;
13174 
13175 			new_plane_state =
13176 				drm_atomic_get_plane_state(state, plane);
13177 
13178 			if (IS_ERR(new_plane_state)) {
13179 				ret = PTR_ERR(new_plane_state);
13180 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
13181 				goto fail;
13182 			}
13183 		}
13184 	}
13185 
13186 	/*
13187 	 * DC consults the zpos (layer_index in DC terminology) to determine the
13188 	 * hw plane on which to enable the hw cursor (see
13189 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
13190 	 * atomic state, so call drm helper to normalize zpos.
13191 	 */
13192 	ret = drm_atomic_normalize_zpos(dev, state);
13193 	if (ret) {
13194 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
13195 		goto fail;
13196 	}
13197 
13198 	/*
13199 	 * Determine whether cursors on each CRTC should be enabled in native or
13200 	 * overlay mode.
13201 	 */
13202 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13203 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13204 
13205 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
13206 					      &dm_new_crtc_state->cursor_mode);
13207 		if (ret) {
13208 			drm_dbg(dev, "Failed to determine cursor mode\n");
13209 			goto fail;
13210 		}
13211 
13212 		/*
13213 		 * If overlay cursor is needed, DC cannot go through the
13214 		 * native cursor update path. All enabled planes on the CRTC
13215 		 * need to be added for DC to not disable a plane by mistake
13216 		 */
13217 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
13218 			if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
13219 				drm_dbg(dev, "Overlay cursor not supported on DCE\n");
13220 				ret = -EINVAL;
13221 				goto fail;
13222 			}
13223 
13224 			ret = drm_atomic_add_affected_planes(state, crtc);
13225 			if (ret)
13226 				goto fail;
13227 		}
13228 	}
13229 
13230 	/* Remove exiting planes if they are modified */
13231 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13232 
13233 		ret = dm_update_plane_state(dc, state, plane,
13234 					    old_plane_state,
13235 					    new_plane_state,
13236 					    false,
13237 					    &lock_and_validation_needed,
13238 					    &is_top_most_overlay);
13239 		if (ret) {
13240 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13241 			goto fail;
13242 		}
13243 	}
13244 
13245 	/* Disable all crtcs which require disable */
13246 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13247 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
13248 					   old_crtc_state,
13249 					   new_crtc_state,
13250 					   false,
13251 					   &lock_and_validation_needed);
13252 		if (ret) {
13253 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
13254 			goto fail;
13255 		}
13256 	}
13257 
13258 	/* Enable all crtcs which require enable */
13259 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13260 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
13261 					   old_crtc_state,
13262 					   new_crtc_state,
13263 					   true,
13264 					   &lock_and_validation_needed);
13265 		if (ret) {
13266 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
13267 			goto fail;
13268 		}
13269 	}
13270 
13271 	/* Add new/modified planes */
13272 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13273 		ret = dm_update_plane_state(dc, state, plane,
13274 					    old_plane_state,
13275 					    new_plane_state,
13276 					    true,
13277 					    &lock_and_validation_needed,
13278 					    &is_top_most_overlay);
13279 		if (ret) {
13280 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13281 			goto fail;
13282 		}
13283 	}
13284 
13285 #if defined(CONFIG_DRM_AMD_DC_FP)
13286 	if (dc_resource_is_dsc_encoding_supported(dc)) {
13287 		ret = pre_validate_dsc(state, &dm_state, vars);
13288 		if (ret != 0)
13289 			goto fail;
13290 	}
13291 #endif
13292 
13293 	/* Run this here since we want to validate the streams we created */
13294 	ret = drm_atomic_helper_check_planes(dev, state);
13295 	if (ret) {
13296 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
13297 		goto fail;
13298 	}
13299 
13300 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13301 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13302 		if (dm_new_crtc_state->mpo_requested)
13303 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
13304 	}
13305 
13306 	/* Check cursor restrictions */
13307 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13308 		enum amdgpu_dm_cursor_mode required_cursor_mode;
13309 		int is_rotated, is_scaled;
13310 
13311 		/* Overlay cusor not subject to native cursor restrictions */
13312 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13313 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
13314 			continue;
13315 
13316 		/* Check if rotation or scaling is enabled on DCN401 */
13317 		if ((drm_plane_mask(crtc->cursor) &
13318 		     new_crtc_state->plane_mask) &&
13319 		    (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 1) ||
13320 		     amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
13321 		     amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1))) {
13322 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
13323 
13324 			is_rotated = new_cursor_state &&
13325 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
13326 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
13327 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
13328 
13329 			if (is_rotated || is_scaled) {
13330 				drm_dbg_driver(
13331 					crtc->dev,
13332 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
13333 					crtc->base.id, crtc->name);
13334 				ret = -EINVAL;
13335 				goto fail;
13336 			}
13337 		}
13338 
13339 		/* If HW can only do native cursor, check restrictions again */
13340 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
13341 					      &required_cursor_mode);
13342 		if (ret) {
13343 			drm_dbg_driver(crtc->dev,
13344 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
13345 				       crtc->base.id, crtc->name);
13346 			goto fail;
13347 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
13348 			drm_dbg_driver(crtc->dev,
13349 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling, YUV, or color pipeline restrictions\n",
13350 				       crtc->base.id, crtc->name);
13351 			ret = -EINVAL;
13352 			goto fail;
13353 		}
13354 	}
13355 
13356 	if (state->legacy_cursor_update) {
13357 		/*
13358 		 * This is a fast cursor update coming from the plane update
13359 		 * helper, check if it can be done asynchronously for better
13360 		 * performance.
13361 		 */
13362 		state->async_update =
13363 			!drm_atomic_helper_async_check(dev, state);
13364 
13365 		/*
13366 		 * Skip the remaining global validation if this is an async
13367 		 * update. Cursor updates can be done without affecting
13368 		 * state or bandwidth calcs and this avoids the performance
13369 		 * penalty of locking the private state object and
13370 		 * allocating a new dc_state.
13371 		 */
13372 		if (state->async_update)
13373 			return 0;
13374 	}
13375 
13376 	/* Check scaling and underscan changes*/
13377 	/* TODO Removed scaling changes validation due to inability to commit
13378 	 * new stream into context w\o causing full reset. Need to
13379 	 * decide how to handle.
13380 	 */
13381 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
13382 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
13383 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
13384 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
13385 
13386 		/* Skip any modesets/resets */
13387 		if (!acrtc || drm_atomic_crtc_needs_modeset(
13388 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
13389 			continue;
13390 
13391 		/* Skip any thing not scale or underscan changes */
13392 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
13393 			continue;
13394 
13395 		lock_and_validation_needed = true;
13396 	}
13397 
13398 	/* set the slot info for each mst_state based on the link encoding format */
13399 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
13400 		struct amdgpu_dm_connector *aconnector;
13401 		struct drm_connector *connector;
13402 		struct drm_connector_list_iter iter;
13403 		u8 link_coding_cap;
13404 
13405 		drm_connector_list_iter_begin(dev, &iter);
13406 		drm_for_each_connector_iter(connector, &iter) {
13407 			if (connector->index == mst_state->mgr->conn_base_id) {
13408 				aconnector = to_amdgpu_dm_connector(connector);
13409 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
13410 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
13411 
13412 				break;
13413 			}
13414 		}
13415 		drm_connector_list_iter_end(&iter);
13416 	}
13417 
13418 	/**
13419 	 * Streams and planes are reset when there are changes that affect
13420 	 * bandwidth. Anything that affects bandwidth needs to go through
13421 	 * DC global validation to ensure that the configuration can be applied
13422 	 * to hardware.
13423 	 *
13424 	 * We have to currently stall out here in atomic_check for outstanding
13425 	 * commits to finish in this case because our IRQ handlers reference
13426 	 * DRM state directly - we can end up disabling interrupts too early
13427 	 * if we don't.
13428 	 *
13429 	 * TODO: Remove this stall and drop DM state private objects.
13430 	 */
13431 	if (lock_and_validation_needed) {
13432 		ret = dm_atomic_get_state(state, &dm_state);
13433 		if (ret) {
13434 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
13435 			goto fail;
13436 		}
13437 
13438 		ret = do_aquire_global_lock(dev, state);
13439 		if (ret) {
13440 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
13441 			goto fail;
13442 		}
13443 
13444 #if defined(CONFIG_DRM_AMD_DC_FP)
13445 		if (dc_resource_is_dsc_encoding_supported(dc)) {
13446 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
13447 			if (ret) {
13448 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
13449 				ret = -EINVAL;
13450 				goto fail;
13451 			}
13452 		}
13453 #endif
13454 
13455 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
13456 		if (ret) {
13457 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
13458 			goto fail;
13459 		}
13460 
13461 		/*
13462 		 * Perform validation of MST topology in the state:
13463 		 * We need to perform MST atomic check before calling
13464 		 * dc_validate_global_state(), or there is a chance
13465 		 * to get stuck in an infinite loop and hang eventually.
13466 		 */
13467 		ret = drm_dp_mst_atomic_check(state);
13468 		if (ret) {
13469 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
13470 			goto fail;
13471 		}
13472 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
13473 		if (status != DC_OK) {
13474 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
13475 				       dc_status_to_str(status), status);
13476 			ret = -EINVAL;
13477 			goto fail;
13478 		}
13479 	} else {
13480 		/*
13481 		 * The commit is a fast update. Fast updates shouldn't change
13482 		 * the DC context, affect global validation, and can have their
13483 		 * commit work done in parallel with other commits not touching
13484 		 * the same resource. If we have a new DC context as part of
13485 		 * the DM atomic state from validation we need to free it and
13486 		 * retain the existing one instead.
13487 		 *
13488 		 * Furthermore, since the DM atomic state only contains the DC
13489 		 * context and can safely be annulled, we can free the state
13490 		 * and clear the associated private object now to free
13491 		 * some memory and avoid a possible use-after-free later.
13492 		 */
13493 
13494 		for (i = 0; i < state->num_private_objs; i++) {
13495 			struct drm_private_obj *obj = state->private_objs[i].ptr;
13496 
13497 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
13498 				int j = state->num_private_objs-1;
13499 
13500 				dm_atomic_destroy_state(obj,
13501 						state->private_objs[i].state_to_destroy);
13502 
13503 				/* If i is not at the end of the array then the
13504 				 * last element needs to be moved to where i was
13505 				 * before the array can safely be truncated.
13506 				 */
13507 				if (i != j)
13508 					state->private_objs[i] =
13509 						state->private_objs[j];
13510 
13511 				state->private_objs[j].ptr = NULL;
13512 				state->private_objs[j].state_to_destroy = NULL;
13513 				state->private_objs[j].old_state = NULL;
13514 				state->private_objs[j].new_state = NULL;
13515 
13516 				state->num_private_objs = j;
13517 				break;
13518 			}
13519 		}
13520 	}
13521 
13522 	/* Store the overall update type for use later in atomic check. */
13523 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13524 		struct dm_crtc_state *dm_new_crtc_state =
13525 			to_dm_crtc_state(new_crtc_state);
13526 
13527 		/*
13528 		 * Only allow async flips for fast updates that don't change
13529 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
13530 		 */
13531 		if (new_crtc_state->async_flip &&
13532 		    (lock_and_validation_needed ||
13533 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
13534 			drm_dbg_atomic(crtc->dev,
13535 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
13536 				       crtc->base.id, crtc->name);
13537 			ret = -EINVAL;
13538 			goto fail;
13539 		}
13540 
13541 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
13542 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
13543 	}
13544 
13545 	/* Must be success */
13546 	WARN_ON(ret);
13547 
13548 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13549 
13550 	return ret;
13551 
13552 fail:
13553 	if (ret == -EDEADLK)
13554 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
13555 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
13556 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
13557 	else
13558 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
13559 
13560 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13561 
13562 	return ret;
13563 }
13564 
13565 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
13566 		unsigned int offset,
13567 		unsigned int total_length,
13568 		u8 *data,
13569 		unsigned int length,
13570 		struct amdgpu_hdmi_vsdb_info *vsdb)
13571 {
13572 	bool res;
13573 	union dmub_rb_cmd cmd;
13574 	struct dmub_cmd_send_edid_cea *input;
13575 	struct dmub_cmd_edid_cea_output *output;
13576 
13577 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
13578 		return false;
13579 
13580 	memset(&cmd, 0, sizeof(cmd));
13581 
13582 	input = &cmd.edid_cea.data.input;
13583 
13584 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
13585 	cmd.edid_cea.header.sub_type = 0;
13586 	cmd.edid_cea.header.payload_bytes =
13587 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
13588 	input->offset = offset;
13589 	input->length = length;
13590 	input->cea_total_length = total_length;
13591 	memcpy(input->payload, data, length);
13592 
13593 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
13594 	if (!res) {
13595 		drm_err(adev_to_drm(dm->adev), "EDID CEA parser failed\n");
13596 		return false;
13597 	}
13598 
13599 	output = &cmd.edid_cea.data.output;
13600 
13601 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
13602 		if (!output->ack.success) {
13603 			drm_err(adev_to_drm(dm->adev), "EDID CEA ack failed at offset %d\n",
13604 					output->ack.offset);
13605 		}
13606 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
13607 		if (!output->amd_vsdb.vsdb_found)
13608 			return false;
13609 
13610 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
13611 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
13612 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
13613 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
13614 		vsdb->freesync_mccs_vcp_code = output->amd_vsdb.freesync_mccs_vcp_code;
13615 	} else {
13616 		drm_warn(adev_to_drm(dm->adev), "Unknown EDID CEA parser results\n");
13617 		return false;
13618 	}
13619 
13620 	return true;
13621 }
13622 
13623 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
13624 		u8 *edid_ext, int len,
13625 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13626 {
13627 	int i;
13628 
13629 	/* send extension block to DMCU for parsing */
13630 	for (i = 0; i < len; i += 8) {
13631 		bool res;
13632 		int offset;
13633 
13634 		/* send 8 bytes a time */
13635 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
13636 			return false;
13637 
13638 		if (i+8 == len) {
13639 			/* EDID block sent completed, expect result */
13640 			int version, min_rate, max_rate;
13641 
13642 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
13643 			if (res) {
13644 				/* amd vsdb found */
13645 				vsdb_info->freesync_supported = 1;
13646 				vsdb_info->amd_vsdb_version = version;
13647 				vsdb_info->min_refresh_rate_hz = min_rate;
13648 				vsdb_info->max_refresh_rate_hz = max_rate;
13649 				/* Not enabled on DMCU*/
13650 				vsdb_info->freesync_mccs_vcp_code = 0;
13651 				return true;
13652 			}
13653 			/* not amd vsdb */
13654 			return false;
13655 		}
13656 
13657 		/* check for ack*/
13658 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
13659 		if (!res)
13660 			return false;
13661 	}
13662 
13663 	return false;
13664 }
13665 
13666 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
13667 		u8 *edid_ext, int len,
13668 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13669 {
13670 	int i;
13671 
13672 	/* send extension block to DMCU for parsing */
13673 	for (i = 0; i < len; i += 8) {
13674 		/* send 8 bytes a time */
13675 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
13676 			return false;
13677 	}
13678 
13679 	return vsdb_info->freesync_supported;
13680 }
13681 
13682 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
13683 		u8 *edid_ext, int len,
13684 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13685 {
13686 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
13687 	bool ret;
13688 
13689 	mutex_lock(&adev->dm.dc_lock);
13690 	if (adev->dm.dmub_srv)
13691 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
13692 	else
13693 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
13694 	mutex_unlock(&adev->dm.dc_lock);
13695 	return ret;
13696 }
13697 
13698 static void parse_edid_displayid_vrr(struct drm_connector *connector,
13699 				     const struct edid *edid)
13700 {
13701 	u8 *edid_ext = NULL;
13702 	int i;
13703 	int j = 0;
13704 	u16 min_vfreq;
13705 	u16 max_vfreq;
13706 
13707 	if (!edid || !edid->extensions)
13708 		return;
13709 
13710 	/* Find DisplayID extension */
13711 	for (i = 0; i < edid->extensions; i++) {
13712 		edid_ext = (void *)(edid + (i + 1));
13713 		if (edid_ext[0] == DISPLAYID_EXT)
13714 			break;
13715 	}
13716 
13717 	if (i == edid->extensions)
13718 		return;
13719 
13720 	while (j < EDID_LENGTH) {
13721 		/* Get dynamic video timing range from DisplayID if available */
13722 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
13723 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
13724 			min_vfreq = edid_ext[j+9];
13725 			if (edid_ext[j+1] & 7)
13726 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
13727 			else
13728 				max_vfreq = edid_ext[j+10];
13729 
13730 			if (max_vfreq && min_vfreq) {
13731 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
13732 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
13733 
13734 				return;
13735 			}
13736 		}
13737 		j++;
13738 	}
13739 }
13740 
13741 static int get_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13742 			struct amdgpu_hdmi_vsdb_info *vsdb_info)
13743 {
13744 	struct drm_connector *connector = &aconnector->base;
13745 
13746 	vsdb_info->replay_mode = connector->display_info.amd_vsdb.replay_mode;
13747 	vsdb_info->amd_vsdb_version = connector->display_info.amd_vsdb.version;
13748 
13749 	return connector->display_info.amd_vsdb.version != 0;
13750 }
13751 
13752 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13753 			       const struct edid *edid,
13754 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
13755 {
13756 	u8 *edid_ext = NULL;
13757 	int i;
13758 	bool valid_vsdb_found = false;
13759 
13760 	/*----- drm_find_cea_extension() -----*/
13761 	/* No EDID or EDID extensions */
13762 	if (edid == NULL || edid->extensions == 0)
13763 		return -ENODEV;
13764 
13765 	/* Find CEA extension */
13766 	for (i = 0; i < edid->extensions; i++) {
13767 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
13768 		if (edid_ext[0] == CEA_EXT)
13769 			break;
13770 	}
13771 
13772 	if (i == edid->extensions)
13773 		return -ENODEV;
13774 
13775 	/*----- cea_db_offsets() -----*/
13776 	if (edid_ext[0] != CEA_EXT)
13777 		return -ENODEV;
13778 
13779 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
13780 
13781 	return valid_vsdb_found ? i : -ENODEV;
13782 }
13783 
13784 /**
13785  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
13786  *
13787  * @connector: Connector to query.
13788  * @drm_edid: DRM EDID from monitor
13789  * @do_mccs: Controls whether MCCS (Monitor Control Command Set) over
13790  *	      DDC (Display Data Channel) transactions are performed. When true,
13791  *	      the driver queries the monitor to get or update additional FreeSync
13792  *	      capability information. When false, these transactions are skipped.
13793  *
13794  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
13795  * track of some of the display information in the internal data struct used by
13796  * amdgpu_dm. This function checks which type of connector we need to set the
13797  * FreeSync parameters.
13798  */
13799 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
13800 				    const struct drm_edid *drm_edid, bool do_mccs)
13801 {
13802 	int i = 0;
13803 	struct amdgpu_dm_connector *amdgpu_dm_connector =
13804 			to_amdgpu_dm_connector(connector);
13805 	struct dm_connector_state *dm_con_state = NULL;
13806 	struct dc_sink *sink;
13807 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
13808 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
13809 	const struct edid *edid;
13810 	bool freesync_capable = false;
13811 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
13812 
13813 	if (!connector->state) {
13814 		drm_err(adev_to_drm(adev), "%s - Connector has no state", __func__);
13815 		goto update;
13816 	}
13817 
13818 	sink = amdgpu_dm_connector->dc_sink ?
13819 		amdgpu_dm_connector->dc_sink :
13820 		amdgpu_dm_connector->dc_em_sink;
13821 
13822 	drm_edid_connector_update(connector, drm_edid);
13823 
13824 	if (!drm_edid || !sink) {
13825 		dm_con_state = to_dm_connector_state(connector->state);
13826 
13827 		amdgpu_dm_connector->min_vfreq = 0;
13828 		amdgpu_dm_connector->max_vfreq = 0;
13829 		freesync_capable = false;
13830 
13831 		goto update;
13832 	}
13833 
13834 	dm_con_state = to_dm_connector_state(connector->state);
13835 
13836 	if (!adev->dm.freesync_module || !dc_supports_vrr(sink->ctx->dce_version))
13837 		goto update;
13838 
13839 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
13840 
13841 	/* Some eDP panels only have the refresh rate range info in DisplayID */
13842 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
13843 	     connector->display_info.monitor_range.max_vfreq == 0))
13844 		parse_edid_displayid_vrr(connector, edid);
13845 
13846 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
13847 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
13848 		if (amdgpu_dm_connector->dc_link &&
13849 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
13850 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
13851 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
13852 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13853 				freesync_capable = true;
13854 		}
13855 
13856 		get_amd_vsdb(amdgpu_dm_connector, &vsdb_info);
13857 
13858 		if (vsdb_info.replay_mode) {
13859 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
13860 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
13861 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
13862 		}
13863 
13864 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
13865 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13866 		if (i >= 0) {
13867 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13868 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13869 
13870 			if (vsdb_info.freesync_supported) {
13871 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13872 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13873 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13874 					freesync_capable = true;
13875 
13876 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13877 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13878 			}
13879 		}
13880 	}
13881 
13882 	if (amdgpu_dm_connector->dc_link)
13883 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
13884 
13885 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
13886 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13887 		if (i >= 0) {
13888 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13889 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13890 
13891 			if (vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
13892 				amdgpu_dm_connector->pack_sdp_v1_3 = true;
13893 				amdgpu_dm_connector->as_type = as_type;
13894 
13895 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13896 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13897 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13898 					freesync_capable = true;
13899 
13900 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13901 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13902 			}
13903 		}
13904 	}
13905 
13906 	/* Handle MCCS */
13907 	if (do_mccs) {
13908 		dm_helpers_read_mccs_caps(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13909 
13910 		if (sink->edid_caps.freesync_vcp_code && !sink->mccs_caps.freesync_supported)
13911 			freesync_capable = false;
13912 
13913 		if (sink->mccs_caps.freesync_supported && freesync_capable)
13914 			dm_helpers_mccs_vcp_set(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13915 	}
13916 
13917 update:
13918 	if (dm_con_state)
13919 		dm_con_state->freesync_capable = freesync_capable;
13920 
13921 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
13922 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
13923 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
13924 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
13925 	}
13926 
13927 	if (connector->vrr_capable_property)
13928 		drm_connector_set_vrr_capable_property(connector,
13929 						       freesync_capable);
13930 }
13931 
13932 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
13933 {
13934 	struct amdgpu_device *adev = drm_to_adev(dev);
13935 	struct dc *dc = adev->dm.dc;
13936 	int i;
13937 
13938 	mutex_lock(&adev->dm.dc_lock);
13939 	if (dc->current_state) {
13940 		for (i = 0; i < dc->current_state->stream_count; ++i)
13941 			dc->current_state->streams[i]
13942 				->triggered_crtc_reset.enabled =
13943 				adev->dm.force_timing_sync;
13944 
13945 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
13946 		dc_trigger_sync(dc, dc->current_state);
13947 	}
13948 	mutex_unlock(&adev->dm.dc_lock);
13949 }
13950 
13951 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
13952 {
13953 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
13954 		dc_exit_ips_for_hw_access(dc);
13955 }
13956 
13957 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
13958 		       u32 value, const char *func_name)
13959 {
13960 #ifdef DM_CHECK_ADDR_0
13961 	if (address == 0) {
13962 		drm_err(adev_to_drm(ctx->driver_context),
13963 			"invalid register write. address = 0");
13964 		return;
13965 	}
13966 #endif
13967 
13968 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13969 	cgs_write_register(ctx->cgs_device, address, value);
13970 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
13971 }
13972 
13973 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
13974 			  const char *func_name)
13975 {
13976 	u32 value;
13977 #ifdef DM_CHECK_ADDR_0
13978 	if (address == 0) {
13979 		drm_err(adev_to_drm(ctx->driver_context),
13980 			"invalid register read; address = 0\n");
13981 		return 0;
13982 	}
13983 #endif
13984 
13985 	if (ctx->dmub_srv &&
13986 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
13987 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
13988 		ASSERT(false);
13989 		return 0;
13990 	}
13991 
13992 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13993 
13994 	value = cgs_read_register(ctx->cgs_device, address);
13995 
13996 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
13997 
13998 	return value;
13999 }
14000 
14001 int amdgpu_dm_process_dmub_aux_transfer_sync(
14002 		struct dc_context *ctx,
14003 		unsigned int link_index,
14004 		struct aux_payload *payload,
14005 		enum aux_return_code_type *operation_result)
14006 {
14007 	struct amdgpu_device *adev = ctx->driver_context;
14008 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
14009 	int ret = -1;
14010 
14011 	mutex_lock(&adev->dm.dpia_aux_lock);
14012 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
14013 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
14014 		goto out;
14015 	}
14016 
14017 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
14018 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
14019 		*operation_result = AUX_RET_ERROR_TIMEOUT;
14020 		goto out;
14021 	}
14022 
14023 	if (p_notify->result != AUX_RET_SUCCESS) {
14024 		/*
14025 		 * Transient states before tunneling is enabled could
14026 		 * lead to this error. We can ignore this for now.
14027 		 */
14028 		if (p_notify->result == AUX_RET_ERROR_PROTOCOL_ERROR) {
14029 			drm_warn(adev_to_drm(adev), "DPIA AUX failed on 0x%x(%d), error %d\n",
14030 					payload->address, payload->length,
14031 					p_notify->result);
14032 		}
14033 		*operation_result = p_notify->result;
14034 		goto out;
14035 	}
14036 
14037 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command & 0xF;
14038 	if (adev->dm.dmub_notify->aux_reply.command & 0xF0)
14039 		/* The reply is stored in the top nibble of the command. */
14040 		payload->reply[0] = (adev->dm.dmub_notify->aux_reply.command >> 4) & 0xF;
14041 
14042 	/*write req may receive a byte indicating partially written number as well*/
14043 	if (p_notify->aux_reply.length)
14044 		memcpy(payload->data, p_notify->aux_reply.data,
14045 				p_notify->aux_reply.length);
14046 
14047 	/* success */
14048 	ret = p_notify->aux_reply.length;
14049 	*operation_result = p_notify->result;
14050 out:
14051 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
14052 	mutex_unlock(&adev->dm.dpia_aux_lock);
14053 	return ret;
14054 }
14055 
14056 static void abort_fused_io(
14057 		struct dc_context *ctx,
14058 		const struct dmub_cmd_fused_request *request
14059 )
14060 {
14061 	union dmub_rb_cmd command = { 0 };
14062 	struct dmub_rb_cmd_fused_io *io = &command.fused_io;
14063 
14064 	io->header.type = DMUB_CMD__FUSED_IO;
14065 	io->header.sub_type = DMUB_CMD__FUSED_IO_ABORT;
14066 	io->header.payload_bytes = sizeof(*io) - sizeof(io->header);
14067 	io->request = *request;
14068 	dm_execute_dmub_cmd(ctx, &command, DM_DMUB_WAIT_TYPE_NO_WAIT);
14069 }
14070 
14071 static bool execute_fused_io(
14072 		struct amdgpu_device *dev,
14073 		struct dc_context *ctx,
14074 		union dmub_rb_cmd *commands,
14075 		uint8_t count,
14076 		uint32_t timeout_us
14077 )
14078 {
14079 	const uint8_t ddc_line = commands[0].fused_io.request.u.aux.ddc_line;
14080 
14081 	if (ddc_line >= ARRAY_SIZE(dev->dm.fused_io))
14082 		return false;
14083 
14084 	struct fused_io_sync *sync = &dev->dm.fused_io[ddc_line];
14085 	struct dmub_rb_cmd_fused_io *first = &commands[0].fused_io;
14086 	const bool result = dm_execute_dmub_cmd_list(ctx, count, commands, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY)
14087 			&& first->header.ret_status
14088 			&& first->request.status == FUSED_REQUEST_STATUS_SUCCESS;
14089 
14090 	if (!result)
14091 		return false;
14092 
14093 	while (wait_for_completion_timeout(&sync->replied, usecs_to_jiffies(timeout_us))) {
14094 		reinit_completion(&sync->replied);
14095 
14096 		struct dmub_cmd_fused_request *reply = (struct dmub_cmd_fused_request *) sync->reply_data;
14097 
14098 		static_assert(sizeof(*reply) <= sizeof(sync->reply_data), "Size mismatch");
14099 
14100 		if (reply->identifier == first->request.identifier) {
14101 			first->request = *reply;
14102 			return true;
14103 		}
14104 	}
14105 
14106 	reinit_completion(&sync->replied);
14107 	first->request.status = FUSED_REQUEST_STATUS_TIMEOUT;
14108 	abort_fused_io(ctx, &first->request);
14109 	return false;
14110 }
14111 
14112 bool amdgpu_dm_execute_fused_io(
14113 		struct amdgpu_device *dev,
14114 		struct dc_link *link,
14115 		union dmub_rb_cmd *commands,
14116 		uint8_t count,
14117 		uint32_t timeout_us)
14118 {
14119 	struct amdgpu_display_manager *dm = &dev->dm;
14120 
14121 	mutex_lock(&dm->dpia_aux_lock);
14122 
14123 	const bool result = execute_fused_io(dev, link->ctx, commands, count, timeout_us);
14124 
14125 	mutex_unlock(&dm->dpia_aux_lock);
14126 	return result;
14127 }
14128 
14129 int amdgpu_dm_process_dmub_set_config_sync(
14130 		struct dc_context *ctx,
14131 		unsigned int link_index,
14132 		struct set_config_cmd_payload *payload,
14133 		enum set_config_status *operation_result)
14134 {
14135 	struct amdgpu_device *adev = ctx->driver_context;
14136 	bool is_cmd_complete;
14137 	int ret;
14138 
14139 	mutex_lock(&adev->dm.dpia_aux_lock);
14140 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
14141 			link_index, payload, adev->dm.dmub_notify);
14142 
14143 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
14144 		ret = 0;
14145 		*operation_result = adev->dm.dmub_notify->sc_status;
14146 	} else {
14147 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
14148 		ret = -1;
14149 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
14150 	}
14151 
14152 	if (!is_cmd_complete)
14153 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
14154 	mutex_unlock(&adev->dm.dpia_aux_lock);
14155 	return ret;
14156 }
14157 
14158 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
14159 {
14160 	struct amdgpu_device *adev = ctx->driver_context;
14161 
14162 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
14163 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
14164 }
14165 
14166 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)
14167 {
14168 	struct amdgpu_device *adev = ctx->driver_context;
14169 
14170 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
14171 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
14172 }
14173 
14174 void dm_acpi_process_phy_transition_interlock(
14175 	const struct dc_context *ctx,
14176 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
14177 {
14178 	// Not yet implemented
14179 }
14180