xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision c2572d535be4847f8caba58b4ee8446b4ee15b57)
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 /**
162  * DOC: overview
163  *
164  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
165  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
166  * requests into DC requests, and DC responses into DRM responses.
167  *
168  * The root control structure is &struct amdgpu_display_manager.
169  */
170 
171 /* basic init/fini API */
172 static int amdgpu_dm_init(struct amdgpu_device *adev);
173 static void amdgpu_dm_fini(struct amdgpu_device *adev);
174 static bool is_freesync_video_mode(const struct drm_display_mode *mode, struct amdgpu_dm_connector *aconnector);
175 static void reset_freesync_config_for_crtc(struct dm_crtc_state *new_crtc_state);
176 static struct amdgpu_i2c_adapter *
177 create_i2c(struct ddc_service *ddc_service, bool oem);
178 
179 static enum drm_mode_subconnector get_subconnector_type(struct dc_link *link)
180 {
181 	switch (link->dpcd_caps.dongle_type) {
182 	case DISPLAY_DONGLE_NONE:
183 		return DRM_MODE_SUBCONNECTOR_Native;
184 	case DISPLAY_DONGLE_DP_VGA_CONVERTER:
185 		return DRM_MODE_SUBCONNECTOR_VGA;
186 	case DISPLAY_DONGLE_DP_DVI_CONVERTER:
187 	case DISPLAY_DONGLE_DP_DVI_DONGLE:
188 		return DRM_MODE_SUBCONNECTOR_DVID;
189 	case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
190 	case DISPLAY_DONGLE_DP_HDMI_DONGLE:
191 		return DRM_MODE_SUBCONNECTOR_HDMIA;
192 	case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
193 	default:
194 		return DRM_MODE_SUBCONNECTOR_Unknown;
195 	}
196 }
197 
198 static void update_subconnector_property(struct amdgpu_dm_connector *aconnector)
199 {
200 	struct dc_link *link = aconnector->dc_link;
201 	struct drm_connector *connector = &aconnector->base;
202 	enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
203 
204 	if (connector->connector_type != DRM_MODE_CONNECTOR_DisplayPort)
205 		return;
206 
207 	if (aconnector->dc_sink)
208 		subconnector = get_subconnector_type(link);
209 
210 	drm_object_property_set_value(&connector->base,
211 			connector->dev->mode_config.dp_subconnector_property,
212 			subconnector);
213 }
214 
215 /*
216  * initializes drm_device display related structures, based on the information
217  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
218  * drm_encoder, drm_mode_config
219  *
220  * Returns 0 on success
221  */
222 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
223 /* removes and deallocates the drm structures, created by the above function */
224 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
225 
226 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
227 				    struct amdgpu_dm_connector *amdgpu_dm_connector,
228 				    u32 link_index,
229 				    struct amdgpu_encoder *amdgpu_encoder);
230 static int amdgpu_dm_encoder_init(struct drm_device *dev,
231 				  struct amdgpu_encoder *aencoder,
232 				  uint32_t link_index);
233 
234 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
235 
236 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state);
237 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state);
238 
239 static int amdgpu_dm_atomic_check(struct drm_device *dev,
240 				  struct drm_atomic_commit *state);
241 
242 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector);
243 static void handle_hpd_rx_irq(void *param);
244 
245 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
246 					 int bl_idx,
247 					 u32 user_brightness);
248 
249 static bool
250 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
251 				 struct drm_crtc_state *new_crtc_state);
252 /*
253  * dm_vblank_get_counter
254  *
255  * @brief
256  * Get counter for number of vertical blanks
257  *
258  * @param
259  * struct amdgpu_device *adev - [in] desired amdgpu device
260  * int disp_idx - [in] which CRTC to get the counter from
261  *
262  * @return
263  * Counter for vertical blanks
264  */
265 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
266 {
267 	struct amdgpu_crtc *acrtc = NULL;
268 
269 	if (crtc >= adev->mode_info.num_crtc)
270 		return 0;
271 
272 	acrtc = adev->mode_info.crtcs[crtc];
273 
274 	if (!acrtc->dm_irq_params.stream) {
275 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
276 			  crtc);
277 		return 0;
278 	}
279 
280 	return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
281 }
282 
283 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
284 				  u32 *vbl, u32 *position)
285 {
286 	u32 v_blank_start = 0, v_blank_end = 0, h_position = 0, v_position = 0;
287 	struct amdgpu_crtc *acrtc = NULL;
288 	struct dc *dc = adev->dm.dc;
289 
290 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
291 		return -EINVAL;
292 
293 	acrtc = adev->mode_info.crtcs[crtc];
294 
295 	if (!acrtc->dm_irq_params.stream) {
296 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
297 			  crtc);
298 		return 0;
299 	}
300 
301 	if (dc && dc->caps.ips_support && dc->idle_optimizations_allowed)
302 		dc_allow_idle_optimizations(dc, false);
303 
304 	/*
305 	 * TODO rework base driver to use values directly.
306 	 * for now parse it back into reg-format
307 	 */
308 	dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
309 				 &v_blank_start,
310 				 &v_blank_end,
311 				 &h_position,
312 				 &v_position);
313 
314 	*position = v_position | (h_position << 16);
315 	*vbl = v_blank_start | (v_blank_end << 16);
316 
317 	return 0;
318 }
319 
320 static bool dm_is_idle(struct amdgpu_ip_block *ip_block)
321 {
322 	/* XXX todo */
323 	return true;
324 }
325 
326 static int dm_wait_for_idle(struct amdgpu_ip_block *ip_block)
327 {
328 	/* XXX todo */
329 	return 0;
330 }
331 
332 static bool dm_check_soft_reset(struct amdgpu_ip_block *ip_block)
333 {
334 	return false;
335 }
336 
337 static int dm_soft_reset(struct amdgpu_ip_block *ip_block)
338 {
339 	/* XXX todo */
340 	return 0;
341 }
342 
343 static struct amdgpu_crtc *
344 get_crtc_by_otg_inst(struct amdgpu_device *adev,
345 		     int otg_inst)
346 {
347 	struct drm_device *dev = adev_to_drm(adev);
348 	struct drm_crtc *crtc;
349 	struct amdgpu_crtc *amdgpu_crtc;
350 
351 	if (WARN_ON(otg_inst == -1))
352 		return adev->mode_info.crtcs[0];
353 
354 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
355 		amdgpu_crtc = to_amdgpu_crtc(crtc);
356 
357 		if (amdgpu_crtc->otg_inst == otg_inst)
358 			return amdgpu_crtc;
359 	}
360 
361 	return NULL;
362 }
363 
364 static inline bool is_dc_timing_adjust_needed(struct dm_crtc_state *old_state,
365 					      struct dm_crtc_state *new_state)
366 {
367 	if (new_state->stream->adjust.timing_adjust_pending)
368 		return true;
369 	if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
370 		return true;
371 	else if (amdgpu_dm_crtc_vrr_active(old_state) != amdgpu_dm_crtc_vrr_active(new_state))
372 		return true;
373 	else
374 		return false;
375 }
376 
377 /*
378  * DC will program planes with their z-order determined by their ordering
379  * in the dc_surface_updates array. This comparator is used to sort them
380  * by descending zpos.
381  */
382 static int dm_plane_layer_index_cmp(const void *a, const void *b)
383 {
384 	const struct dc_surface_update *sa = (struct dc_surface_update *)a;
385 	const struct dc_surface_update *sb = (struct dc_surface_update *)b;
386 
387 	/* Sort by descending dc_plane layer_index (i.e. normalized_zpos) */
388 	return sb->surface->layer_index - sa->surface->layer_index;
389 }
390 
391 /**
392  * update_planes_and_stream_adapter() - Send planes to be updated in DC
393  *
394  * DC has a generic way to update planes and stream via
395  * dc_update_planes_and_stream function; however, DM might need some
396  * adjustments and preparation before calling it. This function is a wrapper
397  * for the dc_update_planes_and_stream that does any required configuration
398  * before passing control to DC.
399  *
400  * @dc: Display Core control structure
401  * @update_type: specify whether it is FULL/MEDIUM/FAST update
402  * @planes_count: planes count to update
403  * @stream: stream state
404  * @stream_update: stream update
405  * @array_of_surface_update: dc surface update pointer
406  *
407  */
408 static inline bool update_planes_and_stream_adapter(struct dc *dc,
409 						    int update_type,
410 						    int planes_count,
411 						    struct dc_stream_state *stream,
412 						    struct dc_stream_update *stream_update,
413 						    struct dc_surface_update *array_of_surface_update)
414 {
415 	sort(array_of_surface_update, planes_count,
416 	     sizeof(*array_of_surface_update), dm_plane_layer_index_cmp, NULL);
417 
418 	/*
419 	 * Previous frame finished and HW is ready for optimization.
420 	 */
421 	dc_post_update_surfaces_to_stream(dc);
422 
423 	return dc_update_planes_and_stream(dc,
424 					   array_of_surface_update,
425 					   planes_count,
426 					   stream,
427 					   stream_update);
428 }
429 
430 /**
431  * dm_pflip_high_irq() - Handle pageflip interrupt
432  * @interrupt_params: ignored
433  *
434  * Handles the pageflip interrupt by notifying all interested parties
435  * that the pageflip has been completed.
436  */
437 static void dm_pflip_high_irq(void *interrupt_params)
438 {
439 	struct amdgpu_crtc *amdgpu_crtc;
440 	struct common_irq_params *irq_params = interrupt_params;
441 	struct amdgpu_device *adev = irq_params->adev;
442 	struct drm_device *dev = adev_to_drm(adev);
443 	unsigned long flags;
444 	struct drm_pending_vblank_event *e;
445 	u32 vpos, hpos, v_blank_start, v_blank_end;
446 	bool vrr_active;
447 
448 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
449 
450 	/* IRQ could occur when in initial stage */
451 	/* TODO work and BO cleanup */
452 	if (amdgpu_crtc == NULL) {
453 		drm_dbg_state(dev, "CRTC is null, returning.\n");
454 		return;
455 	}
456 
457 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
458 
459 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED) {
460 		drm_dbg_state(dev,
461 			      "amdgpu_crtc->pflip_status = %d != AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p]\n",
462 			      amdgpu_crtc->pflip_status, AMDGPU_FLIP_SUBMITTED,
463 			      amdgpu_crtc->crtc_id, amdgpu_crtc);
464 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
465 		return;
466 	}
467 
468 	/* page flip completed. */
469 	e = amdgpu_crtc->event;
470 	amdgpu_crtc->event = NULL;
471 
472 	WARN_ON(!e);
473 
474 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(amdgpu_crtc);
475 
476 	/* Fixed refresh rate, or VRR scanout position outside front-porch? */
477 	if (!vrr_active ||
478 	    !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
479 				      &v_blank_end, &hpos, &vpos) ||
480 	    (vpos < v_blank_start)) {
481 		/* Update to correct count and vblank timestamp if racing with
482 		 * vblank irq. This also updates to the correct vblank timestamp
483 		 * even in VRR mode, as scanout is past the front-porch atm.
484 		 */
485 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
486 
487 		/* Wake up userspace by sending the pageflip event with proper
488 		 * count and timestamp of vblank of flip completion.
489 		 */
490 		if (e) {
491 			drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
492 
493 			/* Event sent, so done with vblank for this flip */
494 			drm_crtc_vblank_put(&amdgpu_crtc->base);
495 		}
496 	} else if (e) {
497 		/* VRR active and inside front-porch: vblank count and
498 		 * timestamp for pageflip event will only be up to date after
499 		 * drm_crtc_handle_vblank() has been executed from late vblank
500 		 * irq handler after start of back-porch (vline 0). We queue the
501 		 * pageflip event for send-out by drm_crtc_handle_vblank() with
502 		 * updated timestamp and count, once it runs after us.
503 		 *
504 		 * We need to open-code this instead of using the helper
505 		 * drm_crtc_arm_vblank_event(), as that helper would
506 		 * call drm_crtc_accurate_vblank_count(), which we must
507 		 * not call in VRR mode while we are in front-porch!
508 		 */
509 
510 		/* sequence will be replaced by real count during send-out. */
511 		e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
512 		e->pipe = amdgpu_crtc->crtc_id;
513 
514 		list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
515 		e = NULL;
516 	}
517 
518 	/* Keep track of vblank of this flip for flip throttling. We use the
519 	 * cooked hw counter, as that one incremented at start of this vblank
520 	 * of pageflip completion, so last_flip_vblank is the forbidden count
521 	 * for queueing new pageflips if vsync + VRR is enabled.
522 	 */
523 	amdgpu_crtc->dm_irq_params.last_flip_vblank =
524 		amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
525 
526 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
527 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
528 
529 	drm_dbg_state(dev,
530 		      "crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
531 		      amdgpu_crtc->crtc_id, amdgpu_crtc, vrr_active, (int)!e);
532 }
533 
534 static void dm_handle_vmin_vmax_update(struct work_struct *offload_work)
535 {
536 	struct vupdate_offload_work *work = container_of(offload_work, struct vupdate_offload_work, work);
537 	struct amdgpu_device *adev = work->adev;
538 	struct dc_stream_state *stream = work->stream;
539 	struct dc_crtc_timing_adjust *adjust = work->adjust;
540 
541 	mutex_lock(&adev->dm.dc_lock);
542 	dc_stream_adjust_vmin_vmax(adev->dm.dc, stream, adjust);
543 	mutex_unlock(&adev->dm.dc_lock);
544 
545 	dc_stream_release(stream);
546 	kfree(work->adjust);
547 	kfree(work);
548 }
549 
550 static void schedule_dc_vmin_vmax(struct amdgpu_device *adev,
551 	struct dc_stream_state *stream,
552 	struct dc_crtc_timing_adjust *adjust)
553 {
554 	struct vupdate_offload_work *offload_work = kzalloc_obj(*offload_work,
555 								GFP_NOWAIT);
556 	if (!offload_work) {
557 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate vupdate_offload_work\n");
558 		return;
559 	}
560 
561 	struct dc_crtc_timing_adjust *adjust_copy = kzalloc_obj(*adjust_copy,
562 								GFP_NOWAIT);
563 	if (!adjust_copy) {
564 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate adjust_copy\n");
565 		kfree(offload_work);
566 		return;
567 	}
568 
569 	dc_stream_retain(stream);
570 	memcpy(adjust_copy, adjust, sizeof(*adjust_copy));
571 
572 	INIT_WORK(&offload_work->work, dm_handle_vmin_vmax_update);
573 	offload_work->adev = adev;
574 	offload_work->stream = stream;
575 	offload_work->adjust = adjust_copy;
576 
577 	queue_work(system_percpu_wq, &offload_work->work);
578 }
579 
580 static void dm_vupdate_high_irq(void *interrupt_params)
581 {
582 	struct common_irq_params *irq_params = interrupt_params;
583 	struct amdgpu_device *adev = irq_params->adev;
584 	struct amdgpu_crtc *acrtc;
585 	struct drm_device *drm_dev;
586 	struct drm_vblank_crtc *vblank;
587 	ktime_t frame_duration_ns, previous_timestamp;
588 	unsigned long flags;
589 	int vrr_active;
590 
591 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
592 
593 	if (acrtc) {
594 		vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
595 		drm_dev = acrtc->base.dev;
596 		vblank = drm_crtc_vblank_crtc(&acrtc->base);
597 		previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
598 		frame_duration_ns = vblank->time - previous_timestamp;
599 
600 		if (frame_duration_ns > 0) {
601 			trace_amdgpu_refresh_rate_track(acrtc->base.index,
602 						frame_duration_ns,
603 						ktime_divns(NSEC_PER_SEC, frame_duration_ns));
604 			atomic64_set(&irq_params->previous_timestamp, vblank->time);
605 		}
606 
607 		drm_dbg_vbl(drm_dev,
608 			    "crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
609 			    vrr_active);
610 
611 		/* Core vblank handling is done here after end of front-porch in
612 		 * vrr mode, as vblank timestamping will give valid results
613 		 * while now done after front-porch. This will also deliver
614 		 * page-flip completion events that have been queued to us
615 		 * if a pageflip happened inside front-porch.
616 		 */
617 		if (vrr_active && acrtc->dm_irq_params.stream) {
618 			bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
619 			bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
620 			bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state
621 				== VRR_STATE_ACTIVE_VARIABLE;
622 
623 			amdgpu_dm_crtc_handle_vblank(acrtc);
624 
625 			/* BTR processing for pre-DCE12 ASICs */
626 			if (adev->family < AMDGPU_FAMILY_AI) {
627 				spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
628 				mod_freesync_handle_v_update(
629 				    adev->dm.freesync_module,
630 				    acrtc->dm_irq_params.stream,
631 				    &acrtc->dm_irq_params.vrr_params);
632 
633 				if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
634 					schedule_dc_vmin_vmax(adev,
635 						acrtc->dm_irq_params.stream,
636 						&acrtc->dm_irq_params.vrr_params.adjust);
637 				}
638 				spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
639 			}
640 		}
641 	}
642 }
643 
644 /**
645  * dm_crtc_high_irq() - Handles CRTC interrupt
646  * @interrupt_params: used for determining the CRTC instance
647  *
648  * Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
649  * event handler.
650  */
651 static void dm_crtc_high_irq(void *interrupt_params)
652 {
653 	struct common_irq_params *irq_params = interrupt_params;
654 	struct amdgpu_device *adev = irq_params->adev;
655 	struct drm_writeback_job *job;
656 	struct amdgpu_crtc *acrtc;
657 	unsigned long flags;
658 	int vrr_active;
659 
660 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
661 	if (!acrtc)
662 		return;
663 
664 	if (acrtc->wb_conn) {
665 		spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
666 
667 		if (acrtc->wb_pending) {
668 			job = list_first_entry_or_null(&acrtc->wb_conn->job_queue,
669 						       struct drm_writeback_job,
670 						       list_entry);
671 			acrtc->wb_pending = false;
672 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
673 
674 			if (job) {
675 				unsigned int v_total, refresh_hz;
676 				struct dc_stream_state *stream = acrtc->dm_irq_params.stream;
677 
678 				v_total = stream->adjust.v_total_max ?
679 					  stream->adjust.v_total_max : stream->timing.v_total;
680 				refresh_hz = div_u64((uint64_t) stream->timing.pix_clk_100hz *
681 					     100LL, (v_total * stream->timing.h_total));
682 				mdelay(1000 / refresh_hz);
683 
684 				drm_writeback_signal_completion(acrtc->wb_conn, 0);
685 				dc_stream_fc_disable_writeback(adev->dm.dc,
686 							       acrtc->dm_irq_params.stream, 0);
687 			}
688 		} else
689 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
690 	}
691 
692 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
693 
694 	drm_dbg_vbl(adev_to_drm(adev),
695 		    "crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
696 		    vrr_active, acrtc->dm_irq_params.active_planes);
697 
698 	/**
699 	 * Core vblank handling at start of front-porch is only possible
700 	 * in non-vrr mode, as only there vblank timestamping will give
701 	 * valid results while done in front-porch. Otherwise defer it
702 	 * to dm_vupdate_high_irq after end of front-porch.
703 	 */
704 	if (!vrr_active)
705 		amdgpu_dm_crtc_handle_vblank(acrtc);
706 
707 	/**
708 	 * Following stuff must happen at start of vblank, for crc
709 	 * computation and below-the-range btr support in vrr mode.
710 	 */
711 	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
712 
713 	/* BTR updates need to happen before VUPDATE on Vega and above. */
714 	if (adev->family < AMDGPU_FAMILY_AI)
715 		return;
716 
717 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
718 
719 	if (acrtc->dm_irq_params.stream &&
720 		acrtc->dm_irq_params.vrr_params.supported) {
721 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
722 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
723 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state == VRR_STATE_ACTIVE_VARIABLE;
724 
725 		mod_freesync_handle_v_update(adev->dm.freesync_module,
726 					     acrtc->dm_irq_params.stream,
727 					     &acrtc->dm_irq_params.vrr_params);
728 
729 		/* update vmin_vmax only if freesync is enabled, or only if PSR and REPLAY are disabled */
730 		if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
731 			schedule_dc_vmin_vmax(adev, acrtc->dm_irq_params.stream,
732 					&acrtc->dm_irq_params.vrr_params.adjust);
733 		}
734 	}
735 
736 	/*
737 	 * If there aren't any active_planes then DCH HUBP may be clock-gated.
738 	 * In that case, pageflip completion interrupts won't fire and pageflip
739 	 * completion events won't get delivered. Prevent this by sending
740 	 * pending pageflip events from here if a flip is still pending.
741 	 *
742 	 * If any planes are enabled, use dm_pflip_high_irq() instead, to
743 	 * avoid race conditions between flip programming and completion,
744 	 * which could cause too early flip completion events.
745 	 */
746 	if (adev->family >= AMDGPU_FAMILY_RV &&
747 	    acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
748 	    acrtc->dm_irq_params.active_planes == 0) {
749 		if (acrtc->event) {
750 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
751 			acrtc->event = NULL;
752 			drm_crtc_vblank_put(&acrtc->base);
753 		}
754 		acrtc->pflip_status = AMDGPU_FLIP_NONE;
755 	}
756 
757 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
758 }
759 
760 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
761 /**
762  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
763  * DCN generation ASICs
764  * @interrupt_params: interrupt parameters
765  *
766  * Used to set crc window/read out crc value at vertical line 0 position
767  */
768 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
769 {
770 	struct common_irq_params *irq_params = interrupt_params;
771 	struct amdgpu_device *adev = irq_params->adev;
772 	struct amdgpu_crtc *acrtc;
773 
774 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
775 
776 	if (!acrtc)
777 		return;
778 
779 	amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
780 }
781 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
782 
783 /**
784  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
785  * @adev: amdgpu_device pointer
786  * @notify: dmub notification structure
787  *
788  * Dmub AUX or SET_CONFIG command completion processing callback
789  * Copies dmub notification to DM which is to be read by AUX command.
790  * issuing thread and also signals the event to wake up the thread.
791  */
792 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
793 					struct dmub_notification *notify)
794 {
795 	if (adev->dm.dmub_notify)
796 		memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
797 	if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
798 		complete(&adev->dm.dmub_aux_transfer_done);
799 }
800 
801 static void dmub_aux_fused_io_callback(struct amdgpu_device *adev,
802 					struct dmub_notification *notify)
803 {
804 	if (!adev || !notify) {
805 		ASSERT(false);
806 		return;
807 	}
808 
809 	const struct dmub_cmd_fused_request *req = &notify->fused_request;
810 	const uint8_t ddc_line = req->u.aux.ddc_line;
811 
812 	if (ddc_line >= ARRAY_SIZE(adev->dm.fused_io)) {
813 		ASSERT(false);
814 		return;
815 	}
816 
817 	struct fused_io_sync *sync = &adev->dm.fused_io[ddc_line];
818 
819 	static_assert(sizeof(*req) <= sizeof(sync->reply_data), "Size mismatch");
820 	memcpy(sync->reply_data, req, sizeof(*req));
821 	complete(&sync->replied);
822 }
823 
824 /**
825  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
826  * @adev: amdgpu_device pointer
827  * @notify: dmub notification structure
828  *
829  * Dmub Hpd interrupt processing callback. Gets displayindex through the
830  * ink index and calls helper to do the processing.
831  */
832 static void dmub_hpd_callback(struct amdgpu_device *adev,
833 			      struct dmub_notification *notify)
834 {
835 	struct amdgpu_dm_connector *aconnector;
836 	struct amdgpu_dm_connector *hpd_aconnector = NULL;
837 	struct drm_connector *connector;
838 	struct drm_connector_list_iter iter;
839 	struct dc_link *link;
840 	u8 link_index = 0;
841 	struct drm_device *dev;
842 
843 	if (adev == NULL)
844 		return;
845 
846 	if (notify == NULL) {
847 		drm_err(adev_to_drm(adev), "DMUB HPD callback notification was NULL");
848 		return;
849 	}
850 
851 	if (notify->link_index > adev->dm.dc->link_count) {
852 		drm_err(adev_to_drm(adev), "DMUB HPD index (%u)is abnormal", notify->link_index);
853 		return;
854 	}
855 
856 	/* Skip DMUB HPD IRQ in suspend/resume. We will probe them later. */
857 	if (notify->type == DMUB_NOTIFICATION_HPD && adev->in_suspend) {
858 		drm_info(adev_to_drm(adev), "Skip DMUB HPD IRQ callback in suspend/resume\n");
859 		return;
860 	}
861 
862 	link_index = notify->link_index;
863 	link = adev->dm.dc->links[link_index];
864 	dev = adev->dm.ddev;
865 
866 	drm_connector_list_iter_begin(dev, &iter);
867 	drm_for_each_connector_iter(connector, &iter) {
868 
869 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
870 			continue;
871 
872 		aconnector = to_amdgpu_dm_connector(connector);
873 		if (link && aconnector->dc_link == link) {
874 			if (notify->type == DMUB_NOTIFICATION_HPD)
875 				drm_info(adev_to_drm(adev), "DMUB HPD IRQ callback: link_index=%u\n", link_index);
876 			else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
877 				drm_info(adev_to_drm(adev), "DMUB HPD RX IRQ callback: link_index=%u\n", link_index);
878 			else
879 				drm_warn(adev_to_drm(adev), "DMUB Unknown HPD callback type %d, link_index=%u\n",
880 						notify->type, link_index);
881 
882 			hpd_aconnector = aconnector;
883 			break;
884 		}
885 	}
886 	drm_connector_list_iter_end(&iter);
887 
888 	if (hpd_aconnector) {
889 		if (notify->type == DMUB_NOTIFICATION_HPD) {
890 			if (hpd_aconnector->dc_link->hpd_status == (notify->hpd_status == DP_HPD_PLUG))
891 				drm_warn(adev_to_drm(adev), "DMUB reported hpd status unchanged. link_index=%u\n", link_index);
892 			handle_hpd_irq_helper(hpd_aconnector);
893 		} else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ) {
894 			handle_hpd_rx_irq(hpd_aconnector);
895 		}
896 	}
897 }
898 
899 /**
900  * dmub_hpd_sense_callback - DMUB HPD sense processing callback.
901  * @adev: amdgpu_device pointer
902  * @notify: dmub notification structure
903  *
904  * HPD sense changes can occur during low power states and need to be
905  * notified from firmware to driver.
906  */
907 static void dmub_hpd_sense_callback(struct amdgpu_device *adev,
908 			      struct dmub_notification *notify)
909 {
910 	drm_dbg_driver(adev_to_drm(adev), "DMUB HPD SENSE callback.\n");
911 }
912 
913 /**
914  * register_dmub_notify_callback - Sets callback for DMUB notify
915  * @adev: amdgpu_device pointer
916  * @type: Type of dmub notification
917  * @callback: Dmub interrupt callback function
918  * @dmub_int_thread_offload: offload indicator
919  *
920  * API to register a dmub callback handler for a dmub notification
921  * Also sets indicator whether callback processing to be offloaded.
922  * to dmub interrupt handling thread
923  * Return: true if successfully registered, false if there is existing registration
924  */
925 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
926 					  enum dmub_notification_type type,
927 					  dmub_notify_interrupt_callback_t callback,
928 					  bool dmub_int_thread_offload)
929 {
930 	if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
931 		adev->dm.dmub_callback[type] = callback;
932 		adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
933 	} else
934 		return false;
935 
936 	return true;
937 }
938 
939 static void dm_handle_hpd_work(struct work_struct *work)
940 {
941 	struct dmub_hpd_work *dmub_hpd_wrk;
942 
943 	dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
944 
945 	if (!dmub_hpd_wrk->dmub_notify) {
946 		drm_err(adev_to_drm(dmub_hpd_wrk->adev), "dmub_hpd_wrk dmub_notify is NULL");
947 		return;
948 	}
949 
950 	if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
951 		dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
952 		dmub_hpd_wrk->dmub_notify);
953 	}
954 
955 	kfree(dmub_hpd_wrk->dmub_notify);
956 	kfree(dmub_hpd_wrk);
957 
958 }
959 
960 static const char *dmub_notification_type_str(enum dmub_notification_type e)
961 {
962 	switch (e) {
963 	case DMUB_NOTIFICATION_NO_DATA:
964 		return "NO_DATA";
965 	case DMUB_NOTIFICATION_AUX_REPLY:
966 		return "AUX_REPLY";
967 	case DMUB_NOTIFICATION_HPD:
968 		return "HPD";
969 	case DMUB_NOTIFICATION_HPD_IRQ:
970 		return "HPD_IRQ";
971 	case DMUB_NOTIFICATION_SET_CONFIG_REPLY:
972 		return "SET_CONFIG_REPLY";
973 	case DMUB_NOTIFICATION_DPIA_NOTIFICATION:
974 		return "DPIA_NOTIFICATION";
975 	case DMUB_NOTIFICATION_HPD_SENSE_NOTIFY:
976 		return "HPD_SENSE_NOTIFY";
977 	case DMUB_NOTIFICATION_FUSED_IO:
978 		return "FUSED_IO";
979 	default:
980 		return "<unknown>";
981 	}
982 }
983 
984 #define DMUB_TRACE_MAX_READ 64
985 /**
986  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
987  * @interrupt_params: used for determining the Outbox instance
988  *
989  * Handles the Outbox Interrupt
990  * event handler.
991  */
992 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
993 {
994 	struct dmub_notification notify = {0};
995 	struct common_irq_params *irq_params = interrupt_params;
996 	struct amdgpu_device *adev = irq_params->adev;
997 	struct amdgpu_display_manager *dm = &adev->dm;
998 	struct dmcub_trace_buf_entry entry = { 0 };
999 	u32 count = 0;
1000 	struct dmub_hpd_work *dmub_hpd_wrk;
1001 
1002 	do {
1003 		if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
1004 			trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
1005 							entry.param0, entry.param1);
1006 
1007 			drm_dbg_driver(adev_to_drm(adev), "trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
1008 				 entry.trace_code, entry.tick_count, entry.param0, entry.param1);
1009 		} else
1010 			break;
1011 
1012 		count++;
1013 
1014 	} while (count <= DMUB_TRACE_MAX_READ);
1015 
1016 	if (count > DMUB_TRACE_MAX_READ)
1017 		drm_dbg_driver(adev_to_drm(adev), "Warning : count > DMUB_TRACE_MAX_READ");
1018 
1019 	if (dc_enable_dmub_notifications(adev->dm.dc) &&
1020 		irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
1021 
1022 		do {
1023 			dc_stat_get_dmub_notification(adev->dm.dc, &notify);
1024 			if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
1025 				drm_err(adev_to_drm(adev), "DM: notify type %d invalid!", notify.type);
1026 				continue;
1027 			}
1028 			if (!dm->dmub_callback[notify.type]) {
1029 				drm_warn(adev_to_drm(adev), "DMUB notification skipped due to no handler: type=%s\n",
1030 					dmub_notification_type_str(notify.type));
1031 				continue;
1032 			}
1033 			if (dm->dmub_thread_offload[notify.type] == true) {
1034 				dmub_hpd_wrk = kzalloc_obj(*dmub_hpd_wrk,
1035 							   GFP_ATOMIC);
1036 				if (!dmub_hpd_wrk) {
1037 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk");
1038 					return;
1039 				}
1040 				dmub_hpd_wrk->dmub_notify = kmemdup(&notify, sizeof(struct dmub_notification),
1041 								    GFP_ATOMIC);
1042 				if (!dmub_hpd_wrk->dmub_notify) {
1043 					kfree(dmub_hpd_wrk);
1044 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk->dmub_notify");
1045 					return;
1046 				}
1047 				INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
1048 				dmub_hpd_wrk->adev = adev;
1049 				queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
1050 			} else {
1051 				dm->dmub_callback[notify.type](adev, &notify);
1052 			}
1053 		} while (notify.pending_notification);
1054 	}
1055 }
1056 
1057 static int dm_set_clockgating_state(struct amdgpu_ip_block *ip_block,
1058 		  enum amd_clockgating_state state)
1059 {
1060 	return 0;
1061 }
1062 
1063 static int dm_set_powergating_state(struct amdgpu_ip_block *ip_block,
1064 		  enum amd_powergating_state state)
1065 {
1066 	return 0;
1067 }
1068 
1069 /* Prototypes of private functions */
1070 static int dm_early_init(struct amdgpu_ip_block *ip_block);
1071 
1072 /* Allocate memory for FBC compressed data  */
1073 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
1074 {
1075 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
1076 	struct dm_compressor_info *compressor = &adev->dm.compressor;
1077 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
1078 	struct drm_display_mode *mode;
1079 	unsigned long max_size = 0;
1080 
1081 	if (adev->dm.dc->fbc_compressor == NULL)
1082 		return;
1083 
1084 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
1085 		return;
1086 
1087 	if (compressor->bo_ptr)
1088 		return;
1089 
1090 
1091 	list_for_each_entry(mode, &connector->modes, head) {
1092 		if (max_size < (unsigned long) mode->htotal * mode->vtotal)
1093 			max_size = (unsigned long) mode->htotal * mode->vtotal;
1094 	}
1095 
1096 	if (max_size) {
1097 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
1098 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
1099 			    &compressor->gpu_addr, &compressor->cpu_addr);
1100 
1101 		if (r)
1102 			drm_err(adev_to_drm(adev), "DM: Failed to initialize FBC\n");
1103 		else {
1104 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
1105 			drm_info(adev_to_drm(adev), "DM: FBC alloc %lu\n", max_size*4);
1106 		}
1107 
1108 	}
1109 
1110 }
1111 
1112 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
1113 					  int pipe, bool *enabled,
1114 					  unsigned char *buf, int max_bytes)
1115 {
1116 	struct drm_device *dev = dev_get_drvdata(kdev);
1117 	struct amdgpu_device *adev = drm_to_adev(dev);
1118 	struct drm_connector *connector;
1119 	struct drm_connector_list_iter conn_iter;
1120 	struct amdgpu_dm_connector *aconnector;
1121 	int ret = 0;
1122 
1123 	*enabled = false;
1124 
1125 	mutex_lock(&adev->dm.audio_lock);
1126 
1127 	drm_connector_list_iter_begin(dev, &conn_iter);
1128 	drm_for_each_connector_iter(connector, &conn_iter) {
1129 
1130 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1131 			continue;
1132 
1133 		aconnector = to_amdgpu_dm_connector(connector);
1134 		if (aconnector->audio_inst != port)
1135 			continue;
1136 
1137 		*enabled = true;
1138 		mutex_lock(&connector->eld_mutex);
1139 		ret = drm_eld_size(connector->eld);
1140 		memcpy(buf, connector->eld, min(max_bytes, ret));
1141 		mutex_unlock(&connector->eld_mutex);
1142 
1143 		break;
1144 	}
1145 	drm_connector_list_iter_end(&conn_iter);
1146 
1147 	mutex_unlock(&adev->dm.audio_lock);
1148 
1149 	drm_dbg_kms(adev_to_drm(adev), "Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
1150 
1151 	return ret;
1152 }
1153 
1154 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
1155 	.get_eld = amdgpu_dm_audio_component_get_eld,
1156 };
1157 
1158 static int amdgpu_dm_audio_component_bind(struct device *kdev,
1159 				       struct device *hda_kdev, void *data)
1160 {
1161 	struct drm_device *dev = dev_get_drvdata(kdev);
1162 	struct amdgpu_device *adev = drm_to_adev(dev);
1163 	struct drm_audio_component *acomp = data;
1164 
1165 	acomp->ops = &amdgpu_dm_audio_component_ops;
1166 	acomp->dev = kdev;
1167 	adev->dm.audio_component = acomp;
1168 
1169 	return 0;
1170 }
1171 
1172 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
1173 					  struct device *hda_kdev, void *data)
1174 {
1175 	struct amdgpu_device *adev = drm_to_adev(dev_get_drvdata(kdev));
1176 	struct drm_audio_component *acomp = data;
1177 
1178 	acomp->ops = NULL;
1179 	acomp->dev = NULL;
1180 	adev->dm.audio_component = NULL;
1181 }
1182 
1183 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
1184 	.bind	= amdgpu_dm_audio_component_bind,
1185 	.unbind	= amdgpu_dm_audio_component_unbind,
1186 };
1187 
1188 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
1189 {
1190 	int i, ret;
1191 
1192 	if (!amdgpu_audio)
1193 		return 0;
1194 
1195 	adev->mode_info.audio.enabled = true;
1196 
1197 	adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
1198 
1199 	for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
1200 		adev->mode_info.audio.pin[i].channels = -1;
1201 		adev->mode_info.audio.pin[i].rate = -1;
1202 		adev->mode_info.audio.pin[i].bits_per_sample = -1;
1203 		adev->mode_info.audio.pin[i].status_bits = 0;
1204 		adev->mode_info.audio.pin[i].category_code = 0;
1205 		adev->mode_info.audio.pin[i].connected = false;
1206 		adev->mode_info.audio.pin[i].id =
1207 			adev->dm.dc->res_pool->audios[i]->inst;
1208 		adev->mode_info.audio.pin[i].offset = 0;
1209 	}
1210 
1211 	ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1212 	if (ret < 0)
1213 		return ret;
1214 
1215 	adev->dm.audio_registered = true;
1216 
1217 	return 0;
1218 }
1219 
1220 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
1221 {
1222 	if (!amdgpu_audio)
1223 		return;
1224 
1225 	if (!adev->mode_info.audio.enabled)
1226 		return;
1227 
1228 	if (adev->dm.audio_registered) {
1229 		component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1230 		adev->dm.audio_registered = false;
1231 	}
1232 
1233 	/* TODO: Disable audio? */
1234 
1235 	adev->mode_info.audio.enabled = false;
1236 }
1237 
1238 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
1239 {
1240 	struct drm_audio_component *acomp = adev->dm.audio_component;
1241 
1242 	if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
1243 		drm_dbg_kms(adev_to_drm(adev), "Notify ELD: %d\n", pin);
1244 
1245 		acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1246 						 pin, -1);
1247 	}
1248 }
1249 
1250 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1251 {
1252 	const struct dmcub_firmware_header_v1_0 *hdr;
1253 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1254 	struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1255 	const struct firmware *dmub_fw = adev->dm.dmub_fw;
1256 	struct dc *dc = adev->dm.dc;
1257 	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1258 	struct abm *abm = adev->dm.dc->res_pool->abm;
1259 	struct dc_context *ctx = adev->dm.dc->ctx;
1260 	struct dmub_srv_hw_params hw_params;
1261 	enum dmub_status status;
1262 	const unsigned char *fw_inst_const, *fw_bss_data;
1263 	u32 i, fw_inst_const_size, fw_bss_data_size;
1264 	bool has_hw_support;
1265 
1266 	if (!dmub_srv)
1267 		/* DMUB isn't supported on the ASIC. */
1268 		return 0;
1269 
1270 	if (!fb_info) {
1271 		drm_err(adev_to_drm(adev), "No framebuffer info for DMUB service.\n");
1272 		return -EINVAL;
1273 	}
1274 
1275 	if (!dmub_fw) {
1276 		/* Firmware required for DMUB support. */
1277 		drm_err(adev_to_drm(adev), "No firmware provided for DMUB.\n");
1278 		return -EINVAL;
1279 	}
1280 
1281 	/* initialize register offsets for ASICs with runtime initialization available */
1282 	if (dmub_srv->hw_funcs.init_reg_offsets)
1283 		dmub_srv->hw_funcs.init_reg_offsets(dmub_srv, ctx);
1284 
1285 	status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1286 	if (status != DMUB_STATUS_OK) {
1287 		drm_err(adev_to_drm(adev), "Error checking HW support for DMUB: %d\n", status);
1288 		return -EINVAL;
1289 	}
1290 
1291 	if (!has_hw_support) {
1292 		drm_info(adev_to_drm(adev), "DMUB unsupported on ASIC\n");
1293 		return 0;
1294 	}
1295 
1296 	/* Reset DMCUB if it was previously running - before we overwrite its memory. */
1297 	status = dmub_srv_hw_reset(dmub_srv);
1298 	if (status != DMUB_STATUS_OK)
1299 		drm_warn(adev_to_drm(adev), "Error resetting DMUB HW: %d\n", status);
1300 
1301 	hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1302 
1303 	fw_inst_const = dmub_fw->data +
1304 			le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1305 			PSP_HEADER_BYTES_256;
1306 
1307 	fw_bss_data = dmub_fw->data +
1308 		      le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1309 		      le32_to_cpu(hdr->inst_const_bytes);
1310 
1311 	/* Copy firmware and bios info into FB memory. */
1312 	fw_inst_const_size = adev->dm.fw_inst_size;
1313 
1314 	fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1315 
1316 	/* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1317 	 * amdgpu_ucode_init_single_fw will load dmub firmware
1318 	 * fw_inst_const part to cw0; otherwise, the firmware back door load
1319 	 * will be done by dm_dmub_hw_init
1320 	 */
1321 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1322 		memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1323 				fw_inst_const_size);
1324 	}
1325 
1326 	if (fw_bss_data_size)
1327 		memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1328 		       fw_bss_data, fw_bss_data_size);
1329 
1330 	/* Copy firmware bios info into FB memory. */
1331 	memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1332 	       adev->bios_size);
1333 
1334 	/* Reset regions that need to be reset. */
1335 	memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1336 	fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1337 
1338 	memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1339 	       fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1340 
1341 	memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1342 	       fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1343 
1344 	memset(fb_info->fb[DMUB_WINDOW_SHARED_STATE].cpu_addr, 0,
1345 	       fb_info->fb[DMUB_WINDOW_SHARED_STATE].size);
1346 
1347 	/* Initialize hardware. */
1348 	memset(&hw_params, 0, sizeof(hw_params));
1349 	hw_params.soc_fb_info.fb_base = adev->gmc.fb_start;
1350 	hw_params.soc_fb_info.fb_offset = adev->vm_manager.vram_base_offset;
1351 
1352 	/* backdoor load firmware and trigger dmub running */
1353 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1354 		hw_params.load_inst_const = true;
1355 
1356 	if (dmcu)
1357 		hw_params.psp_version = dmcu->psp_version;
1358 
1359 	for (i = 0; i < fb_info->num_fb; ++i)
1360 		hw_params.fb[i] = &fb_info->fb[i];
1361 
1362 	/* Enable usb4 dpia in the FW APU */
1363 	if (dc->caps.is_apu &&
1364 		dc->res_pool->usb4_dpia_count != 0 &&
1365 		!dc->debug.dpia_debug.bits.disable_dpia) {
1366 		hw_params.dpia_supported = true;
1367 		hw_params.disable_dpia = dc->debug.dpia_debug.bits.disable_dpia;
1368 		hw_params.dpia_hpd_int_enable_supported = false;
1369 		hw_params.enable_non_transparent_setconfig = dc->config.consolidated_dpia_dp_lt;
1370 		hw_params.disable_dpia_bw_allocation = !dc->config.usb4_bw_alloc_support;
1371 	}
1372 
1373 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1374 	case IP_VERSION(3, 5, 0):
1375 	case IP_VERSION(3, 5, 1):
1376 	case IP_VERSION(3, 6, 0):
1377 	case IP_VERSION(4, 2, 0):
1378 		hw_params.ips_sequential_ono = adev->external_rev_id > 0x10;
1379 		hw_params.lower_hbr3_phy_ssc = true;
1380 		break;
1381 	default:
1382 		break;
1383 	}
1384 
1385 	status = dmub_srv_hw_init(dmub_srv, &hw_params);
1386 	if (status != DMUB_STATUS_OK) {
1387 		drm_err(adev_to_drm(adev), "Error initializing DMUB HW: %d\n", status);
1388 		return -EINVAL;
1389 	}
1390 
1391 	/* Wait for firmware load to finish. */
1392 	status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1393 	if (status != DMUB_STATUS_OK)
1394 		drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1395 
1396 	/* Init DMCU and ABM if available. */
1397 	if (dmcu && abm) {
1398 		dmcu->funcs->dmcu_init(dmcu);
1399 		abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1400 	}
1401 
1402 	if (!adev->dm.dc->ctx->dmub_srv)
1403 		adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1404 	if (!adev->dm.dc->ctx->dmub_srv) {
1405 		drm_err(adev_to_drm(adev), "Couldn't allocate DC DMUB server!\n");
1406 		return -ENOMEM;
1407 	}
1408 
1409 	drm_info(adev_to_drm(adev), "DMUB hardware initialized: version=0x%08X\n",
1410 		 adev->dm.dmcub_fw_version);
1411 
1412 	/* Keeping sanity checks off if
1413 	 * DCN31 >= 4.0.59.0
1414 	 * DCN314 >= 8.0.16.0
1415 	 * Otherwise, turn on sanity checks
1416 	 */
1417 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1418 	case IP_VERSION(3, 1, 2):
1419 	case IP_VERSION(3, 1, 3):
1420 		if (adev->dm.dmcub_fw_version &&
1421 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1422 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(4, 0, 59))
1423 				adev->dm.dc->debug.sanity_checks = true;
1424 		break;
1425 	case IP_VERSION(3, 1, 4):
1426 		if (adev->dm.dmcub_fw_version &&
1427 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1428 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(8, 0, 16))
1429 				adev->dm.dc->debug.sanity_checks = true;
1430 		break;
1431 	default:
1432 		break;
1433 	}
1434 
1435 	return 0;
1436 }
1437 
1438 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1439 {
1440 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1441 	enum dmub_status status;
1442 	bool init;
1443 	int r;
1444 
1445 	if (!dmub_srv) {
1446 		/* DMUB isn't supported on the ASIC. */
1447 		return;
1448 	}
1449 
1450 	status = dmub_srv_is_hw_init(dmub_srv, &init);
1451 	if (status != DMUB_STATUS_OK)
1452 		drm_warn(adev_to_drm(adev), "DMUB hardware init check failed: %d\n", status);
1453 
1454 	if (status == DMUB_STATUS_OK && init) {
1455 		/* Wait for firmware load to finish. */
1456 		status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1457 		if (status != DMUB_STATUS_OK)
1458 			drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1459 	} else {
1460 		/* Perform the full hardware initialization. */
1461 		r = dm_dmub_hw_init(adev);
1462 		if (r)
1463 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
1464 	}
1465 }
1466 
1467 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1468 {
1469 	u64 pt_base;
1470 	u32 logical_addr_low;
1471 	u32 logical_addr_high;
1472 	u32 agp_base, agp_bot, agp_top;
1473 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1474 
1475 	memset(pa_config, 0, sizeof(*pa_config));
1476 
1477 	agp_base = 0;
1478 	agp_bot = adev->gmc.agp_start >> 24;
1479 	agp_top = adev->gmc.agp_end >> 24;
1480 
1481 	/* AGP aperture is disabled */
1482 	if (agp_bot > agp_top) {
1483 		logical_addr_low = adev->gmc.fb_start >> 18;
1484 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1485 				       AMD_APU_IS_RENOIR |
1486 				       AMD_APU_IS_GREEN_SARDINE))
1487 			/*
1488 			 * Raven2 has a HW issue that it is unable to use the vram which
1489 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1490 			 * workaround that increase system aperture high address (add 1)
1491 			 * to get rid of the VM fault and hardware hang.
1492 			 */
1493 			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
1494 		else
1495 			logical_addr_high = adev->gmc.fb_end >> 18;
1496 	} else {
1497 		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1498 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1499 				       AMD_APU_IS_RENOIR |
1500 				       AMD_APU_IS_GREEN_SARDINE))
1501 			/*
1502 			 * Raven2 has a HW issue that it is unable to use the vram which
1503 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1504 			 * workaround that increase system aperture high address (add 1)
1505 			 * to get rid of the VM fault and hardware hang.
1506 			 */
1507 			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1508 		else
1509 			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1510 	}
1511 
1512 	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1513 
1514 	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
1515 						   AMDGPU_GPU_PAGE_SHIFT);
1516 	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
1517 						  AMDGPU_GPU_PAGE_SHIFT);
1518 	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
1519 						 AMDGPU_GPU_PAGE_SHIFT);
1520 	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
1521 						AMDGPU_GPU_PAGE_SHIFT);
1522 	page_table_base.high_part = upper_32_bits(pt_base);
1523 	page_table_base.low_part = lower_32_bits(pt_base);
1524 
1525 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1526 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1527 
1528 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
1529 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1530 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1531 
1532 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1533 	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
1534 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1535 
1536 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1537 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1538 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1539 
1540 	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
1541 
1542 }
1543 
1544 static void force_connector_state(
1545 	struct amdgpu_dm_connector *aconnector,
1546 	enum drm_connector_force force_state)
1547 {
1548 	struct drm_connector *connector = &aconnector->base;
1549 
1550 	mutex_lock(&connector->dev->mode_config.mutex);
1551 	aconnector->base.force = force_state;
1552 	mutex_unlock(&connector->dev->mode_config.mutex);
1553 
1554 	mutex_lock(&aconnector->hpd_lock);
1555 	drm_kms_helper_connector_hotplug_event(connector);
1556 	mutex_unlock(&aconnector->hpd_lock);
1557 }
1558 
1559 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1560 {
1561 	struct hpd_rx_irq_offload_work *offload_work;
1562 	struct amdgpu_dm_connector *aconnector;
1563 	struct dc_link *dc_link;
1564 	struct amdgpu_device *adev;
1565 	enum dc_connection_type new_connection_type = dc_connection_none;
1566 	unsigned long flags;
1567 	union test_response test_response;
1568 
1569 	memset(&test_response, 0, sizeof(test_response));
1570 
1571 	offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1572 	aconnector = offload_work->offload_wq->aconnector;
1573 	adev = offload_work->adev;
1574 
1575 	if (!aconnector) {
1576 		drm_err(adev_to_drm(adev), "Can't retrieve aconnector in hpd_rx_irq_offload_work");
1577 		goto skip;
1578 	}
1579 
1580 	dc_link = aconnector->dc_link;
1581 
1582 	mutex_lock(&aconnector->hpd_lock);
1583 	if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
1584 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
1585 	mutex_unlock(&aconnector->hpd_lock);
1586 
1587 	if (new_connection_type == dc_connection_none)
1588 		goto skip;
1589 
1590 	if (amdgpu_in_reset(adev))
1591 		goto skip;
1592 
1593 	if (offload_work->data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
1594 		offload_work->data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
1595 		dm_handle_mst_sideband_msg_ready_event(&aconnector->mst_mgr, DOWN_OR_UP_MSG_RDY_EVENT);
1596 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1597 		offload_work->offload_wq->is_handling_mst_msg_rdy_event = false;
1598 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1599 		goto skip;
1600 	}
1601 
1602 	mutex_lock(&adev->dm.dc_lock);
1603 	if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
1604 		dc_link_dp_handle_automated_test(dc_link);
1605 
1606 		if (aconnector->timing_changed) {
1607 			/* force connector disconnect and reconnect */
1608 			force_connector_state(aconnector, DRM_FORCE_OFF);
1609 			msleep(100);
1610 			force_connector_state(aconnector, DRM_FORCE_UNSPECIFIED);
1611 		}
1612 
1613 		test_response.bits.ACK = 1;
1614 
1615 		core_link_write_dpcd(
1616 		dc_link,
1617 		DP_TEST_RESPONSE,
1618 		&test_response.raw,
1619 		sizeof(test_response));
1620 	} else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1621 			dc_link_check_link_loss_status(dc_link, &offload_work->data) &&
1622 			dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1623 		/* offload_work->data is from handle_hpd_rx_irq->
1624 		 * schedule_hpd_rx_offload_work.this is defer handle
1625 		 * for hpd short pulse. upon here, link status may be
1626 		 * changed, need get latest link status from dpcd
1627 		 * registers. if link status is good, skip run link
1628 		 * training again.
1629 		 */
1630 		union hpd_irq_data irq_data;
1631 
1632 		memset(&irq_data, 0, sizeof(irq_data));
1633 
1634 		/* before dc_link_dp_handle_link_loss, allow new link lost handle
1635 		 * request be added to work queue if link lost at end of dc_link_
1636 		 * dp_handle_link_loss
1637 		 */
1638 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1639 		offload_work->offload_wq->is_handling_link_loss = false;
1640 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1641 
1642 		if ((dc_link_dp_read_hpd_rx_irq_data(dc_link, &irq_data) == DC_OK) &&
1643 			dc_link_check_link_loss_status(dc_link, &irq_data))
1644 			dc_link_dp_handle_link_loss(dc_link);
1645 	}
1646 	mutex_unlock(&adev->dm.dc_lock);
1647 
1648 skip:
1649 	kfree(offload_work);
1650 
1651 }
1652 
1653 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct amdgpu_device *adev)
1654 {
1655 	struct dc *dc = adev->dm.dc;
1656 	int max_caps = dc->caps.max_links;
1657 	int i = 0;
1658 	struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1659 
1660 	hpd_rx_offload_wq = kzalloc_objs(*hpd_rx_offload_wq, max_caps);
1661 
1662 	if (!hpd_rx_offload_wq)
1663 		return NULL;
1664 
1665 
1666 	for (i = 0; i < max_caps; i++) {
1667 		hpd_rx_offload_wq[i].wq =
1668 				    create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1669 
1670 		if (hpd_rx_offload_wq[i].wq == NULL) {
1671 			drm_err(adev_to_drm(adev), "create amdgpu_dm_hpd_rx_offload_wq fail!");
1672 			goto out_err;
1673 		}
1674 
1675 		spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
1676 	}
1677 
1678 	return hpd_rx_offload_wq;
1679 
1680 out_err:
1681 	for (i = 0; i < max_caps; i++) {
1682 		if (hpd_rx_offload_wq[i].wq)
1683 			destroy_workqueue(hpd_rx_offload_wq[i].wq);
1684 	}
1685 	kfree(hpd_rx_offload_wq);
1686 	return NULL;
1687 }
1688 
1689 struct amdgpu_stutter_quirk {
1690 	u16 chip_vendor;
1691 	u16 chip_device;
1692 	u16 subsys_vendor;
1693 	u16 subsys_device;
1694 	u8 revision;
1695 };
1696 
1697 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1698 	/* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1699 	{ 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1700 	{ 0, 0, 0, 0, 0 },
1701 };
1702 
1703 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1704 {
1705 	const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1706 
1707 	while (p && p->chip_device != 0) {
1708 		if (pdev->vendor == p->chip_vendor &&
1709 		    pdev->device == p->chip_device &&
1710 		    pdev->subsystem_vendor == p->subsys_vendor &&
1711 		    pdev->subsystem_device == p->subsys_device &&
1712 		    pdev->revision == p->revision) {
1713 			return true;
1714 		}
1715 		++p;
1716 	}
1717 	return false;
1718 }
1719 
1720 
1721 void*
1722 dm_allocate_gpu_mem(
1723 		struct amdgpu_device *adev,
1724 		enum dc_gpu_mem_alloc_type type,
1725 		size_t size,
1726 		long long *addr)
1727 {
1728 	struct dal_allocation *da;
1729 	u32 domain = (type == DC_MEM_ALLOC_TYPE_GART) ?
1730 		AMDGPU_GEM_DOMAIN_GTT : AMDGPU_GEM_DOMAIN_VRAM;
1731 	int ret;
1732 
1733 	da = kzalloc_obj(struct dal_allocation);
1734 	if (!da)
1735 		return NULL;
1736 
1737 	ret = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
1738 				      domain, &da->bo,
1739 				      &da->gpu_addr, &da->cpu_ptr);
1740 
1741 	*addr = da->gpu_addr;
1742 
1743 	if (ret) {
1744 		kfree(da);
1745 		return NULL;
1746 	}
1747 
1748 	/* add da to list in dm */
1749 	list_add(&da->list, &adev->dm.da_list);
1750 
1751 	return da->cpu_ptr;
1752 }
1753 
1754 void
1755 dm_free_gpu_mem(
1756 		struct amdgpu_device *adev,
1757 		enum dc_gpu_mem_alloc_type type,
1758 		void *pvMem)
1759 {
1760 	struct dal_allocation *da;
1761 
1762 	/* walk the da list in DM */
1763 	list_for_each_entry(da, &adev->dm.da_list, list) {
1764 		if (pvMem == da->cpu_ptr) {
1765 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
1766 			list_del(&da->list);
1767 			kfree(da);
1768 			break;
1769 		}
1770 	}
1771 
1772 }
1773 
1774 static enum dmub_status
1775 dm_dmub_send_vbios_gpint_command(struct amdgpu_device *adev,
1776 				 enum dmub_gpint_command command_code,
1777 				 uint16_t param,
1778 				 uint32_t timeout_us)
1779 {
1780 	union dmub_gpint_data_register reg, test;
1781 	uint32_t i;
1782 
1783 	/* Assume that VBIOS DMUB is ready to take commands */
1784 
1785 	reg.bits.status = 1;
1786 	reg.bits.command_code = command_code;
1787 	reg.bits.param = param;
1788 
1789 	cgs_write_register(adev->dm.cgs_device, 0x34c0 + 0x01f8, reg.all);
1790 
1791 	for (i = 0; i < timeout_us; ++i) {
1792 		udelay(1);
1793 
1794 		/* Check if our GPINT got acked */
1795 		reg.bits.status = 0;
1796 		test = (union dmub_gpint_data_register)
1797 			cgs_read_register(adev->dm.cgs_device, 0x34c0 + 0x01f8);
1798 
1799 		if (test.all == reg.all)
1800 			return DMUB_STATUS_OK;
1801 	}
1802 
1803 	return DMUB_STATUS_TIMEOUT;
1804 }
1805 
1806 static void *dm_dmub_get_vbios_bounding_box(struct amdgpu_device *adev)
1807 {
1808 	void *bb;
1809 	long long addr;
1810 	unsigned int bb_size;
1811 	int i = 0;
1812 	uint16_t chunk;
1813 	enum dmub_gpint_command send_addrs[] = {
1814 		DMUB_GPINT__SET_BB_ADDR_WORD0,
1815 		DMUB_GPINT__SET_BB_ADDR_WORD1,
1816 		DMUB_GPINT__SET_BB_ADDR_WORD2,
1817 		DMUB_GPINT__SET_BB_ADDR_WORD3,
1818 	};
1819 	enum dmub_status ret;
1820 
1821 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1822 	case IP_VERSION(4, 0, 1):
1823 		bb_size = sizeof(struct dml2_soc_bb);
1824 		break;
1825 	case IP_VERSION(4, 2, 0):
1826 		bb_size = sizeof(struct dml2_soc_bb);
1827 		break;
1828 	default:
1829 		return NULL;
1830 	}
1831 
1832 	bb =  dm_allocate_gpu_mem(adev,
1833 				  DC_MEM_ALLOC_TYPE_GART,
1834 				  bb_size,
1835 				  &addr);
1836 	if (!bb)
1837 		return NULL;
1838 
1839 	for (i = 0; i < 4; i++) {
1840 		/* Extract 16-bit chunk */
1841 		chunk = ((uint64_t) addr >> (i * 16)) & 0xFFFF;
1842 		/* Send the chunk */
1843 		ret = dm_dmub_send_vbios_gpint_command(adev, send_addrs[i], chunk, 30000);
1844 		if (ret != DMUB_STATUS_OK)
1845 			goto free_bb;
1846 	}
1847 
1848 	/* Now ask DMUB to copy the bb */
1849 	ret = dm_dmub_send_vbios_gpint_command(adev, DMUB_GPINT__BB_COPY, 1, 200000);
1850 	if (ret != DMUB_STATUS_OK)
1851 		goto free_bb;
1852 
1853 	return bb;
1854 
1855 free_bb:
1856 	dm_free_gpu_mem(adev, DC_MEM_ALLOC_TYPE_GART, (void *) bb);
1857 	return NULL;
1858 
1859 }
1860 
1861 static enum dmub_ips_disable_type dm_get_default_ips_mode(
1862 	struct amdgpu_device *adev)
1863 {
1864 	enum dmub_ips_disable_type ret = DMUB_IPS_ENABLE;
1865 
1866 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1867 	case IP_VERSION(3, 5, 0):
1868 	case IP_VERSION(3, 6, 0):
1869 	case IP_VERSION(3, 5, 1):
1870 		ret =  DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
1871 		break;
1872 	case IP_VERSION(4, 2, 0):
1873 		ret =  DMUB_IPS_ENABLE;
1874 		break;
1875 	default:
1876 		/* ASICs older than DCN35 do not have IPSs */
1877 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 5, 0))
1878 			ret = DMUB_IPS_DISABLE_ALL;
1879 		break;
1880 	}
1881 
1882 	return ret;
1883 }
1884 
1885 static int amdgpu_dm_init_power_module(struct amdgpu_display_manager *dm)
1886 {
1887 	struct mod_power_init_params init_data[MAX_NUM_EDP];
1888 
1889 	if (dm->num_of_edps == 0) {
1890 		drm_dbg_driver(
1891 			dm->ddev,
1892 			"amdgpu: No eDP detected, skip initializing power module\n");
1893 		return 0;
1894 	}
1895 
1896 	/* Initialize all the power module parameters */
1897 	for (int i = 0; i < dm->num_of_edps; i++) {
1898 		init_data[i].allow_psr_smu_optimizations =
1899 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_SMU_OPT);
1900 		init_data[i].allow_psr_multi_disp_optimizations =
1901 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_MULTI_DISP_OPT);
1902 		/* See dm_late_init */
1903 		init_data[i].backlight_ramping_override = false;
1904 		init_data[i].backlight_ramping_start = 0xCCCC;
1905 		init_data[i].backlight_ramping_reduction = 0xCCCCCCCC;
1906 		init_data[i].def_varibright_level = 0;
1907 		init_data[i].abm_config_setting = 0;
1908 		init_data[i].num_backlight_levels = 101;
1909 		init_data[i].use_nits_based_brightness = false;
1910 		init_data[i].panel_max_millinits = 0;
1911 		init_data[i].panel_min_millinits = 0;
1912 		init_data[i].disable_fractional_pwm =
1913 			!(amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK);
1914 		init_data[i].use_custom_backlight_caps = false;
1915 		init_data[i].custom_backlight_caps_config_no = 0;
1916 		init_data[i].use_linear_backlight_curve = false;
1917 		init_data[i].def_varibright_enable = 0;
1918 		init_data[i].varibright_level = 0;
1919 		/*
1920 		 * Power module uses 16-bit backlight levels (0xFFFF max) rather
1921 		 * than 8-bit(0XFF max)
1922 		 */
1923 		init_data[i].min_backlight_pwm =
1924 			dm->backlight_caps[i].min_input_signal * 0x101;
1925 		init_data[i].max_backlight_pwm =
1926 			dm->backlight_caps[i].max_input_signal * 0x101;
1927 		init_data[i].min_abm_backlight =
1928 			dm->backlight_caps[i].min_input_signal * 0x101;
1929 
1930 		/* Min backlight level after ABM reduction,  Don't allow below 1%
1931 		 * 0xFFFF x 0.01 = 0x28F
1932 		 */
1933 		init_data[i].min_abm_backlight = (init_data[i].min_abm_backlight < 0x28F) ?
1934 			0x28F : init_data[i].min_abm_backlight;
1935 	}
1936 
1937 	dm->power_module = mod_power_create(dm->dc, init_data, dm->num_of_edps);
1938 	if (!dm->power_module) {
1939 		drm_err(dm->ddev, "amdgpu: Error allocating memory for power module\n");
1940 		return -ENOMEM;
1941 	}
1942 
1943 	mod_power_hw_init(dm->power_module);
1944 	drm_dbg_driver(dm->ddev, "amdgpu: Power module init done\n");
1945 
1946 	return 0;
1947 }
1948 
1949 static int amdgpu_dm_init(struct amdgpu_device *adev)
1950 {
1951 	struct dc_init_data init_data;
1952 	struct dc_callback_init init_params;
1953 	int r;
1954 
1955 	adev->dm.ddev = adev_to_drm(adev);
1956 	adev->dm.adev = adev;
1957 
1958 	/* Zero all the fields */
1959 	memset(&init_data, 0, sizeof(init_data));
1960 	memset(&init_params, 0, sizeof(init_params));
1961 
1962 	mutex_init(&adev->dm.dpia_aux_lock);
1963 	mutex_init(&adev->dm.dc_lock);
1964 	mutex_init(&adev->dm.audio_lock);
1965 
1966 	spin_lock_init(&adev->dm.dmub_lock);
1967 
1968 	if (amdgpu_dm_irq_init(adev)) {
1969 		drm_err(adev_to_drm(adev), "failed to initialize DM IRQ support.\n");
1970 		goto error;
1971 	}
1972 
1973 	/* special handling for early revisions of GC 11.5.4 */
1974 	if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(11, 5, 4))
1975 		init_data.asic_id.chip_family = AMDGPU_FAMILY_GC_11_5_4;
1976 	else
1977 		init_data.asic_id.chip_family = adev->family;
1978 
1979 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
1980 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
1981 	init_data.asic_id.chip_id = adev->pdev->device;
1982 
1983 	init_data.asic_id.vram_width = adev->gmc.vram_width;
1984 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
1985 	init_data.asic_id.atombios_base_address =
1986 		adev->mode_info.atom_context->bios;
1987 
1988 	init_data.driver = adev;
1989 
1990 	/* cgs_device was created in dm_sw_init() */
1991 	init_data.cgs_device = adev->dm.cgs_device;
1992 
1993 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
1994 
1995 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1996 	case IP_VERSION(2, 1, 0):
1997 		switch (adev->dm.dmcub_fw_version) {
1998 		case 0: /* development */
1999 		case 0x1: /* linux-firmware.git hash 6d9f399 */
2000 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
2001 			init_data.flags.disable_dmcu = false;
2002 			break;
2003 		default:
2004 			init_data.flags.disable_dmcu = true;
2005 		}
2006 		break;
2007 	case IP_VERSION(2, 0, 3):
2008 		init_data.flags.disable_dmcu = true;
2009 		break;
2010 	default:
2011 		break;
2012 	}
2013 
2014 	/* APU support S/G display by default except:
2015 	 * ASICs before Carrizo,
2016 	 * RAVEN1 (Users reported stability issue)
2017 	 */
2018 
2019 	if (adev->asic_type < CHIP_CARRIZO) {
2020 		init_data.flags.gpu_vm_support = false;
2021 	} else if (adev->asic_type == CHIP_RAVEN) {
2022 		if (adev->apu_flags & AMD_APU_IS_RAVEN)
2023 			init_data.flags.gpu_vm_support = false;
2024 		else
2025 			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
2026 	} else {
2027 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(2, 0, 3))
2028 			init_data.flags.gpu_vm_support = (amdgpu_sg_display == 1);
2029 		else
2030 			init_data.flags.gpu_vm_support =
2031 				(amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
2032 	}
2033 
2034 	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
2035 
2036 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
2037 		init_data.flags.fbc_support = true;
2038 
2039 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
2040 		init_data.flags.multi_mon_pp_mclk_switch = true;
2041 
2042 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
2043 		init_data.flags.disable_fractional_pwm = true;
2044 
2045 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
2046 		init_data.flags.edp_no_power_sequencing = true;
2047 
2048 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
2049 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
2050 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
2051 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
2052 
2053 	init_data.flags.seamless_boot_edp_requested = false;
2054 
2055 	if (amdgpu_device_seamless_boot_supported(adev)) {
2056 		init_data.flags.seamless_boot_edp_requested = true;
2057 		init_data.flags.allow_seamless_boot_optimization = true;
2058 		drm_dbg(adev->dm.ddev, "Seamless boot requested\n");
2059 	}
2060 
2061 	init_data.flags.enable_mipi_converter_optimization = true;
2062 
2063 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
2064 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
2065 	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
2066 
2067 	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
2068 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
2069 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS_DYNAMIC)
2070 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_DYNAMIC;
2071 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS2_DYNAMIC)
2072 		init_data.flags.disable_ips = DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
2073 	else if (amdgpu_dc_debug_mask & DC_FORCE_IPS_ENABLE)
2074 		init_data.flags.disable_ips = DMUB_IPS_ENABLE;
2075 	else
2076 		init_data.flags.disable_ips = dm_get_default_ips_mode(adev);
2077 
2078 	init_data.flags.disable_ips_in_vpb = 0;
2079 
2080 	/* DCN35 and above supports dynamic DTBCLK switch */
2081 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 5, 0))
2082 		init_data.flags.allow_0_dtb_clk = true;
2083 
2084 	/* Enable DWB for tested platforms only */
2085 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
2086 		init_data.num_virtual_links = 1;
2087 
2088 	/* DCN42 and above dpia switch to unified link training path */
2089 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 2, 0)) {
2090 		init_data.flags.consolidated_dpia_dp_lt = true;
2091 		init_data.flags.enable_dpia_pre_training = true;
2092 		init_data.flags.unify_link_enc_assignment = true;
2093 		init_data.flags.usb4_bw_alloc_support = true;
2094 	}
2095 	retrieve_dmi_info(&adev->dm);
2096 	if (adev->dm.edp0_on_dp1_quirk)
2097 		init_data.flags.support_edp0_on_dp1 = true;
2098 
2099 	if (adev->dm.bb_from_dmub)
2100 		init_data.bb_from_dmub = adev->dm.bb_from_dmub;
2101 	else
2102 		init_data.bb_from_dmub = NULL;
2103 
2104 	/* Display Core create. */
2105 	adev->dm.dc = dc_create(&init_data);
2106 
2107 	if (adev->dm.dc) {
2108 		drm_info(adev_to_drm(adev), "Display Core v%s initialized on %s\n", DC_VER,
2109 			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
2110 	} else {
2111 		drm_info(adev_to_drm(adev), "Display Core failed to initialize with v%s!\n", DC_VER);
2112 		goto error;
2113 	}
2114 
2115 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
2116 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
2117 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
2118 	}
2119 
2120 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2121 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2122 	if (dm_should_disable_stutter(adev->pdev))
2123 		adev->dm.dc->debug.disable_stutter = true;
2124 
2125 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
2126 		adev->dm.dc->debug.disable_stutter = true;
2127 
2128 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
2129 		adev->dm.dc->debug.disable_dsc = true;
2130 
2131 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
2132 		adev->dm.dc->debug.disable_clock_gate = true;
2133 
2134 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
2135 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
2136 
2137 	if (amdgpu_dc_debug_mask & DC_DISABLE_SUBVP_FAMS) {
2138 		adev->dm.dc->debug.force_disable_subvp = true;
2139 		adev->dm.dc->debug.fams2_config.bits.enable = false;
2140 	}
2141 
2142 	if (amdgpu_dc_debug_mask & DC_ENABLE_DML2) {
2143 		adev->dm.dc->debug.using_dml2 = true;
2144 		adev->dm.dc->debug.using_dml21 = true;
2145 	}
2146 
2147 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_FORCE_FW_ENABLE)
2148 		adev->dm.dc->debug.hdcp_lc_force_fw_enable = true;
2149 
2150 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_ENABLE_SW_FALLBACK)
2151 		adev->dm.dc->debug.hdcp_lc_enable_sw_fallback = true;
2152 
2153 	if (amdgpu_dc_debug_mask & DC_SKIP_DETECTION_LT)
2154 		adev->dm.dc->debug.skip_detection_link_training = true;
2155 
2156 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
2157 
2158 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
2159 	adev->dm.dc->debug.ignore_cable_id = true;
2160 
2161 	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
2162 		drm_info(adev_to_drm(adev), "DP-HDMI FRL PCON supported\n");
2163 
2164 	r = dm_dmub_hw_init(adev);
2165 	if (r) {
2166 		drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
2167 		goto error;
2168 	}
2169 
2170 	dc_hardware_init(adev->dm.dc);
2171 
2172 	adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev);
2173 	if (!adev->dm.hpd_rx_offload_wq) {
2174 		drm_err(adev_to_drm(adev), "failed to create hpd rx offload workqueue.\n");
2175 		goto error;
2176 	}
2177 
2178 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
2179 		struct dc_phy_addr_space_config pa_config;
2180 
2181 		mmhub_read_system_context(adev, &pa_config);
2182 
2183 		// Call the DC init_memory func
2184 		dc_setup_system_context(adev->dm.dc, &pa_config);
2185 	}
2186 
2187 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
2188 	if (!adev->dm.freesync_module) {
2189 		drm_err(adev_to_drm(adev),
2190 		"failed to initialize freesync_module.\n");
2191 	} else
2192 		drm_dbg_driver(adev_to_drm(adev), "freesync_module init done %p.\n",
2193 				adev->dm.freesync_module);
2194 
2195 	amdgpu_dm_init_color_mod();
2196 
2197 	if (adev->dm.dc->caps.max_links > 0) {
2198 		adev->dm.vblank_control_workqueue =
2199 			create_singlethread_workqueue("dm_vblank_control_workqueue");
2200 		if (!adev->dm.vblank_control_workqueue)
2201 			drm_err(adev_to_drm(adev), "failed to initialize vblank_workqueue.\n");
2202 	}
2203 
2204 	if (adev->dm.dc->caps.ips_support &&
2205 	    adev->dm.dc->config.disable_ips != DMUB_IPS_DISABLE_ALL)
2206 		adev->dm.idle_workqueue = idle_create_workqueue(adev);
2207 
2208 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
2209 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
2210 
2211 		if (!adev->dm.hdcp_workqueue)
2212 			drm_err(adev_to_drm(adev), "failed to initialize hdcp_workqueue.\n");
2213 		else
2214 			drm_dbg_driver(adev_to_drm(adev),
2215 				       "hdcp_workqueue init done %p.\n",
2216 				       adev->dm.hdcp_workqueue);
2217 
2218 		dc_init_callbacks(adev->dm.dc, &init_params);
2219 	}
2220 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2221 		init_completion(&adev->dm.dmub_aux_transfer_done);
2222 		adev->dm.dmub_notify = kzalloc_obj(struct dmub_notification);
2223 		if (!adev->dm.dmub_notify) {
2224 			drm_info(adev_to_drm(adev), "fail to allocate adev->dm.dmub_notify");
2225 			goto error;
2226 		}
2227 
2228 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
2229 		if (!adev->dm.delayed_hpd_wq) {
2230 			drm_err(adev_to_drm(adev), "failed to create hpd offload workqueue.\n");
2231 			goto error;
2232 		}
2233 
2234 		amdgpu_dm_outbox_init(adev);
2235 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
2236 			dmub_aux_setconfig_callback, false)) {
2237 			drm_err(adev_to_drm(adev), "fail to register dmub aux callback");
2238 			goto error;
2239 		}
2240 
2241 		for (size_t i = 0; i < ARRAY_SIZE(adev->dm.fused_io); i++)
2242 			init_completion(&adev->dm.fused_io[i].replied);
2243 
2244 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_FUSED_IO,
2245 			dmub_aux_fused_io_callback, false)) {
2246 			drm_err(adev_to_drm(adev), "fail to register dmub fused io callback");
2247 			goto error;
2248 		}
2249 		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
2250 		 * It is expected that DMUB will resend any pending notifications at this point. Note
2251 		 * that hpd and hpd_irq handler registration are deferred to register_hpd_handlers() to
2252 		 * align legacy interface initialization sequence. Connection status will be proactivly
2253 		 * detected once in the amdgpu_dm_initialize_drm_device.
2254 		 */
2255 		dc_enable_dmub_outbox(adev->dm.dc);
2256 
2257 		/* DPIA trace goes to dmesg logs only if outbox is enabled */
2258 		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
2259 			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
2260 	}
2261 
2262 	if (amdgpu_dm_initialize_drm_device(adev)) {
2263 		drm_err(adev_to_drm(adev),
2264 		"failed to initialize sw for display support.\n");
2265 		goto error;
2266 	}
2267 
2268 	if (amdgpu_dm_init_power_module(&adev->dm))
2269 		goto error;
2270 
2271 	/* create fake encoders for MST */
2272 	dm_dp_create_fake_mst_encoders(adev);
2273 
2274 	/* TODO: Add_display_info? */
2275 
2276 	/* TODO use dynamic cursor width */
2277 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
2278 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
2279 
2280 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
2281 		drm_err(adev_to_drm(adev),
2282 		"failed to initialize vblank for display support.\n");
2283 		goto error;
2284 	}
2285 
2286 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2287 	amdgpu_dm_crtc_secure_display_create_contexts(adev);
2288 	if (!adev->dm.secure_display_ctx.crtc_ctx)
2289 		drm_err(adev_to_drm(adev), "failed to initialize secure display contexts.\n");
2290 
2291 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))
2292 		adev->dm.secure_display_ctx.support_mul_roi = true;
2293 
2294 #endif
2295 
2296 	drm_dbg_driver(adev_to_drm(adev), "KMS initialized.\n");
2297 
2298 	return 0;
2299 error:
2300 	amdgpu_dm_fini(adev);
2301 
2302 	return -EINVAL;
2303 }
2304 
2305 static int amdgpu_dm_early_fini(struct amdgpu_ip_block *ip_block)
2306 {
2307 	struct amdgpu_device *adev = ip_block->adev;
2308 
2309 	amdgpu_dm_audio_fini(adev);
2310 
2311 	return 0;
2312 }
2313 
2314 static void amdgpu_dm_fini(struct amdgpu_device *adev)
2315 {
2316 	int i;
2317 
2318 	if (adev->dm.vblank_control_workqueue) {
2319 		destroy_workqueue(adev->dm.vblank_control_workqueue);
2320 		adev->dm.vblank_control_workqueue = NULL;
2321 	}
2322 
2323 	if (adev->dm.idle_workqueue) {
2324 		if (adev->dm.idle_workqueue->running) {
2325 			adev->dm.idle_workqueue->enable = false;
2326 			flush_work(&adev->dm.idle_workqueue->work);
2327 		}
2328 
2329 		kfree(adev->dm.idle_workqueue);
2330 		adev->dm.idle_workqueue = NULL;
2331 	}
2332 
2333 	/*
2334 	 * Disable ISM before dc_destroy() invalidates dm->dc.
2335 	 *
2336 	 * Quiesce workers first without dc_lock (they take dc_lock
2337 	 * themselves, so syncing under it would deadlock), then drive the
2338 	 * FSM back to FULL_POWER_RUNNING under dc_lock.
2339 	 */
2340 	amdgpu_dm_ism_disable(&adev->dm);
2341 	scoped_guard(mutex, &adev->dm.dc_lock)
2342 		amdgpu_dm_ism_force_full_power(&adev->dm);
2343 
2344 	amdgpu_dm_destroy_drm_device(&adev->dm);
2345 
2346 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2347 	if (adev->dm.secure_display_ctx.crtc_ctx) {
2348 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
2349 			if (adev->dm.secure_display_ctx.crtc_ctx[i].crtc) {
2350 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].notify_ta_work);
2351 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].forward_roi_work);
2352 			}
2353 		}
2354 		kfree(adev->dm.secure_display_ctx.crtc_ctx);
2355 		adev->dm.secure_display_ctx.crtc_ctx = NULL;
2356 	}
2357 #endif
2358 	if (adev->dm.hdcp_workqueue) {
2359 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
2360 		adev->dm.hdcp_workqueue = NULL;
2361 	}
2362 
2363 	if (adev->dm.dc) {
2364 		dc_deinit_callbacks(adev->dm.dc);
2365 		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
2366 		if (dc_enable_dmub_notifications(adev->dm.dc)) {
2367 			kfree(adev->dm.dmub_notify);
2368 			adev->dm.dmub_notify = NULL;
2369 			destroy_workqueue(adev->dm.delayed_hpd_wq);
2370 			adev->dm.delayed_hpd_wq = NULL;
2371 		}
2372 	}
2373 
2374 	if (adev->dm.dmub_bo)
2375 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
2376 				      &adev->dm.dmub_bo_gpu_addr,
2377 				      &adev->dm.dmub_bo_cpu_addr);
2378 
2379 	if (adev->dm.boot_time_crc_info.bo_ptr)
2380 		amdgpu_bo_free_kernel(&adev->dm.boot_time_crc_info.bo_ptr,
2381 					&adev->dm.boot_time_crc_info.gpu_addr,
2382 					&adev->dm.boot_time_crc_info.cpu_addr);
2383 
2384 	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
2385 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
2386 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
2387 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
2388 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
2389 			}
2390 		}
2391 
2392 		kfree(adev->dm.hpd_rx_offload_wq);
2393 		adev->dm.hpd_rx_offload_wq = NULL;
2394 	}
2395 
2396 	/* DC Destroy TODO: Replace destroy DAL */
2397 	if (adev->dm.dc)
2398 		dc_destroy(&adev->dm.dc);
2399 	/*
2400 	 * TODO: pageflip, vlank interrupt
2401 	 *
2402 	 * amdgpu_dm_irq_fini(adev);
2403 	 */
2404 
2405 	if (adev->dm.cgs_device) {
2406 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
2407 		adev->dm.cgs_device = NULL;
2408 	}
2409 	if (adev->dm.freesync_module) {
2410 		mod_freesync_destroy(adev->dm.freesync_module);
2411 		adev->dm.freesync_module = NULL;
2412 	}
2413 
2414 	if (adev->dm.power_module) {
2415 		mod_power_destroy(adev->dm.power_module);
2416 		adev->dm.power_module = NULL;
2417 	}
2418 	mutex_destroy(&adev->dm.audio_lock);
2419 	mutex_destroy(&adev->dm.dc_lock);
2420 	mutex_destroy(&adev->dm.dpia_aux_lock);
2421 }
2422 
2423 static int load_dmcu_fw(struct amdgpu_device *adev)
2424 {
2425 	const char *fw_name_dmcu = NULL;
2426 	int r;
2427 	const struct dmcu_firmware_header_v1_0 *hdr;
2428 
2429 	switch (adev->asic_type) {
2430 #if defined(CONFIG_DRM_AMD_DC_SI)
2431 	case CHIP_TAHITI:
2432 	case CHIP_PITCAIRN:
2433 	case CHIP_VERDE:
2434 	case CHIP_OLAND:
2435 #endif
2436 	case CHIP_BONAIRE:
2437 	case CHIP_HAWAII:
2438 	case CHIP_KAVERI:
2439 	case CHIP_KABINI:
2440 	case CHIP_MULLINS:
2441 	case CHIP_TONGA:
2442 	case CHIP_FIJI:
2443 	case CHIP_CARRIZO:
2444 	case CHIP_STONEY:
2445 	case CHIP_POLARIS11:
2446 	case CHIP_POLARIS10:
2447 	case CHIP_POLARIS12:
2448 	case CHIP_VEGAM:
2449 	case CHIP_VEGA10:
2450 	case CHIP_VEGA12:
2451 	case CHIP_VEGA20:
2452 		return 0;
2453 	case CHIP_NAVI12:
2454 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
2455 		break;
2456 	case CHIP_RAVEN:
2457 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
2458 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2459 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
2460 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2461 		else
2462 			return 0;
2463 		break;
2464 	default:
2465 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2466 		case IP_VERSION(2, 0, 2):
2467 		case IP_VERSION(2, 0, 3):
2468 		case IP_VERSION(2, 0, 0):
2469 		case IP_VERSION(2, 1, 0):
2470 		case IP_VERSION(3, 0, 0):
2471 		case IP_VERSION(3, 0, 2):
2472 		case IP_VERSION(3, 0, 3):
2473 		case IP_VERSION(3, 0, 1):
2474 		case IP_VERSION(3, 1, 2):
2475 		case IP_VERSION(3, 1, 3):
2476 		case IP_VERSION(3, 1, 4):
2477 		case IP_VERSION(3, 1, 5):
2478 		case IP_VERSION(3, 1, 6):
2479 		case IP_VERSION(3, 2, 0):
2480 		case IP_VERSION(3, 2, 1):
2481 		case IP_VERSION(3, 5, 0):
2482 		case IP_VERSION(3, 5, 1):
2483 		case IP_VERSION(3, 6, 0):
2484 		case IP_VERSION(4, 0, 1):
2485 		case IP_VERSION(4, 2, 0):
2486 			return 0;
2487 		default:
2488 			break;
2489 		}
2490 		drm_err(adev_to_drm(adev), "Unsupported ASIC type: 0x%X\n", adev->asic_type);
2491 		return -EINVAL;
2492 	}
2493 
2494 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
2495 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not supported on direct or SMU loading\n");
2496 		return 0;
2497 	}
2498 
2499 	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, AMDGPU_UCODE_REQUIRED,
2500 				 "%s", fw_name_dmcu);
2501 	if (r == -ENODEV) {
2502 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
2503 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not found\n");
2504 		adev->dm.fw_dmcu = NULL;
2505 		return 0;
2506 	}
2507 	if (r) {
2508 		drm_err(adev_to_drm(adev), "amdgpu_dm: Can't validate firmware \"%s\"\n",
2509 			fw_name_dmcu);
2510 		amdgpu_ucode_release(&adev->dm.fw_dmcu);
2511 		return r;
2512 	}
2513 
2514 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
2515 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
2516 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
2517 	adev->firmware.fw_size +=
2518 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2519 
2520 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
2521 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
2522 	adev->firmware.fw_size +=
2523 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2524 
2525 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
2526 
2527 	drm_dbg_kms(adev_to_drm(adev), "PSP loading DMCU firmware\n");
2528 
2529 	return 0;
2530 }
2531 
2532 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
2533 {
2534 	struct amdgpu_device *adev = ctx;
2535 
2536 	return dm_read_reg(adev->dm.dc->ctx, address);
2537 }
2538 
2539 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
2540 				     uint32_t value)
2541 {
2542 	struct amdgpu_device *adev = ctx;
2543 
2544 	return dm_write_reg(adev->dm.dc->ctx, address, value);
2545 }
2546 
2547 static int dm_dmub_sw_init(struct amdgpu_device *adev)
2548 {
2549 	struct dmub_srv_create_params create_params;
2550 	struct dmub_srv_fw_meta_info_params fw_meta_info_params;
2551 	struct dmub_srv_region_params region_params;
2552 	struct dmub_srv_region_info region_info;
2553 	struct dmub_srv_memory_params memory_params;
2554 	struct dmub_fw_meta_info fw_info;
2555 	struct dmub_srv_fb_info *fb_info;
2556 	struct dmub_srv *dmub_srv;
2557 	const struct dmcub_firmware_header_v1_0 *hdr;
2558 	enum dmub_asic dmub_asic;
2559 	enum dmub_status status;
2560 	static enum dmub_window_memory_type window_memory_type[DMUB_WINDOW_TOTAL] = {
2561 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_0_INST_CONST
2562 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_1_STACK
2563 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_2_BSS_DATA
2564 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_3_VBIOS
2565 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_4_MAILBOX
2566 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_5_TRACEBUFF
2567 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_6_FW_STATE
2568 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_7_SCRATCH_MEM
2569 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_IB_MEM
2570 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_SHARED_STATE
2571 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_LSDMA_BUFFER
2572 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_CURSOR_OFFLOAD
2573 	};
2574 	int r;
2575 
2576 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2577 	case IP_VERSION(2, 1, 0):
2578 		dmub_asic = DMUB_ASIC_DCN21;
2579 		break;
2580 	case IP_VERSION(3, 0, 0):
2581 		dmub_asic = DMUB_ASIC_DCN30;
2582 		break;
2583 	case IP_VERSION(3, 0, 1):
2584 		dmub_asic = DMUB_ASIC_DCN301;
2585 		break;
2586 	case IP_VERSION(3, 0, 2):
2587 		dmub_asic = DMUB_ASIC_DCN302;
2588 		break;
2589 	case IP_VERSION(3, 0, 3):
2590 		dmub_asic = DMUB_ASIC_DCN303;
2591 		break;
2592 	case IP_VERSION(3, 1, 2):
2593 	case IP_VERSION(3, 1, 3):
2594 		dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
2595 		break;
2596 	case IP_VERSION(3, 1, 4):
2597 		dmub_asic = DMUB_ASIC_DCN314;
2598 		break;
2599 	case IP_VERSION(3, 1, 5):
2600 		dmub_asic = DMUB_ASIC_DCN315;
2601 		break;
2602 	case IP_VERSION(3, 1, 6):
2603 		dmub_asic = DMUB_ASIC_DCN316;
2604 		break;
2605 	case IP_VERSION(3, 2, 0):
2606 		dmub_asic = DMUB_ASIC_DCN32;
2607 		break;
2608 	case IP_VERSION(3, 2, 1):
2609 		dmub_asic = DMUB_ASIC_DCN321;
2610 		break;
2611 	case IP_VERSION(3, 5, 0):
2612 	case IP_VERSION(3, 5, 1):
2613 		dmub_asic = DMUB_ASIC_DCN35;
2614 		break;
2615 	case IP_VERSION(3, 6, 0):
2616 		dmub_asic = DMUB_ASIC_DCN36;
2617 		break;
2618 	case IP_VERSION(4, 0, 1):
2619 		dmub_asic = DMUB_ASIC_DCN401;
2620 		break;
2621 	case IP_VERSION(4, 2, 0):
2622 		dmub_asic = DMUB_ASIC_DCN42;
2623 		break;
2624 	default:
2625 		/* ASIC doesn't support DMUB. */
2626 		return 0;
2627 	}
2628 
2629 	hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
2630 	adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
2631 
2632 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
2633 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
2634 			AMDGPU_UCODE_ID_DMCUB;
2635 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
2636 			adev->dm.dmub_fw;
2637 		adev->firmware.fw_size +=
2638 			ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
2639 
2640 		drm_info(adev_to_drm(adev), "Loading DMUB firmware via PSP: version=0x%08X\n",
2641 			 adev->dm.dmcub_fw_version);
2642 	}
2643 
2644 
2645 	adev->dm.dmub_srv = kzalloc_obj(*adev->dm.dmub_srv);
2646 	dmub_srv = adev->dm.dmub_srv;
2647 
2648 	if (!dmub_srv) {
2649 		drm_err(adev_to_drm(adev), "Failed to allocate DMUB service!\n");
2650 		return -ENOMEM;
2651 	}
2652 
2653 	memset(&create_params, 0, sizeof(create_params));
2654 	create_params.user_ctx = adev;
2655 	create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2656 	create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2657 	create_params.asic = dmub_asic;
2658 
2659 	/* Create the DMUB service. */
2660 	status = dmub_srv_create(dmub_srv, &create_params);
2661 	if (status != DMUB_STATUS_OK) {
2662 		drm_err(adev_to_drm(adev), "Error creating DMUB service: %d\n", status);
2663 		return -EINVAL;
2664 	}
2665 
2666 	/* Extract the FW meta info. */
2667 	memset(&fw_meta_info_params, 0, sizeof(fw_meta_info_params));
2668 
2669 	fw_meta_info_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2670 					      PSP_HEADER_BYTES_256;
2671 	fw_meta_info_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2672 	fw_meta_info_params.fw_inst_const = adev->dm.dmub_fw->data +
2673 					    le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2674 					    PSP_HEADER_BYTES_256;
2675 	fw_meta_info_params.fw_bss_data = fw_meta_info_params.bss_data_size ? adev->dm.dmub_fw->data +
2676 					  le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2677 					  le32_to_cpu(hdr->inst_const_bytes) : NULL;
2678 	fw_meta_info_params.custom_psp_footer_size = 0;
2679 
2680 	status = dmub_srv_get_fw_meta_info_from_raw_fw(&fw_meta_info_params, &fw_info);
2681 	if (status != DMUB_STATUS_OK) {
2682 		/* Skip returning early, just log the error. */
2683 		drm_err(adev_to_drm(adev), "Error getting DMUB FW meta info: %d\n", status);
2684 		// return -EINVAL;
2685 	}
2686 
2687 	/* Calculate the size of all the regions for the DMUB service. */
2688 	memset(&region_params, 0, sizeof(region_params));
2689 
2690 	region_params.inst_const_size = fw_meta_info_params.inst_const_size;
2691 	region_params.bss_data_size = fw_meta_info_params.bss_data_size;
2692 	region_params.vbios_size = adev->bios_size;
2693 	region_params.fw_bss_data = fw_meta_info_params.fw_bss_data;
2694 	region_params.fw_inst_const = fw_meta_info_params.fw_inst_const;
2695 	region_params.window_memory_type = window_memory_type;
2696 	region_params.fw_info = (status == DMUB_STATUS_OK) ? &fw_info : NULL;
2697 
2698 	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2699 					   &region_info);
2700 
2701 	if (status != DMUB_STATUS_OK) {
2702 		drm_err(adev_to_drm(adev), "Error calculating DMUB region info: %d\n", status);
2703 		return -EINVAL;
2704 	}
2705 
2706 	/*
2707 	 * Allocate a framebuffer based on the total size of all the regions.
2708 	 * TODO: Move this into GART.
2709 	 */
2710 	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2711 				    AMDGPU_GEM_DOMAIN_VRAM |
2712 				    AMDGPU_GEM_DOMAIN_GTT,
2713 				    &adev->dm.dmub_bo,
2714 				    &adev->dm.dmub_bo_gpu_addr,
2715 				    &adev->dm.dmub_bo_cpu_addr);
2716 	if (r)
2717 		return r;
2718 
2719 	/* Rebase the regions on the framebuffer address. */
2720 	memset(&memory_params, 0, sizeof(memory_params));
2721 	memory_params.cpu_fb_addr = adev->dm.dmub_bo_cpu_addr;
2722 	memory_params.gpu_fb_addr = adev->dm.dmub_bo_gpu_addr;
2723 	memory_params.region_info = &region_info;
2724 	memory_params.window_memory_type = window_memory_type;
2725 
2726 	adev->dm.dmub_fb_info = kzalloc_obj(*adev->dm.dmub_fb_info);
2727 	fb_info = adev->dm.dmub_fb_info;
2728 
2729 	if (!fb_info) {
2730 		drm_err(adev_to_drm(adev),
2731 			"Failed to allocate framebuffer info for DMUB service!\n");
2732 		return -ENOMEM;
2733 	}
2734 
2735 	status = dmub_srv_calc_mem_info(dmub_srv, &memory_params, fb_info);
2736 	if (status != DMUB_STATUS_OK) {
2737 		drm_err(adev_to_drm(adev), "Error calculating DMUB FB info: %d\n", status);
2738 		return -EINVAL;
2739 	}
2740 
2741 	adev->dm.bb_from_dmub = dm_dmub_get_vbios_bounding_box(adev);
2742 	adev->dm.fw_inst_size = fw_meta_info_params.inst_const_size;
2743 
2744 	return 0;
2745 }
2746 
2747 static int dm_sw_init(struct amdgpu_ip_block *ip_block)
2748 {
2749 	struct amdgpu_device *adev = ip_block->adev;
2750 	int r;
2751 
2752 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
2753 
2754 	if (!adev->dm.cgs_device) {
2755 		drm_err(adev_to_drm(adev), "failed to create cgs device.\n");
2756 		return -EINVAL;
2757 	}
2758 
2759 	/* Moved from dm init since we need to use allocations for storing bounding box data */
2760 	INIT_LIST_HEAD(&adev->dm.da_list);
2761 
2762 	r = dm_dmub_sw_init(adev);
2763 	if (r)
2764 		return r;
2765 
2766 	return load_dmcu_fw(adev);
2767 }
2768 
2769 static int dm_sw_fini(struct amdgpu_ip_block *ip_block)
2770 {
2771 	struct amdgpu_device *adev = ip_block->adev;
2772 	struct dal_allocation *da;
2773 
2774 	list_for_each_entry(da, &adev->dm.da_list, list) {
2775 		if (adev->dm.bb_from_dmub == (void *) da->cpu_ptr) {
2776 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
2777 			list_del(&da->list);
2778 			kfree(da);
2779 			adev->dm.bb_from_dmub = NULL;
2780 			break;
2781 		}
2782 	}
2783 
2784 
2785 	kfree(adev->dm.dmub_fb_info);
2786 	adev->dm.dmub_fb_info = NULL;
2787 
2788 	if (adev->dm.dmub_srv) {
2789 		dmub_srv_destroy(adev->dm.dmub_srv);
2790 		kfree(adev->dm.dmub_srv);
2791 		adev->dm.dmub_srv = NULL;
2792 	}
2793 
2794 	amdgpu_ucode_release(&adev->dm.dmub_fw);
2795 	amdgpu_ucode_release(&adev->dm.fw_dmcu);
2796 
2797 	return 0;
2798 }
2799 
2800 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2801 {
2802 	struct amdgpu_dm_connector *aconnector;
2803 	struct drm_connector *connector;
2804 	struct drm_connector_list_iter iter;
2805 	int ret = 0;
2806 
2807 	drm_connector_list_iter_begin(dev, &iter);
2808 	drm_for_each_connector_iter(connector, &iter) {
2809 
2810 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2811 			continue;
2812 
2813 		aconnector = to_amdgpu_dm_connector(connector);
2814 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
2815 		    aconnector->mst_mgr.aux) {
2816 			drm_dbg_kms(dev, "DM_MST: starting TM on aconnector: %p [id: %d]\n",
2817 					 aconnector,
2818 					 aconnector->base.base.id);
2819 
2820 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2821 			if (ret < 0) {
2822 				drm_err(dev, "DM_MST: Failed to start MST\n");
2823 				aconnector->dc_link->type =
2824 					dc_connection_single;
2825 				ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2826 								     aconnector->dc_link);
2827 				break;
2828 			}
2829 		}
2830 	}
2831 	drm_connector_list_iter_end(&iter);
2832 
2833 	return ret;
2834 }
2835 
2836 static void amdgpu_dm_boot_time_crc_init(struct amdgpu_device *adev)
2837 {
2838 	struct dm_boot_time_crc_info *bootcrc_info = NULL;
2839 	struct dmub_srv *dmub = NULL;
2840 	union dmub_fw_boot_options option = {0};
2841 	int ret = 0;
2842 	const uint32_t fb_size = 3 * 1024 * 1024;	/* 3MB for DCC pattern */
2843 
2844 	if (!adev || !adev->dm.dc || !adev->dm.dc->ctx ||
2845 		!adev->dm.dc->ctx->dmub_srv) {
2846 		return;
2847 	}
2848 
2849 	dmub = adev->dm.dc->ctx->dmub_srv->dmub;
2850 	bootcrc_info = &adev->dm.boot_time_crc_info;
2851 
2852 	if (!dmub || !dmub->hw_funcs.get_fw_boot_option) {
2853 		drm_dbg(adev_to_drm(adev), "failed to init boot time crc buffer\n");
2854 		return;
2855 	}
2856 
2857 	option = dmub->hw_funcs.get_fw_boot_option(dmub);
2858 
2859 	/* Return if boot time CRC is not enabled */
2860 	if (option.bits.bootcrc_en_at_S0i3 == 0)
2861 		return;
2862 
2863 	/* Create a buffer for boot time CRC */
2864 	ret = amdgpu_bo_create_kernel(adev, fb_size, PAGE_SIZE,
2865 		AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT,
2866 		&bootcrc_info->bo_ptr,
2867 		&bootcrc_info->gpu_addr,
2868 		&bootcrc_info->cpu_addr);
2869 
2870 	if (ret) {
2871 		drm_dbg(adev_to_drm(adev), "failed to create boot time crc buffer\n");
2872 	} else {
2873 		bootcrc_info->size = fb_size;
2874 
2875 		drm_dbg(adev_to_drm(adev), "boot time crc buffer created addr 0x%llx, size %u\n",
2876 			bootcrc_info->gpu_addr, bootcrc_info->size);
2877 
2878 		/* Send the buffer info to DMUB */
2879 		dc_dmub_srv_boot_time_crc_init(adev->dm.dc,
2880 			bootcrc_info->gpu_addr, bootcrc_info->size);
2881 	}
2882 }
2883 
2884 static int dm_late_init(struct amdgpu_ip_block *ip_block)
2885 {
2886 	struct amdgpu_device *adev = ip_block->adev;
2887 
2888 	struct dmcu_iram_parameters params;
2889 	unsigned int linear_lut[16];
2890 	int i;
2891 	struct dmcu *dmcu = NULL;
2892 
2893 	dmcu = adev->dm.dc->res_pool->dmcu;
2894 
2895 	/* Init the boot time CRC (skip in resume) */
2896 	if ((adev->in_suspend == 0) &&
2897 		(amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(3, 6, 0)))
2898 		amdgpu_dm_boot_time_crc_init(adev);
2899 
2900 	for (i = 0; i < 16; i++)
2901 		linear_lut[i] = 0xFFFF * i / 15;
2902 
2903 	params.set = 0;
2904 	params.backlight_ramping_override = false;
2905 	params.backlight_ramping_start = 0xCCCC;
2906 	params.backlight_ramping_reduction = 0xCCCCCCCC;
2907 	params.backlight_lut_array_size = 16;
2908 	params.backlight_lut_array = linear_lut;
2909 
2910 	/* Min backlight level after ABM reduction,  Don't allow below 1%
2911 	 * 0xFFFF x 0.01 = 0x28F
2912 	 */
2913 	params.min_abm_backlight = 0x28F;
2914 	/* In the case where abm is implemented on dmcub,
2915 	 * dmcu object will be null.
2916 	 * ABM 2.4 and up are implemented on dmcub.
2917 	 */
2918 	if (dmcu) {
2919 		if (!dmcu_load_iram(dmcu, params))
2920 			return -EINVAL;
2921 	} else if (adev->dm.dc->ctx->dmub_srv) {
2922 		struct dc_link *edp_links[MAX_NUM_EDP];
2923 		int edp_num;
2924 
2925 		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
2926 		for (i = 0; i < edp_num; i++) {
2927 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
2928 				return -EINVAL;
2929 		}
2930 	}
2931 
2932 	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
2933 }
2934 
2935 static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
2936 {
2937 	u8 buf[UUID_SIZE];
2938 	guid_t guid;
2939 	int ret;
2940 
2941 	mutex_lock(&mgr->lock);
2942 	if (!mgr->mst_primary)
2943 		goto out_fail;
2944 
2945 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
2946 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2947 		goto out_fail;
2948 	}
2949 
2950 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
2951 				 DP_MST_EN |
2952 				 DP_UP_REQ_EN |
2953 				 DP_UPSTREAM_IS_SRC);
2954 	if (ret < 0) {
2955 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
2956 		goto out_fail;
2957 	}
2958 
2959 	/* Some hubs forget their guids after they resume */
2960 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, buf, sizeof(buf));
2961 	if (ret != sizeof(buf)) {
2962 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2963 		goto out_fail;
2964 	}
2965 
2966 	import_guid(&guid, buf);
2967 
2968 	if (guid_is_null(&guid)) {
2969 		guid_gen(&guid);
2970 		export_guid(buf, &guid);
2971 
2972 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, buf, sizeof(buf));
2973 
2974 		if (ret != sizeof(buf)) {
2975 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
2976 			goto out_fail;
2977 		}
2978 	}
2979 
2980 	guid_copy(&mgr->mst_primary->guid, &guid);
2981 
2982 out_fail:
2983 	mutex_unlock(&mgr->lock);
2984 }
2985 
2986 void hdmi_cec_unset_edid(struct amdgpu_dm_connector *aconnector)
2987 {
2988 	struct cec_notifier *n = aconnector->notifier;
2989 
2990 	if (!n)
2991 		return;
2992 
2993 	cec_notifier_phys_addr_invalidate(n);
2994 }
2995 
2996 void hdmi_cec_set_edid(struct amdgpu_dm_connector *aconnector)
2997 {
2998 	struct drm_connector *connector = &aconnector->base;
2999 	struct cec_notifier *n = aconnector->notifier;
3000 
3001 	if (!n)
3002 		return;
3003 
3004 	cec_notifier_set_phys_addr(n,
3005 				   connector->display_info.source_physical_address);
3006 }
3007 
3008 static void s3_handle_hdmi_cec(struct drm_device *ddev, bool suspend)
3009 {
3010 	struct amdgpu_dm_connector *aconnector;
3011 	struct drm_connector *connector;
3012 	struct drm_connector_list_iter conn_iter;
3013 
3014 	drm_connector_list_iter_begin(ddev, &conn_iter);
3015 	drm_for_each_connector_iter(connector, &conn_iter) {
3016 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3017 			continue;
3018 
3019 		aconnector = to_amdgpu_dm_connector(connector);
3020 		if (suspend)
3021 			hdmi_cec_unset_edid(aconnector);
3022 		else
3023 			hdmi_cec_set_edid(aconnector);
3024 	}
3025 	drm_connector_list_iter_end(&conn_iter);
3026 }
3027 
3028 static void s3_handle_mst(struct drm_device *dev, bool suspend)
3029 {
3030 	struct amdgpu_dm_connector *aconnector;
3031 	struct drm_connector *connector;
3032 	struct drm_connector_list_iter iter;
3033 	struct drm_dp_mst_topology_mgr *mgr;
3034 
3035 	drm_connector_list_iter_begin(dev, &iter);
3036 	drm_for_each_connector_iter(connector, &iter) {
3037 
3038 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3039 			continue;
3040 
3041 		aconnector = to_amdgpu_dm_connector(connector);
3042 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3043 		    aconnector->mst_root)
3044 			continue;
3045 
3046 		mgr = &aconnector->mst_mgr;
3047 
3048 		if (suspend) {
3049 			drm_dp_mst_topology_mgr_suspend(mgr);
3050 		} else {
3051 			/* if extended timeout is supported in hardware,
3052 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
3053 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
3054 			 */
3055 			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
3056 			if (!dp_is_lttpr_present(aconnector->dc_link))
3057 				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
3058 
3059 			/* TODO: move resume_mst_branch_status() into drm mst resume again
3060 			 * once topology probing work is pulled out from mst resume into mst
3061 			 * resume 2nd step. mst resume 2nd step should be called after old
3062 			 * state getting restored (i.e. drm_atomic_helper_resume()).
3063 			 */
3064 			resume_mst_branch_status(mgr);
3065 		}
3066 	}
3067 	drm_connector_list_iter_end(&iter);
3068 }
3069 
3070 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
3071 {
3072 	int ret = 0;
3073 
3074 	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
3075 	 * on window driver dc implementation.
3076 	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
3077 	 * should be passed to smu during boot up and resume from s3.
3078 	 * boot up: dc calculate dcn watermark clock settings within dc_create,
3079 	 * dcn20_resource_construct
3080 	 * then call pplib functions below to pass the settings to smu:
3081 	 * smu_set_watermarks_for_clock_ranges
3082 	 * smu_set_watermarks_table
3083 	 * navi10_set_watermarks_table
3084 	 * smu_write_watermarks_table
3085 	 *
3086 	 * For Renoir, clock settings of dcn watermark are also fixed values.
3087 	 * dc has implemented different flow for window driver:
3088 	 * dc_hardware_init / dc_set_power_state
3089 	 * dcn10_init_hw
3090 	 * notify_wm_ranges
3091 	 * set_wm_ranges
3092 	 * -- Linux
3093 	 * smu_set_watermarks_for_clock_ranges
3094 	 * renoir_set_watermarks_table
3095 	 * smu_write_watermarks_table
3096 	 *
3097 	 * For Linux,
3098 	 * dc_hardware_init -> amdgpu_dm_init
3099 	 * dc_set_power_state --> dm_resume
3100 	 *
3101 	 * therefore, this function apply to navi10/12/14 but not Renoir
3102 	 * *
3103 	 */
3104 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
3105 	case IP_VERSION(2, 0, 2):
3106 	case IP_VERSION(2, 0, 0):
3107 		break;
3108 	default:
3109 		return 0;
3110 	}
3111 
3112 	ret = amdgpu_dpm_write_watermarks_table(adev);
3113 	if (ret) {
3114 		drm_err(adev_to_drm(adev), "Failed to update WMTABLE!\n");
3115 		return ret;
3116 	}
3117 
3118 	return 0;
3119 }
3120 
3121 static int dm_oem_i2c_hw_init(struct amdgpu_device *adev)
3122 {
3123 	struct amdgpu_display_manager *dm = &adev->dm;
3124 	struct amdgpu_i2c_adapter *oem_i2c;
3125 	struct ddc_service *oem_ddc_service;
3126 	int r;
3127 
3128 	oem_ddc_service = dc_get_oem_i2c_device(adev->dm.dc);
3129 	if (oem_ddc_service) {
3130 		oem_i2c = create_i2c(oem_ddc_service, true);
3131 		if (!oem_i2c) {
3132 			drm_info(adev_to_drm(adev), "Failed to create oem i2c adapter data\n");
3133 			return -ENOMEM;
3134 		}
3135 
3136 		r = devm_i2c_add_adapter(adev->dev, &oem_i2c->base);
3137 		if (r) {
3138 			drm_info(adev_to_drm(adev), "Failed to register oem i2c\n");
3139 			kfree(oem_i2c);
3140 			return r;
3141 		}
3142 		dm->oem_i2c = oem_i2c;
3143 	}
3144 
3145 	return 0;
3146 }
3147 
3148 /**
3149  * dm_hw_init() - Initialize DC device
3150  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3151  *
3152  * Initialize the &struct amdgpu_display_manager device. This involves calling
3153  * the initializers of each DM component, then populating the struct with them.
3154  *
3155  * Although the function implies hardware initialization, both hardware and
3156  * software are initialized here. Splitting them out to their relevant init
3157  * hooks is a future TODO item.
3158  *
3159  * Some notable things that are initialized here:
3160  *
3161  * - Display Core, both software and hardware
3162  * - DC modules that we need (freesync and color management)
3163  * - DRM software states
3164  * - Interrupt sources and handlers
3165  * - Vblank support
3166  * - Debug FS entries, if enabled
3167  */
3168 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
3169 {
3170 	struct amdgpu_device *adev = ip_block->adev;
3171 	int r;
3172 
3173 	/* Create DAL display manager */
3174 	r = amdgpu_dm_init(adev);
3175 	if (r)
3176 		return r;
3177 	amdgpu_dm_hpd_init(adev);
3178 
3179 	r = dm_oem_i2c_hw_init(adev);
3180 	if (r)
3181 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
3182 
3183 	return 0;
3184 }
3185 
3186 /**
3187  * dm_hw_fini() - Teardown DC device
3188  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3189  *
3190  * Teardown components within &struct amdgpu_display_manager that require
3191  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
3192  * were loaded. Also flush IRQ workqueues and disable them.
3193  */
3194 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
3195 {
3196 	struct amdgpu_device *adev = ip_block->adev;
3197 
3198 	amdgpu_dm_hpd_fini(adev);
3199 
3200 	amdgpu_dm_irq_fini(adev);
3201 	amdgpu_dm_fini(adev);
3202 	return 0;
3203 }
3204 
3205 
3206 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
3207 				 struct dc_state *state, bool enable)
3208 {
3209 	enum dc_irq_source irq_source;
3210 	struct amdgpu_crtc *acrtc;
3211 	int rc = -EBUSY;
3212 	int i = 0;
3213 
3214 	for (i = 0; i < state->stream_count; i++) {
3215 		acrtc = get_crtc_by_otg_inst(
3216 				adev, state->stream_status[i].primary_otg_inst);
3217 
3218 		if (acrtc && state->stream_status[i].plane_count != 0) {
3219 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
3220 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3221 			if (rc)
3222 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
3223 					 enable ? "enable" : "disable");
3224 
3225 			if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
3226 				if (enable) {
3227 					if (amdgpu_dm_crtc_vrr_active(
3228 							to_dm_crtc_state(acrtc->base.state)))
3229 						rc = amdgpu_dm_crtc_set_vupdate_irq(
3230 							&acrtc->base, true);
3231 				} else
3232 					rc = amdgpu_dm_crtc_set_vupdate_irq(
3233 							&acrtc->base, false);
3234 
3235 				if (rc)
3236 					drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
3237 						enable ? "en" : "dis");
3238 			}
3239 
3240 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3241 			/* During gpu-reset we disable and then enable vblank irq, so
3242 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
3243 			 */
3244 			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
3245 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
3246 		}
3247 	}
3248 
3249 }
3250 
3251 DEFINE_FREE(state_release, struct dc_state *, if (_T) dc_state_release(_T))
3252 
3253 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
3254 {
3255 	struct dc_state *context __free(state_release) = NULL;
3256 	int i;
3257 	struct dc_stream_state *del_streams[MAX_PIPES];
3258 	int del_streams_count = 0;
3259 	struct dc_commit_streams_params params = {};
3260 
3261 	memset(del_streams, 0, sizeof(del_streams));
3262 
3263 	context = dc_state_create_current_copy(dc);
3264 	if (context == NULL)
3265 		return DC_ERROR_UNEXPECTED;
3266 
3267 	/* First remove from context all streams */
3268 	for (i = 0; i < context->stream_count; i++) {
3269 		struct dc_stream_state *stream = context->streams[i];
3270 
3271 		del_streams[del_streams_count++] = stream;
3272 	}
3273 
3274 	/* Remove all planes for removed streams and then remove the streams */
3275 	for (i = 0; i < del_streams_count; i++) {
3276 		enum dc_status res;
3277 
3278 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
3279 			return DC_FAIL_DETACH_SURFACES;
3280 
3281 		res = dc_state_remove_stream(dc, context, del_streams[i]);
3282 		if (res != DC_OK)
3283 			return res;
3284 	}
3285 
3286 	params.streams = context->streams;
3287 	params.stream_count = context->stream_count;
3288 
3289 	return dc_commit_streams(dc, &params);
3290 }
3291 
3292 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
3293 {
3294 	int i;
3295 
3296 	if (dm->hpd_rx_offload_wq) {
3297 		for (i = 0; i < dm->dc->caps.max_links; i++)
3298 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
3299 	}
3300 }
3301 
3302 static int dm_cache_state(struct amdgpu_device *adev)
3303 {
3304 	int r;
3305 
3306 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
3307 	if (IS_ERR(adev->dm.cached_state)) {
3308 		r = PTR_ERR(adev->dm.cached_state);
3309 		adev->dm.cached_state = NULL;
3310 	}
3311 
3312 	return adev->dm.cached_state ? 0 : r;
3313 }
3314 
3315 static void dm_destroy_cached_state(struct amdgpu_device *adev)
3316 {
3317 	struct amdgpu_display_manager *dm = &adev->dm;
3318 	struct drm_device *ddev = adev_to_drm(adev);
3319 	struct dm_plane_state *dm_new_plane_state;
3320 	struct drm_plane_state *new_plane_state;
3321 	struct dm_crtc_state *dm_new_crtc_state;
3322 	struct drm_crtc_state *new_crtc_state;
3323 	struct drm_plane *plane;
3324 	struct drm_crtc *crtc;
3325 	int i;
3326 
3327 	if (!dm->cached_state)
3328 		return;
3329 
3330 	/* Force mode set in atomic commit */
3331 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3332 		new_crtc_state->active_changed = true;
3333 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3334 		reset_freesync_config_for_crtc(dm_new_crtc_state);
3335 	}
3336 
3337 	/*
3338 	 * atomic_check is expected to create the dc states. We need to release
3339 	 * them here, since they were duplicated as part of the suspend
3340 	 * procedure.
3341 	 */
3342 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3343 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3344 		if (dm_new_crtc_state->stream) {
3345 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
3346 			dc_stream_release(dm_new_crtc_state->stream);
3347 			dm_new_crtc_state->stream = NULL;
3348 		}
3349 		dm_new_crtc_state->base.color_mgmt_changed = true;
3350 	}
3351 
3352 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
3353 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
3354 		if (dm_new_plane_state->dc_state) {
3355 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
3356 			dc_plane_state_release(dm_new_plane_state->dc_state);
3357 			dm_new_plane_state->dc_state = NULL;
3358 		}
3359 	}
3360 
3361 	drm_atomic_helper_resume(ddev, dm->cached_state);
3362 
3363 	dm->cached_state = NULL;
3364 }
3365 
3366 static int dm_suspend(struct amdgpu_ip_block *ip_block)
3367 {
3368 	struct amdgpu_device *adev = ip_block->adev;
3369 	struct amdgpu_display_manager *dm = &adev->dm;
3370 
3371 	if (amdgpu_in_reset(adev)) {
3372 		enum dc_status res;
3373 
3374 		/* Quiesce ISM workers before taking dc_lock (workers take
3375 		 * dc_lock themselves; syncing under it would deadlock).
3376 		 */
3377 		amdgpu_dm_ism_disable(dm);
3378 
3379 		mutex_lock(&dm->dc_lock);
3380 
3381 		amdgpu_dm_ism_force_full_power(dm);
3382 		dc_allow_idle_optimizations(adev->dm.dc, false);
3383 
3384 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
3385 
3386 		if (dm->cached_dc_state)
3387 			dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
3388 
3389 		res = amdgpu_dm_commit_zero_streams(dm->dc);
3390 		if (res != DC_OK) {
3391 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
3392 			return -EINVAL;
3393 		}
3394 
3395 		amdgpu_dm_irq_suspend(adev);
3396 
3397 		hpd_rx_irq_work_suspend(dm);
3398 
3399 		return 0;
3400 	}
3401 
3402 	if (!adev->dm.cached_state) {
3403 		int r = dm_cache_state(adev);
3404 
3405 		if (r)
3406 			return r;
3407 	}
3408 
3409 	s3_handle_hdmi_cec(adev_to_drm(adev), true);
3410 
3411 	s3_handle_mst(adev_to_drm(adev), true);
3412 
3413 	amdgpu_dm_irq_suspend(adev);
3414 
3415 	/*
3416 	 * Quiesce ISM workers before taking dc_lock (workers take dc_lock
3417 	 * themselves; syncing under it would deadlock).
3418 	 */
3419 	amdgpu_dm_ism_disable(dm);
3420 	scoped_guard(mutex, &dm->dc_lock)
3421 		amdgpu_dm_ism_force_full_power(dm);
3422 
3423 	hpd_rx_irq_work_suspend(dm);
3424 
3425 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
3426 
3427 	if (dm->dc->caps.ips_support && adev->in_s0ix)
3428 		dc_allow_idle_optimizations(dm->dc, true);
3429 
3430 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
3431 
3432 	return 0;
3433 }
3434 
3435 struct drm_connector *
3436 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_commit *state,
3437 					     struct drm_crtc *crtc)
3438 {
3439 	u32 i;
3440 	struct drm_connector_state *new_con_state;
3441 	struct drm_connector *connector;
3442 	struct drm_crtc *crtc_from_state;
3443 
3444 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3445 		crtc_from_state = new_con_state->crtc;
3446 
3447 		if (crtc_from_state == crtc)
3448 			return connector;
3449 	}
3450 
3451 	return NULL;
3452 }
3453 
3454 static void emulated_link_detect(struct dc_link *link)
3455 {
3456 	struct dc_sink_init_data sink_init_data = { 0 };
3457 	struct display_sink_capability sink_caps = { 0 };
3458 	enum dc_edid_status edid_status;
3459 	struct dc_context *dc_ctx = link->ctx;
3460 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
3461 	struct dc_sink *sink = NULL;
3462 	struct dc_sink *prev_sink = NULL;
3463 
3464 	link->type = dc_connection_none;
3465 	prev_sink = link->local_sink;
3466 
3467 	if (prev_sink)
3468 		dc_sink_release(prev_sink);
3469 
3470 	switch (link->connector_signal) {
3471 	case SIGNAL_TYPE_HDMI_TYPE_A: {
3472 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3473 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
3474 		break;
3475 	}
3476 
3477 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
3478 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3479 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
3480 		break;
3481 	}
3482 
3483 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
3484 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3485 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
3486 		break;
3487 	}
3488 
3489 	case SIGNAL_TYPE_LVDS: {
3490 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3491 		sink_caps.signal = SIGNAL_TYPE_LVDS;
3492 		break;
3493 	}
3494 
3495 	case SIGNAL_TYPE_EDP: {
3496 		sink_caps.transaction_type =
3497 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3498 		sink_caps.signal = SIGNAL_TYPE_EDP;
3499 		break;
3500 	}
3501 
3502 	case SIGNAL_TYPE_DISPLAY_PORT: {
3503 		sink_caps.transaction_type =
3504 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3505 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
3506 		break;
3507 	}
3508 
3509 	default:
3510 		drm_err(dev, "Invalid connector type! signal:%d\n",
3511 			link->connector_signal);
3512 		return;
3513 	}
3514 
3515 	sink_init_data.link = link;
3516 	sink_init_data.sink_signal = sink_caps.signal;
3517 
3518 	sink = dc_sink_create(&sink_init_data);
3519 	if (!sink) {
3520 		drm_err(dev, "Failed to create sink!\n");
3521 		return;
3522 	}
3523 
3524 	/* dc_sink_create returns a new reference */
3525 	link->local_sink = sink;
3526 
3527 	edid_status = dm_helpers_read_local_edid(
3528 			link->ctx,
3529 			link,
3530 			sink);
3531 
3532 	if (edid_status != EDID_OK)
3533 		drm_err(dev, "Failed to read EDID\n");
3534 
3535 }
3536 
3537 static void dm_gpureset_commit_state(struct dc_state *dc_state,
3538 				     struct amdgpu_display_manager *dm)
3539 {
3540 	struct {
3541 		struct dc_surface_update surface_updates[MAX_SURFACES];
3542 		struct dc_plane_info plane_infos[MAX_SURFACES];
3543 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3544 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3545 		struct dc_stream_update stream_update;
3546 	} *bundle __free(kfree);
3547 	int k, m;
3548 
3549 	bundle = kzalloc_obj(*bundle);
3550 
3551 	if (!bundle) {
3552 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
3553 		return;
3554 	}
3555 
3556 	for (k = 0; k < dc_state->stream_count; k++) {
3557 		bundle->stream_update.stream = dc_state->streams[k];
3558 
3559 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
3560 			bundle->surface_updates[m].surface =
3561 				dc_state->stream_status[k].plane_states[m];
3562 			bundle->surface_updates[m].surface->force_full_update =
3563 				true;
3564 		}
3565 
3566 		update_planes_and_stream_adapter(dm->dc,
3567 					 UPDATE_TYPE_FULL,
3568 					 dc_state->stream_status[k].plane_count,
3569 					 dc_state->streams[k],
3570 					 &bundle->stream_update,
3571 					 bundle->surface_updates);
3572 	}
3573 }
3574 
3575 static void apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
3576 					    struct dc_sink *sink)
3577 {
3578 	struct dc_panel_patch *ppatch = NULL;
3579 
3580 	if (!sink)
3581 		return;
3582 
3583 	ppatch = &sink->edid_caps.panel_patch;
3584 	if (ppatch->wait_after_dpcd_poweroff_ms) {
3585 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
3586 		drm_dbg_driver(adev_to_drm(adev),
3587 			       "%s: adding a %ds delay as w/a for panel\n",
3588 			       __func__,
3589 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
3590 	}
3591 }
3592 
3593 /**
3594  * amdgpu_dm_dump_links_and_sinks - Debug dump of all DC links and their sinks
3595  * @adev: amdgpu device pointer
3596  *
3597  * Iterates through all DC links and dumps information about local and remote
3598  * (MST) sinks. Should be called after connector detection is complete to see
3599  * the final state of all links.
3600  */
3601 static void amdgpu_dm_dump_links_and_sinks(struct amdgpu_device *adev)
3602 {
3603 	struct dc *dc = adev->dm.dc;
3604 	struct drm_device *dev = adev_to_drm(adev);
3605 	int li;
3606 
3607 	if (!dc)
3608 		return;
3609 
3610 	for (li = 0; li < dc->link_count; li++) {
3611 		struct dc_link *l = dc->links[li];
3612 		const char *name = NULL;
3613 		int rs;
3614 
3615 		if (!l)
3616 			continue;
3617 		if (l->local_sink && l->local_sink->edid_caps.display_name[0])
3618 			name = l->local_sink->edid_caps.display_name;
3619 		else
3620 			name = "n/a";
3621 
3622 		drm_dbg_kms(dev,
3623 			"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",
3624 			li,
3625 			l->local_sink,
3626 			l->type,
3627 			l->local_sink ? l->local_sink->sink_signal : SIGNAL_TYPE_NONE,
3628 			l->sink_count,
3629 			name,
3630 			l->dpcd_caps.is_mst_capable,
3631 			l->mst_stream_alloc_table.stream_count);
3632 
3633 		/* Dump remote (MST) sinks if any */
3634 		for (rs = 0; rs < l->sink_count; rs++) {
3635 			struct dc_sink *rsink = l->remote_sinks[rs];
3636 			const char *rname = NULL;
3637 
3638 			if (!rsink)
3639 				continue;
3640 			if (rsink->edid_caps.display_name[0])
3641 				rname = rsink->edid_caps.display_name;
3642 			else
3643 				rname = "n/a";
3644 			drm_dbg_kms(dev,
3645 				"  REMOTE_SINK[%d:%d]: sink=%p signal=%d edid_name=%s\n",
3646 				li, rs,
3647 				rsink,
3648 				rsink->sink_signal,
3649 				rname);
3650 		}
3651 	}
3652 }
3653 
3654 static int dm_resume(struct amdgpu_ip_block *ip_block)
3655 {
3656 	struct amdgpu_device *adev = ip_block->adev;
3657 	struct drm_device *ddev = adev_to_drm(adev);
3658 	struct amdgpu_display_manager *dm = &adev->dm;
3659 	struct amdgpu_dm_connector *aconnector;
3660 	struct drm_connector *connector;
3661 	struct drm_connector_list_iter iter;
3662 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
3663 	enum dc_connection_type new_connection_type = dc_connection_none;
3664 	struct dc_state *dc_state;
3665 	int i, r, j;
3666 	struct dc_commit_streams_params commit_params = {};
3667 
3668 	if (dm->dc->caps.ips_support) {
3669 		if (!amdgpu_in_reset(adev))
3670 			mutex_lock(&dm->dc_lock);
3671 
3672 		/* Need to set POWER_STATE_D0 first or it will not execute
3673 		 * idle_power_optimizations command to DMUB.
3674 		 */
3675 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3676 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
3677 
3678 		if (!amdgpu_in_reset(adev))
3679 			mutex_unlock(&dm->dc_lock);
3680 	}
3681 
3682 	if (amdgpu_in_reset(adev)) {
3683 		dc_state = dm->cached_dc_state;
3684 
3685 		/*
3686 		 * The dc->current_state is backed up into dm->cached_dc_state
3687 		 * before we commit 0 streams.
3688 		 *
3689 		 * DC will clear link encoder assignments on the real state
3690 		 * but the changes won't propagate over to the copy we made
3691 		 * before the 0 streams commit.
3692 		 *
3693 		 * DC expects that link encoder assignments are *not* valid
3694 		 * when committing a state, so as a workaround we can copy
3695 		 * off of the current state.
3696 		 *
3697 		 * We lose the previous assignments, but we had already
3698 		 * commit 0 streams anyway.
3699 		 */
3700 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
3701 
3702 		r = dm_dmub_hw_init(adev);
3703 		if (r) {
3704 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
3705 			return r;
3706 		}
3707 
3708 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3709 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3710 
3711 		dc_resume(dm->dc);
3712 
3713 		amdgpu_dm_ism_enable(dm);
3714 		amdgpu_dm_irq_resume_early(adev);
3715 
3716 		for (i = 0; i < dc_state->stream_count; i++) {
3717 			dc_state->streams[i]->mode_changed = true;
3718 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
3719 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
3720 					= 0xffffffff;
3721 			}
3722 		}
3723 
3724 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3725 			amdgpu_dm_outbox_init(adev);
3726 			dc_enable_dmub_outbox(adev->dm.dc);
3727 		}
3728 
3729 		commit_params.streams = dc_state->streams;
3730 		commit_params.stream_count = dc_state->stream_count;
3731 		dc_exit_ips_for_hw_access(dm->dc);
3732 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
3733 
3734 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
3735 
3736 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
3737 
3738 		dc_state_release(dm->cached_dc_state);
3739 		dm->cached_dc_state = NULL;
3740 
3741 		amdgpu_dm_irq_resume_late(adev);
3742 
3743 		mutex_unlock(&dm->dc_lock);
3744 
3745 		/* set the backlight after a reset */
3746 		for (i = 0; i < dm->num_of_edps; i++) {
3747 			if (dm->backlight_dev[i])
3748 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
3749 		}
3750 
3751 		return 0;
3752 	}
3753 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
3754 	dc_state_release(dm_state->context);
3755 	dm_state->context = dc_state_create(dm->dc, NULL);
3756 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
3757 
3758 	/* Before powering on DC we need to re-initialize DMUB. */
3759 	dm_dmub_hw_resume(adev);
3760 
3761 	/* Re-enable outbox interrupts for DPIA. */
3762 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3763 		amdgpu_dm_outbox_init(adev);
3764 		dc_enable_dmub_outbox(adev->dm.dc);
3765 	}
3766 
3767 	/* power on hardware */
3768 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3769 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3770 
3771 	/* program HPD filter */
3772 	dc_resume(dm->dc);
3773 
3774 	scoped_guard(mutex, &dm->dc_lock)
3775 		amdgpu_dm_ism_enable(dm);
3776 
3777 	/*
3778 	 * early enable HPD Rx IRQ, should be done before set mode as short
3779 	 * pulse interrupts are used for MST
3780 	 */
3781 	amdgpu_dm_irq_resume_early(adev);
3782 
3783 	s3_handle_hdmi_cec(ddev, false);
3784 
3785 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
3786 	s3_handle_mst(ddev, false);
3787 
3788 	/* Do detection*/
3789 	drm_connector_list_iter_begin(ddev, &iter);
3790 	drm_for_each_connector_iter(connector, &iter) {
3791 		bool ret;
3792 
3793 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3794 			continue;
3795 
3796 		aconnector = to_amdgpu_dm_connector(connector);
3797 
3798 		if (!aconnector->dc_link)
3799 			continue;
3800 
3801 		/*
3802 		 * this is the case when traversing through already created end sink
3803 		 * MST connectors, should be skipped
3804 		 */
3805 		if (aconnector->mst_root)
3806 			continue;
3807 
3808 		/* Skip eDP detection, when there is no sink present */
3809 		if (aconnector->dc_link->connector_signal == SIGNAL_TYPE_EDP &&
3810 		    !aconnector->dc_link->edp_sink_present)
3811 			continue;
3812 
3813 		guard(mutex)(&aconnector->hpd_lock);
3814 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3815 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3816 
3817 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3818 			emulated_link_detect(aconnector->dc_link);
3819 		} else {
3820 			guard(mutex)(&dm->dc_lock);
3821 			dc_exit_ips_for_hw_access(dm->dc);
3822 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
3823 			if (ret) {
3824 				/* w/a delay for certain panels */
3825 				apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3826 			}
3827 		}
3828 
3829 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
3830 			aconnector->fake_enable = false;
3831 
3832 		if (aconnector->dc_sink)
3833 			dc_sink_release(aconnector->dc_sink);
3834 		aconnector->dc_sink = NULL;
3835 		amdgpu_dm_update_connector_after_detect(aconnector);
3836 	}
3837 	drm_connector_list_iter_end(&iter);
3838 
3839 	dm_destroy_cached_state(adev);
3840 
3841 	/* Do mst topology probing after resuming cached state*/
3842 	drm_connector_list_iter_begin(ddev, &iter);
3843 	drm_for_each_connector_iter(connector, &iter) {
3844 		bool init = false;
3845 
3846 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3847 			continue;
3848 
3849 		aconnector = to_amdgpu_dm_connector(connector);
3850 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3851 		    aconnector->mst_root)
3852 			continue;
3853 
3854 		scoped_guard(mutex, &aconnector->mst_mgr.lock) {
3855 			init = !aconnector->mst_mgr.mst_primary;
3856 		}
3857 		if (init)
3858 			dm_helpers_dp_mst_start_top_mgr(aconnector->dc_link->ctx,
3859 				aconnector->dc_link, false);
3860 		else
3861 			drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
3862 	}
3863 	drm_connector_list_iter_end(&iter);
3864 
3865 	/* Debug dump: list all DC links and their associated sinks after detection
3866 	 * is complete for all connectors. This provides a comprehensive view of the
3867 	 * final state without repeating the dump for each connector.
3868 	 */
3869 	amdgpu_dm_dump_links_and_sinks(adev);
3870 
3871 	amdgpu_dm_irq_resume_late(adev);
3872 
3873 	amdgpu_dm_smu_write_watermarks_table(adev);
3874 
3875 	drm_kms_helper_hotplug_event(ddev);
3876 
3877 	return 0;
3878 }
3879 
3880 /**
3881  * DOC: DM Lifecycle
3882  *
3883  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
3884  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
3885  * the base driver's device list to be initialized and torn down accordingly.
3886  *
3887  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
3888  */
3889 
3890 static const struct amd_ip_funcs amdgpu_dm_funcs = {
3891 	.name = "dm",
3892 	.early_init = dm_early_init,
3893 	.late_init = dm_late_init,
3894 	.sw_init = dm_sw_init,
3895 	.sw_fini = dm_sw_fini,
3896 	.early_fini = amdgpu_dm_early_fini,
3897 	.hw_init = dm_hw_init,
3898 	.hw_fini = dm_hw_fini,
3899 	.suspend = dm_suspend,
3900 	.resume = dm_resume,
3901 	.is_idle = dm_is_idle,
3902 	.wait_for_idle = dm_wait_for_idle,
3903 	.check_soft_reset = dm_check_soft_reset,
3904 	.soft_reset = dm_soft_reset,
3905 	.set_clockgating_state = dm_set_clockgating_state,
3906 	.set_powergating_state = dm_set_powergating_state,
3907 };
3908 
3909 const struct amdgpu_ip_block_version dm_ip_block = {
3910 	.type = AMD_IP_BLOCK_TYPE_DCE,
3911 	.major = 1,
3912 	.minor = 0,
3913 	.rev = 0,
3914 	.funcs = &amdgpu_dm_funcs,
3915 };
3916 
3917 
3918 /**
3919  * DOC: atomic
3920  *
3921  * *WIP*
3922  */
3923 
3924 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
3925 	.fb_create = amdgpu_display_user_framebuffer_create,
3926 	.get_format_info = amdgpu_dm_plane_get_format_info,
3927 	.atomic_check = amdgpu_dm_atomic_check,
3928 	.atomic_commit = drm_atomic_helper_commit,
3929 };
3930 
3931 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
3932 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
3933 	.atomic_commit_setup = amdgpu_dm_atomic_setup_commit,
3934 };
3935 
3936 #define DDC_MANUFACTURERNAME_SAMSUNG 0x2D4C
3937 
3938 static void dm_set_panel_type(struct amdgpu_dm_connector *aconnector)
3939 {
3940 	struct drm_connector *connector = &aconnector->base;
3941 	struct drm_display_info *display_info = &connector->display_info;
3942 	struct dc_link *link = aconnector->dc_link;
3943 	struct amdgpu_device *adev;
3944 
3945 	adev = drm_to_adev(connector->dev);
3946 
3947 	link->panel_type = PANEL_TYPE_NONE;
3948 
3949 	switch (display_info->amd_vsdb.panel_type) {
3950 	case AMD_VSDB_PANEL_TYPE_OLED:
3951 		link->panel_type = PANEL_TYPE_OLED;
3952 		break;
3953 	case AMD_VSDB_PANEL_TYPE_MINILED:
3954 		link->panel_type = PANEL_TYPE_MINILED;
3955 		break;
3956 	}
3957 
3958 	/* If VSDB didn't determine panel type, check DPCD ext caps */
3959 	if (link->panel_type == PANEL_TYPE_NONE) {
3960 		if (link->dpcd_sink_ext_caps.bits.miniled == 1)
3961 			link->panel_type = PANEL_TYPE_MINILED;
3962 		if (link->dpcd_sink_ext_caps.bits.oled == 1)
3963 			link->panel_type = PANEL_TYPE_OLED;
3964 	}
3965 
3966 	/*
3967 	 * TODO: get panel type from DID2 that has device technology field
3968 	 * to specify if it's OLED or not. But we need to wait for DID2
3969 	 * support in DC and EDID parser to be able to use it here.
3970 	 */
3971 
3972 	if (link->panel_type == PANEL_TYPE_NONE) {
3973 		struct drm_amd_vsdb_info *vsdb = &display_info->amd_vsdb;
3974 		u32 lum1_max = vsdb->luminance_range1.max_luminance;
3975 		u32 lum2_max = vsdb->luminance_range2.max_luminance;
3976 
3977 		if (vsdb->version && link->local_sink &&
3978 		    link->local_sink->edid_caps.manufacturer_id ==
3979 		    DDC_MANUFACTURERNAME_SAMSUNG &&
3980 		    lum1_max >= ((lum2_max * 3) / 2))
3981 			link->panel_type = PANEL_TYPE_MINILED;
3982 	}
3983 
3984 	if (link->panel_type == PANEL_TYPE_OLED)
3985 		drm_object_property_set_value(&connector->base,
3986 		    adev_to_drm(adev)->mode_config.panel_type_property,
3987 		    DRM_MODE_PANEL_TYPE_OLED);
3988 	else
3989 		drm_object_property_set_value(&connector->base,
3990 		    adev_to_drm(adev)->mode_config.panel_type_property,
3991 		    DRM_MODE_PANEL_TYPE_UNKNOWN);
3992 
3993 	drm_dbg_kms(aconnector->base.dev, "Panel type: %d\n", link->panel_type);
3994 }
3995 
3996 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
3997 {
3998 	const struct drm_panel_backlight_quirk *panel_backlight_quirk;
3999 	struct amdgpu_dm_backlight_caps *caps;
4000 	struct drm_connector *conn_base;
4001 	struct amdgpu_device *adev;
4002 	struct drm_luminance_range_info *luminance_range;
4003 	struct drm_device *drm;
4004 
4005 	if (aconnector->bl_idx == -1 ||
4006 	    aconnector->dc_link->connector_signal != SIGNAL_TYPE_EDP)
4007 		return;
4008 
4009 	conn_base = &aconnector->base;
4010 	drm = conn_base->dev;
4011 	adev = drm_to_adev(drm);
4012 
4013 	caps = &adev->dm.backlight_caps[aconnector->bl_idx];
4014 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
4015 	caps->aux_support = false;
4016 
4017 	if (caps->ext_caps->bits.oled == 1
4018 	    /*
4019 	     * ||
4020 	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
4021 	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
4022 	     */)
4023 		caps->aux_support = true;
4024 
4025 	if (amdgpu_backlight == 0)
4026 		caps->aux_support = false;
4027 	else if (amdgpu_backlight == 1)
4028 		caps->aux_support = true;
4029 	if (caps->aux_support)
4030 		aconnector->dc_link->backlight_control_type = BACKLIGHT_CONTROL_AMD_AUX;
4031 
4032 	luminance_range = &conn_base->display_info.luminance_range;
4033 
4034 	if (luminance_range->max_luminance)
4035 		caps->aux_max_input_signal = luminance_range->max_luminance;
4036 	else
4037 		caps->aux_max_input_signal = 512;
4038 
4039 	if (luminance_range->min_luminance)
4040 		caps->aux_min_input_signal = luminance_range->min_luminance;
4041 	else
4042 		caps->aux_min_input_signal = 1;
4043 
4044 	panel_backlight_quirk =
4045 		drm_get_panel_backlight_quirk(aconnector->drm_edid);
4046 	if (!IS_ERR_OR_NULL(panel_backlight_quirk)) {
4047 		if (panel_backlight_quirk->min_brightness) {
4048 			caps->min_input_signal =
4049 				panel_backlight_quirk->min_brightness - 1;
4050 			drm_info(drm,
4051 				 "Applying panel backlight quirk, min_brightness: %d\n",
4052 				 caps->min_input_signal);
4053 		}
4054 		if (panel_backlight_quirk->brightness_mask) {
4055 			drm_info(drm,
4056 				 "Applying panel backlight quirk, brightness_mask: 0x%X\n",
4057 				 panel_backlight_quirk->brightness_mask);
4058 			caps->brightness_mask =
4059 				panel_backlight_quirk->brightness_mask;
4060 		}
4061 	}
4062 }
4063 
4064 DEFINE_FREE(sink_release, struct dc_sink *, if (_T) dc_sink_release(_T))
4065 
4066 void amdgpu_dm_update_connector_after_detect(
4067 		struct amdgpu_dm_connector *aconnector)
4068 {
4069 	struct drm_connector *connector = &aconnector->base;
4070 	struct dc_sink *sink __free(sink_release) = NULL;
4071 	struct drm_device *dev = connector->dev;
4072 
4073 	/* MST handled by drm_mst framework */
4074 	if (aconnector->mst_mgr.mst_state == true)
4075 		return;
4076 
4077 	sink = aconnector->dc_link->local_sink;
4078 	if (sink)
4079 		dc_sink_retain(sink);
4080 
4081 	/*
4082 	 * Edid mgmt connector gets first update only in mode_valid hook and then
4083 	 * the connector sink is set to either fake or physical sink depends on link status.
4084 	 * Skip if already done during boot.
4085 	 */
4086 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
4087 			&& aconnector->dc_em_sink) {
4088 
4089 		/*
4090 		 * For S3 resume with headless use eml_sink to fake stream
4091 		 * because on resume connector->sink is set to NULL
4092 		 */
4093 		guard(mutex)(&dev->mode_config.mutex);
4094 
4095 		if (sink) {
4096 			if (aconnector->dc_sink) {
4097 				amdgpu_dm_update_freesync_caps(connector, NULL, true);
4098 				/*
4099 				 * retain and release below are used to
4100 				 * bump up refcount for sink because the link doesn't point
4101 				 * to it anymore after disconnect, so on next crtc to connector
4102 				 * reshuffle by UMD we will get into unwanted dc_sink release
4103 				 */
4104 				dc_sink_release(aconnector->dc_sink);
4105 			}
4106 			aconnector->dc_sink = sink;
4107 			dc_sink_retain(aconnector->dc_sink);
4108 			amdgpu_dm_update_freesync_caps(connector,
4109 					aconnector->drm_edid, true);
4110 		} else {
4111 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4112 			if (!aconnector->dc_sink) {
4113 				aconnector->dc_sink = aconnector->dc_em_sink;
4114 				dc_sink_retain(aconnector->dc_sink);
4115 			}
4116 		}
4117 
4118 		return;
4119 	}
4120 
4121 	/*
4122 	 * TODO: temporary guard to look for proper fix
4123 	 * if this sink is MST sink, we should not do anything
4124 	 */
4125 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
4126 		return;
4127 
4128 	if (aconnector->dc_sink == sink) {
4129 		/*
4130 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
4131 		 * Do nothing!!
4132 		 */
4133 		drm_dbg_kms(dev, "DCHPD: connector_id=%d: dc_sink didn't change.\n",
4134 				 aconnector->connector_id);
4135 		return;
4136 	}
4137 
4138 	drm_dbg_kms(dev, "DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
4139 		    aconnector->connector_id, aconnector->dc_sink, sink);
4140 
4141 	/* When polling, DRM has already locked the mutex for us. */
4142 	if (!drm_kms_helper_is_poll_worker())
4143 		mutex_lock(&dev->mode_config.mutex);
4144 
4145 	/*
4146 	 * 1. Update status of the drm connector
4147 	 * 2. Send an event and let userspace tell us what to do
4148 	 */
4149 	if (sink) {
4150 		/*
4151 		 * TODO: check if we still need the S3 mode update workaround.
4152 		 * If yes, put it here.
4153 		 */
4154 		if (aconnector->dc_sink) {
4155 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4156 			dc_sink_release(aconnector->dc_sink);
4157 		}
4158 
4159 		aconnector->dc_sink = sink;
4160 		dc_sink_retain(aconnector->dc_sink);
4161 		drm_edid_free(aconnector->drm_edid);
4162 		aconnector->drm_edid = NULL;
4163 		if (sink->dc_edid.length == 0) {
4164 			hdmi_cec_unset_edid(aconnector);
4165 			if (aconnector->dc_link->aux_mode) {
4166 				drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4167 			}
4168 		} else {
4169 			const struct edid *edid = (const struct edid *)sink->dc_edid.raw_edid;
4170 
4171 			aconnector->drm_edid = drm_edid_alloc(edid, sink->dc_edid.length);
4172 			drm_edid_connector_update(connector, aconnector->drm_edid);
4173 
4174 			hdmi_cec_set_edid(aconnector);
4175 			if (aconnector->dc_link->aux_mode)
4176 				drm_dp_cec_attach(&aconnector->dm_dp_aux.aux,
4177 						  connector->display_info.source_physical_address);
4178 		}
4179 
4180 		if (!aconnector->timing_requested) {
4181 			aconnector->timing_requested =
4182 				kzalloc_obj(struct dc_crtc_timing);
4183 			if (!aconnector->timing_requested)
4184 				drm_err(dev,
4185 					"failed to create aconnector->requested_timing\n");
4186 		}
4187 
4188 		amdgpu_dm_update_freesync_caps(connector, aconnector->drm_edid, true);
4189 		update_connector_ext_caps(aconnector);
4190 		dm_set_panel_type(aconnector);
4191 	} else {
4192 		hdmi_cec_unset_edid(aconnector);
4193 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4194 		amdgpu_dm_update_freesync_caps(connector, NULL, true);
4195 		aconnector->num_modes = 0;
4196 		dc_sink_release(aconnector->dc_sink);
4197 		aconnector->dc_sink = NULL;
4198 		drm_edid_free(aconnector->drm_edid);
4199 		aconnector->drm_edid = NULL;
4200 		kfree(aconnector->timing_requested);
4201 		aconnector->timing_requested = NULL;
4202 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
4203 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
4204 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
4205 	}
4206 
4207 	update_subconnector_property(aconnector);
4208 
4209 	/* When polling, the mutex will be unlocked for us by DRM. */
4210 	if (!drm_kms_helper_is_poll_worker())
4211 		mutex_unlock(&dev->mode_config.mutex);
4212 }
4213 
4214 static bool are_sinks_equal(const struct dc_sink *sink1, const struct dc_sink *sink2)
4215 {
4216 	if (!sink1 || !sink2)
4217 		return false;
4218 	if (sink1->sink_signal != sink2->sink_signal)
4219 		return false;
4220 
4221 	if (sink1->dc_edid.length != sink2->dc_edid.length)
4222 		return false;
4223 
4224 	if (memcmp(sink1->dc_edid.raw_edid, sink2->dc_edid.raw_edid,
4225 		   sink1->dc_edid.length) != 0)
4226 		return false;
4227 	return true;
4228 }
4229 
4230 
4231 /**
4232  * DOC: hdmi_hpd_debounce_work
4233  *
4234  * HDMI HPD debounce delay in milliseconds. When an HDMI display toggles HPD
4235  * (such as during power save transitions), this delay determines how long to
4236  * wait before processing the HPD event. This allows distinguishing between a
4237  * physical unplug (>hdmi_hpd_debounce_delay)
4238  * and a spontaneous RX HPD toggle (<hdmi_hpd_debounce_delay).
4239  *
4240  * If the toggle is less than this delay, the driver compares sink capabilities
4241  * and permits a hotplug event if they changed.
4242  *
4243  * The default value of 1500ms was chosen based on experimental testing with
4244  * various monitors that exhibit spontaneous HPD toggling behavior.
4245  */
4246 static void hdmi_hpd_debounce_work(struct work_struct *work)
4247 {
4248 	struct amdgpu_dm_connector *aconnector =
4249 		container_of(to_delayed_work(work), struct amdgpu_dm_connector,
4250 			     hdmi_hpd_debounce_work);
4251 	struct drm_connector *connector = &aconnector->base;
4252 	struct drm_device *dev = connector->dev;
4253 	struct amdgpu_device *adev = drm_to_adev(dev);
4254 	struct dc *dc = aconnector->dc_link->ctx->dc;
4255 	bool fake_reconnect = false;
4256 	bool reallow_idle = false;
4257 	bool ret = false;
4258 	guard(mutex)(&aconnector->hpd_lock);
4259 
4260 	/* Re-detect the display */
4261 	scoped_guard(mutex, &adev->dm.dc_lock) {
4262 		if (dc->caps.ips_support && dc->ctx->dmub_srv->idle_allowed) {
4263 			dc_allow_idle_optimizations(dc, false);
4264 			reallow_idle = true;
4265 		}
4266 		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4267 	}
4268 
4269 	if (ret) {
4270 		/* Apply workaround delay for certain panels */
4271 		apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4272 		/* Compare sinks to determine if this was a spontaneous HPD toggle */
4273 		if (are_sinks_equal(aconnector->dc_link->local_sink, aconnector->hdmi_prev_sink)) {
4274 			/*
4275 			* Sinks match - this was a spontaneous HDMI HPD toggle.
4276 			*/
4277 			drm_dbg_kms(dev, "HDMI HPD: Sink unchanged after debounce, internal re-enable\n");
4278 			fake_reconnect = true;
4279 		}
4280 
4281 		/* Update connector state */
4282 		amdgpu_dm_update_connector_after_detect(aconnector);
4283 
4284 		drm_modeset_lock_all(dev);
4285 		dm_restore_drm_connector_state(dev, connector);
4286 		drm_modeset_unlock_all(dev);
4287 
4288 		/* Only notify OS if sink actually changed */
4289 		if (!fake_reconnect && aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4290 			drm_kms_helper_hotplug_event(dev);
4291 	}
4292 
4293 	/* Release the cached sink reference */
4294 	if (aconnector->hdmi_prev_sink) {
4295 		dc_sink_release(aconnector->hdmi_prev_sink);
4296 		aconnector->hdmi_prev_sink = NULL;
4297 	}
4298 
4299 	scoped_guard(mutex, &adev->dm.dc_lock) {
4300 		if (reallow_idle && dc->caps.ips_support)
4301 			dc_allow_idle_optimizations(dc, true);
4302 	}
4303 }
4304 
4305 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
4306 {
4307 	struct drm_connector *connector = &aconnector->base;
4308 	struct drm_device *dev = connector->dev;
4309 	enum dc_connection_type new_connection_type = dc_connection_none;
4310 	struct amdgpu_device *adev = drm_to_adev(dev);
4311 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
4312 	struct dc *dc = aconnector->dc_link->ctx->dc;
4313 	bool ret = false;
4314 	bool debounce_required = false;
4315 
4316 	if (adev->dm.disable_hpd_irq)
4317 		return;
4318 
4319 	/*
4320 	 * In case of failure or MST no need to update connector status or notify the OS
4321 	 * since (for MST case) MST does this in its own context.
4322 	 */
4323 	guard(mutex)(&aconnector->hpd_lock);
4324 
4325 	if (adev->dm.hdcp_workqueue) {
4326 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
4327 		dm_con_state->update_hdcp = true;
4328 	}
4329 	if (aconnector->fake_enable)
4330 		aconnector->fake_enable = false;
4331 
4332 	aconnector->timing_changed = false;
4333 
4334 	if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
4335 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4336 
4337 	/*
4338 	 * Check for HDMI disconnect with debounce enabled.
4339 	 */
4340 	debounce_required = (aconnector->hdmi_hpd_debounce_delay_ms > 0 &&
4341 			      dc_is_hdmi_signal(aconnector->dc_link->connector_signal) &&
4342 			      new_connection_type == dc_connection_none &&
4343 			      aconnector->dc_link->local_sink != NULL);
4344 
4345 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
4346 		emulated_link_detect(aconnector->dc_link);
4347 
4348 		drm_modeset_lock_all(dev);
4349 		dm_restore_drm_connector_state(dev, connector);
4350 		drm_modeset_unlock_all(dev);
4351 
4352 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4353 			drm_kms_helper_connector_hotplug_event(connector);
4354 	} else if (debounce_required) {
4355 		/*
4356 		 * HDMI disconnect detected - schedule delayed work instead of
4357 		 * processing immediately. This allows us to coalesce spurious
4358 		 * HDMI signals from physical unplugs.
4359 		 */
4360 		drm_dbg_kms(dev, "HDMI HPD: Disconnect detected, scheduling debounce work (%u ms)\n",
4361 			    aconnector->hdmi_hpd_debounce_delay_ms);
4362 
4363 		/* Cache the current sink for later comparison */
4364 		if (aconnector->hdmi_prev_sink)
4365 			dc_sink_release(aconnector->hdmi_prev_sink);
4366 		aconnector->hdmi_prev_sink = aconnector->dc_link->local_sink;
4367 		if (aconnector->hdmi_prev_sink)
4368 			dc_sink_retain(aconnector->hdmi_prev_sink);
4369 
4370 		/* Schedule delayed detection. */
4371 		if (mod_delayed_work(system_percpu_wq,
4372 				 &aconnector->hdmi_hpd_debounce_work,
4373 				 msecs_to_jiffies(aconnector->hdmi_hpd_debounce_delay_ms)))
4374 			drm_dbg_kms(dev, "HDMI HPD: Re-scheduled debounce work\n");
4375 
4376 	} else {
4377 
4378 		/* If the aconnector->hdmi_hpd_debounce_work is scheduled, exit early */
4379 		if (delayed_work_pending(&aconnector->hdmi_hpd_debounce_work))
4380 			return;
4381 
4382 		scoped_guard(mutex, &adev->dm.dc_lock) {
4383 			dc_exit_ips_for_hw_access(dc);
4384 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4385 		}
4386 		if (ret) {
4387 			/* w/a delay for certain panels */
4388 			apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4389 			amdgpu_dm_update_connector_after_detect(aconnector);
4390 
4391 			drm_modeset_lock_all(dev);
4392 			dm_restore_drm_connector_state(dev, connector);
4393 			drm_modeset_unlock_all(dev);
4394 
4395 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4396 				drm_kms_helper_connector_hotplug_event(connector);
4397 		}
4398 	}
4399 }
4400 
4401 static void handle_hpd_irq(void *param)
4402 {
4403 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4404 
4405 	handle_hpd_irq_helper(aconnector);
4406 
4407 }
4408 
4409 static void schedule_hpd_rx_offload_work(struct amdgpu_device *adev, struct hpd_rx_irq_offload_work_queue *offload_wq,
4410 							union hpd_irq_data hpd_irq_data)
4411 {
4412 	struct hpd_rx_irq_offload_work *offload_work = kzalloc_obj(*offload_work);
4413 
4414 	if (!offload_work) {
4415 		drm_err(adev_to_drm(adev), "Failed to allocate hpd_rx_irq_offload_work.\n");
4416 		return;
4417 	}
4418 
4419 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
4420 	offload_work->data = hpd_irq_data;
4421 	offload_work->offload_wq = offload_wq;
4422 	offload_work->adev = adev;
4423 
4424 	queue_work(offload_wq->wq, &offload_work->work);
4425 	drm_dbg_kms(adev_to_drm(adev), "queue work to handle hpd_rx offload work");
4426 }
4427 
4428 static void handle_hpd_rx_irq(void *param)
4429 {
4430 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4431 	struct drm_connector *connector = &aconnector->base;
4432 	struct drm_device *dev = connector->dev;
4433 	struct dc_link *dc_link = aconnector->dc_link;
4434 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
4435 	bool result = false;
4436 	enum dc_connection_type new_connection_type = dc_connection_none;
4437 	struct amdgpu_device *adev = drm_to_adev(dev);
4438 	union hpd_irq_data hpd_irq_data;
4439 	bool link_loss = false;
4440 	bool has_left_work = false;
4441 	int idx = dc_link->link_index;
4442 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
4443 	struct dc *dc = aconnector->dc_link->ctx->dc;
4444 
4445 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
4446 
4447 	if (adev->dm.disable_hpd_irq)
4448 		return;
4449 
4450 	/*
4451 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
4452 	 * conflict, after implement i2c helper, this mutex should be
4453 	 * retired.
4454 	 */
4455 	mutex_lock(&aconnector->hpd_lock);
4456 
4457 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
4458 						&link_loss, true, &has_left_work);
4459 
4460 	if (!has_left_work)
4461 		goto out;
4462 
4463 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
4464 		schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4465 		goto out;
4466 	}
4467 
4468 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
4469 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
4470 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
4471 			bool skip = false;
4472 
4473 			/*
4474 			 * DOWN_REP_MSG_RDY is also handled by polling method
4475 			 * mgr->cbs->poll_hpd_irq()
4476 			 */
4477 			spin_lock(&offload_wq->offload_lock);
4478 			skip = offload_wq->is_handling_mst_msg_rdy_event;
4479 
4480 			if (!skip)
4481 				offload_wq->is_handling_mst_msg_rdy_event = true;
4482 
4483 			spin_unlock(&offload_wq->offload_lock);
4484 
4485 			if (!skip)
4486 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4487 
4488 			goto out;
4489 		}
4490 
4491 		if (link_loss) {
4492 			bool skip = false;
4493 
4494 			spin_lock(&offload_wq->offload_lock);
4495 			skip = offload_wq->is_handling_link_loss;
4496 
4497 			if (!skip)
4498 				offload_wq->is_handling_link_loss = true;
4499 
4500 			spin_unlock(&offload_wq->offload_lock);
4501 
4502 			if (!skip)
4503 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4504 
4505 			goto out;
4506 		}
4507 	}
4508 
4509 out:
4510 	if (result && !is_mst_root_connector) {
4511 		/* Downstream Port status changed. */
4512 		if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
4513 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4514 
4515 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4516 			emulated_link_detect(dc_link);
4517 
4518 			if (aconnector->fake_enable)
4519 				aconnector->fake_enable = false;
4520 
4521 			amdgpu_dm_update_connector_after_detect(aconnector);
4522 
4523 
4524 			drm_modeset_lock_all(dev);
4525 			dm_restore_drm_connector_state(dev, connector);
4526 			drm_modeset_unlock_all(dev);
4527 
4528 			drm_kms_helper_connector_hotplug_event(connector);
4529 		} else {
4530 			bool ret = false;
4531 
4532 			mutex_lock(&adev->dm.dc_lock);
4533 			dc_exit_ips_for_hw_access(dc);
4534 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
4535 			mutex_unlock(&adev->dm.dc_lock);
4536 
4537 			if (ret) {
4538 				if (aconnector->fake_enable)
4539 					aconnector->fake_enable = false;
4540 
4541 				amdgpu_dm_update_connector_after_detect(aconnector);
4542 
4543 				drm_modeset_lock_all(dev);
4544 				dm_restore_drm_connector_state(dev, connector);
4545 				drm_modeset_unlock_all(dev);
4546 
4547 				drm_kms_helper_connector_hotplug_event(connector);
4548 			}
4549 		}
4550 	}
4551 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
4552 		if (adev->dm.hdcp_workqueue)
4553 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
4554 	}
4555 
4556 	if (dc_link->type != dc_connection_mst_branch)
4557 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
4558 
4559 	mutex_unlock(&aconnector->hpd_lock);
4560 }
4561 
4562 static int register_hpd_handlers(struct amdgpu_device *adev)
4563 {
4564 	struct drm_device *dev = adev_to_drm(adev);
4565 	struct drm_connector *connector;
4566 	struct amdgpu_dm_connector *aconnector;
4567 	const struct dc_link *dc_link;
4568 	struct dc_interrupt_params int_params = {0};
4569 
4570 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4571 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4572 
4573 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
4574 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD,
4575 			dmub_hpd_callback, true)) {
4576 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4577 			return -EINVAL;
4578 		}
4579 
4580 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ,
4581 			dmub_hpd_callback, true)) {
4582 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4583 			return -EINVAL;
4584 		}
4585 
4586 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_SENSE_NOTIFY,
4587 			dmub_hpd_sense_callback, true)) {
4588 			drm_err(adev_to_drm(adev), "fail to register dmub hpd sense callback");
4589 			return -EINVAL;
4590 		}
4591 	}
4592 
4593 	list_for_each_entry(connector,
4594 			&dev->mode_config.connector_list, head)	{
4595 
4596 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
4597 			continue;
4598 
4599 		aconnector = to_amdgpu_dm_connector(connector);
4600 		dc_link = aconnector->dc_link;
4601 
4602 		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
4603 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4604 			int_params.irq_source = dc_link->irq_source_hpd;
4605 
4606 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4607 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1 ||
4608 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6) {
4609 				drm_err(adev_to_drm(adev), "Failed to register hpd irq!\n");
4610 				return -EINVAL;
4611 			}
4612 
4613 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4614 				handle_hpd_irq, (void *) aconnector))
4615 				return -ENOMEM;
4616 		}
4617 
4618 		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
4619 
4620 			/* Also register for DP short pulse (hpd_rx). */
4621 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4622 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
4623 
4624 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4625 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1RX ||
4626 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6RX) {
4627 				drm_err(adev_to_drm(adev), "Failed to register hpd rx irq!\n");
4628 				return -EINVAL;
4629 			}
4630 
4631 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4632 				handle_hpd_rx_irq, (void *) aconnector))
4633 				return -ENOMEM;
4634 		}
4635 	}
4636 	return 0;
4637 }
4638 
4639 /* Register IRQ sources and initialize IRQ callbacks */
4640 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
4641 {
4642 	struct dc *dc = adev->dm.dc;
4643 	struct common_irq_params *c_irq_params;
4644 	struct dc_interrupt_params int_params = {0};
4645 	int r;
4646 	int i;
4647 	unsigned int src_id;
4648 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4649 	/* Use different interrupts for VBLANK on DCE 6 vs. newer. */
4650 	const unsigned int vblank_d1 =
4651 		adev->dm.dc->ctx->dce_version >= DCE_VERSION_8_0
4652 		? VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0 : 1;
4653 
4654 	if (adev->family >= AMDGPU_FAMILY_AI)
4655 		client_id = SOC15_IH_CLIENTID_DCE;
4656 
4657 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4658 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4659 
4660 	/*
4661 	 * Actions of amdgpu_irq_add_id():
4662 	 * 1. Register a set() function with base driver.
4663 	 *    Base driver will call set() function to enable/disable an
4664 	 *    interrupt in DC hardware.
4665 	 * 2. Register amdgpu_dm_irq_handler().
4666 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4667 	 *    coming from DC hardware.
4668 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4669 	 *    for acknowledging and handling.
4670 	 */
4671 
4672 	/* Use VBLANK interrupt */
4673 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
4674 		src_id = vblank_d1 + i;
4675 		r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->crtc_irq);
4676 		if (r) {
4677 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4678 			return r;
4679 		}
4680 
4681 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4682 		int_params.irq_source =
4683 			dc_interrupt_to_irq_source(dc, src_id, 0);
4684 
4685 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4686 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4687 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4688 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4689 			return -EINVAL;
4690 		}
4691 
4692 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4693 
4694 		c_irq_params->adev = adev;
4695 		c_irq_params->irq_src = int_params.irq_source;
4696 
4697 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4698 			dm_crtc_high_irq, c_irq_params))
4699 			return -ENOMEM;
4700 	}
4701 
4702 	if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
4703 		/* Use VUPDATE interrupt */
4704 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
4705 			src_id = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT + i * 2;
4706 			r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->vupdate_irq);
4707 			if (r) {
4708 				drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4709 				return r;
4710 			}
4711 
4712 			int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4713 			int_params.irq_source =
4714 				dc_interrupt_to_irq_source(dc, src_id, 0);
4715 
4716 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4717 				int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4718 				int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4719 				drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4720 				return -EINVAL;
4721 			}
4722 
4723 			c_irq_params = &adev->dm.vupdate_params[
4724 				int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4725 			c_irq_params->adev = adev;
4726 			c_irq_params->irq_src = int_params.irq_source;
4727 
4728 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4729 				dm_vupdate_high_irq, c_irq_params))
4730 				return -ENOMEM;
4731 		}
4732 	}
4733 
4734 	/* Use GRPH_PFLIP interrupt */
4735 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4736 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4737 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4738 		if (r) {
4739 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4740 			return r;
4741 		}
4742 
4743 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4744 		int_params.irq_source =
4745 			dc_interrupt_to_irq_source(dc, i, 0);
4746 
4747 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4748 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4749 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4750 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4751 			return -EINVAL;
4752 		}
4753 
4754 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4755 
4756 		c_irq_params->adev = adev;
4757 		c_irq_params->irq_src = int_params.irq_source;
4758 
4759 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4760 			dm_pflip_high_irq, c_irq_params))
4761 			return -ENOMEM;
4762 	}
4763 
4764 	/* HPD */
4765 	r = amdgpu_irq_add_id(adev, client_id,
4766 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4767 	if (r) {
4768 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4769 		return r;
4770 	}
4771 
4772 	r = register_hpd_handlers(adev);
4773 
4774 	return r;
4775 }
4776 
4777 /* Register IRQ sources and initialize IRQ callbacks */
4778 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
4779 {
4780 	struct dc *dc = adev->dm.dc;
4781 	struct common_irq_params *c_irq_params;
4782 	struct dc_interrupt_params int_params = {0};
4783 	int r;
4784 	int i;
4785 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4786 	static const unsigned int vrtl_int_srcid[] = {
4787 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
4788 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
4789 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
4790 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
4791 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
4792 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
4793 	};
4794 #endif
4795 
4796 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4797 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4798 
4799 	/*
4800 	 * Actions of amdgpu_irq_add_id():
4801 	 * 1. Register a set() function with base driver.
4802 	 *    Base driver will call set() function to enable/disable an
4803 	 *    interrupt in DC hardware.
4804 	 * 2. Register amdgpu_dm_irq_handler().
4805 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4806 	 *    coming from DC hardware.
4807 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4808 	 *    for acknowledging and handling.
4809 	 */
4810 
4811 	/* Use VSTARTUP interrupt */
4812 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
4813 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
4814 			i++) {
4815 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
4816 
4817 		if (r) {
4818 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4819 			return r;
4820 		}
4821 
4822 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4823 		int_params.irq_source =
4824 			dc_interrupt_to_irq_source(dc, i, 0);
4825 
4826 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4827 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4828 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4829 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4830 			return -EINVAL;
4831 		}
4832 
4833 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4834 
4835 		c_irq_params->adev = adev;
4836 		c_irq_params->irq_src = int_params.irq_source;
4837 
4838 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4839 			dm_crtc_high_irq, c_irq_params))
4840 			return -ENOMEM;
4841 	}
4842 
4843 	/* Use otg vertical line interrupt */
4844 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4845 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
4846 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
4847 				vrtl_int_srcid[i], &adev->vline0_irq);
4848 
4849 		if (r) {
4850 			drm_err(adev_to_drm(adev), "Failed to add vline0 irq id!\n");
4851 			return r;
4852 		}
4853 
4854 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4855 		int_params.irq_source =
4856 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
4857 
4858 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4859 			int_params.irq_source < DC_IRQ_SOURCE_DC1_VLINE0 ||
4860 			int_params.irq_source > DC_IRQ_SOURCE_DC6_VLINE0) {
4861 			drm_err(adev_to_drm(adev), "Failed to register vline0 irq!\n");
4862 			return -EINVAL;
4863 		}
4864 
4865 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
4866 					- DC_IRQ_SOURCE_DC1_VLINE0];
4867 
4868 		c_irq_params->adev = adev;
4869 		c_irq_params->irq_src = int_params.irq_source;
4870 
4871 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4872 			dm_dcn_vertical_interrupt0_high_irq,
4873 			c_irq_params))
4874 			return -ENOMEM;
4875 	}
4876 #endif
4877 
4878 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
4879 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
4880 	 * to trigger at end of each vblank, regardless of state of the lock,
4881 	 * matching DCE behaviour.
4882 	 */
4883 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
4884 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
4885 	     i++) {
4886 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
4887 
4888 		if (r) {
4889 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4890 			return r;
4891 		}
4892 
4893 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4894 		int_params.irq_source =
4895 			dc_interrupt_to_irq_source(dc, i, 0);
4896 
4897 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4898 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4899 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4900 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4901 			return -EINVAL;
4902 		}
4903 
4904 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4905 
4906 		c_irq_params->adev = adev;
4907 		c_irq_params->irq_src = int_params.irq_source;
4908 
4909 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4910 			dm_vupdate_high_irq, c_irq_params))
4911 			return -ENOMEM;
4912 	}
4913 
4914 	/* Use GRPH_PFLIP interrupt */
4915 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
4916 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
4917 			i++) {
4918 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
4919 		if (r) {
4920 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4921 			return r;
4922 		}
4923 
4924 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4925 		int_params.irq_source =
4926 			dc_interrupt_to_irq_source(dc, i, 0);
4927 
4928 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4929 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4930 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4931 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4932 			return -EINVAL;
4933 		}
4934 
4935 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4936 
4937 		c_irq_params->adev = adev;
4938 		c_irq_params->irq_src = int_params.irq_source;
4939 
4940 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4941 			dm_pflip_high_irq, c_irq_params))
4942 			return -ENOMEM;
4943 	}
4944 
4945 	/* HPD */
4946 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
4947 			&adev->hpd_irq);
4948 	if (r) {
4949 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4950 		return r;
4951 	}
4952 
4953 	r = register_hpd_handlers(adev);
4954 
4955 	return r;
4956 }
4957 /* Register Outbox IRQ sources and initialize IRQ callbacks */
4958 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
4959 {
4960 	struct dc *dc = adev->dm.dc;
4961 	struct common_irq_params *c_irq_params;
4962 	struct dc_interrupt_params int_params = {0};
4963 	int r, i;
4964 
4965 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4966 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4967 
4968 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
4969 			&adev->dmub_outbox_irq);
4970 	if (r) {
4971 		drm_err(adev_to_drm(adev), "Failed to add outbox irq id!\n");
4972 		return r;
4973 	}
4974 
4975 	if (dc->ctx->dmub_srv) {
4976 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
4977 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4978 		int_params.irq_source =
4979 		dc_interrupt_to_irq_source(dc, i, 0);
4980 
4981 		c_irq_params = &adev->dm.dmub_outbox_params[0];
4982 
4983 		c_irq_params->adev = adev;
4984 		c_irq_params->irq_src = int_params.irq_source;
4985 
4986 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4987 			dm_dmub_outbox1_low_irq, c_irq_params))
4988 			return -ENOMEM;
4989 	}
4990 
4991 	return 0;
4992 }
4993 
4994 /*
4995  * Acquires the lock for the atomic state object and returns
4996  * the new atomic state.
4997  *
4998  * This should only be called during atomic check.
4999  */
5000 int dm_atomic_get_state(struct drm_atomic_commit *state,
5001 			struct dm_atomic_state **dm_state)
5002 {
5003 	struct drm_device *dev = state->dev;
5004 	struct amdgpu_device *adev = drm_to_adev(dev);
5005 	struct amdgpu_display_manager *dm = &adev->dm;
5006 	struct drm_private_state *priv_state;
5007 
5008 	if (*dm_state)
5009 		return 0;
5010 
5011 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
5012 	if (IS_ERR(priv_state))
5013 		return PTR_ERR(priv_state);
5014 
5015 	*dm_state = to_dm_atomic_state(priv_state);
5016 
5017 	return 0;
5018 }
5019 
5020 static struct dm_atomic_state *
5021 dm_atomic_get_new_state(struct drm_atomic_commit *state)
5022 {
5023 	struct drm_device *dev = state->dev;
5024 	struct amdgpu_device *adev = drm_to_adev(dev);
5025 	struct amdgpu_display_manager *dm = &adev->dm;
5026 	struct drm_private_obj *obj;
5027 	struct drm_private_state *new_obj_state;
5028 	int i;
5029 
5030 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
5031 		if (obj->funcs == dm->atomic_obj.funcs)
5032 			return to_dm_atomic_state(new_obj_state);
5033 	}
5034 
5035 	return NULL;
5036 }
5037 
5038 static struct drm_private_state *
5039 dm_atomic_duplicate_state(struct drm_private_obj *obj)
5040 {
5041 	struct dm_atomic_state *old_state, *new_state;
5042 
5043 	new_state = kzalloc_obj(*new_state);
5044 	if (!new_state)
5045 		return NULL;
5046 
5047 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
5048 
5049 	old_state = to_dm_atomic_state(obj->state);
5050 
5051 	if (old_state && old_state->context)
5052 		new_state->context = dc_state_create_copy(old_state->context);
5053 
5054 	if (!new_state->context) {
5055 		kfree(new_state);
5056 		return NULL;
5057 	}
5058 
5059 	return &new_state->base;
5060 }
5061 
5062 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
5063 				    struct drm_private_state *state)
5064 {
5065 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
5066 
5067 	if (dm_state && dm_state->context)
5068 		dc_state_release(dm_state->context);
5069 
5070 	kfree(dm_state);
5071 }
5072 
5073 static struct drm_private_state *
5074 dm_atomic_create_state(struct drm_private_obj *obj)
5075 {
5076 	struct amdgpu_device *adev = drm_to_adev(obj->dev);
5077 	struct dm_atomic_state *dm_state;
5078 	struct dc_state *context;
5079 
5080 	dm_state = kzalloc_obj(*dm_state);
5081 	if (!dm_state)
5082 		return ERR_PTR(-ENOMEM);
5083 
5084 	context = dc_state_create_current_copy(adev->dm.dc);
5085 	if (!context) {
5086 		kfree(dm_state);
5087 		return ERR_PTR(-ENOMEM);
5088 	}
5089 
5090 	__drm_atomic_helper_private_obj_create_state(obj, &dm_state->base);
5091 	dm_state->context = context;
5092 
5093 	return &dm_state->base;
5094 }
5095 
5096 static struct drm_private_state_funcs dm_atomic_state_funcs = {
5097 	.atomic_create_state = dm_atomic_create_state,
5098 	.atomic_duplicate_state = dm_atomic_duplicate_state,
5099 	.atomic_destroy_state = dm_atomic_destroy_state,
5100 };
5101 
5102 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
5103 {
5104 	int r;
5105 
5106 	adev->mode_info.mode_config_initialized = true;
5107 
5108 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
5109 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
5110 
5111 	adev_to_drm(adev)->mode_config.max_width = 16384;
5112 	adev_to_drm(adev)->mode_config.max_height = 16384;
5113 
5114 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
5115 	if (adev->asic_type == CHIP_HAWAII)
5116 		/* disable prefer shadow for now due to hibernation issues */
5117 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
5118 	else
5119 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
5120 	/* indicates support for immediate flip */
5121 	adev_to_drm(adev)->mode_config.async_page_flip = true;
5122 
5123 	drm_atomic_private_obj_init(adev_to_drm(adev),
5124 				    &adev->dm.atomic_obj,
5125 				    &dm_atomic_state_funcs);
5126 
5127 	r = amdgpu_display_modeset_create_props(adev);
5128 	if (r)
5129 		return r;
5130 
5131 #ifdef AMD_PRIVATE_COLOR
5132 	if (amdgpu_dm_create_color_properties(adev))
5133 		return -ENOMEM;
5134 #endif
5135 
5136 	r = amdgpu_dm_audio_init(adev);
5137 	if (r)
5138 		return r;
5139 
5140 	return 0;
5141 }
5142 
5143 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
5144 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
5145 #define AMDGPU_DM_MIN_SPREAD ((AMDGPU_DM_DEFAULT_MAX_BACKLIGHT - AMDGPU_DM_DEFAULT_MIN_BACKLIGHT) / 2)
5146 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
5147 
5148 void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
5149 				     int bl_idx)
5150 {
5151 	struct amdgpu_dm_backlight_caps *caps = &dm->backlight_caps[bl_idx];
5152 
5153 	if (caps->caps_valid)
5154 		return;
5155 
5156 #if defined(CONFIG_ACPI)
5157 	amdgpu_acpi_get_backlight_caps(caps);
5158 
5159 	/* validate the firmware value is sane */
5160 	if (caps->caps_valid) {
5161 		int spread = caps->max_input_signal - caps->min_input_signal;
5162 
5163 		if (caps->max_input_signal > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5164 		    caps->min_input_signal < 0 ||
5165 		    spread > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5166 		    spread < AMDGPU_DM_MIN_SPREAD) {
5167 			drm_dbg_kms(adev_to_drm(dm->adev), "DM: Invalid backlight caps: min=%d, max=%d\n",
5168 				      caps->min_input_signal, caps->max_input_signal);
5169 			caps->caps_valid = false;
5170 		}
5171 	}
5172 
5173 	if (!caps->caps_valid) {
5174 		caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5175 		caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5176 		caps->caps_valid = true;
5177 	}
5178 #else
5179 	if (caps->aux_support)
5180 		return;
5181 
5182 	caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5183 	caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5184 	caps->caps_valid = true;
5185 #endif
5186 }
5187 
5188 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
5189 				unsigned int *min, unsigned int *max)
5190 {
5191 	if (!caps)
5192 		return 0;
5193 
5194 	if (caps->aux_support) {
5195 		// Firmware limits are in nits, DC API wants millinits.
5196 		*max = 1000 * caps->aux_max_input_signal;
5197 		*min = 1000 * caps->aux_min_input_signal;
5198 	} else {
5199 		// Firmware limits are 8-bit, PWM control is 16-bit.
5200 		*max = 0x101 * caps->max_input_signal;
5201 		*min = 0x101 * caps->min_input_signal;
5202 	}
5203 	return 1;
5204 }
5205 
5206 /* Rescale from [min..max] to [0..AMDGPU_MAX_BL_LEVEL] */
5207 static inline u32 scale_input_to_fw(int min, int max, u64 input)
5208 {
5209 	return DIV_ROUND_CLOSEST_ULL(input * AMDGPU_MAX_BL_LEVEL, max - min);
5210 }
5211 
5212 /* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [min..max] */
5213 static inline u32 scale_fw_to_input(int min, int max, u64 input)
5214 {
5215 	return min + DIV_ROUND_CLOSEST_ULL(input * (max - min), AMDGPU_MAX_BL_LEVEL);
5216 }
5217 
5218 static void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps,
5219 				      unsigned int min, unsigned int max,
5220 				      uint32_t *user_brightness)
5221 {
5222 	u32 brightness = scale_input_to_fw(min, max, *user_brightness);
5223 	u8 lower_signal, upper_signal, upper_lum, lower_lum, lum;
5224 	int left, right;
5225 
5226 	if (amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)
5227 		return;
5228 
5229 	if (!caps->data_points)
5230 		return;
5231 
5232 	/*
5233 	 * Handle the case where brightness is below the first data point
5234 	 * Interpolate between (0,0) and (first_signal, first_lum)
5235 	 */
5236 	if (brightness < caps->luminance_data[0].input_signal) {
5237 		lum = DIV_ROUND_CLOSEST(caps->luminance_data[0].luminance * brightness,
5238 					caps->luminance_data[0].input_signal);
5239 		goto scale;
5240 	}
5241 
5242 	left = 0;
5243 	right = caps->data_points - 1;
5244 	while (left <= right) {
5245 		int mid = left + (right - left) / 2;
5246 		u8 signal = caps->luminance_data[mid].input_signal;
5247 
5248 		/* Exact match found */
5249 		if (signal == brightness) {
5250 			lum = caps->luminance_data[mid].luminance;
5251 			goto scale;
5252 		}
5253 
5254 		if (signal < brightness)
5255 			left = mid + 1;
5256 		else
5257 			right = mid - 1;
5258 	}
5259 
5260 	/* verify bound */
5261 	if (left >= caps->data_points)
5262 		left = caps->data_points - 1;
5263 
5264 	/* At this point, left > right */
5265 	lower_signal = caps->luminance_data[right].input_signal;
5266 	upper_signal = caps->luminance_data[left].input_signal;
5267 	lower_lum = caps->luminance_data[right].luminance;
5268 	upper_lum = caps->luminance_data[left].luminance;
5269 
5270 	/* interpolate */
5271 	if (right == left || !lower_lum)
5272 		lum = upper_lum;
5273 	else
5274 		lum = lower_lum + DIV_ROUND_CLOSEST((upper_lum - lower_lum) *
5275 						    (brightness - lower_signal),
5276 						    upper_signal - lower_signal);
5277 scale:
5278 	*user_brightness = scale_fw_to_input(min, max,
5279 					     DIV_ROUND_CLOSEST(lum * brightness, 101));
5280 }
5281 
5282 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
5283 					uint32_t brightness)
5284 {
5285 	unsigned int min, max;
5286 
5287 	if (!get_brightness_range(caps, &min, &max))
5288 		return brightness;
5289 
5290 	convert_custom_brightness(caps, min, max, &brightness);
5291 
5292 	// Rescale 0..max to min..max
5293 	return min + DIV_ROUND_CLOSEST_ULL((u64)(max - min) * brightness, max);
5294 }
5295 
5296 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
5297 				      uint32_t brightness)
5298 {
5299 	unsigned int min, max;
5300 
5301 	if (!get_brightness_range(caps, &min, &max))
5302 		return brightness;
5303 
5304 	if (brightness < min)
5305 		return 0;
5306 	// Rescale min..max to 0..max
5307 	return DIV_ROUND_CLOSEST_ULL((u64)max * (brightness - min),
5308 				 max - min);
5309 }
5310 
5311 static struct dc_stream_state *dm_find_stream_with_link(
5312 	struct amdgpu_display_manager *dm,
5313 	struct dc_link *link)
5314 {
5315 	struct dc_state *cur_dc_state = dm->dc->current_state;
5316 	struct dc_stream_state *stream = NULL;
5317 	int i;
5318 
5319 	for (i = 0; i < cur_dc_state->stream_count; i++) {
5320 		stream = cur_dc_state->streams[i];
5321 		if (stream->link == link)
5322 			return stream;
5323 	}
5324 
5325 	return NULL;
5326 }
5327 
5328 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
5329 					 int bl_idx,
5330 					 u32 user_brightness)
5331 {
5332 	struct amdgpu_dm_backlight_caps *caps;
5333 	struct dc_link *link;
5334 	u32 brightness = 0;
5335 	bool rc = false, reallow_idle = false;
5336 	struct drm_connector *connector;
5337 	struct dc_stream_state *stream;
5338 	unsigned int min, max;
5339 
5340 	list_for_each_entry(connector, &dm->ddev->mode_config.connector_list, head) {
5341 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5342 
5343 		if (aconnector->bl_idx != bl_idx)
5344 			continue;
5345 
5346 		/* if connector is off, save the brightness for next time it's on */
5347 		if (!aconnector->base.encoder) {
5348 			dm->brightness[bl_idx] = user_brightness;
5349 			dm->actual_brightness[bl_idx] = 0;
5350 			return;
5351 		}
5352 	}
5353 
5354 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5355 	caps = &dm->backlight_caps[bl_idx];
5356 
5357 	dm->brightness[bl_idx] = user_brightness;
5358 	/* update scratch register */
5359 	if (bl_idx == 0)
5360 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
5361 	brightness = convert_brightness_from_user(caps, dm->brightness[bl_idx]);
5362 	link = (struct dc_link *)dm->backlight_link[bl_idx];
5363 
5364 	/* Apply brightness quirk */
5365 	if (caps->brightness_mask)
5366 		brightness |= caps->brightness_mask;
5367 
5368 	if (trace_amdgpu_dm_brightness_enabled()) {
5369 		trace_amdgpu_dm_brightness(__builtin_return_address(0),
5370 					   user_brightness,
5371 					   brightness,
5372 					   caps->aux_support,
5373 					   power_supply_is_system_supplied() > 0);
5374 	}
5375 
5376 	stream = dm_find_stream_with_link(dm, link);
5377 	if (!stream)
5378 		return;
5379 
5380 	mutex_lock(&dm->dc_lock);
5381 	if (dm->dc->caps.ips_support && dm->dc->ctx->dmub_srv->idle_allowed) {
5382 		dc_allow_idle_optimizations(dm->dc, false);
5383 		reallow_idle = true;
5384 	}
5385 
5386 	if (caps->aux_support) {
5387 		rc = mod_power_set_backlight_nits(dm->power_module, stream, brightness,
5388 			AUX_BL_DEFAULT_TRANSITION_TIME_MS, false, true);
5389 	} else {
5390 		/* power module uses millipercent */
5391 		get_brightness_range(caps, &min, &max);
5392 		brightness = DIV_ROUND_CLOSEST(brightness * 100, (max - min)) * 1000;
5393 		rc = mod_power_set_backlight_percent(dm->power_module, stream,
5394 						     brightness, 0, false);
5395 	}
5396 
5397 	/*
5398 	 * Some kms clients create a ramped backlight transition effect
5399 	 * by rapidly changing the backlight. Yet we must wait on dmcub
5400 	 * fw to exit psr/replay before programming backlight. To
5401 	 * prevent lag, keep disable psr/replay and let the next atomic
5402 	 * flip clear the event.
5403 	 *
5404 	 * ToDo: use ISM to handle rapidly backlight change
5405 	 *
5406 	 * Rapidly backlight change is similar to rapidly cursor events,
5407 	 * which is now handled by ISM. ISM can delay the event until system
5408 	 * is really idle, so we may use ISM to handle backlight change as well.
5409 	 */
5410 	amdgpu_dm_psr_set_event(dm, stream, true,
5411 		psr_event_hw_programming, true);
5412 	amdgpu_dm_replay_set_event(dm, stream, true,
5413 		replay_event_hw_programming, true);
5414 
5415 	if (dm->dc->caps.ips_support && reallow_idle)
5416 		dc_allow_idle_optimizations(dm->dc, true);
5417 
5418 	mutex_unlock(&dm->dc_lock);
5419 
5420 	if (rc)
5421 		dm->actual_brightness[bl_idx] = user_brightness;
5422 }
5423 
5424 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
5425 {
5426 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5427 	int i;
5428 
5429 	for (i = 0; i < dm->num_of_edps; i++) {
5430 		if (bd == dm->backlight_dev[i])
5431 			break;
5432 	}
5433 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5434 		i = 0;
5435 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
5436 
5437 	return 0;
5438 }
5439 
5440 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
5441 					 int bl_idx)
5442 {
5443 	int ret;
5444 	struct amdgpu_dm_backlight_caps caps;
5445 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
5446 
5447 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5448 	caps = dm->backlight_caps[bl_idx];
5449 
5450 	if (caps.aux_support) {
5451 		u32 avg, peak;
5452 
5453 		if (!dc_link_get_backlight_level_nits(link, &avg, &peak))
5454 			return dm->brightness[bl_idx];
5455 		return convert_brightness_to_user(&caps, avg);
5456 	}
5457 
5458 	ret = dc_link_get_backlight_level(link);
5459 
5460 	if (ret == DC_ERROR_UNEXPECTED)
5461 		return dm->brightness[bl_idx];
5462 
5463 	return convert_brightness_to_user(&caps, ret);
5464 }
5465 
5466 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
5467 {
5468 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5469 	int i;
5470 
5471 	for (i = 0; i < dm->num_of_edps; i++) {
5472 		if (bd == dm->backlight_dev[i])
5473 			break;
5474 	}
5475 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5476 		i = 0;
5477 	return amdgpu_dm_backlight_get_level(dm, i);
5478 }
5479 
5480 static const struct backlight_ops amdgpu_dm_backlight_ops = {
5481 	.options = BL_CORE_SUSPENDRESUME,
5482 	.get_brightness = amdgpu_dm_backlight_get_brightness,
5483 	.update_status	= amdgpu_dm_backlight_update_status,
5484 };
5485 
5486 static void
5487 amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector *aconnector)
5488 {
5489 	struct drm_device *drm = aconnector->base.dev;
5490 	struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
5491 	struct backlight_properties props = { 0 };
5492 	struct amdgpu_dm_backlight_caps *caps;
5493 	char bl_name[16];
5494 	int min, max;
5495 	int real_brightness;
5496 	int init_brightness;
5497 
5498 	if (aconnector->bl_idx == -1)
5499 		return;
5500 
5501 	if (!acpi_video_backlight_use_native()) {
5502 		drm_info(drm, "Skipping amdgpu DM backlight registration\n");
5503 		/* Try registering an ACPI video backlight device instead. */
5504 		acpi_video_register_backlight();
5505 		return;
5506 	}
5507 
5508 	caps = &dm->backlight_caps[aconnector->bl_idx];
5509 	if (get_brightness_range(caps, &min, &max)) {
5510 		if (power_supply_is_system_supplied() > 0)
5511 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->ac_level, 100);
5512 		else
5513 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->dc_level, 100);
5514 		/* min is zero, so max needs to be adjusted */
5515 		props.max_brightness = max - min;
5516 		drm_dbg(drm, "Backlight caps: min: %d, max: %d, ac %d, dc %d\n", min, max,
5517 			caps->ac_level, caps->dc_level);
5518 	} else
5519 		props.brightness = props.max_brightness = MAX_BACKLIGHT_LEVEL;
5520 
5521 	init_brightness = props.brightness;
5522 
5523 	if (caps->data_points && !(amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)) {
5524 		drm_info(drm, "Using custom brightness curve\n");
5525 		props.scale = BACKLIGHT_SCALE_NON_LINEAR;
5526 	} else
5527 		props.scale = BACKLIGHT_SCALE_LINEAR;
5528 	props.type = BACKLIGHT_RAW;
5529 
5530 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
5531 		 drm->primary->index + aconnector->bl_idx);
5532 
5533 	dm->backlight_dev[aconnector->bl_idx] =
5534 		backlight_device_register(bl_name, aconnector->base.kdev, dm,
5535 					  &amdgpu_dm_backlight_ops, &props);
5536 	dm->brightness[aconnector->bl_idx] = props.brightness;
5537 
5538 	if (IS_ERR(dm->backlight_dev[aconnector->bl_idx])) {
5539 		drm_err(drm, "DM: Backlight registration failed!\n");
5540 		dm->backlight_dev[aconnector->bl_idx] = NULL;
5541 	} else {
5542 		/*
5543 		 * dm->brightness[x] can be inconsistent just after startup until
5544 		 * ops.get_brightness is called.
5545 		 */
5546 		real_brightness =
5547 			amdgpu_dm_backlight_ops.get_brightness(dm->backlight_dev[aconnector->bl_idx]);
5548 
5549 		if (real_brightness != init_brightness) {
5550 			dm->actual_brightness[aconnector->bl_idx] = real_brightness;
5551 			dm->brightness[aconnector->bl_idx] = real_brightness;
5552 		}
5553 		drm_dbg_driver(drm, "DM: Registered Backlight device: %s\n", bl_name);
5554 	}
5555 }
5556 
5557 static int initialize_plane(struct amdgpu_display_manager *dm,
5558 			    struct amdgpu_mode_info *mode_info, int plane_id,
5559 			    enum drm_plane_type plane_type,
5560 			    const struct dc_plane_cap *plane_cap)
5561 {
5562 	struct drm_plane *plane;
5563 	unsigned long possible_crtcs;
5564 	int ret = 0;
5565 
5566 	plane = kzalloc_obj(struct drm_plane);
5567 	if (!plane) {
5568 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
5569 		return -ENOMEM;
5570 	}
5571 	plane->type = plane_type;
5572 
5573 	/*
5574 	 * HACK: IGT tests expect that the primary plane for a CRTC
5575 	 * can only have one possible CRTC. Only expose support for
5576 	 * any CRTC if they're not going to be used as a primary plane
5577 	 * for a CRTC - like overlay or underlay planes.
5578 	 */
5579 	possible_crtcs = 1 << plane_id;
5580 	if (plane_id >= dm->dc->caps.max_streams)
5581 		possible_crtcs = 0xff;
5582 
5583 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
5584 
5585 	if (ret) {
5586 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
5587 		kfree(plane);
5588 		return ret;
5589 	}
5590 
5591 	if (mode_info)
5592 		mode_info->planes[plane_id] = plane;
5593 
5594 	return ret;
5595 }
5596 
5597 
5598 static void setup_backlight_device(struct amdgpu_display_manager *dm,
5599 				   struct amdgpu_dm_connector *aconnector)
5600 {
5601 	struct amdgpu_dm_backlight_caps *caps;
5602 	struct dc_link *link = aconnector->dc_link;
5603 	int bl_idx = dm->num_of_edps;
5604 
5605 	if (!(link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) ||
5606 	    link->type == dc_connection_none)
5607 		return;
5608 
5609 	if (dm->num_of_edps >= AMDGPU_DM_MAX_NUM_EDP) {
5610 		drm_warn(adev_to_drm(dm->adev), "Too much eDP connections, skipping backlight setup for additional eDPs\n");
5611 		return;
5612 	}
5613 
5614 	aconnector->bl_idx = bl_idx;
5615 
5616 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5617 	dm->backlight_link[bl_idx] = link;
5618 	dm->num_of_edps++;
5619 
5620 	update_connector_ext_caps(aconnector);
5621 	caps = &dm->backlight_caps[aconnector->bl_idx];
5622 
5623 	/* Only offer ABM property when non-OLED and user didn't turn off by module parameter */
5624 	if (caps->ext_caps && !caps->ext_caps->bits.oled && amdgpu_dm_abm_level < 0)
5625 		drm_object_attach_property(&aconnector->base.base,
5626 					   dm->adev->mode_info.abm_level_property,
5627 					   ABM_SYSFS_CONTROL);
5628 }
5629 
5630 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
5631 
5632 
5633 
5634 /*
5635  * In this architecture, the association
5636  * connector -> encoder -> crtc
5637  * id not really requried. The crtc and connector will hold the
5638  * display_index as an abstraction to use with DAL component
5639  *
5640  * Returns 0 on success
5641  */
5642 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
5643 {
5644 	struct amdgpu_display_manager *dm = &adev->dm;
5645 	s32 i;
5646 	struct amdgpu_dm_connector *aconnector = NULL;
5647 	struct amdgpu_encoder *aencoder = NULL;
5648 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5649 	u32 link_cnt;
5650 	s32 primary_planes;
5651 	enum dc_connection_type new_connection_type = dc_connection_none;
5652 	const struct dc_plane_cap *plane;
5653 	bool psr_feature_enabled = false;
5654 	bool replay_feature_enabled = false;
5655 	int max_overlay = dm->dc->caps.max_slave_planes;
5656 
5657 	dm->display_indexes_num = dm->dc->caps.max_streams;
5658 	/* Update the actual used number of crtc */
5659 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
5660 
5661 	amdgpu_dm_set_irq_funcs(adev);
5662 
5663 	link_cnt = dm->dc->caps.max_links;
5664 	if (amdgpu_dm_mode_config_init(dm->adev)) {
5665 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
5666 		return -EINVAL;
5667 	}
5668 
5669 	/* There is one primary plane per CRTC */
5670 	primary_planes = dm->dc->caps.max_streams;
5671 	if (primary_planes > AMDGPU_MAX_PLANES) {
5672 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
5673 		return -EINVAL;
5674 	}
5675 
5676 	/*
5677 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
5678 	 * Order is reversed to match iteration order in atomic check.
5679 	 */
5680 	for (i = (primary_planes - 1); i >= 0; i--) {
5681 		plane = &dm->dc->caps.planes[i];
5682 
5683 		if (initialize_plane(dm, mode_info, i,
5684 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
5685 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
5686 			goto fail;
5687 		}
5688 	}
5689 
5690 	/*
5691 	 * Initialize overlay planes, index starting after primary planes.
5692 	 * These planes have a higher DRM index than the primary planes since
5693 	 * they should be considered as having a higher z-order.
5694 	 * Order is reversed to match iteration order in atomic check.
5695 	 *
5696 	 * Only support DCN for now, and only expose one so we don't encourage
5697 	 * userspace to use up all the pipes.
5698 	 */
5699 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
5700 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
5701 
5702 		/* Do not create overlay if MPO disabled */
5703 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
5704 			break;
5705 
5706 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
5707 			continue;
5708 
5709 		if (!plane->pixel_format_support.argb8888)
5710 			continue;
5711 
5712 		if (max_overlay-- == 0)
5713 			break;
5714 
5715 		if (initialize_plane(dm, NULL, primary_planes + i,
5716 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
5717 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
5718 			goto fail;
5719 		}
5720 	}
5721 
5722 	for (i = 0; i < dm->dc->caps.max_streams; i++)
5723 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
5724 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
5725 			goto fail;
5726 		}
5727 
5728 	/* Use Outbox interrupt */
5729 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5730 	case IP_VERSION(3, 0, 0):
5731 	case IP_VERSION(3, 1, 2):
5732 	case IP_VERSION(3, 1, 3):
5733 	case IP_VERSION(3, 1, 4):
5734 	case IP_VERSION(3, 1, 5):
5735 	case IP_VERSION(3, 1, 6):
5736 	case IP_VERSION(3, 2, 0):
5737 	case IP_VERSION(3, 2, 1):
5738 	case IP_VERSION(2, 1, 0):
5739 	case IP_VERSION(3, 5, 0):
5740 	case IP_VERSION(3, 5, 1):
5741 	case IP_VERSION(3, 6, 0):
5742 	case IP_VERSION(4, 0, 1):
5743 	case IP_VERSION(4, 2, 0):
5744 		if (register_outbox_irq_handlers(dm->adev)) {
5745 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5746 			goto fail;
5747 		}
5748 		break;
5749 	default:
5750 		drm_dbg_kms(adev_to_drm(adev), "Unsupported DCN IP version for outbox: 0x%X\n",
5751 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
5752 	}
5753 
5754 	/* Determine whether to enable PSR support by default. */
5755 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
5756 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5757 		case IP_VERSION(3, 1, 2):
5758 		case IP_VERSION(3, 1, 3):
5759 		case IP_VERSION(3, 1, 4):
5760 		case IP_VERSION(3, 1, 5):
5761 		case IP_VERSION(3, 1, 6):
5762 		case IP_VERSION(3, 2, 0):
5763 		case IP_VERSION(3, 2, 1):
5764 		case IP_VERSION(3, 5, 0):
5765 		case IP_VERSION(3, 5, 1):
5766 		case IP_VERSION(3, 6, 0):
5767 		case IP_VERSION(4, 0, 1):
5768 		case IP_VERSION(4, 2, 0):
5769 			psr_feature_enabled = true;
5770 			break;
5771 		default:
5772 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
5773 			break;
5774 		}
5775 	}
5776 
5777 	/* Determine whether to enable Replay support by default. */
5778 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
5779 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5780 		case IP_VERSION(3, 1, 4):
5781 		case IP_VERSION(3, 2, 0):
5782 		case IP_VERSION(3, 2, 1):
5783 		case IP_VERSION(3, 5, 0):
5784 		case IP_VERSION(3, 5, 1):
5785 		case IP_VERSION(3, 6, 0):
5786 		case IP_VERSION(4, 2, 0):
5787 			replay_feature_enabled = true;
5788 			break;
5789 
5790 		default:
5791 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
5792 			break;
5793 		}
5794 	}
5795 
5796 	if (link_cnt > MAX_LINKS) {
5797 		drm_err(adev_to_drm(adev),
5798 			"KMS: Cannot support more than %d display indexes\n",
5799 				MAX_LINKS);
5800 		goto fail;
5801 	}
5802 
5803 	/* loops over all connectors on the board */
5804 	for (i = 0; i < link_cnt; i++) {
5805 		struct dc_link *link = NULL;
5806 
5807 		link = dc_get_link_at_index(dm->dc, i);
5808 
5809 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
5810 			struct amdgpu_dm_wb_connector *wbcon = kzalloc_obj(*wbcon);
5811 
5812 			if (!wbcon) {
5813 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
5814 				continue;
5815 			}
5816 
5817 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
5818 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
5819 				kfree(wbcon);
5820 				continue;
5821 			}
5822 
5823 			link->psr_settings.psr_feature_enabled = false;
5824 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
5825 
5826 			continue;
5827 		}
5828 
5829 		aconnector = kzalloc_obj(*aconnector);
5830 		if (!aconnector)
5831 			goto fail;
5832 
5833 		aencoder = kzalloc_obj(*aencoder);
5834 		if (!aencoder)
5835 			goto fail;
5836 
5837 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
5838 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
5839 			goto fail;
5840 		}
5841 
5842 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
5843 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
5844 			goto fail;
5845 		}
5846 
5847 		if (dm->hpd_rx_offload_wq)
5848 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
5849 				aconnector;
5850 
5851 		if (!dc_link_detect_connection_type(link, &new_connection_type))
5852 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
5853 
5854 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
5855 			emulated_link_detect(link);
5856 			amdgpu_dm_update_connector_after_detect(aconnector);
5857 		} else {
5858 			bool ret = false;
5859 
5860 			mutex_lock(&dm->dc_lock);
5861 			dc_exit_ips_for_hw_access(dm->dc);
5862 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
5863 			mutex_unlock(&dm->dc_lock);
5864 
5865 			if (ret) {
5866 				amdgpu_dm_update_connector_after_detect(aconnector);
5867 				setup_backlight_device(dm, aconnector);
5868 
5869 				/* Disable PSR if Replay can be enabled */
5870 				if (replay_feature_enabled)
5871 					if (amdgpu_dm_set_replay_caps(link, aconnector))
5872 						psr_feature_enabled = false;
5873 
5874 				if (psr_feature_enabled) {
5875 					amdgpu_dm_set_psr_caps(link, aconnector);
5876 					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",
5877 						 aconnector->base.name,
5878 						 link->psr_settings.psr_feature_enabled,
5879 						 link->psr_settings.psr_version,
5880 						 link->dpcd_caps.psr_info.psr_version,
5881 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
5882 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
5883 				}
5884 			}
5885 		}
5886 		amdgpu_set_panel_orientation(&aconnector->base);
5887 	}
5888 
5889 	/* Debug dump: list all DC links and their associated sinks after detection
5890 	 * is complete for all connectors. This provides a comprehensive view of the
5891 	 * final state without repeating the dump for each connector.
5892 	 */
5893 	amdgpu_dm_dump_links_and_sinks(adev);
5894 
5895 	/* Software is initialized. Now we can register interrupt handlers. */
5896 	switch (adev->asic_type) {
5897 #if defined(CONFIG_DRM_AMD_DC_SI)
5898 	case CHIP_TAHITI:
5899 	case CHIP_PITCAIRN:
5900 	case CHIP_VERDE:
5901 	case CHIP_OLAND:
5902 #endif
5903 	case CHIP_BONAIRE:
5904 	case CHIP_HAWAII:
5905 	case CHIP_KAVERI:
5906 	case CHIP_KABINI:
5907 	case CHIP_MULLINS:
5908 	case CHIP_TONGA:
5909 	case CHIP_FIJI:
5910 	case CHIP_CARRIZO:
5911 	case CHIP_STONEY:
5912 	case CHIP_POLARIS11:
5913 	case CHIP_POLARIS10:
5914 	case CHIP_POLARIS12:
5915 	case CHIP_VEGAM:
5916 	case CHIP_VEGA10:
5917 	case CHIP_VEGA12:
5918 	case CHIP_VEGA20:
5919 		if (dce110_register_irq_handlers(dm->adev)) {
5920 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5921 			goto fail;
5922 		}
5923 		break;
5924 	default:
5925 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5926 		case IP_VERSION(1, 0, 0):
5927 		case IP_VERSION(1, 0, 1):
5928 		case IP_VERSION(2, 0, 2):
5929 		case IP_VERSION(2, 0, 3):
5930 		case IP_VERSION(2, 0, 0):
5931 		case IP_VERSION(2, 1, 0):
5932 		case IP_VERSION(3, 0, 0):
5933 		case IP_VERSION(3, 0, 2):
5934 		case IP_VERSION(3, 0, 3):
5935 		case IP_VERSION(3, 0, 1):
5936 		case IP_VERSION(3, 1, 2):
5937 		case IP_VERSION(3, 1, 3):
5938 		case IP_VERSION(3, 1, 4):
5939 		case IP_VERSION(3, 1, 5):
5940 		case IP_VERSION(3, 1, 6):
5941 		case IP_VERSION(3, 2, 0):
5942 		case IP_VERSION(3, 2, 1):
5943 		case IP_VERSION(3, 5, 0):
5944 		case IP_VERSION(3, 5, 1):
5945 		case IP_VERSION(3, 6, 0):
5946 		case IP_VERSION(4, 0, 1):
5947 		case IP_VERSION(4, 2, 0):
5948 			if (dcn10_register_irq_handlers(dm->adev)) {
5949 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5950 				goto fail;
5951 			}
5952 			break;
5953 		default:
5954 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
5955 					amdgpu_ip_version(adev, DCE_HWIP, 0));
5956 			goto fail;
5957 		}
5958 		break;
5959 	}
5960 
5961 	return 0;
5962 fail:
5963 	kfree(aencoder);
5964 	kfree(aconnector);
5965 
5966 	return -EINVAL;
5967 }
5968 
5969 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
5970 {
5971 	if (dm->atomic_obj.state)
5972 		drm_atomic_private_obj_fini(&dm->atomic_obj);
5973 }
5974 
5975 /******************************************************************************
5976  * amdgpu_display_funcs functions
5977  *****************************************************************************/
5978 
5979 /*
5980  * dm_bandwidth_update - program display watermarks
5981  *
5982  * @adev: amdgpu_device pointer
5983  *
5984  * Calculate and program the display watermarks and line buffer allocation.
5985  */
5986 static void dm_bandwidth_update(struct amdgpu_device *adev)
5987 {
5988 	/* TODO: implement later */
5989 }
5990 
5991 static const struct amdgpu_display_funcs dm_display_funcs = {
5992 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
5993 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
5994 	.backlight_set_level = NULL, /* never called for DC */
5995 	.backlight_get_level = NULL, /* never called for DC */
5996 	.hpd_sense = NULL,/* called unconditionally */
5997 	.hpd_set_polarity = NULL, /* called unconditionally */
5998 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
5999 	.page_flip_get_scanoutpos =
6000 		dm_crtc_get_scanoutpos,/* called unconditionally */
6001 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
6002 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
6003 };
6004 
6005 #if defined(CONFIG_DEBUG_KERNEL_DC)
6006 
6007 static ssize_t s3_debug_store(struct device *device,
6008 			      struct device_attribute *attr,
6009 			      const char *buf,
6010 			      size_t count)
6011 {
6012 	int ret;
6013 	int s3_state;
6014 	struct drm_device *drm_dev = dev_get_drvdata(device);
6015 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
6016 	struct amdgpu_ip_block *ip_block;
6017 
6018 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
6019 	if (!ip_block)
6020 		return -EINVAL;
6021 
6022 	ret = kstrtoint(buf, 0, &s3_state);
6023 
6024 	if (ret == 0) {
6025 		if (s3_state) {
6026 			dm_resume(ip_block);
6027 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
6028 		} else
6029 			dm_suspend(ip_block);
6030 	}
6031 
6032 	return ret == 0 ? count : 0;
6033 }
6034 
6035 DEVICE_ATTR_WO(s3_debug);
6036 
6037 #endif
6038 
6039 static int dm_init_microcode(struct amdgpu_device *adev)
6040 {
6041 	char *fw_name_dmub;
6042 	int r;
6043 
6044 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6045 	case IP_VERSION(2, 1, 0):
6046 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
6047 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
6048 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
6049 		break;
6050 	case IP_VERSION(3, 0, 0):
6051 		if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(10, 3, 0))
6052 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
6053 		else
6054 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
6055 		break;
6056 	case IP_VERSION(3, 0, 1):
6057 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
6058 		break;
6059 	case IP_VERSION(3, 0, 2):
6060 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
6061 		break;
6062 	case IP_VERSION(3, 0, 3):
6063 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
6064 		break;
6065 	case IP_VERSION(3, 1, 2):
6066 	case IP_VERSION(3, 1, 3):
6067 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
6068 		break;
6069 	case IP_VERSION(3, 1, 4):
6070 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
6071 		break;
6072 	case IP_VERSION(3, 1, 5):
6073 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
6074 		break;
6075 	case IP_VERSION(3, 1, 6):
6076 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
6077 		break;
6078 	case IP_VERSION(3, 2, 0):
6079 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
6080 		break;
6081 	case IP_VERSION(3, 2, 1):
6082 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
6083 		break;
6084 	case IP_VERSION(3, 5, 0):
6085 		fw_name_dmub = FIRMWARE_DCN_35_DMUB;
6086 		break;
6087 	case IP_VERSION(3, 5, 1):
6088 		fw_name_dmub = FIRMWARE_DCN_351_DMUB;
6089 		break;
6090 	case IP_VERSION(3, 6, 0):
6091 		fw_name_dmub = FIRMWARE_DCN_36_DMUB;
6092 		break;
6093 	case IP_VERSION(4, 0, 1):
6094 		fw_name_dmub = FIRMWARE_DCN_401_DMUB;
6095 		break;
6096 	case IP_VERSION(4, 2, 0):
6097 		fw_name_dmub = FIRMWARE_DCN_42_DMUB;
6098 		break;
6099 	default:
6100 		/* ASIC doesn't support DMUB. */
6101 		return 0;
6102 	}
6103 	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, AMDGPU_UCODE_REQUIRED,
6104 				 "%s", fw_name_dmub);
6105 	return r;
6106 }
6107 
6108 static int dm_early_init(struct amdgpu_ip_block *ip_block)
6109 {
6110 	struct amdgpu_device *adev = ip_block->adev;
6111 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
6112 	struct atom_context *ctx = mode_info->atom_context;
6113 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
6114 	u16 data_offset;
6115 
6116 	/* if there is no object header, skip DM */
6117 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
6118 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
6119 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
6120 		return -ENOENT;
6121 	}
6122 
6123 	switch (adev->asic_type) {
6124 #if defined(CONFIG_DRM_AMD_DC_SI)
6125 	case CHIP_TAHITI:
6126 	case CHIP_PITCAIRN:
6127 	case CHIP_VERDE:
6128 		adev->mode_info.num_crtc = 6;
6129 		adev->mode_info.num_hpd = 6;
6130 		adev->mode_info.num_dig = 6;
6131 		break;
6132 	case CHIP_OLAND:
6133 		adev->mode_info.num_crtc = 2;
6134 		adev->mode_info.num_hpd = 2;
6135 		adev->mode_info.num_dig = 2;
6136 		break;
6137 #endif
6138 	case CHIP_BONAIRE:
6139 	case CHIP_HAWAII:
6140 		adev->mode_info.num_crtc = 6;
6141 		adev->mode_info.num_hpd = 6;
6142 		adev->mode_info.num_dig = 6;
6143 		break;
6144 	case CHIP_KAVERI:
6145 		adev->mode_info.num_crtc = 4;
6146 		adev->mode_info.num_hpd = 6;
6147 		adev->mode_info.num_dig = 7;
6148 		break;
6149 	case CHIP_KABINI:
6150 	case CHIP_MULLINS:
6151 		adev->mode_info.num_crtc = 2;
6152 		adev->mode_info.num_hpd = 6;
6153 		adev->mode_info.num_dig = 6;
6154 		break;
6155 	case CHIP_FIJI:
6156 	case CHIP_TONGA:
6157 		adev->mode_info.num_crtc = 6;
6158 		adev->mode_info.num_hpd = 6;
6159 		adev->mode_info.num_dig = 7;
6160 		break;
6161 	case CHIP_CARRIZO:
6162 		adev->mode_info.num_crtc = 3;
6163 		adev->mode_info.num_hpd = 6;
6164 		adev->mode_info.num_dig = 9;
6165 		break;
6166 	case CHIP_STONEY:
6167 		adev->mode_info.num_crtc = 2;
6168 		adev->mode_info.num_hpd = 6;
6169 		adev->mode_info.num_dig = 9;
6170 		break;
6171 	case CHIP_POLARIS11:
6172 	case CHIP_POLARIS12:
6173 		adev->mode_info.num_crtc = 5;
6174 		adev->mode_info.num_hpd = 5;
6175 		adev->mode_info.num_dig = 5;
6176 		break;
6177 	case CHIP_POLARIS10:
6178 	case CHIP_VEGAM:
6179 		adev->mode_info.num_crtc = 6;
6180 		adev->mode_info.num_hpd = 6;
6181 		adev->mode_info.num_dig = 6;
6182 		break;
6183 	case CHIP_VEGA10:
6184 	case CHIP_VEGA12:
6185 	case CHIP_VEGA20:
6186 		adev->mode_info.num_crtc = 6;
6187 		adev->mode_info.num_hpd = 6;
6188 		adev->mode_info.num_dig = 6;
6189 		break;
6190 	default:
6191 
6192 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6193 		case IP_VERSION(2, 0, 2):
6194 		case IP_VERSION(3, 0, 0):
6195 			adev->mode_info.num_crtc = 6;
6196 			adev->mode_info.num_hpd = 6;
6197 			adev->mode_info.num_dig = 6;
6198 			break;
6199 		case IP_VERSION(2, 0, 0):
6200 		case IP_VERSION(3, 0, 2):
6201 			adev->mode_info.num_crtc = 5;
6202 			adev->mode_info.num_hpd = 5;
6203 			adev->mode_info.num_dig = 5;
6204 			break;
6205 		case IP_VERSION(2, 0, 3):
6206 		case IP_VERSION(3, 0, 3):
6207 			adev->mode_info.num_crtc = 2;
6208 			adev->mode_info.num_hpd = 2;
6209 			adev->mode_info.num_dig = 2;
6210 			break;
6211 		case IP_VERSION(1, 0, 0):
6212 		case IP_VERSION(1, 0, 1):
6213 		case IP_VERSION(3, 0, 1):
6214 		case IP_VERSION(2, 1, 0):
6215 		case IP_VERSION(3, 1, 2):
6216 		case IP_VERSION(3, 1, 3):
6217 		case IP_VERSION(3, 1, 4):
6218 		case IP_VERSION(3, 1, 5):
6219 		case IP_VERSION(3, 1, 6):
6220 		case IP_VERSION(3, 2, 0):
6221 		case IP_VERSION(3, 2, 1):
6222 		case IP_VERSION(3, 5, 0):
6223 		case IP_VERSION(3, 5, 1):
6224 		case IP_VERSION(3, 6, 0):
6225 		case IP_VERSION(4, 0, 1):
6226 		case IP_VERSION(4, 2, 0):
6227 			adev->mode_info.num_crtc = 4;
6228 			adev->mode_info.num_hpd = 4;
6229 			adev->mode_info.num_dig = 4;
6230 			break;
6231 		default:
6232 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
6233 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6234 			return -EINVAL;
6235 		}
6236 		break;
6237 	}
6238 
6239 	if (adev->mode_info.funcs == NULL)
6240 		adev->mode_info.funcs = &dm_display_funcs;
6241 
6242 	/*
6243 	 * Note: Do NOT change adev->reg.audio_endpt.rreg and
6244 	 * adev->reg.audio_endpt.wreg because they are initialised in
6245 	 * amdgpu_device_init()
6246 	 */
6247 #if defined(CONFIG_DEBUG_KERNEL_DC)
6248 	device_create_file(
6249 		adev_to_drm(adev)->dev,
6250 		&dev_attr_s3_debug);
6251 #endif
6252 	adev->dc_enabled = true;
6253 
6254 	return dm_init_microcode(adev);
6255 }
6256 
6257 static bool modereset_required(struct drm_crtc_state *crtc_state)
6258 {
6259 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
6260 }
6261 
6262 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
6263 {
6264 	drm_encoder_cleanup(encoder);
6265 	kfree(encoder);
6266 }
6267 
6268 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
6269 	.destroy = amdgpu_dm_encoder_destroy,
6270 };
6271 
6272 static int
6273 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
6274 			    const enum surface_pixel_format format,
6275 			    enum dc_color_space *color_space)
6276 {
6277 	bool full_range;
6278 
6279 	*color_space = COLOR_SPACE_SRGB;
6280 
6281 	/* Ignore properties when DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE is set */
6282 	if (plane_state->state && plane_state->state->plane_color_pipeline)
6283 		return 0;
6284 
6285 	/* DRM color properties only affect non-RGB formats. */
6286 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
6287 		return 0;
6288 
6289 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
6290 
6291 	switch (plane_state->color_encoding) {
6292 	case DRM_COLOR_YCBCR_BT601:
6293 		if (full_range)
6294 			*color_space = COLOR_SPACE_YCBCR601;
6295 		else
6296 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
6297 		break;
6298 
6299 	case DRM_COLOR_YCBCR_BT709:
6300 		if (full_range)
6301 			*color_space = COLOR_SPACE_YCBCR709;
6302 		else
6303 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
6304 		break;
6305 
6306 	case DRM_COLOR_YCBCR_BT2020:
6307 		if (full_range)
6308 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
6309 		else
6310 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6311 		break;
6312 
6313 	default:
6314 		return -EINVAL;
6315 	}
6316 
6317 	return 0;
6318 }
6319 
6320 static int
6321 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
6322 			    const struct drm_plane_state *plane_state,
6323 			    const u64 tiling_flags,
6324 			    struct dc_plane_info *plane_info,
6325 			    struct dc_plane_address *address,
6326 			    bool tmz_surface)
6327 {
6328 	const struct drm_framebuffer *fb = plane_state->fb;
6329 	const struct amdgpu_framebuffer *afb =
6330 		to_amdgpu_framebuffer(plane_state->fb);
6331 	int ret;
6332 
6333 	memset(plane_info, 0, sizeof(*plane_info));
6334 
6335 	switch (fb->format->format) {
6336 	case DRM_FORMAT_C8:
6337 		plane_info->format =
6338 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
6339 		break;
6340 	case DRM_FORMAT_RGB565:
6341 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
6342 		break;
6343 	case DRM_FORMAT_XRGB8888:
6344 	case DRM_FORMAT_ARGB8888:
6345 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6346 		break;
6347 	case DRM_FORMAT_XRGB2101010:
6348 	case DRM_FORMAT_ARGB2101010:
6349 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
6350 		break;
6351 	case DRM_FORMAT_XBGR2101010:
6352 	case DRM_FORMAT_ABGR2101010:
6353 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
6354 		break;
6355 	case DRM_FORMAT_XBGR8888:
6356 	case DRM_FORMAT_ABGR8888:
6357 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
6358 		break;
6359 	case DRM_FORMAT_NV21:
6360 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
6361 		break;
6362 	case DRM_FORMAT_NV12:
6363 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
6364 		break;
6365 	case DRM_FORMAT_P010:
6366 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
6367 		break;
6368 	case DRM_FORMAT_XRGB16161616F:
6369 	case DRM_FORMAT_ARGB16161616F:
6370 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
6371 		break;
6372 	case DRM_FORMAT_XBGR16161616F:
6373 	case DRM_FORMAT_ABGR16161616F:
6374 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
6375 		break;
6376 	case DRM_FORMAT_XRGB16161616:
6377 	case DRM_FORMAT_ARGB16161616:
6378 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
6379 		break;
6380 	case DRM_FORMAT_XBGR16161616:
6381 	case DRM_FORMAT_ABGR16161616:
6382 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
6383 		break;
6384 	default:
6385 		drm_err(adev_to_drm(adev),
6386 			"Unsupported screen format %p4cc\n",
6387 			&fb->format->format);
6388 		return -EINVAL;
6389 	}
6390 
6391 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
6392 	case DRM_MODE_ROTATE_0:
6393 		plane_info->rotation = ROTATION_ANGLE_0;
6394 		break;
6395 	case DRM_MODE_ROTATE_90:
6396 		plane_info->rotation = ROTATION_ANGLE_90;
6397 		break;
6398 	case DRM_MODE_ROTATE_180:
6399 		plane_info->rotation = ROTATION_ANGLE_180;
6400 		break;
6401 	case DRM_MODE_ROTATE_270:
6402 		plane_info->rotation = ROTATION_ANGLE_270;
6403 		break;
6404 	default:
6405 		plane_info->rotation = ROTATION_ANGLE_0;
6406 		break;
6407 	}
6408 
6409 
6410 	plane_info->visible = true;
6411 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
6412 
6413 	plane_info->layer_index = plane_state->normalized_zpos;
6414 
6415 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
6416 					  &plane_info->color_space);
6417 	if (ret)
6418 		return ret;
6419 
6420 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
6421 					   plane_info->rotation, tiling_flags,
6422 					   &plane_info->tiling_info,
6423 					   &plane_info->plane_size,
6424 					   &plane_info->dcc, address,
6425 					   tmz_surface);
6426 	if (ret)
6427 		return ret;
6428 
6429 	amdgpu_dm_plane_fill_blending_from_plane_state(
6430 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
6431 		&plane_info->global_alpha, &plane_info->global_alpha_value);
6432 
6433 	return 0;
6434 }
6435 
6436 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
6437 				    struct dc_plane_state *dc_plane_state,
6438 				    struct drm_plane_state *plane_state,
6439 				    struct drm_crtc_state *crtc_state)
6440 {
6441 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6442 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
6443 	struct dc_scaling_info scaling_info;
6444 	struct dc_plane_info plane_info;
6445 	int ret;
6446 
6447 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
6448 	if (ret)
6449 		return ret;
6450 
6451 	dc_plane_state->src_rect = scaling_info.src_rect;
6452 	dc_plane_state->dst_rect = scaling_info.dst_rect;
6453 	dc_plane_state->clip_rect = scaling_info.clip_rect;
6454 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
6455 
6456 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
6457 					  afb->tiling_flags,
6458 					  &plane_info,
6459 					  &dc_plane_state->address,
6460 					  afb->tmz_surface);
6461 	if (ret)
6462 		return ret;
6463 
6464 	dc_plane_state->format = plane_info.format;
6465 	dc_plane_state->color_space = plane_info.color_space;
6466 	dc_plane_state->format = plane_info.format;
6467 	dc_plane_state->plane_size = plane_info.plane_size;
6468 	dc_plane_state->rotation = plane_info.rotation;
6469 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
6470 	dc_plane_state->stereo_format = plane_info.stereo_format;
6471 	dc_plane_state->tiling_info = plane_info.tiling_info;
6472 	dc_plane_state->visible = plane_info.visible;
6473 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
6474 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
6475 	dc_plane_state->global_alpha = plane_info.global_alpha;
6476 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
6477 	dc_plane_state->dcc = plane_info.dcc;
6478 	dc_plane_state->layer_index = plane_info.layer_index;
6479 	dc_plane_state->flip_int_enabled = true;
6480 
6481 	/*
6482 	 * Always set input transfer function, since plane state is refreshed
6483 	 * every time.
6484 	 */
6485 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
6486 						plane_state,
6487 						dc_plane_state);
6488 	if (ret)
6489 		return ret;
6490 
6491 	return 0;
6492 }
6493 
6494 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
6495 				      struct rect *dirty_rect, int32_t x,
6496 				      s32 y, s32 width, s32 height,
6497 				      int *i, bool ffu)
6498 {
6499 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
6500 
6501 	dirty_rect->x = x;
6502 	dirty_rect->y = y;
6503 	dirty_rect->width = width;
6504 	dirty_rect->height = height;
6505 
6506 	if (ffu)
6507 		drm_dbg(plane->dev,
6508 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
6509 			plane->base.id, width, height);
6510 	else
6511 		drm_dbg(plane->dev,
6512 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
6513 			plane->base.id, x, y, width, height);
6514 
6515 	(*i)++;
6516 }
6517 
6518 /**
6519  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
6520  *
6521  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
6522  *         remote fb
6523  * @old_plane_state: Old state of @plane
6524  * @new_plane_state: New state of @plane
6525  * @crtc_state: New state of CRTC connected to the @plane
6526  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
6527  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
6528  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
6529  *             that have changed will be updated. If PSR SU is not enabled,
6530  *             or if damage clips are not available, the entire screen will be updated.
6531  * @dirty_regions_changed: dirty regions changed
6532  *
6533  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
6534  * (referred to as "damage clips" in DRM nomenclature) that require updating on
6535  * the eDP remote buffer. The responsibility of specifying the dirty regions is
6536  * amdgpu_dm's.
6537  *
6538  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
6539  * plane with regions that require flushing to the eDP remote buffer. In
6540  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
6541  * implicitly provide damage clips without any client support via the plane
6542  * bounds.
6543  */
6544 static void fill_dc_dirty_rects(struct drm_plane *plane,
6545 				struct drm_plane_state *old_plane_state,
6546 				struct drm_plane_state *new_plane_state,
6547 				struct drm_crtc_state *crtc_state,
6548 				struct dc_flip_addrs *flip_addrs,
6549 				bool is_psr_su,
6550 				bool *dirty_regions_changed)
6551 {
6552 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6553 	struct rect *dirty_rects = flip_addrs->dirty_rects;
6554 	u32 num_clips;
6555 	struct drm_mode_rect *clips;
6556 	bool bb_changed;
6557 	bool fb_changed;
6558 	u32 i = 0;
6559 	*dirty_regions_changed = false;
6560 
6561 	/*
6562 	 * Cursor plane has it's own dirty rect update interface. See
6563 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
6564 	 */
6565 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
6566 		return;
6567 
6568 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
6569 		goto ffu;
6570 
6571 	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
6572 	clips = drm_plane_get_damage_clips(new_plane_state);
6573 
6574 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
6575 						   is_psr_su)))
6576 		goto ffu;
6577 
6578 	if (!dm_crtc_state->mpo_requested) {
6579 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
6580 			goto ffu;
6581 
6582 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
6583 			fill_dc_dirty_rect(new_plane_state->plane,
6584 					   &dirty_rects[flip_addrs->dirty_rect_count],
6585 					   clips->x1, clips->y1,
6586 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
6587 					   &flip_addrs->dirty_rect_count,
6588 					   false);
6589 		return;
6590 	}
6591 
6592 	/*
6593 	 * MPO is requested. Add entire plane bounding box to dirty rects if
6594 	 * flipped to or damaged.
6595 	 *
6596 	 * If plane is moved or resized, also add old bounding box to dirty
6597 	 * rects.
6598 	 */
6599 	fb_changed = old_plane_state->fb->base.id !=
6600 		     new_plane_state->fb->base.id;
6601 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
6602 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
6603 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
6604 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
6605 
6606 	drm_dbg(plane->dev,
6607 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
6608 		new_plane_state->plane->base.id,
6609 		bb_changed, fb_changed, num_clips);
6610 
6611 	*dirty_regions_changed = bb_changed;
6612 
6613 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
6614 		goto ffu;
6615 
6616 	if (bb_changed) {
6617 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6618 				   new_plane_state->crtc_x,
6619 				   new_plane_state->crtc_y,
6620 				   new_plane_state->crtc_w,
6621 				   new_plane_state->crtc_h, &i, false);
6622 
6623 		/* Add old plane bounding-box if plane is moved or resized */
6624 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6625 				   old_plane_state->crtc_x,
6626 				   old_plane_state->crtc_y,
6627 				   old_plane_state->crtc_w,
6628 				   old_plane_state->crtc_h, &i, false);
6629 	}
6630 
6631 	if (num_clips) {
6632 		for (; i < num_clips; clips++)
6633 			fill_dc_dirty_rect(new_plane_state->plane,
6634 					   &dirty_rects[i], clips->x1,
6635 					   clips->y1, clips->x2 - clips->x1,
6636 					   clips->y2 - clips->y1, &i, false);
6637 	} else if (fb_changed && !bb_changed) {
6638 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6639 				   new_plane_state->crtc_x,
6640 				   new_plane_state->crtc_y,
6641 				   new_plane_state->crtc_w,
6642 				   new_plane_state->crtc_h, &i, false);
6643 	}
6644 
6645 	flip_addrs->dirty_rect_count = i;
6646 	return;
6647 
6648 ffu:
6649 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
6650 			   dm_crtc_state->base.mode.crtc_hdisplay,
6651 			   dm_crtc_state->base.mode.crtc_vdisplay,
6652 			   &flip_addrs->dirty_rect_count, true);
6653 }
6654 
6655 static void update_stream_scaling_settings(struct drm_device *dev,
6656 					   const struct drm_display_mode *mode,
6657 					   const struct dm_connector_state *dm_state,
6658 					   struct dc_stream_state *stream)
6659 {
6660 	enum amdgpu_rmx_type rmx_type;
6661 
6662 	struct rect src = { 0 }; /* viewport in composition space*/
6663 	struct rect dst = { 0 }; /* stream addressable area */
6664 
6665 	/* no mode. nothing to be done */
6666 	if (!mode)
6667 		return;
6668 
6669 	/* Full screen scaling by default */
6670 	src.width = mode->hdisplay;
6671 	src.height = mode->vdisplay;
6672 	dst.width = stream->timing.h_addressable;
6673 	dst.height = stream->timing.v_addressable;
6674 
6675 	if (dm_state) {
6676 		rmx_type = dm_state->scaling;
6677 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
6678 			if (src.width * dst.height <
6679 					src.height * dst.width) {
6680 				/* height needs less upscaling/more downscaling */
6681 				dst.width = src.width *
6682 						dst.height / src.height;
6683 			} else {
6684 				/* width needs less upscaling/more downscaling */
6685 				dst.height = src.height *
6686 						dst.width / src.width;
6687 			}
6688 		} else if (rmx_type == RMX_CENTER) {
6689 			dst = src;
6690 		}
6691 
6692 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
6693 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
6694 
6695 		if (dm_state->underscan_enable) {
6696 			dst.x += dm_state->underscan_hborder / 2;
6697 			dst.y += dm_state->underscan_vborder / 2;
6698 			dst.width -= dm_state->underscan_hborder;
6699 			dst.height -= dm_state->underscan_vborder;
6700 		}
6701 	}
6702 
6703 	stream->src = src;
6704 	stream->dst = dst;
6705 
6706 	drm_dbg_kms(dev, "Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
6707 		    dst.x, dst.y, dst.width, dst.height);
6708 
6709 }
6710 
6711 static enum dc_color_depth
6712 convert_color_depth_from_display_info(const struct drm_connector *connector,
6713 				      bool is_y420, int requested_bpc)
6714 {
6715 	u8 bpc;
6716 
6717 	if (is_y420) {
6718 		bpc = 8;
6719 
6720 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
6721 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
6722 			bpc = 16;
6723 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
6724 			bpc = 12;
6725 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
6726 			bpc = 10;
6727 	} else {
6728 		bpc = (uint8_t)connector->display_info.bpc;
6729 		/* Assume 8 bpc by default if no bpc is specified. */
6730 		bpc = bpc ? bpc : 8;
6731 	}
6732 
6733 	if (requested_bpc > 0) {
6734 		/*
6735 		 * Cap display bpc based on the user requested value.
6736 		 *
6737 		 * The value for state->max_bpc may not correctly updated
6738 		 * depending on when the connector gets added to the state
6739 		 * or if this was called outside of atomic check, so it
6740 		 * can't be used directly.
6741 		 */
6742 		bpc = min_t(u8, bpc, requested_bpc);
6743 
6744 		/* Round down to the nearest even number. */
6745 		bpc = bpc - (bpc & 1);
6746 	}
6747 
6748 	switch (bpc) {
6749 	case 0:
6750 		/*
6751 		 * Temporary Work around, DRM doesn't parse color depth for
6752 		 * EDID revision before 1.4
6753 		 * TODO: Fix edid parsing
6754 		 */
6755 		return COLOR_DEPTH_888;
6756 	case 6:
6757 		return COLOR_DEPTH_666;
6758 	case 8:
6759 		return COLOR_DEPTH_888;
6760 	case 10:
6761 		return COLOR_DEPTH_101010;
6762 	case 12:
6763 		return COLOR_DEPTH_121212;
6764 	case 14:
6765 		return COLOR_DEPTH_141414;
6766 	case 16:
6767 		return COLOR_DEPTH_161616;
6768 	default:
6769 		return COLOR_DEPTH_UNDEFINED;
6770 	}
6771 }
6772 
6773 static enum dc_aspect_ratio
6774 get_aspect_ratio(const struct drm_display_mode *mode_in)
6775 {
6776 	/* 1-1 mapping, since both enums follow the HDMI spec. */
6777 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
6778 }
6779 
6780 static enum dc_color_space
6781 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
6782 		       const struct drm_connector_state *connector_state)
6783 {
6784 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
6785 
6786 	switch (connector_state->colorspace) {
6787 	case DRM_MODE_COLORIMETRY_BT601_YCC:
6788 		if (dc_crtc_timing->flags.Y_ONLY)
6789 			color_space = COLOR_SPACE_YCBCR601_LIMITED;
6790 		else
6791 			color_space = COLOR_SPACE_YCBCR601;
6792 		break;
6793 	case DRM_MODE_COLORIMETRY_BT709_YCC:
6794 		if (dc_crtc_timing->flags.Y_ONLY)
6795 			color_space = COLOR_SPACE_YCBCR709_LIMITED;
6796 		else
6797 			color_space = COLOR_SPACE_YCBCR709;
6798 		break;
6799 	case DRM_MODE_COLORIMETRY_OPRGB:
6800 		color_space = COLOR_SPACE_ADOBERGB;
6801 		break;
6802 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
6803 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
6804 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
6805 			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
6806 		else
6807 			color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6808 		break;
6809 	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
6810 	default:
6811 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
6812 			color_space = COLOR_SPACE_SRGB;
6813 			if (connector_state->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_LIMITED)
6814 				color_space = COLOR_SPACE_SRGB_LIMITED;
6815 		/*
6816 		 * 27030khz is the separation point between HDTV and SDTV
6817 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
6818 		 * respectively
6819 		 */
6820 		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
6821 			if (dc_crtc_timing->flags.Y_ONLY)
6822 				color_space =
6823 					COLOR_SPACE_YCBCR709_LIMITED;
6824 			else
6825 				color_space = COLOR_SPACE_YCBCR709;
6826 		} else {
6827 			if (dc_crtc_timing->flags.Y_ONLY)
6828 				color_space =
6829 					COLOR_SPACE_YCBCR601_LIMITED;
6830 			else
6831 				color_space = COLOR_SPACE_YCBCR601;
6832 		}
6833 		break;
6834 	}
6835 
6836 	return color_space;
6837 }
6838 
6839 static enum display_content_type
6840 get_output_content_type(const struct drm_connector_state *connector_state)
6841 {
6842 	switch (connector_state->content_type) {
6843 	default:
6844 	case DRM_MODE_CONTENT_TYPE_NO_DATA:
6845 		return DISPLAY_CONTENT_TYPE_NO_DATA;
6846 	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
6847 		return DISPLAY_CONTENT_TYPE_GRAPHICS;
6848 	case DRM_MODE_CONTENT_TYPE_PHOTO:
6849 		return DISPLAY_CONTENT_TYPE_PHOTO;
6850 	case DRM_MODE_CONTENT_TYPE_CINEMA:
6851 		return DISPLAY_CONTENT_TYPE_CINEMA;
6852 	case DRM_MODE_CONTENT_TYPE_GAME:
6853 		return DISPLAY_CONTENT_TYPE_GAME;
6854 	}
6855 }
6856 
6857 static bool adjust_colour_depth_from_display_info(
6858 	struct dc_crtc_timing *timing_out,
6859 	const struct drm_display_info *info)
6860 {
6861 	enum dc_color_depth depth = timing_out->display_color_depth;
6862 	int normalized_clk;
6863 
6864 	do {
6865 		normalized_clk = timing_out->pix_clk_100hz / 10;
6866 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
6867 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
6868 			normalized_clk /= 2;
6869 		/* Adjusting pix clock following on HDMI spec based on colour depth */
6870 		switch (depth) {
6871 		case COLOR_DEPTH_888:
6872 			break;
6873 		case COLOR_DEPTH_101010:
6874 			normalized_clk = (normalized_clk * 30) / 24;
6875 			break;
6876 		case COLOR_DEPTH_121212:
6877 			normalized_clk = (normalized_clk * 36) / 24;
6878 			break;
6879 		case COLOR_DEPTH_161616:
6880 			normalized_clk = (normalized_clk * 48) / 24;
6881 			break;
6882 		default:
6883 			/* The above depths are the only ones valid for HDMI. */
6884 			return false;
6885 		}
6886 		if (normalized_clk <= info->max_tmds_clock) {
6887 			timing_out->display_color_depth = depth;
6888 			return true;
6889 		}
6890 	} while (--depth > COLOR_DEPTH_666);
6891 	return false;
6892 }
6893 
6894 static void fill_stream_properties_from_drm_display_mode(
6895 	struct dc_stream_state *stream,
6896 	const struct drm_display_mode *mode_in,
6897 	const struct drm_connector *connector,
6898 	const struct drm_connector_state *connector_state,
6899 	const struct dc_stream_state *old_stream,
6900 	int requested_bpc)
6901 {
6902 	struct dc_crtc_timing *timing_out = &stream->timing;
6903 	const struct drm_display_info *info = &connector->display_info;
6904 	struct amdgpu_dm_connector *aconnector = NULL;
6905 	struct hdmi_vendor_infoframe hv_frame;
6906 	struct hdmi_avi_infoframe avi_frame;
6907 	ssize_t err;
6908 
6909 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
6910 		aconnector = to_amdgpu_dm_connector(connector);
6911 
6912 	memset(&hv_frame, 0, sizeof(hv_frame));
6913 	memset(&avi_frame, 0, sizeof(avi_frame));
6914 
6915 	timing_out->h_border_left = 0;
6916 	timing_out->h_border_right = 0;
6917 	timing_out->v_border_top = 0;
6918 	timing_out->v_border_bottom = 0;
6919 	/* TODO: un-hardcode */
6920 	if (drm_mode_is_420_only(info, mode_in)
6921 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6922 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6923 	else if (drm_mode_is_420_also(info, mode_in)
6924 			&& aconnector
6925 			&& aconnector->force_yuv420_output)
6926 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6927 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR422))
6928 			&& aconnector
6929 			&& aconnector->force_yuv422_output)
6930 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR422;
6931 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR444))
6932 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6933 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
6934 	else
6935 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
6936 
6937 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
6938 	timing_out->display_color_depth = convert_color_depth_from_display_info(
6939 		connector,
6940 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
6941 		requested_bpc);
6942 	timing_out->scan_type = SCANNING_TYPE_NODATA;
6943 	timing_out->hdmi_vic = 0;
6944 
6945 	if (old_stream) {
6946 		timing_out->vic = old_stream->timing.vic;
6947 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
6948 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
6949 	} else {
6950 		timing_out->vic = drm_match_cea_mode(mode_in);
6951 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
6952 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
6953 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
6954 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
6955 	}
6956 
6957 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
6958 		err = drm_hdmi_avi_infoframe_from_display_mode(&avi_frame,
6959 							       (struct drm_connector *)connector,
6960 							       mode_in);
6961 		if (err < 0)
6962 			drm_warn_once(connector->dev, "Failed to setup avi infoframe on connector %s: %zd\n",
6963 				      connector->name, err);
6964 		timing_out->vic = avi_frame.video_code;
6965 		err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame,
6966 								  (struct drm_connector *)connector,
6967 								  mode_in);
6968 		if (err < 0)
6969 			drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n",
6970 				      connector->name, err);
6971 		timing_out->hdmi_vic = hv_frame.vic;
6972 	}
6973 
6974 	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
6975 		timing_out->h_addressable = mode_in->hdisplay;
6976 		timing_out->h_total = mode_in->htotal;
6977 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
6978 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
6979 		timing_out->v_total = mode_in->vtotal;
6980 		timing_out->v_addressable = mode_in->vdisplay;
6981 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
6982 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
6983 		timing_out->pix_clk_100hz = mode_in->clock * 10;
6984 	} else {
6985 		timing_out->h_addressable = mode_in->crtc_hdisplay;
6986 		timing_out->h_total = mode_in->crtc_htotal;
6987 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
6988 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
6989 		timing_out->v_total = mode_in->crtc_vtotal;
6990 		timing_out->v_addressable = mode_in->crtc_vdisplay;
6991 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
6992 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
6993 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
6994 	}
6995 
6996 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
6997 
6998 	stream->out_transfer_func.type = TF_TYPE_PREDEFINED;
6999 	stream->out_transfer_func.tf = TRANSFER_FUNCTION_SRGB;
7000 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
7001 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
7002 		    drm_mode_is_420_also(info, mode_in) &&
7003 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
7004 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
7005 			adjust_colour_depth_from_display_info(timing_out, info);
7006 		}
7007 	}
7008 
7009 	stream->output_color_space = get_output_color_space(timing_out, connector_state);
7010 	stream->content_type = get_output_content_type(connector_state);
7011 }
7012 
7013 static void fill_audio_info(struct audio_info *audio_info,
7014 			    const struct drm_connector *drm_connector,
7015 			    const struct dc_sink *dc_sink)
7016 {
7017 	int i = 0;
7018 	int cea_revision = 0;
7019 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
7020 
7021 	audio_info->manufacture_id = edid_caps->manufacturer_id;
7022 	audio_info->product_id = edid_caps->product_id;
7023 
7024 	cea_revision = drm_connector->display_info.cea_rev;
7025 
7026 	strscpy(audio_info->display_name,
7027 		edid_caps->display_name,
7028 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
7029 
7030 	if (cea_revision >= 3) {
7031 		audio_info->mode_count = edid_caps->audio_mode_count;
7032 
7033 		for (i = 0; i < audio_info->mode_count; ++i) {
7034 			audio_info->modes[i].format_code =
7035 					(enum audio_format_code)
7036 					(edid_caps->audio_modes[i].format_code);
7037 			audio_info->modes[i].channel_count =
7038 					edid_caps->audio_modes[i].channel_count;
7039 			audio_info->modes[i].sample_rates.all =
7040 					edid_caps->audio_modes[i].sample_rate;
7041 			audio_info->modes[i].sample_size =
7042 					edid_caps->audio_modes[i].sample_size;
7043 		}
7044 	}
7045 
7046 	audio_info->flags.all = edid_caps->speaker_flags;
7047 
7048 	/* TODO: We only check for the progressive mode, check for interlace mode too */
7049 	if (drm_connector->latency_present[0]) {
7050 		audio_info->video_latency = drm_connector->video_latency[0];
7051 		audio_info->audio_latency = drm_connector->audio_latency[0];
7052 	}
7053 
7054 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
7055 
7056 }
7057 
7058 static void
7059 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
7060 				      struct drm_display_mode *dst_mode)
7061 {
7062 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
7063 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
7064 	dst_mode->crtc_clock = src_mode->crtc_clock;
7065 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
7066 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
7067 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
7068 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
7069 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
7070 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
7071 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
7072 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
7073 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
7074 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
7075 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
7076 }
7077 
7078 static void
7079 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
7080 					const struct drm_display_mode *native_mode,
7081 					bool scale_enabled)
7082 {
7083 	if (scale_enabled || (
7084 	    native_mode->clock == drm_mode->clock &&
7085 	    native_mode->htotal == drm_mode->htotal &&
7086 	    native_mode->vtotal == drm_mode->vtotal)) {
7087 		if (native_mode->crtc_clock)
7088 			copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
7089 	} else {
7090 		/* no scaling nor amdgpu inserted, no need to patch */
7091 	}
7092 }
7093 
7094 static struct dc_sink *
7095 create_fake_sink(struct drm_device *dev, struct dc_link *link)
7096 {
7097 	struct dc_sink_init_data sink_init_data = { 0 };
7098 	struct dc_sink *sink = NULL;
7099 
7100 	sink_init_data.link = link;
7101 	sink_init_data.sink_signal = link->connector_signal;
7102 
7103 	sink = dc_sink_create(&sink_init_data);
7104 	if (!sink) {
7105 		drm_err(dev, "Failed to create sink!\n");
7106 		return NULL;
7107 	}
7108 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
7109 
7110 	return sink;
7111 }
7112 
7113 static void set_multisync_trigger_params(
7114 		struct dc_stream_state *stream)
7115 {
7116 	struct dc_stream_state *master = NULL;
7117 
7118 	if (stream->triggered_crtc_reset.enabled) {
7119 		master = stream->triggered_crtc_reset.event_source;
7120 		stream->triggered_crtc_reset.event =
7121 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
7122 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
7123 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
7124 	}
7125 }
7126 
7127 static void set_master_stream(struct dc_stream_state *stream_set[],
7128 			      int stream_count)
7129 {
7130 	int j, highest_rfr = 0, master_stream = 0;
7131 
7132 	for (j = 0;  j < stream_count; j++) {
7133 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
7134 			int refresh_rate = 0;
7135 
7136 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
7137 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
7138 			if (refresh_rate > highest_rfr) {
7139 				highest_rfr = refresh_rate;
7140 				master_stream = j;
7141 			}
7142 		}
7143 	}
7144 	for (j = 0;  j < stream_count; j++) {
7145 		if (stream_set[j])
7146 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
7147 	}
7148 }
7149 
7150 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
7151 {
7152 	int i = 0;
7153 	struct dc_stream_state *stream;
7154 
7155 	if (context->stream_count < 2)
7156 		return;
7157 	for (i = 0; i < context->stream_count ; i++) {
7158 		if (!context->streams[i])
7159 			continue;
7160 		/*
7161 		 * TODO: add a function to read AMD VSDB bits and set
7162 		 * crtc_sync_master.multi_sync_enabled flag
7163 		 * For now it's set to false
7164 		 */
7165 	}
7166 
7167 	set_master_stream(context->streams, context->stream_count);
7168 
7169 	for (i = 0; i < context->stream_count ; i++) {
7170 		stream = context->streams[i];
7171 
7172 		if (!stream)
7173 			continue;
7174 
7175 		set_multisync_trigger_params(stream);
7176 	}
7177 }
7178 
7179 /**
7180  * DOC: FreeSync Video
7181  *
7182  * When a userspace application wants to play a video, the content follows a
7183  * standard format definition that usually specifies the FPS for that format.
7184  * The below list illustrates some video format and the expected FPS,
7185  * respectively:
7186  *
7187  * - TV/NTSC (23.976 FPS)
7188  * - Cinema (24 FPS)
7189  * - TV/PAL (25 FPS)
7190  * - TV/NTSC (29.97 FPS)
7191  * - TV/NTSC (30 FPS)
7192  * - Cinema HFR (48 FPS)
7193  * - TV/PAL (50 FPS)
7194  * - Commonly used (60 FPS)
7195  * - Multiples of 24 (48,72,96 FPS)
7196  *
7197  * The list of standards video format is not huge and can be added to the
7198  * connector modeset list beforehand. With that, userspace can leverage
7199  * FreeSync to extends the front porch in order to attain the target refresh
7200  * rate. Such a switch will happen seamlessly, without screen blanking or
7201  * reprogramming of the output in any other way. If the userspace requests a
7202  * modesetting change compatible with FreeSync modes that only differ in the
7203  * refresh rate, DC will skip the full update and avoid blink during the
7204  * transition. For example, the video player can change the modesetting from
7205  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
7206  * causing any display blink. This same concept can be applied to a mode
7207  * setting change.
7208  */
7209 static struct drm_display_mode *
7210 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
7211 		bool use_probed_modes)
7212 {
7213 	struct drm_display_mode *m, *m_pref = NULL;
7214 	u16 current_refresh, highest_refresh;
7215 	struct list_head *list_head = use_probed_modes ?
7216 		&aconnector->base.probed_modes :
7217 		&aconnector->base.modes;
7218 
7219 	if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
7220 		return NULL;
7221 
7222 	if (aconnector->freesync_vid_base.clock != 0)
7223 		return &aconnector->freesync_vid_base;
7224 
7225 	/* Find the preferred mode */
7226 	list_for_each_entry(m, list_head, head) {
7227 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
7228 			m_pref = m;
7229 			break;
7230 		}
7231 	}
7232 
7233 	if (!m_pref) {
7234 		/* Probably an EDID with no preferred mode. Fallback to first entry */
7235 		m_pref = list_first_entry_or_null(
7236 				&aconnector->base.modes, struct drm_display_mode, head);
7237 		if (!m_pref) {
7238 			drm_dbg_driver(aconnector->base.dev, "No preferred mode found in EDID\n");
7239 			return NULL;
7240 		}
7241 	}
7242 
7243 	highest_refresh = drm_mode_vrefresh(m_pref);
7244 
7245 	/*
7246 	 * Find the mode with highest refresh rate with same resolution.
7247 	 * For some monitors, preferred mode is not the mode with highest
7248 	 * supported refresh rate.
7249 	 */
7250 	list_for_each_entry(m, list_head, head) {
7251 		current_refresh  = drm_mode_vrefresh(m);
7252 
7253 		if (m->hdisplay == m_pref->hdisplay &&
7254 		    m->vdisplay == m_pref->vdisplay &&
7255 		    highest_refresh < current_refresh) {
7256 			highest_refresh = current_refresh;
7257 			m_pref = m;
7258 		}
7259 	}
7260 
7261 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
7262 	return m_pref;
7263 }
7264 
7265 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
7266 		struct amdgpu_dm_connector *aconnector)
7267 {
7268 	struct drm_display_mode *high_mode;
7269 	int timing_diff;
7270 
7271 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
7272 	if (!high_mode || !mode)
7273 		return false;
7274 
7275 	timing_diff = high_mode->vtotal - mode->vtotal;
7276 
7277 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
7278 	    high_mode->hdisplay != mode->hdisplay ||
7279 	    high_mode->vdisplay != mode->vdisplay ||
7280 	    high_mode->hsync_start != mode->hsync_start ||
7281 	    high_mode->hsync_end != mode->hsync_end ||
7282 	    high_mode->htotal != mode->htotal ||
7283 	    high_mode->hskew != mode->hskew ||
7284 	    high_mode->vscan != mode->vscan ||
7285 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
7286 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
7287 		return false;
7288 	else
7289 		return true;
7290 }
7291 
7292 #if defined(CONFIG_DRM_AMD_DC_FP)
7293 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
7294 			    struct dc_sink *sink, struct dc_stream_state *stream,
7295 			    struct dsc_dec_dpcd_caps *dsc_caps)
7296 {
7297 	stream->timing.flags.DSC = 0;
7298 	dsc_caps->is_dsc_supported = false;
7299 
7300 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
7301 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
7302 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
7303 			sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
7304 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7305 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7306 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7307 				dsc_caps);
7308 	}
7309 }
7310 
7311 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
7312 				    struct dc_sink *sink, struct dc_stream_state *stream,
7313 				    struct dsc_dec_dpcd_caps *dsc_caps,
7314 				    uint32_t max_dsc_target_bpp_limit_override)
7315 {
7316 	const struct dc_link_settings *verified_link_cap = NULL;
7317 	u32 link_bw_in_kbps;
7318 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
7319 	struct dc *dc = sink->ctx->dc;
7320 	struct dc_dsc_bw_range bw_range = {0};
7321 	struct dc_dsc_config dsc_cfg = {0};
7322 	struct dc_dsc_config_options dsc_options = {0};
7323 
7324 	dc_dsc_get_default_config_option(dc, &dsc_options);
7325 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7326 
7327 	verified_link_cap = dc_link_get_link_cap(stream->link);
7328 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
7329 	edp_min_bpp_x16 = 8 * 16;
7330 	edp_max_bpp_x16 = 8 * 16;
7331 
7332 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
7333 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
7334 
7335 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
7336 		edp_min_bpp_x16 = edp_max_bpp_x16;
7337 
7338 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
7339 				dc->debug.dsc_min_slice_height_override,
7340 				edp_min_bpp_x16, edp_max_bpp_x16,
7341 				dsc_caps,
7342 				&stream->timing,
7343 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7344 				&bw_range)) {
7345 
7346 		if (bw_range.max_kbps < link_bw_in_kbps) {
7347 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7348 					dsc_caps,
7349 					&dsc_options,
7350 					0,
7351 					&stream->timing,
7352 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7353 					&dsc_cfg)) {
7354 				stream->timing.dsc_cfg = dsc_cfg;
7355 				stream->timing.flags.DSC = 1;
7356 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
7357 			}
7358 			return;
7359 		}
7360 	}
7361 
7362 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7363 				dsc_caps,
7364 				&dsc_options,
7365 				link_bw_in_kbps,
7366 				&stream->timing,
7367 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7368 				&dsc_cfg)) {
7369 		stream->timing.dsc_cfg = dsc_cfg;
7370 		stream->timing.flags.DSC = 1;
7371 	}
7372 }
7373 
7374 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
7375 					struct dc_sink *sink, struct dc_stream_state *stream,
7376 					struct dsc_dec_dpcd_caps *dsc_caps)
7377 {
7378 	struct drm_connector *drm_connector = &aconnector->base;
7379 	u32 link_bandwidth_kbps;
7380 	struct dc *dc = sink->ctx->dc;
7381 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
7382 	u32 dsc_max_supported_bw_in_kbps;
7383 	u32 max_dsc_target_bpp_limit_override =
7384 		drm_connector->display_info.max_dsc_bpp;
7385 	struct dc_dsc_config_options dsc_options = {0};
7386 
7387 	dc_dsc_get_default_config_option(dc, &dsc_options);
7388 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7389 
7390 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
7391 							dc_link_get_link_cap(aconnector->dc_link));
7392 
7393 	/* Set DSC policy according to dsc_clock_en */
7394 	dc_dsc_policy_set_enable_dsc_when_not_needed(
7395 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
7396 
7397 	if (sink->sink_signal == SIGNAL_TYPE_EDP &&
7398 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
7399 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
7400 
7401 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
7402 
7403 	} else if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
7404 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
7405 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7406 						dsc_caps,
7407 						&dsc_options,
7408 						link_bandwidth_kbps,
7409 						&stream->timing,
7410 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7411 						&stream->timing.dsc_cfg)) {
7412 				stream->timing.flags.DSC = 1;
7413 				drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from SST RX\n",
7414 							__func__, drm_connector->name);
7415 			}
7416 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7417 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
7418 					dc_link_get_highest_encoding_format(aconnector->dc_link));
7419 			max_supported_bw_in_kbps = link_bandwidth_kbps;
7420 			dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
7421 
7422 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
7423 					max_supported_bw_in_kbps > 0 &&
7424 					dsc_max_supported_bw_in_kbps > 0)
7425 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7426 						dsc_caps,
7427 						&dsc_options,
7428 						dsc_max_supported_bw_in_kbps,
7429 						&stream->timing,
7430 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7431 						&stream->timing.dsc_cfg)) {
7432 					stream->timing.flags.DSC = 1;
7433 					drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from DP-HDMI PCON\n",
7434 									 __func__, drm_connector->name);
7435 				}
7436 		}
7437 	}
7438 
7439 	/* Overwrite the stream flag if DSC is enabled through debugfs */
7440 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
7441 		stream->timing.flags.DSC = 1;
7442 
7443 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
7444 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
7445 
7446 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
7447 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
7448 
7449 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
7450 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
7451 }
7452 #endif
7453 
7454 static struct dc_stream_state *
7455 create_stream_for_sink(struct drm_connector *connector,
7456 		       const struct drm_display_mode *drm_mode,
7457 		       const struct dm_connector_state *dm_state,
7458 		       const struct dc_stream_state *old_stream,
7459 		       int requested_bpc)
7460 {
7461 	struct drm_device *dev = connector->dev;
7462 	struct amdgpu_dm_connector *aconnector = NULL;
7463 	struct drm_display_mode *preferred_mode = NULL;
7464 	const struct drm_connector_state *con_state = &dm_state->base;
7465 	struct dc_stream_state *stream = NULL;
7466 	struct drm_display_mode mode;
7467 	struct drm_display_mode saved_mode;
7468 	struct drm_display_mode *freesync_mode = NULL;
7469 	bool native_mode_found = false;
7470 	bool recalculate_timing = false;
7471 	bool scale = dm_state->scaling != RMX_OFF;
7472 	int mode_refresh;
7473 	int preferred_refresh = 0;
7474 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
7475 #if defined(CONFIG_DRM_AMD_DC_FP)
7476 	struct dsc_dec_dpcd_caps dsc_caps = {0};
7477 #endif
7478 	struct dc_link *link = NULL;
7479 	struct dc_sink *sink = NULL;
7480 
7481 	drm_mode_init(&mode, drm_mode);
7482 	memset(&saved_mode, 0, sizeof(saved_mode));
7483 
7484 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK) {
7485 		aconnector = NULL;
7486 		aconnector = to_amdgpu_dm_connector(connector);
7487 		link = aconnector->dc_link;
7488 	} else {
7489 		struct drm_writeback_connector *wbcon = NULL;
7490 		struct amdgpu_dm_wb_connector *dm_wbcon = NULL;
7491 
7492 		wbcon = drm_connector_to_writeback(connector);
7493 		dm_wbcon = to_amdgpu_dm_wb_connector(wbcon);
7494 		link = dm_wbcon->link;
7495 	}
7496 
7497 	if (!aconnector || !aconnector->dc_sink) {
7498 		sink = create_fake_sink(dev, link);
7499 		if (!sink)
7500 			return stream;
7501 
7502 	} else {
7503 		sink = aconnector->dc_sink;
7504 		dc_sink_retain(sink);
7505 	}
7506 
7507 	stream = dc_create_stream_for_sink(sink);
7508 
7509 	if (stream == NULL) {
7510 		drm_err(dev, "Failed to create stream for sink!\n");
7511 		goto finish;
7512 	}
7513 
7514 	/* We leave this NULL for writeback connectors */
7515 	stream->dm_stream_context = aconnector;
7516 
7517 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
7518 		connector->display_info.hdmi.scdc.scrambling.low_rates;
7519 
7520 	list_for_each_entry(preferred_mode, &connector->modes, head) {
7521 		/* Search for preferred mode */
7522 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
7523 			native_mode_found = true;
7524 			break;
7525 		}
7526 	}
7527 	if (!native_mode_found)
7528 		preferred_mode = list_first_entry_or_null(
7529 				&connector->modes,
7530 				struct drm_display_mode,
7531 				head);
7532 
7533 	mode_refresh = drm_mode_vrefresh(&mode);
7534 
7535 	if (preferred_mode == NULL) {
7536 		/*
7537 		 * This may not be an error, the use case is when we have no
7538 		 * usermode calls to reset and set mode upon hotplug. In this
7539 		 * case, we call set mode ourselves to restore the previous mode
7540 		 * and the modelist may not be filled in time.
7541 		 */
7542 		drm_dbg_driver(dev, "No preferred mode found\n");
7543 	} else if (aconnector) {
7544 		recalculate_timing = amdgpu_freesync_vid_mode &&
7545 				 is_freesync_video_mode(&mode, aconnector);
7546 		if (recalculate_timing) {
7547 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
7548 			drm_mode_copy(&saved_mode, &mode);
7549 			saved_mode.picture_aspect_ratio = mode.picture_aspect_ratio;
7550 			drm_mode_copy(&mode, freesync_mode);
7551 			mode.picture_aspect_ratio = saved_mode.picture_aspect_ratio;
7552 		} else {
7553 			decide_crtc_timing_for_drm_display_mode(
7554 					&mode, preferred_mode, scale);
7555 
7556 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
7557 		}
7558 	}
7559 
7560 	if (recalculate_timing)
7561 		drm_mode_set_crtcinfo(&saved_mode, 0);
7562 
7563 	/*
7564 	 * If scaling is enabled and refresh rate didn't change
7565 	 * we copy the vic and polarities of the old timings
7566 	 */
7567 	if (!scale || mode_refresh != preferred_refresh)
7568 		fill_stream_properties_from_drm_display_mode(
7569 			stream, &mode, connector, con_state, NULL,
7570 			requested_bpc);
7571 	else
7572 		fill_stream_properties_from_drm_display_mode(
7573 			stream, &mode, connector, con_state, old_stream,
7574 			requested_bpc);
7575 
7576 	/* The rest isn't needed for writeback connectors */
7577 	if (!aconnector)
7578 		goto finish;
7579 
7580 	if (aconnector->timing_changed) {
7581 		drm_dbg(aconnector->base.dev,
7582 			"overriding timing for automated test, bpc %d, changing to %d\n",
7583 			stream->timing.display_color_depth,
7584 			aconnector->timing_requested->display_color_depth);
7585 		stream->timing = *aconnector->timing_requested;
7586 	}
7587 
7588 #if defined(CONFIG_DRM_AMD_DC_FP)
7589 	/* SST DSC determination policy */
7590 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
7591 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
7592 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
7593 #endif
7594 
7595 	update_stream_scaling_settings(dev, &mode, dm_state, stream);
7596 
7597 	fill_audio_info(
7598 		&stream->audio_info,
7599 		connector,
7600 		sink);
7601 
7602 	update_stream_signal(stream, sink);
7603 
7604 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
7605 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket);
7606 
7607 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT ||
7608 	    stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
7609 	    stream->signal == SIGNAL_TYPE_EDP) {
7610 		const struct dc_edid_caps *edid_caps;
7611 		unsigned int disable_colorimetry = 0;
7612 
7613 		if (aconnector->dc_sink) {
7614 			edid_caps = &aconnector->dc_sink->edid_caps;
7615 			disable_colorimetry = edid_caps->panel_patch.disable_colorimetry;
7616 		}
7617 
7618 		//
7619 		// should decide stream support vsc sdp colorimetry capability
7620 		// before building vsc info packet
7621 		//
7622 		stream->use_vsc_sdp_for_colorimetry = stream->link->dpcd_caps.dpcd_rev.raw >= 0x14 &&
7623 						      stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED &&
7624 						      !disable_colorimetry;
7625 
7626 		if (stream->out_transfer_func.tf == TRANSFER_FUNCTION_GAMMA22)
7627 			tf = TRANSFER_FUNC_GAMMA_22;
7628 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
7629 		aconnector->sr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
7630 
7631 	}
7632 finish:
7633 	dc_sink_release(sink);
7634 
7635 	return stream;
7636 }
7637 
7638 /**
7639  * amdgpu_dm_connector_poll - Poll a connector to see if it's connected to a display
7640  * @aconnector: DM connector to poll (owns @base drm_connector and @dc_link)
7641  * @force: if true, force polling even when DAC load detection was used
7642  *
7643  * Used for connectors that don't support HPD (hotplug detection) to
7644  * periodically check whether the connector is connected to a display.
7645  *
7646  * When connection was determined via DAC load detection, we avoid
7647  * re-running it on normal polls to prevent visible glitches, unless
7648  * @force is set.
7649  *
7650  * Return: The probed connector status (connected/disconnected/unknown).
7651  */
7652 static enum drm_connector_status
7653 amdgpu_dm_connector_poll(struct amdgpu_dm_connector *aconnector, bool force)
7654 {
7655 	struct drm_connector *connector = &aconnector->base;
7656 	struct drm_device *dev = connector->dev;
7657 	struct amdgpu_device *adev = drm_to_adev(dev);
7658 	struct dc_link *link = aconnector->dc_link;
7659 	enum dc_connection_type conn_type = dc_connection_none;
7660 	enum drm_connector_status status = connector_status_disconnected;
7661 
7662 	/* When we determined the connection using DAC load detection,
7663 	 * do NOT poll the connector do detect disconnect because
7664 	 * that would run DAC load detection again which can cause
7665 	 * visible visual glitches.
7666 	 *
7667 	 * Only allow to poll such a connector again when forcing.
7668 	 */
7669 	if (!force && link->local_sink && link->type == dc_connection_analog_load)
7670 		return connector->status;
7671 
7672 	mutex_lock(&aconnector->hpd_lock);
7673 
7674 	if (dc_link_detect_connection_type(aconnector->dc_link, &conn_type) &&
7675 	    conn_type != dc_connection_none) {
7676 		mutex_lock(&adev->dm.dc_lock);
7677 
7678 		/* Only call full link detection when a sink isn't created yet,
7679 		 * ie. just when the display is plugged in, otherwise we risk flickering.
7680 		 */
7681 		if (link->local_sink ||
7682 			dc_link_detect(link, DETECT_REASON_HPD))
7683 			status = connector_status_connected;
7684 
7685 		mutex_unlock(&adev->dm.dc_lock);
7686 	}
7687 
7688 	if (connector->status != status) {
7689 		if (status == connector_status_disconnected) {
7690 			if (link->local_sink)
7691 				dc_sink_release(link->local_sink);
7692 
7693 			link->local_sink = NULL;
7694 			link->dpcd_sink_count = 0;
7695 			link->type = dc_connection_none;
7696 		}
7697 
7698 		amdgpu_dm_update_connector_after_detect(aconnector);
7699 	}
7700 
7701 	mutex_unlock(&aconnector->hpd_lock);
7702 	return status;
7703 }
7704 
7705 /**
7706  * amdgpu_dm_connector_detect() - Detect whether a DRM connector is connected to a display
7707  *
7708  * A connector is considered connected when it has a sink that is not NULL.
7709  * For connectors that support HPD (hotplug detection), the connection is
7710  * handled in the HPD interrupt.
7711  * For connectors that may not support HPD, such as analog connectors,
7712  * DRM will call this function repeatedly to poll them.
7713  *
7714  * Notes:
7715  * 1. This interface is NOT called in context of HPD irq.
7716  * 2. This interface *is called* in context of user-mode ioctl. Which
7717  *    makes it a bad place for *any* MST-related activity.
7718  *
7719  * @connector: The DRM connector we are checking. We convert it to
7720  *             amdgpu_dm_connector so we can read the DC link and state.
7721  * @force:     If true, do a full detect again. This is used even when
7722  *             a lighter check would normally be used to avoid flicker.
7723  *
7724  * Return: The connector status (connected, disconnected, or unknown).
7725  *
7726  */
7727 static enum drm_connector_status
7728 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
7729 {
7730 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7731 
7732 	update_subconnector_property(aconnector);
7733 
7734 	if (aconnector->base.force == DRM_FORCE_ON ||
7735 		aconnector->base.force == DRM_FORCE_ON_DIGITAL)
7736 		return connector_status_connected;
7737 	else if (aconnector->base.force == DRM_FORCE_OFF)
7738 		return connector_status_disconnected;
7739 
7740 	/* Poll analog connectors and only when either
7741 	 * disconnected or connected to an analog display.
7742 	 */
7743 	if (drm_kms_helper_is_poll_worker() &&
7744 		dc_connector_supports_analog(aconnector->dc_link->link_id.id) &&
7745 		(!aconnector->dc_sink || aconnector->dc_sink->edid_caps.analog))
7746 		return amdgpu_dm_connector_poll(aconnector, force);
7747 
7748 	return (aconnector->dc_sink ? connector_status_connected :
7749 			connector_status_disconnected);
7750 }
7751 
7752 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
7753 					    struct drm_connector_state *connector_state,
7754 					    struct drm_property *property,
7755 					    uint64_t val)
7756 {
7757 	struct drm_device *dev = connector->dev;
7758 	struct amdgpu_device *adev = drm_to_adev(dev);
7759 	struct dm_connector_state *dm_old_state =
7760 		to_dm_connector_state(connector->state);
7761 	struct dm_connector_state *dm_new_state =
7762 		to_dm_connector_state(connector_state);
7763 
7764 	int ret = -EINVAL;
7765 
7766 	if (property == dev->mode_config.scaling_mode_property) {
7767 		enum amdgpu_rmx_type rmx_type;
7768 
7769 		switch (val) {
7770 		case DRM_MODE_SCALE_CENTER:
7771 			rmx_type = RMX_CENTER;
7772 			break;
7773 		case DRM_MODE_SCALE_ASPECT:
7774 			rmx_type = RMX_ASPECT;
7775 			break;
7776 		case DRM_MODE_SCALE_FULLSCREEN:
7777 			rmx_type = RMX_FULL;
7778 			break;
7779 		case DRM_MODE_SCALE_NONE:
7780 		default:
7781 			rmx_type = RMX_OFF;
7782 			break;
7783 		}
7784 
7785 		if (dm_old_state->scaling == rmx_type)
7786 			return 0;
7787 
7788 		dm_new_state->scaling = rmx_type;
7789 		ret = 0;
7790 	} else if (property == adev->mode_info.underscan_hborder_property) {
7791 		dm_new_state->underscan_hborder = val;
7792 		ret = 0;
7793 	} else if (property == adev->mode_info.underscan_vborder_property) {
7794 		dm_new_state->underscan_vborder = val;
7795 		ret = 0;
7796 	} else if (property == adev->mode_info.underscan_property) {
7797 		dm_new_state->underscan_enable = val;
7798 		ret = 0;
7799 	} else if (property == adev->mode_info.abm_level_property) {
7800 		switch (val) {
7801 		case ABM_SYSFS_CONTROL:
7802 			dm_new_state->abm_sysfs_forbidden = false;
7803 			break;
7804 		case ABM_LEVEL_OFF:
7805 			dm_new_state->abm_sysfs_forbidden = true;
7806 			dm_new_state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7807 			break;
7808 		default:
7809 			dm_new_state->abm_sysfs_forbidden = true;
7810 			dm_new_state->abm_level = val;
7811 		}
7812 		ret = 0;
7813 	}
7814 
7815 	return ret;
7816 }
7817 
7818 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
7819 					    const struct drm_connector_state *state,
7820 					    struct drm_property *property,
7821 					    uint64_t *val)
7822 {
7823 	struct drm_device *dev = connector->dev;
7824 	struct amdgpu_device *adev = drm_to_adev(dev);
7825 	struct dm_connector_state *dm_state =
7826 		to_dm_connector_state(state);
7827 	int ret = -EINVAL;
7828 
7829 	if (property == dev->mode_config.scaling_mode_property) {
7830 		switch (dm_state->scaling) {
7831 		case RMX_CENTER:
7832 			*val = DRM_MODE_SCALE_CENTER;
7833 			break;
7834 		case RMX_ASPECT:
7835 			*val = DRM_MODE_SCALE_ASPECT;
7836 			break;
7837 		case RMX_FULL:
7838 			*val = DRM_MODE_SCALE_FULLSCREEN;
7839 			break;
7840 		case RMX_OFF:
7841 		default:
7842 			*val = DRM_MODE_SCALE_NONE;
7843 			break;
7844 		}
7845 		ret = 0;
7846 	} else if (property == adev->mode_info.underscan_hborder_property) {
7847 		*val = dm_state->underscan_hborder;
7848 		ret = 0;
7849 	} else if (property == adev->mode_info.underscan_vborder_property) {
7850 		*val = dm_state->underscan_vborder;
7851 		ret = 0;
7852 	} else if (property == adev->mode_info.underscan_property) {
7853 		*val = dm_state->underscan_enable;
7854 		ret = 0;
7855 	} else if (property == adev->mode_info.abm_level_property) {
7856 		if (!dm_state->abm_sysfs_forbidden)
7857 			*val = ABM_SYSFS_CONTROL;
7858 		else
7859 			*val = (dm_state->abm_level != ABM_LEVEL_IMMEDIATE_DISABLE) ?
7860 				dm_state->abm_level : 0;
7861 		ret = 0;
7862 	}
7863 
7864 	return ret;
7865 }
7866 
7867 /**
7868  * DOC: panel power savings
7869  *
7870  * The display manager allows you to set your desired **panel power savings**
7871  * level (between 0-4, with 0 representing off), e.g. using the following::
7872  *
7873  *   # echo 3 > /sys/class/drm/card0-eDP-1/amdgpu/panel_power_savings
7874  *
7875  * Modifying this value can have implications on color accuracy, so tread
7876  * carefully.
7877  */
7878 
7879 static ssize_t panel_power_savings_show(struct device *device,
7880 					struct device_attribute *attr,
7881 					char *buf)
7882 {
7883 	struct drm_connector *connector = dev_get_drvdata(device);
7884 	struct drm_device *dev = connector->dev;
7885 	u8 val;
7886 
7887 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
7888 	val = to_dm_connector_state(connector->state)->abm_level ==
7889 		ABM_LEVEL_IMMEDIATE_DISABLE ? 0 :
7890 		to_dm_connector_state(connector->state)->abm_level;
7891 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
7892 
7893 	return sysfs_emit(buf, "%u\n", val);
7894 }
7895 
7896 static ssize_t panel_power_savings_store(struct device *device,
7897 					 struct device_attribute *attr,
7898 					 const char *buf, size_t count)
7899 {
7900 	struct drm_connector *connector = dev_get_drvdata(device);
7901 	struct drm_device *dev = connector->dev;
7902 	long val;
7903 	int ret;
7904 
7905 	ret = kstrtol(buf, 0, &val);
7906 
7907 	if (ret)
7908 		return ret;
7909 
7910 	if (val < 0 || val > 4)
7911 		return -EINVAL;
7912 
7913 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
7914 	if (to_dm_connector_state(connector->state)->abm_sysfs_forbidden)
7915 		ret = -EBUSY;
7916 	else
7917 		to_dm_connector_state(connector->state)->abm_level = val ?:
7918 			ABM_LEVEL_IMMEDIATE_DISABLE;
7919 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
7920 
7921 	if (ret)
7922 		return ret;
7923 
7924 	drm_kms_helper_hotplug_event(dev);
7925 
7926 	return count;
7927 }
7928 
7929 static DEVICE_ATTR_RW(panel_power_savings);
7930 
7931 static struct attribute *amdgpu_attrs[] = {
7932 	&dev_attr_panel_power_savings.attr,
7933 	NULL
7934 };
7935 
7936 static const struct attribute_group amdgpu_group = {
7937 	.name = "amdgpu",
7938 	.attrs = amdgpu_attrs
7939 };
7940 
7941 static bool
7942 amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector *amdgpu_dm_connector)
7943 {
7944 	if (amdgpu_dm_abm_level >= 0)
7945 		return false;
7946 
7947 	if (amdgpu_dm_connector->base.connector_type != DRM_MODE_CONNECTOR_eDP)
7948 		return false;
7949 
7950 	/* check for OLED panels */
7951 	if (amdgpu_dm_connector->bl_idx >= 0) {
7952 		struct drm_device *drm = amdgpu_dm_connector->base.dev;
7953 		struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
7954 		struct amdgpu_dm_backlight_caps *caps;
7955 
7956 		caps = &dm->backlight_caps[amdgpu_dm_connector->bl_idx];
7957 		if (caps->aux_support)
7958 			return false;
7959 	}
7960 
7961 	return true;
7962 }
7963 
7964 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
7965 {
7966 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
7967 
7968 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector))
7969 		sysfs_remove_group(&connector->kdev->kobj, &amdgpu_group);
7970 
7971 	cec_notifier_conn_unregister(amdgpu_dm_connector->notifier);
7972 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
7973 }
7974 
7975 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
7976 {
7977 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7978 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
7979 	struct amdgpu_display_manager *dm = &adev->dm;
7980 
7981 	/*
7982 	 * Call only if mst_mgr was initialized before since it's not done
7983 	 * for all connector types.
7984 	 */
7985 	if (aconnector->mst_mgr.dev)
7986 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
7987 
7988 	/* Cancel and flush any pending HDMI HPD debounce work */
7989 	if (aconnector->hdmi_hpd_debounce_delay_ms) {
7990 		cancel_delayed_work_sync(&aconnector->hdmi_hpd_debounce_work);
7991 		if (aconnector->hdmi_prev_sink) {
7992 			dc_sink_release(aconnector->hdmi_prev_sink);
7993 			aconnector->hdmi_prev_sink = NULL;
7994 		}
7995 	}
7996 
7997 	if (aconnector->bl_idx != -1) {
7998 		backlight_device_unregister(dm->backlight_dev[aconnector->bl_idx]);
7999 		dm->backlight_dev[aconnector->bl_idx] = NULL;
8000 	}
8001 
8002 	if (aconnector->dc_em_sink)
8003 		dc_sink_release(aconnector->dc_em_sink);
8004 	aconnector->dc_em_sink = NULL;
8005 	if (aconnector->dc_sink)
8006 		dc_sink_release(aconnector->dc_sink);
8007 	aconnector->dc_sink = NULL;
8008 
8009 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
8010 	drm_connector_unregister(connector);
8011 	drm_connector_cleanup(connector);
8012 	kfree(aconnector->dm_dp_aux.aux.name);
8013 
8014 	kfree(connector);
8015 }
8016 
8017 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
8018 {
8019 	struct dm_connector_state *state =
8020 		to_dm_connector_state(connector->state);
8021 
8022 	if (connector->state)
8023 		__drm_atomic_helper_connector_destroy_state(connector->state);
8024 
8025 	kfree(state);
8026 
8027 	state = kzalloc_obj(*state);
8028 
8029 	if (state) {
8030 		state->scaling = RMX_OFF;
8031 		state->underscan_enable = false;
8032 		state->underscan_hborder = 0;
8033 		state->underscan_vborder = 0;
8034 		state->base.max_requested_bpc = 8;
8035 		state->vcpi_slots = 0;
8036 		state->pbn = 0;
8037 
8038 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) {
8039 			if (amdgpu_dm_abm_level <= 0)
8040 				state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
8041 			else
8042 				state->abm_level = amdgpu_dm_abm_level;
8043 		}
8044 
8045 		__drm_atomic_helper_connector_reset(connector, &state->base);
8046 	}
8047 }
8048 
8049 struct drm_connector_state *
8050 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
8051 {
8052 	struct dm_connector_state *state =
8053 		to_dm_connector_state(connector->state);
8054 
8055 	struct dm_connector_state *new_state =
8056 			kmemdup(state, sizeof(*state), GFP_KERNEL);
8057 
8058 	if (!new_state)
8059 		return NULL;
8060 
8061 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
8062 
8063 	new_state->freesync_capable = state->freesync_capable;
8064 	new_state->abm_level = state->abm_level;
8065 	new_state->scaling = state->scaling;
8066 	new_state->underscan_enable = state->underscan_enable;
8067 	new_state->underscan_hborder = state->underscan_hborder;
8068 	new_state->underscan_vborder = state->underscan_vborder;
8069 	new_state->vcpi_slots = state->vcpi_slots;
8070 	new_state->pbn = state->pbn;
8071 	return &new_state->base;
8072 }
8073 
8074 static int
8075 amdgpu_dm_connector_late_register(struct drm_connector *connector)
8076 {
8077 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8078 		to_amdgpu_dm_connector(connector);
8079 	int r;
8080 
8081 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector)) {
8082 		r = sysfs_create_group(&connector->kdev->kobj,
8083 				       &amdgpu_group);
8084 		if (r)
8085 			return r;
8086 	}
8087 
8088 	amdgpu_dm_register_backlight_device(amdgpu_dm_connector);
8089 
8090 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
8091 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
8092 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
8093 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
8094 		if (r)
8095 			return r;
8096 	}
8097 
8098 #if defined(CONFIG_DEBUG_FS)
8099 	connector_debugfs_init(amdgpu_dm_connector);
8100 #endif
8101 
8102 	return 0;
8103 }
8104 
8105 static void amdgpu_dm_connector_funcs_force(struct drm_connector *connector)
8106 {
8107 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8108 	struct dc_link *dc_link = aconnector->dc_link;
8109 	struct dc_sink *dc_em_sink = aconnector->dc_em_sink;
8110 	const struct drm_edid *drm_edid;
8111 	struct i2c_adapter *ddc;
8112 	struct drm_device *dev = connector->dev;
8113 
8114 	if (dc_link && dc_link->aux_mode)
8115 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8116 	else
8117 		ddc = &aconnector->i2c->base;
8118 
8119 	drm_edid = drm_edid_read_ddc(connector, ddc);
8120 	drm_edid_connector_update(connector, drm_edid);
8121 	if (!drm_edid) {
8122 		drm_err(dev, "No EDID found on connector: %s.\n", connector->name);
8123 		return;
8124 	}
8125 
8126 	aconnector->drm_edid = drm_edid;
8127 	/* Update emulated (virtual) sink's EDID */
8128 	if (dc_em_sink && dc_link) {
8129 		// FIXME: Get rid of drm_edid_raw()
8130 		const struct edid *edid = drm_edid_raw(drm_edid);
8131 
8132 		memset(&dc_em_sink->edid_caps, 0, sizeof(struct dc_edid_caps));
8133 		memmove(dc_em_sink->dc_edid.raw_edid, edid,
8134 			(edid->extensions + 1) * EDID_LENGTH);
8135 		dm_helpers_parse_edid_caps(
8136 			dc_link,
8137 			&dc_em_sink->dc_edid,
8138 			&dc_em_sink->edid_caps);
8139 	}
8140 }
8141 
8142 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
8143 	.reset = amdgpu_dm_connector_funcs_reset,
8144 	.detect = amdgpu_dm_connector_detect,
8145 	.fill_modes = drm_helper_probe_single_connector_modes,
8146 	.destroy = amdgpu_dm_connector_destroy,
8147 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
8148 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
8149 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
8150 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
8151 	.late_register = amdgpu_dm_connector_late_register,
8152 	.early_unregister = amdgpu_dm_connector_unregister,
8153 	.force = amdgpu_dm_connector_funcs_force
8154 };
8155 
8156 static int get_modes(struct drm_connector *connector)
8157 {
8158 	return amdgpu_dm_connector_get_modes(connector);
8159 }
8160 
8161 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
8162 {
8163 	struct drm_connector *connector = &aconnector->base;
8164 	struct dc_link *dc_link = aconnector->dc_link;
8165 	struct dc_sink_init_data init_params = {
8166 			.link = aconnector->dc_link,
8167 			.sink_signal = SIGNAL_TYPE_VIRTUAL
8168 	};
8169 	const struct drm_edid *drm_edid;
8170 	const struct edid *edid;
8171 	struct i2c_adapter *ddc;
8172 
8173 	if (dc_link && dc_link->aux_mode)
8174 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8175 	else
8176 		ddc = &aconnector->i2c->base;
8177 
8178 	drm_edid = drm_edid_read_ddc(connector, ddc);
8179 	drm_edid_connector_update(connector, drm_edid);
8180 	if (!drm_edid) {
8181 		drm_err(connector->dev, "No EDID found on connector: %s.\n", connector->name);
8182 		return;
8183 	}
8184 
8185 	if (connector->display_info.is_hdmi)
8186 		init_params.sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
8187 
8188 	aconnector->drm_edid = drm_edid;
8189 
8190 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
8191 	aconnector->dc_em_sink = dc_link_add_remote_sink(
8192 		aconnector->dc_link,
8193 		(uint8_t *)edid,
8194 		(edid->extensions + 1) * EDID_LENGTH,
8195 		&init_params);
8196 
8197 	if (aconnector->base.force == DRM_FORCE_ON) {
8198 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
8199 		aconnector->dc_link->local_sink :
8200 		aconnector->dc_em_sink;
8201 		if (aconnector->dc_sink)
8202 			dc_sink_retain(aconnector->dc_sink);
8203 	}
8204 }
8205 
8206 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
8207 {
8208 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
8209 
8210 	/*
8211 	 * In case of headless boot with force on for DP managed connector
8212 	 * Those settings have to be != 0 to get initial modeset
8213 	 */
8214 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
8215 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
8216 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
8217 	}
8218 
8219 	create_eml_sink(aconnector);
8220 }
8221 
8222 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
8223 						struct dc_stream_state *stream)
8224 {
8225 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
8226 	struct dc_plane_state *dc_plane_state = NULL;
8227 	struct dc_state *dc_state = NULL;
8228 
8229 	if (!stream)
8230 		goto cleanup;
8231 
8232 	dc_plane_state = dc_create_plane_state(dc);
8233 	if (!dc_plane_state)
8234 		goto cleanup;
8235 
8236 	dc_state = dc_state_create(dc, NULL);
8237 	if (!dc_state)
8238 		goto cleanup;
8239 
8240 	/* populate stream to plane */
8241 	dc_plane_state->src_rect.height  = stream->src.height;
8242 	dc_plane_state->src_rect.width   = stream->src.width;
8243 	dc_plane_state->dst_rect.height  = stream->src.height;
8244 	dc_plane_state->dst_rect.width   = stream->src.width;
8245 	dc_plane_state->clip_rect.height = stream->src.height;
8246 	dc_plane_state->clip_rect.width  = stream->src.width;
8247 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
8248 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
8249 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
8250 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
8251 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
8252 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
8253 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
8254 	dc_plane_state->rotation = ROTATION_ANGLE_0;
8255 	dc_plane_state->is_tiling_rotated = false;
8256 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
8257 
8258 	dc_result = dc_validate_stream(dc, stream);
8259 	if (dc_result == DC_OK)
8260 		dc_result = dc_validate_plane(dc, dc_plane_state);
8261 
8262 	if (dc_result == DC_OK)
8263 		dc_result = dc_state_add_stream(dc, dc_state, stream);
8264 
8265 	if (dc_result == DC_OK && !dc_state_add_plane(
8266 						dc,
8267 						stream,
8268 						dc_plane_state,
8269 						dc_state))
8270 		dc_result = DC_FAIL_ATTACH_SURFACES;
8271 
8272 	if (dc_result == DC_OK)
8273 		dc_result = dc_validate_global_state(dc, dc_state, DC_VALIDATE_MODE_ONLY);
8274 
8275 cleanup:
8276 	if (dc_state)
8277 		dc_state_release(dc_state);
8278 
8279 	if (dc_plane_state)
8280 		dc_plane_state_release(dc_plane_state);
8281 
8282 	return dc_result;
8283 }
8284 
8285 struct dc_stream_state *
8286 create_validate_stream_for_sink(struct drm_connector *connector,
8287 				const struct drm_display_mode *drm_mode,
8288 				const struct dm_connector_state *dm_state,
8289 				const struct dc_stream_state *old_stream)
8290 {
8291 	struct amdgpu_dm_connector *aconnector = NULL;
8292 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8293 	struct dc_stream_state *stream;
8294 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
8295 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
8296 	enum dc_status dc_result = DC_OK;
8297 	uint8_t bpc_limit = 6;
8298 
8299 	if (!dm_state)
8300 		return NULL;
8301 
8302 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
8303 		aconnector = to_amdgpu_dm_connector(connector);
8304 
8305 	if (aconnector &&
8306 	    (aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
8307 	     aconnector->dc_link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER))
8308 		bpc_limit = 8;
8309 
8310 	do {
8311 		drm_dbg_kms(connector->dev, "Trying with %d bpc\n", requested_bpc);
8312 		stream = create_stream_for_sink(connector, drm_mode,
8313 						dm_state, old_stream,
8314 						requested_bpc);
8315 		if (stream == NULL) {
8316 			drm_err(adev_to_drm(adev), "Failed to create stream for sink!\n");
8317 			break;
8318 		}
8319 
8320 		dc_result = dc_validate_stream(adev->dm.dc, stream);
8321 
8322 		if (!aconnector) /* writeback connector */
8323 			return stream;
8324 
8325 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
8326 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
8327 
8328 		if (dc_result == DC_OK)
8329 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
8330 
8331 		if (dc_result != DC_OK) {
8332 			drm_dbg_kms(connector->dev, "Pruned mode %d x %d (clk %d) %s %s -- %s\n",
8333 				      drm_mode->hdisplay,
8334 				      drm_mode->vdisplay,
8335 				      drm_mode->clock,
8336 				      dc_pixel_encoding_to_str(stream->timing.pixel_encoding),
8337 				      dc_color_depth_to_str(stream->timing.display_color_depth),
8338 				      dc_status_to_str(dc_result));
8339 
8340 			dc_stream_release(stream);
8341 			stream = NULL;
8342 			requested_bpc -= 2; /* lower bpc to retry validation */
8343 		}
8344 
8345 	} while (stream == NULL && requested_bpc >= bpc_limit);
8346 
8347 	switch (dc_result) {
8348 	/*
8349 	 * If we failed to validate DP bandwidth stream with the requested RGB color depth,
8350 	 * we try to fallback and configure in order:
8351 	 * YUV422 (8bpc, 6bpc)
8352 	 * YUV420 (8bpc, 6bpc)
8353 	 */
8354 	case DC_FAIL_ENC_VALIDATE:
8355 	case DC_EXCEED_DONGLE_CAP:
8356 	case DC_NO_DP_LINK_BANDWIDTH:
8357 		/* recursively entered twice and already tried both YUV422 and YUV420 */
8358 		if (aconnector->force_yuv422_output && aconnector->force_yuv420_output)
8359 			break;
8360 		/* first failure; try YUV422 */
8361 		if (!aconnector->force_yuv422_output) {
8362 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV422\n",
8363 				    __func__, __LINE__, dc_result);
8364 			aconnector->force_yuv422_output = true;
8365 		/* recursively entered and YUV422 failed, try YUV420 */
8366 		} else if (!aconnector->force_yuv420_output) {
8367 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV420\n",
8368 				    __func__, __LINE__, dc_result);
8369 			aconnector->force_yuv420_output = true;
8370 		}
8371 		stream = create_validate_stream_for_sink(connector, drm_mode,
8372 							 dm_state, old_stream);
8373 		aconnector->force_yuv422_output = false;
8374 		aconnector->force_yuv420_output = false;
8375 		break;
8376 	case DC_OK:
8377 		break;
8378 	default:
8379 		drm_dbg_kms(connector->dev, "%s:%d Unhandled validation failure %d\n",
8380 			    __func__, __LINE__, dc_result);
8381 		break;
8382 	}
8383 
8384 	return stream;
8385 }
8386 
8387 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
8388 				   const struct drm_display_mode *mode)
8389 {
8390 	int result = MODE_ERROR;
8391 	struct dc_sink *dc_sink;
8392 	struct drm_display_mode *test_mode;
8393 	/* TODO: Unhardcode stream count */
8394 	struct dc_stream_state *stream;
8395 	/* we always have an amdgpu_dm_connector here since we got
8396 	 * here via the amdgpu_dm_connector_helper_funcs
8397 	 */
8398 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8399 
8400 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
8401 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
8402 		return result;
8403 
8404 	/*
8405 	 * Only run this the first time mode_valid is called to initilialize
8406 	 * EDID mgmt
8407 	 */
8408 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
8409 		!aconnector->dc_em_sink)
8410 		handle_edid_mgmt(aconnector);
8411 
8412 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
8413 
8414 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
8415 				aconnector->base.force != DRM_FORCE_ON) {
8416 		drm_err(connector->dev, "dc_sink is NULL!\n");
8417 		goto fail;
8418 	}
8419 
8420 	test_mode = drm_mode_duplicate(connector->dev, mode);
8421 	if (!test_mode)
8422 		goto fail;
8423 
8424 	drm_mode_set_crtcinfo(test_mode, 0);
8425 
8426 	stream = create_validate_stream_for_sink(connector, test_mode,
8427 						 to_dm_connector_state(connector->state),
8428 						 NULL);
8429 	drm_mode_destroy(connector->dev, test_mode);
8430 	if (stream) {
8431 		dc_stream_release(stream);
8432 		result = MODE_OK;
8433 	}
8434 
8435 fail:
8436 	/* TODO: error handling*/
8437 	return result;
8438 }
8439 
8440 static int fill_hdr_info_packet(const struct drm_connector_state *state,
8441 				struct dc_info_packet *out)
8442 {
8443 	struct hdmi_drm_infoframe frame;
8444 	unsigned char buf[30]; /* 26 + 4 */
8445 	ssize_t len;
8446 	int ret, i;
8447 
8448 	memset(out, 0, sizeof(*out));
8449 
8450 	if (!state->hdr_output_metadata)
8451 		return 0;
8452 
8453 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
8454 	if (ret)
8455 		return ret;
8456 
8457 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
8458 	if (len < 0)
8459 		return (int)len;
8460 
8461 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
8462 	if (len != 30)
8463 		return -EINVAL;
8464 
8465 	/* Prepare the infopacket for DC. */
8466 	switch (state->connector->connector_type) {
8467 	case DRM_MODE_CONNECTOR_HDMIA:
8468 		out->hb0 = 0x87; /* type */
8469 		out->hb1 = 0x01; /* version */
8470 		out->hb2 = 0x1A; /* length */
8471 		out->sb[0] = buf[3]; /* checksum */
8472 		i = 1;
8473 		break;
8474 
8475 	case DRM_MODE_CONNECTOR_DisplayPort:
8476 	case DRM_MODE_CONNECTOR_eDP:
8477 		out->hb0 = 0x00; /* sdp id, zero */
8478 		out->hb1 = 0x87; /* type */
8479 		out->hb2 = 0x1D; /* payload len - 1 */
8480 		out->hb3 = (0x13 << 2); /* sdp version */
8481 		out->sb[0] = 0x01; /* version */
8482 		out->sb[1] = 0x1A; /* length */
8483 		i = 2;
8484 		break;
8485 
8486 	default:
8487 		return -EINVAL;
8488 	}
8489 
8490 	memcpy(&out->sb[i], &buf[4], 26);
8491 	out->valid = true;
8492 
8493 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
8494 		       sizeof(out->sb), false);
8495 
8496 	return 0;
8497 }
8498 
8499 static int
8500 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
8501 				 struct drm_atomic_commit *state)
8502 {
8503 	struct drm_connector_state *new_con_state =
8504 		drm_atomic_get_new_connector_state(state, conn);
8505 	struct drm_connector_state *old_con_state =
8506 		drm_atomic_get_old_connector_state(state, conn);
8507 	struct drm_crtc *crtc = new_con_state->crtc;
8508 	struct drm_crtc_state *new_crtc_state;
8509 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
8510 	int ret;
8511 
8512 	if (WARN_ON(unlikely(!old_con_state || !new_con_state)))
8513 		return -EINVAL;
8514 
8515 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
8516 
8517 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
8518 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
8519 		if (ret < 0)
8520 			return ret;
8521 	}
8522 
8523 	if (!crtc)
8524 		return 0;
8525 
8526 	if (new_con_state->privacy_screen_sw_state != old_con_state->privacy_screen_sw_state) {
8527 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8528 		if (IS_ERR(new_crtc_state))
8529 			return PTR_ERR(new_crtc_state);
8530 
8531 		new_crtc_state->mode_changed = true;
8532 	}
8533 
8534 	if (new_con_state->colorspace != old_con_state->colorspace) {
8535 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8536 		if (IS_ERR(new_crtc_state))
8537 			return PTR_ERR(new_crtc_state);
8538 
8539 		new_crtc_state->mode_changed = true;
8540 	}
8541 
8542 	if (new_con_state->content_type != old_con_state->content_type) {
8543 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8544 		if (IS_ERR(new_crtc_state))
8545 			return PTR_ERR(new_crtc_state);
8546 
8547 		new_crtc_state->mode_changed = true;
8548 	}
8549 
8550 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
8551 		struct dc_info_packet hdr_infopacket;
8552 
8553 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
8554 		if (ret)
8555 			return ret;
8556 
8557 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8558 		if (IS_ERR(new_crtc_state))
8559 			return PTR_ERR(new_crtc_state);
8560 
8561 		/*
8562 		 * DC considers the stream backends changed if the
8563 		 * static metadata changes. Forcing the modeset also
8564 		 * gives a simple way for userspace to switch from
8565 		 * 8bpc to 10bpc when setting the metadata to enter
8566 		 * or exit HDR.
8567 		 *
8568 		 * Changing the static metadata after it's been
8569 		 * set is permissible, however. So only force a
8570 		 * modeset if we're entering or exiting HDR.
8571 		 */
8572 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
8573 			!old_con_state->hdr_output_metadata ||
8574 			!new_con_state->hdr_output_metadata;
8575 	}
8576 
8577 	return 0;
8578 }
8579 
8580 static const struct drm_connector_helper_funcs
8581 amdgpu_dm_connector_helper_funcs = {
8582 	/*
8583 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
8584 	 * modes will be filtered by drm_mode_validate_size(), and those modes
8585 	 * are missing after user start lightdm. So we need to renew modes list.
8586 	 * in get_modes call back, not just return the modes count
8587 	 */
8588 	.get_modes = get_modes,
8589 	.mode_valid = amdgpu_dm_connector_mode_valid,
8590 	.atomic_check = amdgpu_dm_connector_atomic_check,
8591 };
8592 
8593 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
8594 {
8595 
8596 }
8597 
8598 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
8599 {
8600 	switch (display_color_depth) {
8601 	case COLOR_DEPTH_666:
8602 		return 6;
8603 	case COLOR_DEPTH_888:
8604 		return 8;
8605 	case COLOR_DEPTH_101010:
8606 		return 10;
8607 	case COLOR_DEPTH_121212:
8608 		return 12;
8609 	case COLOR_DEPTH_141414:
8610 		return 14;
8611 	case COLOR_DEPTH_161616:
8612 		return 16;
8613 	default:
8614 		break;
8615 	}
8616 	return 0;
8617 }
8618 
8619 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
8620 					  struct drm_crtc_state *crtc_state,
8621 					  struct drm_connector_state *conn_state)
8622 {
8623 	struct drm_atomic_commit *state = crtc_state->state;
8624 	struct drm_connector *connector = conn_state->connector;
8625 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8626 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
8627 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
8628 	struct drm_dp_mst_topology_mgr *mst_mgr;
8629 	struct drm_dp_mst_port *mst_port;
8630 	struct drm_dp_mst_topology_state *mst_state;
8631 	enum dc_color_depth color_depth;
8632 	int clock, bpp = 0;
8633 	bool is_y420 = false;
8634 
8635 	if ((connector->connector_type == DRM_MODE_CONNECTOR_eDP) ||
8636 	    (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)) {
8637 		struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8638 		struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8639 		enum drm_mode_status result;
8640 
8641 		result = drm_crtc_helper_mode_valid_fixed(encoder->crtc, adjusted_mode, native_mode);
8642 		if (result != MODE_OK && dm_new_connector_state->scaling == RMX_OFF) {
8643 			drm_dbg_driver(encoder->dev,
8644 				       "mode %dx%d@%dHz is not native, enabling scaling\n",
8645 				       adjusted_mode->hdisplay, adjusted_mode->vdisplay,
8646 				       drm_mode_vrefresh(adjusted_mode));
8647 			dm_new_connector_state->scaling = RMX_ASPECT;
8648 		}
8649 		return 0;
8650 	}
8651 
8652 	if (!aconnector->mst_output_port)
8653 		return 0;
8654 
8655 	mst_port = aconnector->mst_output_port;
8656 	mst_mgr = &aconnector->mst_root->mst_mgr;
8657 
8658 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
8659 		return 0;
8660 
8661 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
8662 	if (IS_ERR(mst_state))
8663 		return PTR_ERR(mst_state);
8664 
8665 	mst_state->pbn_div.full = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
8666 
8667 	if (!state->duplicated) {
8668 		int max_bpc = conn_state->max_requested_bpc;
8669 
8670 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
8671 			  aconnector->force_yuv420_output;
8672 		color_depth = convert_color_depth_from_display_info(connector,
8673 								    is_y420,
8674 								    max_bpc);
8675 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
8676 		clock = adjusted_mode->clock;
8677 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
8678 	}
8679 
8680 	dm_new_connector_state->vcpi_slots =
8681 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
8682 					      dm_new_connector_state->pbn);
8683 	if (dm_new_connector_state->vcpi_slots < 0) {
8684 		drm_dbg_atomic(connector->dev, "failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
8685 		return dm_new_connector_state->vcpi_slots;
8686 	}
8687 	return 0;
8688 }
8689 
8690 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
8691 	.disable = dm_encoder_helper_disable,
8692 	.atomic_check = dm_encoder_helper_atomic_check
8693 };
8694 
8695 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_commit *state,
8696 					    struct dc_state *dc_state,
8697 					    struct dsc_mst_fairness_vars *vars)
8698 {
8699 	struct dc_stream_state *stream = NULL;
8700 	struct drm_connector *connector;
8701 	struct drm_connector_state *new_con_state;
8702 	struct amdgpu_dm_connector *aconnector;
8703 	struct dm_connector_state *dm_conn_state;
8704 	int i, j, ret;
8705 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
8706 
8707 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8708 
8709 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
8710 			continue;
8711 
8712 		aconnector = to_amdgpu_dm_connector(connector);
8713 
8714 		if (!aconnector->mst_output_port)
8715 			continue;
8716 
8717 		if (!new_con_state || !new_con_state->crtc)
8718 			continue;
8719 
8720 		dm_conn_state = to_dm_connector_state(new_con_state);
8721 
8722 		for (j = 0; j < dc_state->stream_count; j++) {
8723 			stream = dc_state->streams[j];
8724 			if (!stream)
8725 				continue;
8726 
8727 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
8728 				break;
8729 
8730 			stream = NULL;
8731 		}
8732 
8733 		if (!stream)
8734 			continue;
8735 
8736 		pbn_div = dm_mst_get_pbn_divider(stream->link);
8737 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
8738 		for (j = 0; j < dc_state->stream_count; j++) {
8739 			if (vars[j].aconnector == aconnector) {
8740 				pbn = vars[j].pbn;
8741 				break;
8742 			}
8743 		}
8744 
8745 		if (j == dc_state->stream_count || pbn_div == 0)
8746 			continue;
8747 
8748 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
8749 
8750 		if (stream->timing.flags.DSC != 1) {
8751 			dm_conn_state->pbn = pbn;
8752 			dm_conn_state->vcpi_slots = slot_num;
8753 
8754 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
8755 							   dm_conn_state->pbn, false);
8756 			if (ret < 0)
8757 				return ret;
8758 
8759 			continue;
8760 		}
8761 
8762 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
8763 		if (vcpi < 0)
8764 			return vcpi;
8765 
8766 		dm_conn_state->pbn = pbn;
8767 		dm_conn_state->vcpi_slots = vcpi;
8768 	}
8769 	return 0;
8770 }
8771 
8772 static int to_drm_connector_type(enum signal_type st, uint32_t connector_id)
8773 {
8774 	switch (st) {
8775 	case SIGNAL_TYPE_HDMI_TYPE_A:
8776 		return DRM_MODE_CONNECTOR_HDMIA;
8777 	case SIGNAL_TYPE_EDP:
8778 		return DRM_MODE_CONNECTOR_eDP;
8779 	case SIGNAL_TYPE_LVDS:
8780 		return DRM_MODE_CONNECTOR_LVDS;
8781 	case SIGNAL_TYPE_RGB:
8782 		return DRM_MODE_CONNECTOR_VGA;
8783 	case SIGNAL_TYPE_DISPLAY_PORT:
8784 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
8785 		/* External DP bridges have a different connector type. */
8786 		if (connector_id == CONNECTOR_ID_VGA)
8787 			return DRM_MODE_CONNECTOR_VGA;
8788 		else if (connector_id == CONNECTOR_ID_LVDS)
8789 			return DRM_MODE_CONNECTOR_LVDS;
8790 
8791 		return DRM_MODE_CONNECTOR_DisplayPort;
8792 	case SIGNAL_TYPE_DVI_DUAL_LINK:
8793 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
8794 		if (connector_id == CONNECTOR_ID_SINGLE_LINK_DVII ||
8795 			connector_id == CONNECTOR_ID_DUAL_LINK_DVII)
8796 			return DRM_MODE_CONNECTOR_DVII;
8797 
8798 		return DRM_MODE_CONNECTOR_DVID;
8799 	case SIGNAL_TYPE_VIRTUAL:
8800 		return DRM_MODE_CONNECTOR_VIRTUAL;
8801 
8802 	default:
8803 		return DRM_MODE_CONNECTOR_Unknown;
8804 	}
8805 }
8806 
8807 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
8808 {
8809 	struct drm_encoder *encoder;
8810 
8811 	/* There is only one encoder per connector */
8812 	drm_connector_for_each_possible_encoder(connector, encoder)
8813 		return encoder;
8814 
8815 	return NULL;
8816 }
8817 
8818 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
8819 {
8820 	struct drm_encoder *encoder;
8821 	struct amdgpu_encoder *amdgpu_encoder;
8822 
8823 	encoder = amdgpu_dm_connector_to_encoder(connector);
8824 
8825 	if (encoder == NULL)
8826 		return;
8827 
8828 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8829 
8830 	amdgpu_encoder->native_mode.clock = 0;
8831 
8832 	if (!list_empty(&connector->probed_modes)) {
8833 		struct drm_display_mode *preferred_mode = NULL;
8834 
8835 		list_for_each_entry(preferred_mode,
8836 				    &connector->probed_modes,
8837 				    head) {
8838 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
8839 				amdgpu_encoder->native_mode = *preferred_mode;
8840 
8841 			break;
8842 		}
8843 
8844 	}
8845 }
8846 
8847 static struct drm_display_mode *
8848 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
8849 			     const char *name,
8850 			     int hdisplay, int vdisplay)
8851 {
8852 	struct drm_device *dev = encoder->dev;
8853 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8854 	struct drm_display_mode *mode = NULL;
8855 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8856 
8857 	mode = drm_mode_duplicate(dev, native_mode);
8858 
8859 	if (mode == NULL)
8860 		return NULL;
8861 
8862 	mode->hdisplay = hdisplay;
8863 	mode->vdisplay = vdisplay;
8864 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8865 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
8866 
8867 	return mode;
8868 
8869 }
8870 
8871 static const struct amdgpu_dm_mode_size {
8872 	char name[DRM_DISPLAY_MODE_LEN];
8873 	int w;
8874 	int h;
8875 } common_modes[] = {
8876 	{  "640x480",  640,  480},
8877 	{  "800x600",  800,  600},
8878 	{ "1024x768", 1024,  768},
8879 	{ "1280x720", 1280,  720},
8880 	{ "1280x800", 1280,  800},
8881 	{"1280x1024", 1280, 1024},
8882 	{ "1440x900", 1440,  900},
8883 	{"1680x1050", 1680, 1050},
8884 	{"1600x1200", 1600, 1200},
8885 	{"1920x1080", 1920, 1080},
8886 	{"1920x1200", 1920, 1200}
8887 };
8888 
8889 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
8890 						 struct drm_connector *connector)
8891 {
8892 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8893 	struct drm_display_mode *mode = NULL;
8894 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8895 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8896 				to_amdgpu_dm_connector(connector);
8897 	int i;
8898 	int n;
8899 
8900 	if ((connector->connector_type != DRM_MODE_CONNECTOR_eDP) &&
8901 	    (connector->connector_type != DRM_MODE_CONNECTOR_LVDS))
8902 		return;
8903 
8904 	n = ARRAY_SIZE(common_modes);
8905 
8906 	for (i = 0; i < n; i++) {
8907 		struct drm_display_mode *curmode = NULL;
8908 		bool mode_existed = false;
8909 
8910 		if (common_modes[i].w > native_mode->hdisplay ||
8911 		    common_modes[i].h > native_mode->vdisplay ||
8912 		   (common_modes[i].w == native_mode->hdisplay &&
8913 		    common_modes[i].h == native_mode->vdisplay))
8914 			continue;
8915 
8916 		list_for_each_entry(curmode, &connector->probed_modes, head) {
8917 			if (common_modes[i].w == curmode->hdisplay &&
8918 			    common_modes[i].h == curmode->vdisplay) {
8919 				mode_existed = true;
8920 				break;
8921 			}
8922 		}
8923 
8924 		if (mode_existed)
8925 			continue;
8926 
8927 		mode = amdgpu_dm_create_common_mode(encoder,
8928 				common_modes[i].name, common_modes[i].w,
8929 				common_modes[i].h);
8930 		if (!mode)
8931 			continue;
8932 
8933 		drm_mode_probed_add(connector, mode);
8934 		amdgpu_dm_connector->num_modes++;
8935 	}
8936 }
8937 
8938 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
8939 {
8940 	struct drm_encoder *encoder;
8941 	struct amdgpu_encoder *amdgpu_encoder;
8942 	const struct drm_display_mode *native_mode;
8943 
8944 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
8945 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
8946 		return;
8947 
8948 	mutex_lock(&connector->dev->mode_config.mutex);
8949 	amdgpu_dm_connector_get_modes(connector);
8950 	mutex_unlock(&connector->dev->mode_config.mutex);
8951 
8952 	encoder = amdgpu_dm_connector_to_encoder(connector);
8953 	if (!encoder)
8954 		return;
8955 
8956 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8957 
8958 	native_mode = &amdgpu_encoder->native_mode;
8959 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
8960 		return;
8961 
8962 	drm_connector_set_panel_orientation_with_quirk(connector,
8963 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
8964 						       native_mode->hdisplay,
8965 						       native_mode->vdisplay);
8966 }
8967 
8968 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
8969 					      const struct drm_edid *drm_edid)
8970 {
8971 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8972 			to_amdgpu_dm_connector(connector);
8973 
8974 	if (drm_edid) {
8975 		/* empty probed_modes */
8976 		INIT_LIST_HEAD(&connector->probed_modes);
8977 		amdgpu_dm_connector->num_modes =
8978 				drm_edid_connector_add_modes(connector);
8979 
8980 		/* sorting the probed modes before calling function
8981 		 * amdgpu_dm_get_native_mode() since EDID can have
8982 		 * more than one preferred mode. The modes that are
8983 		 * later in the probed mode list could be of higher
8984 		 * and preferred resolution. For example, 3840x2160
8985 		 * resolution in base EDID preferred timing and 4096x2160
8986 		 * preferred resolution in DID extension block later.
8987 		 */
8988 		drm_mode_sort(&connector->probed_modes);
8989 		amdgpu_dm_get_native_mode(connector);
8990 
8991 		/* Freesync capabilities are reset by calling
8992 		 * drm_edid_connector_add_modes() and need to be
8993 		 * restored here.
8994 		 */
8995 		amdgpu_dm_update_freesync_caps(connector, drm_edid, false);
8996 	} else {
8997 		amdgpu_dm_connector->num_modes = 0;
8998 	}
8999 }
9000 
9001 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
9002 			      struct drm_display_mode *mode)
9003 {
9004 	struct drm_display_mode *m;
9005 
9006 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
9007 		if (drm_mode_equal(m, mode))
9008 			return true;
9009 	}
9010 
9011 	return false;
9012 }
9013 
9014 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
9015 {
9016 	const struct drm_display_mode *m;
9017 	struct drm_display_mode *new_mode;
9018 	uint i;
9019 	u32 new_modes_count = 0;
9020 
9021 	/* Standard FPS values
9022 	 *
9023 	 * 23.976       - TV/NTSC
9024 	 * 24           - Cinema
9025 	 * 25           - TV/PAL
9026 	 * 29.97        - TV/NTSC
9027 	 * 30           - TV/NTSC
9028 	 * 48           - Cinema HFR
9029 	 * 50           - TV/PAL
9030 	 * 60           - Commonly used
9031 	 * 48,72,96,120 - Multiples of 24
9032 	 */
9033 	static const u32 common_rates[] = {
9034 		23976, 24000, 25000, 29970, 30000,
9035 		48000, 50000, 60000, 72000, 96000, 120000
9036 	};
9037 
9038 	/*
9039 	 * Find mode with highest refresh rate with the same resolution
9040 	 * as the preferred mode. Some monitors report a preferred mode
9041 	 * with lower resolution than the highest refresh rate supported.
9042 	 */
9043 
9044 	m = get_highest_refresh_rate_mode(aconnector, true);
9045 	if (!m)
9046 		return 0;
9047 
9048 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
9049 		u64 target_vtotal, target_vtotal_diff;
9050 		u64 num, den;
9051 
9052 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
9053 			continue;
9054 
9055 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
9056 		    common_rates[i] > aconnector->max_vfreq * 1000)
9057 			continue;
9058 
9059 		num = (unsigned long long)m->clock * 1000 * 1000;
9060 		den = common_rates[i] * (unsigned long long)m->htotal;
9061 		target_vtotal = div_u64(num, den);
9062 		target_vtotal_diff = target_vtotal - m->vtotal;
9063 
9064 		/* Check for illegal modes */
9065 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
9066 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
9067 		    m->vtotal + target_vtotal_diff < m->vsync_end)
9068 			continue;
9069 
9070 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
9071 		if (!new_mode)
9072 			goto out;
9073 
9074 		new_mode->vtotal += (u16)target_vtotal_diff;
9075 		new_mode->vsync_start += (u16)target_vtotal_diff;
9076 		new_mode->vsync_end += (u16)target_vtotal_diff;
9077 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
9078 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
9079 
9080 		if (!is_duplicate_mode(aconnector, new_mode)) {
9081 			drm_mode_probed_add(&aconnector->base, new_mode);
9082 			new_modes_count += 1;
9083 		} else
9084 			drm_mode_destroy(aconnector->base.dev, new_mode);
9085 	}
9086  out:
9087 	return new_modes_count;
9088 }
9089 
9090 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
9091 						   const struct drm_edid *drm_edid)
9092 {
9093 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9094 		to_amdgpu_dm_connector(connector);
9095 
9096 	if (!(amdgpu_freesync_vid_mode && drm_edid))
9097 		return;
9098 
9099 	if (!amdgpu_dm_connector->dc_sink || !amdgpu_dm_connector->dc_link)
9100 		return;
9101 
9102 	if (!dc_supports_vrr(amdgpu_dm_connector->dc_sink->ctx->dce_version))
9103 		return;
9104 
9105 	if (dc_connector_supports_analog(amdgpu_dm_connector->dc_link->link_id.id) &&
9106 	    amdgpu_dm_connector->dc_sink->edid_caps.analog)
9107 		return;
9108 
9109 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
9110 		amdgpu_dm_connector->num_modes +=
9111 			add_fs_modes(amdgpu_dm_connector);
9112 }
9113 
9114 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
9115 {
9116 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9117 			to_amdgpu_dm_connector(connector);
9118 	struct dc_link *dc_link = amdgpu_dm_connector->dc_link;
9119 	struct drm_encoder *encoder;
9120 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
9121 	struct dc_link_settings *verified_link_cap = &dc_link->verified_link_cap;
9122 	const struct dc *dc = dc_link->dc;
9123 
9124 	encoder = amdgpu_dm_connector_to_encoder(connector);
9125 
9126 	if (!drm_edid) {
9127 		amdgpu_dm_connector->num_modes =
9128 				drm_add_modes_noedid(connector, 640, 480);
9129 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
9130 			amdgpu_dm_connector->num_modes +=
9131 				drm_add_modes_noedid(connector, 1920, 1080);
9132 
9133 		if (amdgpu_dm_connector->dc_sink &&
9134 		    amdgpu_dm_connector->dc_sink->edid_caps.analog &&
9135 		    dc_connector_supports_analog(dc_link->link_id.id)) {
9136 			/* Analog monitor connected by DAC load detection.
9137 			 * Add common modes. It will be up to the user to select one that works.
9138 			 */
9139 			for (int i = 0; i < ARRAY_SIZE(common_modes); i++)
9140 				amdgpu_dm_connector->num_modes += drm_add_modes_noedid(
9141 					connector, common_modes[i].w, common_modes[i].h);
9142 		}
9143 	} else {
9144 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
9145 		if (encoder)
9146 			amdgpu_dm_connector_add_common_modes(encoder, connector);
9147 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
9148 	}
9149 	amdgpu_dm_fbc_init(connector);
9150 
9151 	return amdgpu_dm_connector->num_modes;
9152 }
9153 
9154 static const u32 supported_colorspaces =
9155 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
9156 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
9157 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
9158 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
9159 
9160 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
9161 				     struct amdgpu_dm_connector *aconnector,
9162 				     int connector_type,
9163 				     struct dc_link *link,
9164 				     int link_index)
9165 {
9166 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
9167 
9168 	/*
9169 	 * Some of the properties below require access to state, like bpc.
9170 	 * Allocate some default initial connector state with our reset helper.
9171 	 */
9172 	if (aconnector->base.funcs->reset)
9173 		aconnector->base.funcs->reset(&aconnector->base);
9174 
9175 	aconnector->connector_id = link_index;
9176 	aconnector->bl_idx = -1;
9177 	aconnector->dc_link = link;
9178 	aconnector->base.interlace_allowed = false;
9179 	aconnector->base.doublescan_allowed = false;
9180 	aconnector->base.stereo_allowed = false;
9181 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
9182 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
9183 	aconnector->audio_inst = -1;
9184 	aconnector->pack_sdp_v1_3 = false;
9185 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
9186 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
9187 	mutex_init(&aconnector->hpd_lock);
9188 	mutex_init(&aconnector->handle_mst_msg_ready);
9189 
9190 	/*
9191 	 * If HDMI HPD debounce delay is set, use the minimum between selected
9192 	 * value and AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS
9193 	 */
9194 	if (amdgpu_hdmi_hpd_debounce_delay_ms) {
9195 		aconnector->hdmi_hpd_debounce_delay_ms = min(amdgpu_hdmi_hpd_debounce_delay_ms,
9196 							     AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS);
9197 		INIT_DELAYED_WORK(&aconnector->hdmi_hpd_debounce_work, hdmi_hpd_debounce_work);
9198 		aconnector->hdmi_prev_sink = NULL;
9199 	} else {
9200 		aconnector->hdmi_hpd_debounce_delay_ms = 0;
9201 	}
9202 
9203 	/*
9204 	 * configure support HPD hot plug connector_>polled default value is 0
9205 	 * which means HPD hot plug not supported
9206 	 */
9207 	switch (connector_type) {
9208 	case DRM_MODE_CONNECTOR_HDMIA:
9209 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9210 		aconnector->base.ycbcr_420_allowed =
9211 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
9212 		break;
9213 	case DRM_MODE_CONNECTOR_DisplayPort:
9214 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9215 		link->link_enc = link_enc_cfg_get_link_enc(link);
9216 		ASSERT(link->link_enc);
9217 		if (link->link_enc)
9218 			aconnector->base.ycbcr_420_allowed =
9219 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
9220 		break;
9221 	case DRM_MODE_CONNECTOR_DVID:
9222 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9223 		break;
9224 	case DRM_MODE_CONNECTOR_DVII:
9225 	case DRM_MODE_CONNECTOR_VGA:
9226 		aconnector->base.polled =
9227 			DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT;
9228 		break;
9229 	default:
9230 		break;
9231 	}
9232 
9233 	drm_object_attach_property(&aconnector->base.base,
9234 				dm->ddev->mode_config.scaling_mode_property,
9235 				DRM_MODE_SCALE_NONE);
9236 
9237 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA
9238 		|| (connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root))
9239 		drm_connector_attach_broadcast_rgb_property(&aconnector->base);
9240 
9241 	drm_object_attach_property(&aconnector->base.base,
9242 				adev->mode_info.underscan_property,
9243 				UNDERSCAN_OFF);
9244 	drm_object_attach_property(&aconnector->base.base,
9245 				adev->mode_info.underscan_hborder_property,
9246 				0);
9247 	drm_object_attach_property(&aconnector->base.base,
9248 				adev->mode_info.underscan_vborder_property,
9249 				0);
9250 
9251 	if (!aconnector->mst_root)
9252 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
9253 
9254 	aconnector->base.state->max_bpc = 16;
9255 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
9256 
9257 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9258 		/* Content Type is currently only implemented for HDMI. */
9259 		drm_connector_attach_content_type_property(&aconnector->base);
9260 	}
9261 
9262 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9263 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
9264 			drm_connector_attach_colorspace_property(&aconnector->base);
9265 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
9266 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
9267 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
9268 			drm_connector_attach_colorspace_property(&aconnector->base);
9269 	}
9270 
9271 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9272 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
9273 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
9274 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
9275 
9276 		if (!aconnector->mst_root)
9277 			drm_connector_attach_vrr_capable_property(&aconnector->base);
9278 
9279 		if (adev->dm.hdcp_workqueue)
9280 			drm_connector_attach_content_protection_property(&aconnector->base, true);
9281 	}
9282 
9283 	if (connector_type == DRM_MODE_CONNECTOR_eDP) {
9284 		struct drm_privacy_screen *privacy_screen;
9285 
9286 		drm_connector_attach_panel_type_property(&aconnector->base);
9287 
9288 		privacy_screen = drm_privacy_screen_get(adev_to_drm(adev)->dev, NULL);
9289 		if (!IS_ERR(privacy_screen)) {
9290 			drm_connector_attach_privacy_screen_provider(&aconnector->base,
9291 								     privacy_screen);
9292 		} else if (PTR_ERR(privacy_screen) != -ENODEV) {
9293 			drm_warn(adev_to_drm(adev), "Error getting privacy-screen\n");
9294 		}
9295 	}
9296 }
9297 
9298 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
9299 			      struct i2c_msg *msgs, int num)
9300 {
9301 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
9302 	struct ddc_service *ddc_service = i2c->ddc_service;
9303 	struct i2c_command cmd;
9304 	int i;
9305 	int result = -EIO;
9306 
9307 	if (!ddc_service->ddc_pin)
9308 		return result;
9309 
9310 	cmd.payloads = kzalloc_objs(struct i2c_payload, num);
9311 
9312 	if (!cmd.payloads)
9313 		return result;
9314 
9315 	cmd.number_of_payloads = num;
9316 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
9317 	cmd.speed = 100;
9318 
9319 	for (i = 0; i < num; i++) {
9320 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
9321 		cmd.payloads[i].address = msgs[i].addr;
9322 		cmd.payloads[i].length = msgs[i].len;
9323 		cmd.payloads[i].data = msgs[i].buf;
9324 	}
9325 
9326 	if (i2c->oem) {
9327 		if (dc_submit_i2c_oem(
9328 			    ddc_service->ctx->dc,
9329 			    &cmd))
9330 			result = num;
9331 	} else {
9332 		if (dc_submit_i2c(
9333 			    ddc_service->ctx->dc,
9334 			    ddc_service->link->link_index,
9335 			    &cmd))
9336 			result = num;
9337 	}
9338 
9339 	kfree(cmd.payloads);
9340 	return result;
9341 }
9342 
9343 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
9344 {
9345 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
9346 }
9347 
9348 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
9349 	.master_xfer = amdgpu_dm_i2c_xfer,
9350 	.functionality = amdgpu_dm_i2c_func,
9351 };
9352 
9353 static struct amdgpu_i2c_adapter *
9354 create_i2c(struct ddc_service *ddc_service, bool oem)
9355 {
9356 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
9357 	struct amdgpu_i2c_adapter *i2c;
9358 
9359 	i2c = kzalloc_obj(struct amdgpu_i2c_adapter);
9360 	if (!i2c)
9361 		return NULL;
9362 	i2c->base.owner = THIS_MODULE;
9363 	i2c->base.dev.parent = &adev->pdev->dev;
9364 	i2c->base.algo = &amdgpu_dm_i2c_algo;
9365 	if (oem)
9366 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c OEM bus");
9367 	else
9368 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d",
9369 			 ddc_service->link->link_index);
9370 	i2c_set_adapdata(&i2c->base, i2c);
9371 	i2c->ddc_service = ddc_service;
9372 	i2c->oem = oem;
9373 
9374 	return i2c;
9375 }
9376 
9377 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
9378 {
9379 	struct cec_connector_info conn_info;
9380 	struct drm_device *ddev = aconnector->base.dev;
9381 	struct device *hdmi_dev = ddev->dev;
9382 
9383 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
9384 		drm_info(ddev, "HDMI-CEC feature masked\n");
9385 		return -EINVAL;
9386 	}
9387 
9388 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
9389 	aconnector->notifier =
9390 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
9391 	if (!aconnector->notifier) {
9392 		drm_err(ddev, "Failed to create cec notifier\n");
9393 		return -ENOMEM;
9394 	}
9395 
9396 	return 0;
9397 }
9398 
9399 /*
9400  * Note: this function assumes that dc_link_detect() was called for the
9401  * dc_link which will be represented by this aconnector.
9402  */
9403 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
9404 				    struct amdgpu_dm_connector *aconnector,
9405 				    u32 link_index,
9406 				    struct amdgpu_encoder *aencoder)
9407 {
9408 	int res = 0;
9409 	int connector_type;
9410 	struct dc *dc = dm->dc;
9411 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
9412 	struct amdgpu_i2c_adapter *i2c;
9413 
9414 	/* Not needed for writeback connector */
9415 	link->priv = aconnector;
9416 
9417 
9418 	i2c = create_i2c(link->ddc, false);
9419 	if (!i2c) {
9420 		drm_err(adev_to_drm(dm->adev), "Failed to create i2c adapter data\n");
9421 		return -ENOMEM;
9422 	}
9423 
9424 	aconnector->i2c = i2c;
9425 	res = devm_i2c_add_adapter(dm->adev->dev, &i2c->base);
9426 
9427 	if (res) {
9428 		drm_err(adev_to_drm(dm->adev), "Failed to register hw i2c %d\n", link->link_index);
9429 		goto out_free;
9430 	}
9431 
9432 	connector_type = to_drm_connector_type(link->connector_signal, link->link_id.id);
9433 
9434 	res = drm_connector_init_with_ddc(
9435 			dm->ddev,
9436 			&aconnector->base,
9437 			&amdgpu_dm_connector_funcs,
9438 			connector_type,
9439 			&i2c->base);
9440 
9441 	if (res) {
9442 		drm_err(adev_to_drm(dm->adev), "connector_init failed\n");
9443 		aconnector->connector_id = -1;
9444 		goto out_free;
9445 	}
9446 
9447 	drm_connector_helper_add(
9448 			&aconnector->base,
9449 			&amdgpu_dm_connector_helper_funcs);
9450 
9451 	amdgpu_dm_connector_init_helper(
9452 		dm,
9453 		aconnector,
9454 		connector_type,
9455 		link,
9456 		link_index);
9457 
9458 	drm_connector_attach_encoder(
9459 		&aconnector->base, &aencoder->base);
9460 
9461 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9462 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
9463 		amdgpu_dm_initialize_hdmi_connector(aconnector);
9464 
9465 	if (dc_is_dp_signal(link->connector_signal))
9466 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
9467 
9468 out_free:
9469 	if (res) {
9470 		kfree(i2c);
9471 		aconnector->i2c = NULL;
9472 	}
9473 	return res;
9474 }
9475 
9476 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
9477 {
9478 	switch (adev->mode_info.num_crtc) {
9479 	case 1:
9480 		return 0x1;
9481 	case 2:
9482 		return 0x3;
9483 	case 3:
9484 		return 0x7;
9485 	case 4:
9486 		return 0xf;
9487 	case 5:
9488 		return 0x1f;
9489 	case 6:
9490 	default:
9491 		return 0x3f;
9492 	}
9493 }
9494 
9495 static int amdgpu_dm_encoder_init(struct drm_device *dev,
9496 				  struct amdgpu_encoder *aencoder,
9497 				  uint32_t link_index)
9498 {
9499 	struct amdgpu_device *adev = drm_to_adev(dev);
9500 
9501 	int res = drm_encoder_init(dev,
9502 				   &aencoder->base,
9503 				   &amdgpu_dm_encoder_funcs,
9504 				   DRM_MODE_ENCODER_TMDS,
9505 				   NULL);
9506 
9507 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
9508 
9509 	if (!res)
9510 		aencoder->encoder_id = link_index;
9511 	else
9512 		aencoder->encoder_id = -1;
9513 
9514 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
9515 
9516 	return res;
9517 }
9518 
9519 static void manage_dm_interrupts(struct amdgpu_device *adev,
9520 				 struct amdgpu_crtc *acrtc,
9521 				 struct dm_crtc_state *acrtc_state)
9522 {	/*
9523 	 * We cannot be sure that the frontend index maps to the same
9524 	 * backend index - some even map to more than one.
9525 	 * So we have to go through the CRTC to find the right IRQ.
9526 	 */
9527 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
9528 			adev,
9529 			acrtc->crtc_id);
9530 	struct drm_device *dev = adev_to_drm(adev);
9531 
9532 	struct drm_vblank_crtc_config config = {0};
9533 	struct dc_crtc_timing *timing;
9534 	int offdelay;
9535 
9536 	if (acrtc_state) {
9537 		timing = &acrtc_state->stream->timing;
9538 
9539 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) >=
9540 		      IP_VERSION(3, 2, 0) &&
9541 		      !(adev->flags & AMD_IS_APU)) {
9542 			/*
9543 			 * DGPUs NV3x and newer that support idle optimizations
9544 			 * experience intermittent flip-done timeouts on cursor
9545 			 * updates. Restore 5s offdelay behavior for now.
9546 			 *
9547 			 * Discussion on the issue:
9548 			 * https://lore.kernel.org/amd-gfx/20260217191632.1243826-1-sysdadmin@m1k.cloud/
9549 			 */
9550 			config.offdelay_ms = 5000;
9551 			config.disable_immediate = false;
9552 		} else if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
9553 			     IP_VERSION(3, 5, 0)) {
9554 			/*
9555 			 * Older HW and DGPU have issues with instant off;
9556 			 * use a 2 frame offdelay.
9557 			 */
9558 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
9559 						      timing->v_total *
9560 						      timing->h_total,
9561 						      timing->pix_clk_100hz);
9562 
9563 			config.offdelay_ms = offdelay ?: 30;
9564 		} else {
9565 			/* offdelay_ms = 0 will never disable vblank */
9566 			config.offdelay_ms = 1;
9567 			config.disable_immediate = true;
9568 		}
9569 
9570 		drm_crtc_vblank_on_config(&acrtc->base,
9571 					  &config);
9572 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_get.*/
9573 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9574 		case IP_VERSION(3, 0, 0):
9575 		case IP_VERSION(3, 0, 2):
9576 		case IP_VERSION(3, 0, 3):
9577 		case IP_VERSION(3, 2, 0):
9578 			if (amdgpu_irq_get(adev, &adev->pageflip_irq, irq_type))
9579 				drm_err(dev, "DM_IRQ: Cannot get pageflip irq!\n");
9580 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9581 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
9582 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
9583 #endif
9584 		}
9585 
9586 	} else {
9587 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
9588 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9589 		case IP_VERSION(3, 0, 0):
9590 		case IP_VERSION(3, 0, 2):
9591 		case IP_VERSION(3, 0, 3):
9592 		case IP_VERSION(3, 2, 0):
9593 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9594 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
9595 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
9596 #endif
9597 			if (amdgpu_irq_put(adev, &adev->pageflip_irq, irq_type))
9598 				drm_err(dev, "DM_IRQ: Cannot put pageflip irq!\n");
9599 		}
9600 
9601 		drm_crtc_vblank_off(&acrtc->base);
9602 	}
9603 }
9604 
9605 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
9606 				      struct amdgpu_crtc *acrtc)
9607 {
9608 	int irq_type =
9609 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
9610 
9611 	/**
9612 	 * This reads the current state for the IRQ and force reapplies
9613 	 * the setting to hardware.
9614 	 */
9615 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
9616 }
9617 
9618 static bool
9619 is_scaling_state_different(const struct dm_connector_state *dm_state,
9620 			   const struct dm_connector_state *old_dm_state)
9621 {
9622 	if (dm_state->scaling != old_dm_state->scaling)
9623 		return true;
9624 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
9625 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
9626 			return true;
9627 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
9628 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
9629 			return true;
9630 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
9631 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
9632 		return true;
9633 	return false;
9634 }
9635 
9636 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
9637 					    struct drm_crtc_state *old_crtc_state,
9638 					    struct drm_connector_state *new_conn_state,
9639 					    struct drm_connector_state *old_conn_state,
9640 					    const struct drm_connector *connector,
9641 					    struct hdcp_workqueue *hdcp_w)
9642 {
9643 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
9644 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
9645 
9646 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
9647 		connector->index, connector->status, connector->dpms);
9648 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
9649 		old_conn_state->content_protection, new_conn_state->content_protection);
9650 
9651 	if (old_crtc_state)
9652 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9653 		old_crtc_state->enable,
9654 		old_crtc_state->active,
9655 		old_crtc_state->mode_changed,
9656 		old_crtc_state->active_changed,
9657 		old_crtc_state->connectors_changed);
9658 
9659 	if (new_crtc_state)
9660 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9661 		new_crtc_state->enable,
9662 		new_crtc_state->active,
9663 		new_crtc_state->mode_changed,
9664 		new_crtc_state->active_changed,
9665 		new_crtc_state->connectors_changed);
9666 
9667 	/* hdcp content type change */
9668 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
9669 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
9670 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9671 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
9672 		return true;
9673 	}
9674 
9675 	/* CP is being re enabled, ignore this */
9676 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
9677 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9678 		if (new_crtc_state && new_crtc_state->mode_changed) {
9679 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9680 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
9681 			return true;
9682 		}
9683 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
9684 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
9685 		return false;
9686 	}
9687 
9688 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
9689 	 *
9690 	 * Handles:	UNDESIRED -> ENABLED
9691 	 */
9692 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
9693 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
9694 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9695 
9696 	/* Stream removed and re-enabled
9697 	 *
9698 	 * Can sometimes overlap with the HPD case,
9699 	 * thus set update_hdcp to false to avoid
9700 	 * setting HDCP multiple times.
9701 	 *
9702 	 * Handles:	DESIRED -> DESIRED (Special case)
9703 	 */
9704 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
9705 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
9706 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9707 		dm_con_state->update_hdcp = false;
9708 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
9709 			__func__);
9710 		return true;
9711 	}
9712 
9713 	/* Hot-plug, headless s3, dpms
9714 	 *
9715 	 * Only start HDCP if the display is connected/enabled.
9716 	 * update_hdcp flag will be set to false until the next
9717 	 * HPD comes in.
9718 	 *
9719 	 * Handles:	DESIRED -> DESIRED (Special case)
9720 	 */
9721 	if (dm_con_state->update_hdcp &&
9722 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
9723 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
9724 		dm_con_state->update_hdcp = false;
9725 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
9726 			__func__);
9727 		return true;
9728 	}
9729 
9730 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
9731 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9732 			if (new_crtc_state && new_crtc_state->mode_changed) {
9733 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
9734 					__func__);
9735 				return true;
9736 			}
9737 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
9738 				__func__);
9739 			return false;
9740 		}
9741 
9742 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
9743 		return false;
9744 	}
9745 
9746 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9747 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
9748 			__func__);
9749 		return true;
9750 	}
9751 
9752 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
9753 	return false;
9754 }
9755 
9756 static void remove_stream(struct amdgpu_device *adev,
9757 			  struct amdgpu_crtc *acrtc,
9758 			  struct dc_stream_state *stream)
9759 {
9760 	/* this is the update mode case */
9761 
9762 	acrtc->otg_inst = -1;
9763 	acrtc->enabled = false;
9764 }
9765 
9766 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
9767 {
9768 
9769 	assert_spin_locked(&acrtc->base.dev->event_lock);
9770 	WARN_ON(acrtc->event);
9771 
9772 	acrtc->event = acrtc->base.state->event;
9773 
9774 	/* Set the flip status */
9775 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
9776 
9777 	/* Mark this event as consumed */
9778 	acrtc->base.state->event = NULL;
9779 
9780 	drm_dbg_state(acrtc->base.dev,
9781 		      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
9782 		      acrtc->crtc_id);
9783 }
9784 
9785 static void update_freesync_state_on_stream(
9786 	struct amdgpu_display_manager *dm,
9787 	struct dm_crtc_state *new_crtc_state,
9788 	struct dc_stream_state *new_stream,
9789 	struct dc_plane_state *surface,
9790 	u32 flip_timestamp_in_us)
9791 {
9792 	struct mod_vrr_params vrr_params;
9793 	struct dc_info_packet vrr_infopacket = {0};
9794 	struct amdgpu_device *adev = dm->adev;
9795 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9796 	unsigned long flags;
9797 	bool pack_sdp_v1_3 = false;
9798 	struct amdgpu_dm_connector *aconn;
9799 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
9800 
9801 	if (!new_stream)
9802 		return;
9803 
9804 	/*
9805 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9806 	 * For now it's sufficient to just guard against these conditions.
9807 	 */
9808 
9809 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9810 		return;
9811 
9812 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9813 	vrr_params = acrtc->dm_irq_params.vrr_params;
9814 
9815 	if (surface) {
9816 		mod_freesync_handle_preflip(
9817 			dm->freesync_module,
9818 			surface,
9819 			new_stream,
9820 			flip_timestamp_in_us,
9821 			&vrr_params);
9822 
9823 		if (adev->family < AMDGPU_FAMILY_AI &&
9824 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
9825 			mod_freesync_handle_v_update(dm->freesync_module,
9826 						     new_stream, &vrr_params);
9827 
9828 			/* Need to call this before the frame ends. */
9829 			dc_stream_adjust_vmin_vmax(dm->dc,
9830 						   new_crtc_state->stream,
9831 						   &vrr_params.adjust);
9832 		}
9833 	}
9834 
9835 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
9836 
9837 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
9838 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
9839 
9840 		if (aconn->vsdb_info.amd_vsdb_version == 1)
9841 			packet_type = PACKET_TYPE_FS_V1;
9842 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
9843 			packet_type = PACKET_TYPE_FS_V2;
9844 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
9845 			packet_type = PACKET_TYPE_FS_V3;
9846 
9847 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
9848 					&new_stream->adaptive_sync_infopacket);
9849 	}
9850 
9851 	mod_freesync_build_vrr_infopacket(
9852 		dm->freesync_module,
9853 		new_stream,
9854 		&vrr_params,
9855 		packet_type,
9856 		TRANSFER_FUNC_UNKNOWN,
9857 		&vrr_infopacket,
9858 		pack_sdp_v1_3);
9859 
9860 	new_crtc_state->freesync_vrr_info_changed |=
9861 		(memcmp(&new_crtc_state->vrr_infopacket,
9862 			&vrr_infopacket,
9863 			sizeof(vrr_infopacket)) != 0);
9864 
9865 	acrtc->dm_irq_params.vrr_params = vrr_params;
9866 	new_crtc_state->vrr_infopacket = vrr_infopacket;
9867 
9868 	new_stream->vrr_infopacket = vrr_infopacket;
9869 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
9870 
9871 	if (new_crtc_state->freesync_vrr_info_changed)
9872 		drm_dbg_kms(adev_to_drm(adev), "VRR packet update: crtc=%u enabled=%d state=%d",
9873 			      new_crtc_state->base.crtc->base.id,
9874 			      (int)new_crtc_state->base.vrr_enabled,
9875 			      (int)vrr_params.state);
9876 
9877 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9878 }
9879 
9880 static void update_stream_irq_parameters(
9881 	struct amdgpu_display_manager *dm,
9882 	struct dm_crtc_state *new_crtc_state)
9883 {
9884 	struct dc_stream_state *new_stream = new_crtc_state->stream;
9885 	struct mod_vrr_params vrr_params;
9886 	struct mod_freesync_config config = new_crtc_state->freesync_config;
9887 	struct amdgpu_device *adev = dm->adev;
9888 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9889 	unsigned long flags;
9890 
9891 	if (!new_stream)
9892 		return;
9893 
9894 	/*
9895 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9896 	 * For now it's sufficient to just guard against these conditions.
9897 	 */
9898 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9899 		return;
9900 
9901 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9902 	vrr_params = acrtc->dm_irq_params.vrr_params;
9903 
9904 	if (new_crtc_state->vrr_supported &&
9905 	    config.min_refresh_in_uhz &&
9906 	    config.max_refresh_in_uhz) {
9907 		/*
9908 		 * if freesync compatible mode was set, config.state will be set
9909 		 * in atomic check
9910 		 */
9911 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
9912 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
9913 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
9914 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
9915 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
9916 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
9917 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
9918 		} else {
9919 			config.state = new_crtc_state->base.vrr_enabled ?
9920 						     VRR_STATE_ACTIVE_VARIABLE :
9921 						     VRR_STATE_INACTIVE;
9922 		}
9923 	} else {
9924 		config.state = VRR_STATE_UNSUPPORTED;
9925 	}
9926 
9927 	mod_freesync_build_vrr_params(dm->freesync_module,
9928 				      new_stream,
9929 				      &config, &vrr_params);
9930 
9931 	new_crtc_state->freesync_config = config;
9932 	/* Copy state for access from DM IRQ handler */
9933 	acrtc->dm_irq_params.freesync_config = config;
9934 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
9935 	acrtc->dm_irq_params.vrr_params = vrr_params;
9936 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9937 }
9938 
9939 static void amdgpu_dm_handle_vrr_transition(struct amdgpu_display_manager *dm,
9940 					    struct dm_crtc_state *old_state,
9941 					    struct dm_crtc_state *new_state)
9942 {
9943 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
9944 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
9945 
9946 	if (!old_vrr_active && new_vrr_active) {
9947 		/* Transition VRR inactive -> active:
9948 		 * While VRR is active, we must not disable vblank irq, as a
9949 		 * reenable after disable would compute bogus vblank/pflip
9950 		 * timestamps if it likely happened inside display front-porch.
9951 		 *
9952 		 * We also need vupdate irq for the actual core vblank handling
9953 		 * at end of vblank.
9954 		 */
9955 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
9956 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
9957 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR off->on: Get vblank ref\n",
9958 				 __func__, new_state->base.crtc->base.id);
9959 
9960 		scoped_guard(mutex, &dm->dc_lock) {
9961 			dc_exit_ips_for_hw_access(dm->dc);
9962 			amdgpu_dm_psr_set_event(dm, new_state->stream, true,
9963 				psr_event_vrr_transition, true);
9964 			amdgpu_dm_replay_set_event(dm, new_state->stream, true,
9965 				replay_event_vrr, true);
9966 		}
9967 	} else if (old_vrr_active && !new_vrr_active) {
9968 		/* Transition VRR active -> inactive:
9969 		 * Allow vblank irq disable again for fixed refresh rate.
9970 		 */
9971 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
9972 		drm_crtc_vblank_put(new_state->base.crtc);
9973 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR on->off: Drop vblank ref\n",
9974 				 __func__, new_state->base.crtc->base.id);
9975 
9976 		scoped_guard(mutex, &dm->dc_lock) {
9977 			dc_exit_ips_for_hw_access(dm->dc);
9978 			amdgpu_dm_psr_set_event(dm, new_state->stream, false,
9979 				psr_event_vrr_transition, false);
9980 			amdgpu_dm_replay_set_event(dm, new_state->stream, false,
9981 				replay_event_vrr, false);
9982 		}
9983 	}
9984 }
9985 
9986 static void amdgpu_dm_commit_cursors(struct drm_atomic_commit *state)
9987 {
9988 	struct drm_plane *plane;
9989 	struct drm_plane_state *old_plane_state;
9990 	int i;
9991 
9992 	/*
9993 	 * TODO: Make this per-stream so we don't issue redundant updates for
9994 	 * commits with multiple streams.
9995 	 */
9996 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
9997 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
9998 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
9999 }
10000 
10001 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
10002 {
10003 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
10004 
10005 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
10006 }
10007 
10008 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
10009 				    struct drm_plane_state *old_plane_state,
10010 				    struct dc_stream_update *update)
10011 {
10012 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
10013 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
10014 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
10015 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
10016 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
10017 	uint64_t address = afb ? afb->address : 0;
10018 	struct dc_cursor_position position = {0};
10019 	struct dc_cursor_attributes attributes;
10020 	int ret;
10021 
10022 	if (!plane->state->fb && !old_plane_state->fb)
10023 		return;
10024 
10025 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
10026 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
10027 		       plane->state->crtc_h);
10028 
10029 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
10030 	if (ret)
10031 		return;
10032 
10033 	if (!position.enable) {
10034 		/* turn off cursor */
10035 		if (crtc_state && crtc_state->stream) {
10036 			dc_stream_set_cursor_position(crtc_state->stream,
10037 						      &position);
10038 			update->cursor_position = &crtc_state->stream->cursor_position;
10039 		}
10040 		return;
10041 	}
10042 
10043 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
10044 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
10045 
10046 	memset(&attributes, 0, sizeof(attributes));
10047 	attributes.address.high_part = upper_32_bits(address);
10048 	attributes.address.low_part  = lower_32_bits(address);
10049 	attributes.width             = plane->state->crtc_w;
10050 	attributes.height            = plane->state->crtc_h;
10051 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
10052 	attributes.rotation_angle    = 0;
10053 	attributes.attribute_flags.value = 0;
10054 
10055 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
10056 	 * legacy gamma setup.
10057 	 */
10058 	if (crtc_state->cm_is_degamma_srgb &&
10059 	    adev->dm.dc->caps.color.dpp.gamma_corr)
10060 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
10061 
10062 	if (afb)
10063 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
10064 
10065 	if (crtc_state->stream) {
10066 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
10067 						     &attributes))
10068 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
10069 
10070 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
10071 
10072 		if (!dc_stream_set_cursor_position(crtc_state->stream,
10073 						   &position))
10074 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
10075 
10076 		update->cursor_position = &crtc_state->stream->cursor_position;
10077 	}
10078 }
10079 
10080 static void amdgpu_dm_enable_self_refresh(struct amdgpu_display_manager *dm,
10081 					  struct amdgpu_crtc *acrtc_attach,
10082 					  const struct dm_crtc_state *acrtc_state,
10083 					  const u64 current_ts)
10084 {
10085 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
10086 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
10087 	struct amdgpu_dm_connector *aconn =
10088 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
10089 
10090 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
10091 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
10092 	    (psr->psr_feature_enabled || pr->replay_feature_enabled)) {
10093 		if (aconn->sr_skip_count > 0)
10094 			aconn->sr_skip_count--;
10095 
10096 		/* Allow SR when skip count is 0. */
10097 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
10098 
10099 		/*
10100 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
10101 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
10102 		 * can be enabled immediately once OS demonstrates an
10103 		 * adequate number of fast atomic commits to notify KMD
10104 		 * of update events.
10105 		 * See `amdgpu_dm_crtc_vblank_control_worker()`.
10106 		 */
10107 		if (acrtc_attach->dm_irq_params.allow_sr_entry &&
10108 			(current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
10109 			amdgpu_dm_psr_set_event(dm, acrtc_state->stream, false,
10110 				psr_event_hw_programming, false);
10111 
10112 			amdgpu_dm_replay_set_event(dm, acrtc_state->stream, false,
10113 				replay_event_hw_programming, false);
10114 		}
10115 	} else {
10116 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
10117 	}
10118 }
10119 
10120 static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state,
10121 				    struct drm_device *dev,
10122 				    struct amdgpu_display_manager *dm,
10123 				    struct drm_crtc *pcrtc,
10124 				    bool wait_for_vblank)
10125 {
10126 	u32 i;
10127 	u64 timestamp_ns = ktime_get_ns();
10128 	struct drm_plane *plane;
10129 	struct drm_plane_state *old_plane_state, *new_plane_state;
10130 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
10131 	struct drm_crtc_state *new_pcrtc_state =
10132 			drm_atomic_get_new_crtc_state(state, pcrtc);
10133 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
10134 	struct dm_crtc_state *dm_old_crtc_state =
10135 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
10136 	int planes_count = 0, vpos, hpos;
10137 	unsigned long flags;
10138 	u32 target_vblank, last_flip_vblank;
10139 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
10140 	bool cursor_update = false;
10141 	bool pflip_present = false;
10142 	bool dirty_rects_changed = false;
10143 	bool updated_planes_and_streams = false;
10144 	struct {
10145 		struct dc_surface_update surface_updates[MAX_SURFACES];
10146 		struct dc_plane_info plane_infos[MAX_SURFACES];
10147 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
10148 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
10149 		struct dc_stream_update stream_update;
10150 	} *bundle;
10151 
10152 	bundle = kzalloc_obj(*bundle);
10153 
10154 	if (!bundle) {
10155 		drm_err(dev, "Failed to allocate update bundle\n");
10156 		goto cleanup;
10157 	}
10158 
10159 	/*
10160 	 * Disable the cursor first if we're disabling all the planes.
10161 	 * It'll remain on the screen after the planes are re-enabled
10162 	 * if we don't.
10163 	 *
10164 	 * If the cursor is transitioning from native to overlay mode, the
10165 	 * native cursor needs to be disabled first.
10166 	 */
10167 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
10168 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10169 		struct dc_cursor_position cursor_position = {0};
10170 
10171 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
10172 						   &cursor_position))
10173 			drm_err(dev, "DC failed to disable native cursor\n");
10174 
10175 		bundle->stream_update.cursor_position =
10176 				&acrtc_state->stream->cursor_position;
10177 	}
10178 
10179 	if (acrtc_state->active_planes == 0 &&
10180 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10181 		amdgpu_dm_commit_cursors(state);
10182 
10183 	/* update planes when needed */
10184 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
10185 		struct drm_crtc *crtc = new_plane_state->crtc;
10186 		struct drm_crtc_state *new_crtc_state;
10187 		struct drm_framebuffer *fb = new_plane_state->fb;
10188 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
10189 		bool plane_needs_flip;
10190 		struct dc_plane_state *dc_plane;
10191 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
10192 
10193 		/* Cursor plane is handled after stream updates */
10194 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
10195 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10196 			if ((fb && crtc == pcrtc) ||
10197 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
10198 				cursor_update = true;
10199 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
10200 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
10201 			}
10202 
10203 			continue;
10204 		}
10205 
10206 		if (!fb || !crtc || pcrtc != crtc)
10207 			continue;
10208 
10209 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
10210 		if (!new_crtc_state->active)
10211 			continue;
10212 
10213 		dc_plane = dm_new_plane_state->dc_state;
10214 		if (!dc_plane)
10215 			continue;
10216 
10217 		bundle->surface_updates[planes_count].surface = dc_plane;
10218 		if (new_pcrtc_state->color_mgmt_changed) {
10219 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
10220 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
10221 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
10222 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
10223 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
10224 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
10225 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
10226 		}
10227 
10228 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
10229 				     &bundle->scaling_infos[planes_count]);
10230 
10231 		bundle->surface_updates[planes_count].scaling_info =
10232 			&bundle->scaling_infos[planes_count];
10233 
10234 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
10235 
10236 		pflip_present = pflip_present || plane_needs_flip;
10237 
10238 		if (!plane_needs_flip) {
10239 			planes_count += 1;
10240 			continue;
10241 		}
10242 
10243 		fill_dc_plane_info_and_addr(
10244 			dm->adev, new_plane_state,
10245 			afb->tiling_flags,
10246 			&bundle->plane_infos[planes_count],
10247 			&bundle->flip_addrs[planes_count].address,
10248 			afb->tmz_surface);
10249 
10250 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
10251 				 new_plane_state->plane->index,
10252 				 bundle->plane_infos[planes_count].dcc.enable);
10253 
10254 		bundle->surface_updates[planes_count].plane_info =
10255 			&bundle->plane_infos[planes_count];
10256 
10257 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
10258 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
10259 			fill_dc_dirty_rects(plane, old_plane_state,
10260 					    new_plane_state, new_crtc_state,
10261 					    &bundle->flip_addrs[planes_count],
10262 					    acrtc_state->stream->link->psr_settings.psr_version ==
10263 					    DC_PSR_VERSION_SU_1,
10264 					    &dirty_rects_changed);
10265 
10266 			/*
10267 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
10268 			 * and enabled it again after dirty regions are stable to avoid video glitch.
10269 			 * PSR-SU will be enabled in
10270 			 * amdgpu_dm_crtc_vblank_control_worker() if user
10271 			 * pause the video during the PSR-SU was disabled.
10272 			 */
10273 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
10274 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
10275 			    dirty_rects_changed) {
10276 				mutex_lock(&dm->dc_lock);
10277 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
10278 				timestamp_ns;
10279 				dc_exit_ips_for_hw_access(dm->dc);
10280 				amdgpu_dm_psr_set_event(dm, acrtc_state->stream, true,
10281 					psr_event_hw_programming, true);
10282 				mutex_unlock(&dm->dc_lock);
10283 			}
10284 		}
10285 
10286 		/*
10287 		 * Only allow immediate flips for fast updates that don't
10288 		 * change memory domain, FB pitch, DCC state, rotation or
10289 		 * mirroring.
10290 		 *
10291 		 * dm_crtc_helper_atomic_check() only accepts async flips with
10292 		 * fast updates.
10293 		 */
10294 		if (crtc->state->async_flip &&
10295 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
10296 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
10297 			drm_warn_once(state->dev,
10298 				      "[PLANE:%d:%s] async flip with non-fast update\n",
10299 				      plane->base.id, plane->name);
10300 
10301 		bundle->flip_addrs[planes_count].flip_immediate =
10302 			crtc->state->async_flip &&
10303 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
10304 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
10305 
10306 		timestamp_ns = ktime_get_ns();
10307 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
10308 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
10309 		bundle->surface_updates[planes_count].surface = dc_plane;
10310 
10311 		if (!bundle->surface_updates[planes_count].surface) {
10312 			drm_err(dev, "No surface for CRTC: id=%d\n",
10313 					acrtc_attach->crtc_id);
10314 			continue;
10315 		}
10316 
10317 		if (plane == pcrtc->primary)
10318 			update_freesync_state_on_stream(
10319 				dm,
10320 				acrtc_state,
10321 				acrtc_state->stream,
10322 				dc_plane,
10323 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
10324 
10325 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
10326 				 __func__,
10327 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
10328 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
10329 
10330 		planes_count += 1;
10331 
10332 	}
10333 
10334 	if (pflip_present) {
10335 		if (!vrr_active) {
10336 			/* Use old throttling in non-vrr fixed refresh rate mode
10337 			 * to keep flip scheduling based on target vblank counts
10338 			 * working in a backwards compatible way, e.g., for
10339 			 * clients using the GLX_OML_sync_control extension or
10340 			 * DRI3/Present extension with defined target_msc.
10341 			 */
10342 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
10343 		} else {
10344 			/* For variable refresh rate mode only:
10345 			 * Get vblank of last completed flip to avoid > 1 vrr
10346 			 * flips per video frame by use of throttling, but allow
10347 			 * flip programming anywhere in the possibly large
10348 			 * variable vrr vblank interval for fine-grained flip
10349 			 * timing control and more opportunity to avoid stutter
10350 			 * on late submission of flips.
10351 			 */
10352 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10353 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
10354 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10355 		}
10356 
10357 		target_vblank = last_flip_vblank + wait_for_vblank;
10358 
10359 		/*
10360 		 * Wait until we're out of the vertical blank period before the one
10361 		 * targeted by the flip
10362 		 */
10363 		while ((acrtc_attach->enabled &&
10364 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
10365 							    0, &vpos, &hpos, NULL,
10366 							    NULL, &pcrtc->hwmode)
10367 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
10368 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
10369 			(int)(target_vblank -
10370 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
10371 			usleep_range(1000, 1100);
10372 		}
10373 
10374 		/**
10375 		 * Prepare the flip event for the pageflip interrupt to handle.
10376 		 *
10377 		 * This only works in the case where we've already turned on the
10378 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
10379 		 * from 0 -> n planes we have to skip a hardware generated event
10380 		 * and rely on sending it from software.
10381 		 */
10382 		if (acrtc_attach->base.state->event &&
10383 		    acrtc_state->active_planes > 0) {
10384 			drm_crtc_vblank_get(pcrtc);
10385 
10386 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10387 
10388 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
10389 			prepare_flip_isr(acrtc_attach);
10390 
10391 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10392 		}
10393 
10394 		if (acrtc_state->stream) {
10395 			if (acrtc_state->freesync_vrr_info_changed)
10396 				bundle->stream_update.vrr_infopacket =
10397 					&acrtc_state->stream->vrr_infopacket;
10398 		}
10399 	} else if (cursor_update && acrtc_state->active_planes > 0) {
10400 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10401 		if (acrtc_attach->base.state->event) {
10402 			drm_crtc_vblank_get(pcrtc);
10403 			acrtc_attach->event = acrtc_attach->base.state->event;
10404 			acrtc_attach->base.state->event = NULL;
10405 		}
10406 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10407 	}
10408 
10409 	/* Update the planes if changed or disable if we don't have any. */
10410 	if ((planes_count || acrtc_state->active_planes == 0) &&
10411 		acrtc_state->stream) {
10412 		/*
10413 		 * If PSR or idle optimizations are enabled then flush out
10414 		 * any pending work before hardware programming.
10415 		 */
10416 		if (dm->vblank_control_workqueue)
10417 			flush_workqueue(dm->vblank_control_workqueue);
10418 
10419 		bundle->stream_update.stream = acrtc_state->stream;
10420 		if (new_pcrtc_state->mode_changed) {
10421 			bundle->stream_update.src = acrtc_state->stream->src;
10422 			bundle->stream_update.dst = acrtc_state->stream->dst;
10423 		}
10424 
10425 		if (new_pcrtc_state->color_mgmt_changed) {
10426 			/*
10427 			 * TODO: This isn't fully correct since we've actually
10428 			 * already modified the stream in place.
10429 			 */
10430 			bundle->stream_update.gamut_remap =
10431 				&acrtc_state->stream->gamut_remap_matrix;
10432 			bundle->stream_update.output_csc_transform =
10433 				&acrtc_state->stream->csc_color_matrix;
10434 			bundle->stream_update.out_transfer_func =
10435 				&acrtc_state->stream->out_transfer_func;
10436 			bundle->stream_update.lut3d_func =
10437 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
10438 			bundle->stream_update.func_shaper =
10439 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
10440 		}
10441 
10442 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
10443 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
10444 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
10445 
10446 		/*
10447 		 * If FreeSync state on the stream has changed then we need to
10448 		 * re-adjust the min/max bounds now that DC doesn't handle this
10449 		 * as part of commit.
10450 		 */
10451 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
10452 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10453 			dc_stream_adjust_vmin_vmax(
10454 				dm->dc, acrtc_state->stream,
10455 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
10456 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10457 		}
10458 		mutex_lock(&dm->dc_lock);
10459 		update_planes_and_stream_adapter(dm->dc,
10460 					 acrtc_state->update_type,
10461 					 planes_count,
10462 					 acrtc_state->stream,
10463 					 &bundle->stream_update,
10464 					 bundle->surface_updates);
10465 		updated_planes_and_streams = true;
10466 
10467 		/**
10468 		 * Enable or disable the interrupts on the backend.
10469 		 *
10470 		 * Most pipes are put into power gating when unused.
10471 		 *
10472 		 * When power gating is enabled on a pipe we lose the
10473 		 * interrupt enablement state when power gating is disabled.
10474 		 *
10475 		 * So we need to update the IRQ control state in hardware
10476 		 * whenever the pipe turns on (since it could be previously
10477 		 * power gated) or off (since some pipes can't be power gated
10478 		 * on some ASICs).
10479 		 */
10480 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
10481 			dm_update_pflip_irq_state(drm_to_adev(dev),
10482 						  acrtc_attach);
10483 		amdgpu_dm_enable_self_refresh(dm, acrtc_attach, acrtc_state,
10484 					      timestamp_ns);
10485 		mutex_unlock(&dm->dc_lock);
10486 	}
10487 
10488 	/*
10489 	 * Update cursor state *after* programming all the planes.
10490 	 * This avoids redundant programming in the case where we're going
10491 	 * to be disabling a single plane - those pipes are being disabled.
10492 	 */
10493 	if (acrtc_state->active_planes &&
10494 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
10495 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10496 		amdgpu_dm_commit_cursors(state);
10497 
10498 cleanup:
10499 	kfree(bundle);
10500 }
10501 
10502 static void amdgpu_dm_commit_audio(struct drm_device *dev,
10503 				   struct drm_atomic_commit *state)
10504 {
10505 	struct amdgpu_device *adev = drm_to_adev(dev);
10506 	struct amdgpu_dm_connector *aconnector;
10507 	struct drm_connector *connector;
10508 	struct drm_connector_state *old_con_state, *new_con_state;
10509 	struct drm_crtc_state *new_crtc_state;
10510 	struct dm_crtc_state *new_dm_crtc_state;
10511 	const struct dc_stream_status *status;
10512 	int i, inst;
10513 
10514 	/* Notify device removals. */
10515 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10516 		if (old_con_state->crtc != new_con_state->crtc) {
10517 			/* CRTC changes require notification. */
10518 			goto notify;
10519 		}
10520 
10521 		if (!new_con_state->crtc)
10522 			continue;
10523 
10524 		new_crtc_state = drm_atomic_get_new_crtc_state(
10525 			state, new_con_state->crtc);
10526 
10527 		if (!new_crtc_state)
10528 			continue;
10529 
10530 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10531 			continue;
10532 
10533 notify:
10534 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10535 			continue;
10536 
10537 		aconnector = to_amdgpu_dm_connector(connector);
10538 
10539 		mutex_lock(&adev->dm.audio_lock);
10540 		inst = aconnector->audio_inst;
10541 		aconnector->audio_inst = -1;
10542 		mutex_unlock(&adev->dm.audio_lock);
10543 
10544 		amdgpu_dm_audio_eld_notify(adev, inst);
10545 	}
10546 
10547 	/* Notify audio device additions. */
10548 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10549 		if (!new_con_state->crtc)
10550 			continue;
10551 
10552 		new_crtc_state = drm_atomic_get_new_crtc_state(
10553 			state, new_con_state->crtc);
10554 
10555 		if (!new_crtc_state)
10556 			continue;
10557 
10558 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10559 			continue;
10560 
10561 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
10562 		if (!new_dm_crtc_state->stream)
10563 			continue;
10564 
10565 		status = dc_stream_get_status(new_dm_crtc_state->stream);
10566 		if (!status)
10567 			continue;
10568 
10569 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10570 			continue;
10571 
10572 		aconnector = to_amdgpu_dm_connector(connector);
10573 
10574 		mutex_lock(&adev->dm.audio_lock);
10575 		inst = status->audio_inst;
10576 		aconnector->audio_inst = inst;
10577 		mutex_unlock(&adev->dm.audio_lock);
10578 
10579 		amdgpu_dm_audio_eld_notify(adev, inst);
10580 	}
10581 }
10582 
10583 /*
10584  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
10585  * @crtc_state: the DRM CRTC state
10586  * @stream_state: the DC stream state.
10587  *
10588  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
10589  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
10590  */
10591 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
10592 						struct dc_stream_state *stream_state)
10593 {
10594 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
10595 }
10596 
10597 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
10598 			      struct dm_crtc_state *crtc_state)
10599 {
10600 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
10601 }
10602 
10603 /**
10604  * amdgpu_dm_mod_power_update_streams - update mod_power stream state on modeset
10605  * @state: the drm atomic state
10606  * @dm: the display manager to update mod_power on
10607  *
10608  * Notify mod_power of stream changes on modeset events, and disable PSR/Replay
10609  * in preparation for hardware programming. See also
10610  * amdgpu_dm_mod_power_setup_streams() for post-modeset mod_power setup.
10611  */
10612 static void amdgpu_dm_mod_power_update_streams(struct drm_atomic_commit *state,
10613 					       struct amdgpu_display_manager *dm)
10614 {
10615 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10616 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10617 	struct amdgpu_dm_connector *aconnector;
10618 	struct drm_crtc *crtc;
10619 	int i = 0;
10620 
10621 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10622 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10623 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10624 
10625 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10626 			continue;
10627 
10628 		/*
10629 		 * Update mod_power on modeset event in preparation for hw
10630 		 * programming. Always use the old stream, since it would have
10631 		 * been previously added to mod_power. If old stream is null (on
10632 		 * crtc enable, for example), mod_power will no-op, which is the
10633 		 * desried behavior.
10634 		 */
10635 		if (old_crtc_state->active) {
10636 			scoped_guard(mutex, &dm->dc_lock) {
10637 				dc_exit_ips_for_hw_access(dm->dc);
10638 				amdgpu_dm_psr_set_event(dm, dm_old_crtc_state->stream, true,
10639 					psr_event_hw_programming, true);
10640 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, true,
10641 					replay_event_hw_programming, true);
10642 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, false,
10643 					replay_event_general_ui, false);
10644 			}
10645 		}
10646 
10647 		if (new_crtc_state->active) {
10648 			aconnector = (struct amdgpu_dm_connector *)
10649 				dm_new_crtc_state->stream->dm_stream_context;
10650 			if (old_crtc_state->active) {
10651 				mod_power_replace_stream(dm->power_module,
10652 					dm_old_crtc_state->stream,
10653 					dm_new_crtc_state->stream,
10654 					&aconnector->psr_caps);
10655 			} else {
10656 				mod_power_add_stream(dm->power_module,
10657 					dm_new_crtc_state->stream,
10658 					&aconnector->psr_caps);
10659 			}
10660 		} else if (old_crtc_state->active) {
10661 			mod_power_remove_stream(dm->power_module,
10662 				dm_old_crtc_state->stream);
10663 		}
10664 	}
10665 }
10666 
10667 /**
10668  * amdgpu_dm_mod_power_setup_streams - setup mod_power stream state post modeset
10669  * @state: the drm atomic state
10670  * @dm: the display manager to update mod_power on
10671  *
10672  * Notify mod_power of mode_change. This needs to be done after dc_stream
10673  * updates have been committed, and VRR parameters have been updated.
10674  */
10675 static void amdgpu_dm_mod_power_setup_streams(struct drm_atomic_commit *state,
10676 					      struct amdgpu_display_manager *dm)
10677 {
10678 	struct dm_crtc_state *dm_new_crtc_state;
10679 	struct drm_crtc_state *new_crtc_state;
10680 	struct amdgpu_crtc *acrtc;
10681 	struct drm_crtc *crtc;
10682 	int i = 0;
10683 
10684 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10685 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10686 		acrtc = to_amdgpu_crtc(crtc);
10687 
10688 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10689 			continue;
10690 
10691 		if (new_crtc_state->active) {
10692 			amdgpu_dm_link_setup_replay(dm_new_crtc_state->stream,
10693 					&acrtc->dm_irq_params.vrr_params);
10694 			mod_power_notify_mode_change(dm->power_module,
10695 						dm_new_crtc_state->stream,
10696 						false);
10697 
10698 			/*
10699 			 * Block PSR / Replay on the new stream until display settles post-modeset.
10700 			 * These events will be cleared by amdgpu_dm_enable_self_refresh() once
10701 			 * allow_sr_entry becomes true.
10702 			 */
10703 			amdgpu_dm_psr_set_event(dm, dm_new_crtc_state->stream, true,
10704 				psr_event_hw_programming, true);
10705 
10706 			amdgpu_dm_replay_set_event(dm, dm_new_crtc_state->stream, true,
10707 				replay_event_hw_programming | replay_event_general_ui,
10708 				true);
10709 		}
10710 	}
10711 
10712 }
10713 
10714 static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state,
10715 					struct dc_state *dc_state)
10716 {
10717 	struct drm_device *dev = state->dev;
10718 	struct amdgpu_device *adev = drm_to_adev(dev);
10719 	struct amdgpu_display_manager *dm = &adev->dm;
10720 	struct drm_crtc *crtc;
10721 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10722 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10723 	struct drm_connector_state *old_con_state;
10724 	struct drm_connector *connector;
10725 	bool mode_set_reset_required = false;
10726 	u32 i;
10727 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
10728 	bool set_backlight_level = false;
10729 
10730 	/* Disable writeback */
10731 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
10732 		struct dm_connector_state *dm_old_con_state;
10733 		struct amdgpu_crtc *acrtc;
10734 
10735 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
10736 			continue;
10737 
10738 		old_crtc_state = NULL;
10739 
10740 		dm_old_con_state = to_dm_connector_state(old_con_state);
10741 		if (!dm_old_con_state->base.crtc)
10742 			continue;
10743 
10744 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
10745 		if (acrtc)
10746 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10747 
10748 		if (!acrtc || !acrtc->wb_enabled)
10749 			continue;
10750 
10751 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10752 
10753 		dm_clear_writeback(dm, dm_old_crtc_state);
10754 		acrtc->wb_enabled = false;
10755 	}
10756 
10757 	amdgpu_dm_mod_power_update_streams(state, dm);
10758 
10759 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
10760 				      new_crtc_state, i) {
10761 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10762 
10763 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10764 
10765 		if (old_crtc_state->active &&
10766 		    (!new_crtc_state->active ||
10767 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10768 			manage_dm_interrupts(adev, acrtc, NULL);
10769 			dc_stream_release(dm_old_crtc_state->stream);
10770 		}
10771 	}
10772 
10773 	drm_atomic_helper_calc_timestamping_constants(state);
10774 
10775 	/* update changed items */
10776 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10777 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10778 
10779 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10780 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10781 
10782 		drm_dbg_state(state->dev,
10783 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
10784 			acrtc->crtc_id,
10785 			new_crtc_state->enable,
10786 			new_crtc_state->active,
10787 			new_crtc_state->planes_changed,
10788 			new_crtc_state->mode_changed,
10789 			new_crtc_state->active_changed,
10790 			new_crtc_state->connectors_changed);
10791 
10792 		/* Disable cursor if disabling crtc */
10793 		if (old_crtc_state->active && !new_crtc_state->active) {
10794 			struct dc_cursor_position position;
10795 
10796 			memset(&position, 0, sizeof(position));
10797 			mutex_lock(&dm->dc_lock);
10798 			dc_exit_ips_for_hw_access(dm->dc);
10799 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
10800 			mutex_unlock(&dm->dc_lock);
10801 		}
10802 
10803 		/* Copy all transient state flags into dc state */
10804 		if (dm_new_crtc_state->stream) {
10805 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
10806 							    dm_new_crtc_state->stream);
10807 		}
10808 
10809 		/* handles headless hotplug case, updating new_state and
10810 		 * aconnector as needed
10811 		 */
10812 
10813 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
10814 
10815 			drm_dbg_atomic(dev,
10816 				       "Atomic commit: SET crtc id %d: [%p]\n",
10817 				       acrtc->crtc_id, acrtc);
10818 
10819 			if (!dm_new_crtc_state->stream) {
10820 				/*
10821 				 * this could happen because of issues with
10822 				 * userspace notifications delivery.
10823 				 * In this case userspace tries to set mode on
10824 				 * display which is disconnected in fact.
10825 				 * dc_sink is NULL in this case on aconnector.
10826 				 * We expect reset mode will come soon.
10827 				 *
10828 				 * This can also happen when unplug is done
10829 				 * during resume sequence ended
10830 				 *
10831 				 * In this case, we want to pretend we still
10832 				 * have a sink to keep the pipe running so that
10833 				 * hw state is consistent with the sw state
10834 				 */
10835 				drm_dbg_atomic(dev,
10836 					       "Failed to create new stream for crtc %d\n",
10837 						acrtc->base.base.id);
10838 				continue;
10839 			}
10840 
10841 			if (dm_old_crtc_state->stream)
10842 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10843 
10844 			pm_runtime_get_noresume(dev->dev);
10845 
10846 			acrtc->enabled = true;
10847 			acrtc->hw_mode = new_crtc_state->mode;
10848 			crtc->hwmode = new_crtc_state->mode;
10849 			mode_set_reset_required = true;
10850 			set_backlight_level = true;
10851 		} else if (modereset_required(new_crtc_state)) {
10852 			drm_dbg_atomic(dev,
10853 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
10854 				       acrtc->crtc_id, acrtc);
10855 			/* i.e. reset mode */
10856 			if (dm_old_crtc_state->stream)
10857 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10858 
10859 			mode_set_reset_required = true;
10860 		}
10861 	} /* for_each_crtc_in_state() */
10862 
10863 	/* if there mode set or reset, flush vblank work queue */
10864 	if (mode_set_reset_required) {
10865 		if (dm->vblank_control_workqueue)
10866 			flush_workqueue(dm->vblank_control_workqueue);
10867 	}
10868 
10869 	dm_enable_per_frame_crtc_master_sync(dc_state);
10870 	mutex_lock(&dm->dc_lock);
10871 	dc_exit_ips_for_hw_access(dm->dc);
10872 	WARN_ON(!dc_commit_streams(dm->dc, &params));
10873 
10874 	/* Allow idle optimization when vblank count is 0 for display off */
10875 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
10876 		dc_allow_idle_optimizations(dm->dc, true);
10877 	mutex_unlock(&dm->dc_lock);
10878 
10879 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10880 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10881 
10882 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10883 
10884 		if (dm_new_crtc_state->stream != NULL) {
10885 			const struct dc_stream_status *status =
10886 					dc_stream_get_status(dm_new_crtc_state->stream);
10887 
10888 			if (!status)
10889 				status = dc_state_get_stream_status(dc_state,
10890 									 dm_new_crtc_state->stream);
10891 			if (!status)
10892 				drm_err(dev,
10893 					"got no status for stream %p on acrtc%p\n",
10894 					dm_new_crtc_state->stream, acrtc);
10895 			else
10896 				acrtc->otg_inst = status->primary_otg_inst;
10897 		}
10898 	}
10899 
10900 	/* During boot up and resume the DC layer will reset the panel brightness
10901 	 * to fix a flicker issue.
10902 	 * It will cause the dm->actual_brightness is not the current panel brightness
10903 	 * level. (the dm->brightness is the correct panel level)
10904 	 * So we set the backlight level with dm->brightness value after set mode
10905 	 */
10906 	if (set_backlight_level) {
10907 		for (i = 0; i < dm->num_of_edps; i++) {
10908 			if (dm->backlight_dev[i])
10909 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
10910 		}
10911 	}
10912 }
10913 
10914 static void dm_set_writeback(struct amdgpu_display_manager *dm,
10915 			      struct dm_crtc_state *crtc_state,
10916 			      struct drm_connector *connector,
10917 			      struct drm_connector_state *new_con_state)
10918 {
10919 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
10920 	struct amdgpu_device *adev = dm->adev;
10921 	struct amdgpu_crtc *acrtc;
10922 	struct dc_writeback_info *wb_info;
10923 	struct pipe_ctx *pipe = NULL;
10924 	struct amdgpu_framebuffer *afb;
10925 	int i = 0;
10926 
10927 	wb_info = kzalloc_obj(*wb_info);
10928 	if (!wb_info) {
10929 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
10930 		return;
10931 	}
10932 
10933 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
10934 	if (!acrtc) {
10935 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
10936 		kfree(wb_info);
10937 		return;
10938 	}
10939 
10940 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
10941 	if (!afb) {
10942 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
10943 		kfree(wb_info);
10944 		return;
10945 	}
10946 
10947 	for (i = 0; i < MAX_PIPES; i++) {
10948 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
10949 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
10950 			break;
10951 		}
10952 	}
10953 
10954 	/* fill in wb_info */
10955 	wb_info->wb_enabled = true;
10956 
10957 	wb_info->dwb_pipe_inst = 0;
10958 	wb_info->dwb_params.dwbscl_black_color = 0;
10959 	wb_info->dwb_params.hdr_mult = 0x1F000;
10960 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
10961 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
10962 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
10963 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
10964 
10965 	/* width & height from crtc */
10966 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
10967 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
10968 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
10969 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
10970 
10971 	wb_info->dwb_params.cnv_params.crop_en = false;
10972 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
10973 
10974 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
10975 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
10976 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
10977 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
10978 
10979 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
10980 
10981 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
10982 
10983 	wb_info->dwb_params.scaler_taps.h_taps = 1;
10984 	wb_info->dwb_params.scaler_taps.v_taps = 1;
10985 	wb_info->dwb_params.scaler_taps.h_taps_c = 1;
10986 	wb_info->dwb_params.scaler_taps.v_taps_c = 1;
10987 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
10988 
10989 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
10990 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
10991 
10992 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
10993 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
10994 		wb_info->mcif_buf_params.chroma_address[i] = 0;
10995 	}
10996 
10997 	wb_info->mcif_buf_params.p_vmid = 1;
10998 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
10999 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
11000 		wb_info->mcif_warmup_params.region_size =
11001 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
11002 	}
11003 	wb_info->mcif_warmup_params.p_vmid = 1;
11004 	wb_info->writeback_source_plane = pipe->plane_state;
11005 
11006 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
11007 
11008 	acrtc->wb_pending = true;
11009 	acrtc->wb_conn = wb_conn;
11010 	drm_writeback_queue_job(wb_conn, new_con_state);
11011 }
11012 
11013 static void amdgpu_dm_update_hdcp(struct drm_atomic_commit *state)
11014 {
11015 	struct drm_connector_state *old_con_state, *new_con_state;
11016 	struct drm_device *dev = state->dev;
11017 	struct drm_connector *connector;
11018 	struct amdgpu_device *adev = drm_to_adev(dev);
11019 	int i;
11020 
11021 	if (!adev->dm.hdcp_workqueue)
11022 		return;
11023 
11024 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11025 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11026 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11027 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11028 		struct dm_crtc_state *dm_new_crtc_state;
11029 		struct amdgpu_dm_connector *aconnector;
11030 
11031 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11032 			continue;
11033 
11034 		aconnector = to_amdgpu_dm_connector(connector);
11035 
11036 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
11037 
11038 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
11039 			connector->index, connector->status, connector->dpms);
11040 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
11041 			old_con_state->content_protection, new_con_state->content_protection);
11042 
11043 		if (aconnector->dc_sink) {
11044 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
11045 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
11046 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
11047 				aconnector->dc_sink->edid_caps.display_name);
11048 			}
11049 		}
11050 
11051 		new_crtc_state = NULL;
11052 		old_crtc_state = NULL;
11053 
11054 		if (acrtc) {
11055 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11056 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11057 		}
11058 
11059 		if (old_crtc_state)
11060 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11061 			old_crtc_state->enable,
11062 			old_crtc_state->active,
11063 			old_crtc_state->mode_changed,
11064 			old_crtc_state->active_changed,
11065 			old_crtc_state->connectors_changed);
11066 
11067 		if (new_crtc_state)
11068 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11069 			new_crtc_state->enable,
11070 			new_crtc_state->active,
11071 			new_crtc_state->mode_changed,
11072 			new_crtc_state->active_changed,
11073 			new_crtc_state->connectors_changed);
11074 
11075 
11076 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11077 
11078 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
11079 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
11080 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
11081 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
11082 			dm_new_con_state->update_hdcp = true;
11083 			continue;
11084 		}
11085 
11086 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
11087 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
11088 			/* when display is unplugged from mst hub, connctor will
11089 			 * be destroyed within dm_dp_mst_connector_destroy. connector
11090 			 * hdcp perperties, like type, undesired, desired, enabled,
11091 			 * will be lost. So, save hdcp properties into hdcp_work within
11092 			 * amdgpu_dm_atomic_commit_tail. if the same display is
11093 			 * plugged back with same display index, its hdcp properties
11094 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
11095 			 */
11096 
11097 			bool enable_encryption = false;
11098 
11099 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
11100 				enable_encryption = true;
11101 
11102 			if (aconnector->dc_link && aconnector->dc_sink &&
11103 				aconnector->dc_link->type == dc_connection_mst_branch) {
11104 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
11105 				struct hdcp_workqueue *hdcp_w =
11106 					&hdcp_work[aconnector->dc_link->link_index];
11107 
11108 				hdcp_w->hdcp_content_type[connector->index] =
11109 					new_con_state->hdcp_content_type;
11110 				hdcp_w->content_protection[connector->index] =
11111 					new_con_state->content_protection;
11112 			}
11113 
11114 			if (new_crtc_state && new_crtc_state->mode_changed &&
11115 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
11116 				enable_encryption = true;
11117 
11118 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
11119 
11120 			if (aconnector->dc_link)
11121 				hdcp_update_display(
11122 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
11123 					new_con_state->hdcp_content_type, enable_encryption);
11124 		}
11125 	}
11126 }
11127 
11128 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state)
11129 {
11130 	struct drm_crtc *crtc;
11131 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11132 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11133 	int i, ret;
11134 
11135 	ret = drm_dp_mst_atomic_setup_commit(state);
11136 	if (ret)
11137 		return ret;
11138 
11139 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11140 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11141 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11142 		/*
11143 		 * Color management settings. We also update color properties
11144 		 * when a modeset is needed, to ensure it gets reprogrammed.
11145 		 */
11146 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
11147 		    (dm_new_crtc_state->base.color_mgmt_changed ||
11148 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11149 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11150 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
11151 			if (ret) {
11152 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
11153 				return ret;
11154 			}
11155 		}
11156 	}
11157 
11158 	return 0;
11159 }
11160 
11161 /**
11162  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
11163  * @state: The atomic state to commit
11164  *
11165  * This will tell DC to commit the constructed DC state from atomic_check,
11166  * programming the hardware. Any failures here implies a hardware failure, since
11167  * atomic check should have filtered anything non-kosher.
11168  */
11169 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state)
11170 {
11171 	struct drm_device *dev = state->dev;
11172 	struct amdgpu_device *adev = drm_to_adev(dev);
11173 	struct amdgpu_display_manager *dm = &adev->dm;
11174 	struct dm_atomic_state *dm_state;
11175 	struct dc_state *dc_state = NULL;
11176 	u32 i, j;
11177 	struct drm_crtc *crtc;
11178 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11179 	unsigned long flags;
11180 	bool wait_for_vblank = true;
11181 	struct drm_connector *connector;
11182 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
11183 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11184 	int crtc_disable_count = 0;
11185 
11186 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
11187 
11188 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
11189 	drm_dp_mst_atomic_wait_for_dependencies(state);
11190 
11191 	dm_state = dm_atomic_get_new_state(state);
11192 	if (dm_state && dm_state->context) {
11193 		dc_state = dm_state->context;
11194 		amdgpu_dm_commit_streams(state, dc_state);
11195 	}
11196 
11197 	amdgpu_dm_update_hdcp(state);
11198 
11199 	/* Handle connector state changes */
11200 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11201 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11202 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
11203 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11204 		struct dc_surface_update *dummy_updates;
11205 		struct dc_stream_update stream_update;
11206 		struct dc_info_packet hdr_packet;
11207 		struct dc_stream_status *status = NULL;
11208 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
11209 
11210 		memset(&stream_update, 0, sizeof(stream_update));
11211 
11212 		if (acrtc) {
11213 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11214 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11215 		}
11216 
11217 		/* Skip any modesets/resets */
11218 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
11219 			continue;
11220 
11221 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11222 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11223 
11224 		scaling_changed = is_scaling_state_different(dm_new_con_state,
11225 							     dm_old_con_state);
11226 
11227 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
11228 			(dm_old_crtc_state->stream->output_color_space !=
11229 				get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
11230 			output_color_space_changed = true;
11231 
11232 		abm_changed = dm_new_crtc_state->abm_level !=
11233 			      dm_old_crtc_state->abm_level;
11234 
11235 		hdr_changed =
11236 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
11237 
11238 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
11239 			continue;
11240 
11241 		stream_update.stream = dm_new_crtc_state->stream;
11242 		if (scaling_changed) {
11243 			update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
11244 					dm_new_con_state, dm_new_crtc_state->stream);
11245 
11246 			stream_update.src = dm_new_crtc_state->stream->src;
11247 			stream_update.dst = dm_new_crtc_state->stream->dst;
11248 		}
11249 
11250 		if (output_color_space_changed) {
11251 			dm_new_crtc_state->stream->output_color_space
11252 				= get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
11253 
11254 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
11255 		}
11256 
11257 		if (abm_changed) {
11258 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
11259 
11260 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
11261 		}
11262 
11263 		if (hdr_changed) {
11264 			fill_hdr_info_packet(new_con_state, &hdr_packet);
11265 			stream_update.hdr_static_metadata = &hdr_packet;
11266 		}
11267 
11268 		status = dc_stream_get_status(dm_new_crtc_state->stream);
11269 
11270 		if (WARN_ON(!status))
11271 			continue;
11272 
11273 		WARN_ON(!status->plane_count);
11274 
11275 		/*
11276 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
11277 		 * Here we create an empty update on each plane.
11278 		 * To fix this, DC should permit updating only stream properties.
11279 		 */
11280 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
11281 		if (!dummy_updates) {
11282 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
11283 			continue;
11284 		}
11285 		for (j = 0; j < status->plane_count; j++)
11286 			dummy_updates[j].surface = status->plane_states[j];
11287 
11288 		sort(dummy_updates, status->plane_count,
11289 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
11290 
11291 		mutex_lock(&dm->dc_lock);
11292 		dc_exit_ips_for_hw_access(dm->dc);
11293 		dc_update_planes_and_stream(dm->dc,
11294 					    dummy_updates,
11295 					    status->plane_count,
11296 					    dm_new_crtc_state->stream,
11297 					    &stream_update);
11298 		mutex_unlock(&dm->dc_lock);
11299 		kfree(dummy_updates);
11300 
11301 		drm_connector_update_privacy_screen(new_con_state);
11302 	}
11303 
11304 	/**
11305 	 * Enable interrupts for CRTCs that are newly enabled or went through
11306 	 * a modeset. It was intentionally deferred until after the front end
11307 	 * state was modified to wait until the OTG was on and so the IRQ
11308 	 * handlers didn't access stale or invalid state.
11309 	 */
11310 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11311 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11312 #ifdef CONFIG_DEBUG_FS
11313 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
11314 #endif
11315 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
11316 		if (old_crtc_state->active && !new_crtc_state->active)
11317 			crtc_disable_count++;
11318 
11319 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11320 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11321 
11322 		/* For freesync config update on crtc state and params for irq */
11323 		update_stream_irq_parameters(dm, dm_new_crtc_state);
11324 
11325 #ifdef CONFIG_DEBUG_FS
11326 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11327 		cur_crc_src = acrtc->dm_irq_params.crc_src;
11328 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11329 #endif
11330 
11331 		if (new_crtc_state->active &&
11332 		    (!old_crtc_state->active ||
11333 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11334 			dc_stream_retain(dm_new_crtc_state->stream);
11335 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
11336 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
11337 		}
11338 		/* Handle vrr on->off / off->on transitions */
11339 		amdgpu_dm_handle_vrr_transition(dm, dm_old_crtc_state, dm_new_crtc_state);
11340 
11341 #ifdef CONFIG_DEBUG_FS
11342 		if (new_crtc_state->active &&
11343 		    (!old_crtc_state->active ||
11344 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11345 			/**
11346 			 * Frontend may have changed so reapply the CRC capture
11347 			 * settings for the stream.
11348 			 */
11349 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
11350 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
11351 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
11352 					uint8_t cnt;
11353 
11354 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11355 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
11356 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
11357 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
11358 
11359 							/**
11360 							 * It takes 2 frames for HW to stably generate CRC when
11361 							 * resuming from suspend, so we set skip_frame_cnt 2.
11362 							 */
11363 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
11364 						}
11365 					}
11366 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11367 				}
11368 #endif
11369 				if (amdgpu_dm_crtc_configure_crc_source(
11370 					crtc, dm_new_crtc_state, cur_crc_src))
11371 					drm_dbg_atomic(dev, "Failed to configure crc source");
11372 			}
11373 		}
11374 #endif
11375 	}
11376 
11377 	amdgpu_dm_mod_power_setup_streams(state, dm);
11378 
11379 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
11380 		if (new_crtc_state->async_flip)
11381 			wait_for_vblank = false;
11382 
11383 	/* update planes when needed per crtc*/
11384 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
11385 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11386 
11387 		if (dm_new_crtc_state->stream)
11388 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
11389 	}
11390 
11391 	/* Enable writeback */
11392 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11393 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11394 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11395 
11396 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11397 			continue;
11398 
11399 		if (!new_con_state->writeback_job)
11400 			continue;
11401 
11402 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11403 
11404 		if (!new_crtc_state)
11405 			continue;
11406 
11407 		if (acrtc->wb_enabled)
11408 			continue;
11409 
11410 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11411 
11412 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
11413 		acrtc->wb_enabled = true;
11414 	}
11415 
11416 	/* Update audio instances for each connector. */
11417 	amdgpu_dm_commit_audio(dev, state);
11418 
11419 	/* restore the backlight level */
11420 	for (i = 0; i < dm->num_of_edps; i++) {
11421 		if (dm->backlight_dev[i] &&
11422 		    (dm->actual_brightness[i] != dm->brightness[i]))
11423 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11424 	}
11425 
11426 	/*
11427 	 * send vblank event on all events not handled in flip and
11428 	 * mark consumed event for drm_atomic_helper_commit_hw_done
11429 	 */
11430 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11431 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11432 
11433 		if (new_crtc_state->event)
11434 			drm_send_event_locked(dev, &new_crtc_state->event->base);
11435 
11436 		new_crtc_state->event = NULL;
11437 	}
11438 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11439 
11440 	/* Signal HW programming completion */
11441 	drm_atomic_helper_commit_hw_done(state);
11442 
11443 	if (wait_for_vblank)
11444 		drm_atomic_helper_wait_for_flip_done(dev, state);
11445 
11446 	drm_atomic_helper_cleanup_planes(dev, state);
11447 
11448 	/* Don't free the memory if we are hitting this as part of suspend.
11449 	 * This way we don't free any memory during suspend; see
11450 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
11451 	 * non-suspend modeset or when the driver is torn down.
11452 	 */
11453 	if (!adev->in_suspend) {
11454 		/* return the stolen vga memory back to VRAM */
11455 		if (!adev->mman.keep_stolen_vga_memory)
11456 			amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_VGA);
11457 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_EXTENDED);
11458 	}
11459 
11460 	/*
11461 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
11462 	 * so we can put the GPU into runtime suspend if we're not driving any
11463 	 * displays anymore
11464 	 */
11465 	for (i = 0; i < crtc_disable_count; i++)
11466 		pm_runtime_put_autosuspend(dev->dev);
11467 	pm_runtime_mark_last_busy(dev->dev);
11468 
11469 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
11470 }
11471 
11472 static int dm_force_atomic_commit(struct drm_connector *connector)
11473 {
11474 	int ret = 0;
11475 	struct drm_device *ddev = connector->dev;
11476 	struct drm_atomic_commit *state = drm_atomic_commit_alloc(ddev);
11477 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11478 	struct drm_plane *plane = disconnected_acrtc->base.primary;
11479 	struct drm_connector_state *conn_state;
11480 	struct drm_crtc_state *crtc_state;
11481 	struct drm_plane_state *plane_state;
11482 
11483 	if (!state)
11484 		return -ENOMEM;
11485 
11486 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
11487 
11488 	/* Construct an atomic state to restore previous display setting */
11489 
11490 	/*
11491 	 * Attach connectors to drm_atomic_commit
11492 	 */
11493 	conn_state = drm_atomic_get_connector_state(state, connector);
11494 
11495 	/* Check for error in getting connector state */
11496 	if (IS_ERR(conn_state)) {
11497 		ret = PTR_ERR(conn_state);
11498 		goto out;
11499 	}
11500 
11501 	/* Attach crtc to drm_atomic_commit*/
11502 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
11503 
11504 	/* Check for error in getting crtc state */
11505 	if (IS_ERR(crtc_state)) {
11506 		ret = PTR_ERR(crtc_state);
11507 		goto out;
11508 	}
11509 
11510 	/* force a restore */
11511 	crtc_state->mode_changed = true;
11512 
11513 	/* Attach plane to drm_atomic_commit */
11514 	plane_state = drm_atomic_get_plane_state(state, plane);
11515 
11516 	/* Check for error in getting plane state */
11517 	if (IS_ERR(plane_state)) {
11518 		ret = PTR_ERR(plane_state);
11519 		goto out;
11520 	}
11521 
11522 	/* Call commit internally with the state we just constructed */
11523 	ret = drm_atomic_commit(state);
11524 
11525 out:
11526 	drm_atomic_commit_put(state);
11527 	if (ret)
11528 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
11529 
11530 	return ret;
11531 }
11532 
11533 /*
11534  * This function handles all cases when set mode does not come upon hotplug.
11535  * This includes when a display is unplugged then plugged back into the
11536  * same port and when running without usermode desktop manager supprot
11537  */
11538 void dm_restore_drm_connector_state(struct drm_device *dev,
11539 				    struct drm_connector *connector)
11540 {
11541 	struct amdgpu_dm_connector *aconnector;
11542 	struct amdgpu_crtc *disconnected_acrtc;
11543 	struct dm_crtc_state *acrtc_state;
11544 
11545 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11546 		return;
11547 
11548 	aconnector = to_amdgpu_dm_connector(connector);
11549 
11550 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
11551 		return;
11552 
11553 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11554 	if (!disconnected_acrtc)
11555 		return;
11556 
11557 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
11558 	if (!acrtc_state->stream)
11559 		return;
11560 
11561 	/*
11562 	 * If the previous sink is not released and different from the current,
11563 	 * we deduce we are in a state where we can not rely on usermode call
11564 	 * to turn on the display, so we do it here
11565 	 */
11566 	if (acrtc_state->stream->sink != aconnector->dc_sink)
11567 		dm_force_atomic_commit(&aconnector->base);
11568 }
11569 
11570 /*
11571  * Grabs all modesetting locks to serialize against any blocking commits,
11572  * Waits for completion of all non blocking commits.
11573  */
11574 static int do_aquire_global_lock(struct drm_device *dev,
11575 				 struct drm_atomic_commit *state)
11576 {
11577 	struct drm_crtc *crtc;
11578 	struct drm_crtc_commit *commit;
11579 	long ret;
11580 
11581 	/*
11582 	 * Adding all modeset locks to aquire_ctx will
11583 	 * ensure that when the framework release it the
11584 	 * extra locks we are locking here will get released to
11585 	 */
11586 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
11587 	if (ret)
11588 		return ret;
11589 
11590 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
11591 		spin_lock(&crtc->commit_lock);
11592 		commit = list_first_entry_or_null(&crtc->commit_list,
11593 				struct drm_crtc_commit, commit_entry);
11594 		if (commit)
11595 			drm_crtc_commit_get(commit);
11596 		spin_unlock(&crtc->commit_lock);
11597 
11598 		if (!commit)
11599 			continue;
11600 
11601 		/*
11602 		 * Make sure all pending HW programming completed and
11603 		 * page flips done
11604 		 */
11605 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
11606 
11607 		if (ret > 0)
11608 			ret = wait_for_completion_interruptible_timeout(
11609 					&commit->flip_done, 10*HZ);
11610 
11611 		if (ret == 0)
11612 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
11613 				  crtc->base.id, crtc->name);
11614 
11615 		drm_crtc_commit_put(commit);
11616 	}
11617 
11618 	return ret < 0 ? ret : 0;
11619 }
11620 
11621 static void get_freesync_config_for_crtc(
11622 	struct dm_crtc_state *new_crtc_state,
11623 	struct dm_connector_state *new_con_state)
11624 {
11625 	struct mod_freesync_config config = {0};
11626 	struct amdgpu_dm_connector *aconnector;
11627 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
11628 	int vrefresh = drm_mode_vrefresh(mode);
11629 	bool fs_vid_mode = false;
11630 
11631 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11632 		return;
11633 
11634 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
11635 
11636 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
11637 					vrefresh >= aconnector->min_vfreq &&
11638 					vrefresh <= aconnector->max_vfreq;
11639 
11640 	if (new_crtc_state->vrr_supported) {
11641 		new_crtc_state->stream->ignore_msa_timing_param = true;
11642 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
11643 
11644 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
11645 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
11646 		config.vsif_supported = true;
11647 		config.btr = true;
11648 
11649 		if (fs_vid_mode) {
11650 			config.state = VRR_STATE_ACTIVE_FIXED;
11651 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
11652 			goto out;
11653 		} else if (new_crtc_state->base.vrr_enabled) {
11654 			config.state = VRR_STATE_ACTIVE_VARIABLE;
11655 		} else {
11656 			config.state = VRR_STATE_INACTIVE;
11657 		}
11658 	} else {
11659 		config.state = VRR_STATE_UNSUPPORTED;
11660 	}
11661 out:
11662 	new_crtc_state->freesync_config = config;
11663 }
11664 
11665 static void reset_freesync_config_for_crtc(
11666 	struct dm_crtc_state *new_crtc_state)
11667 {
11668 	new_crtc_state->vrr_supported = false;
11669 
11670 	memset(&new_crtc_state->vrr_infopacket, 0,
11671 	       sizeof(new_crtc_state->vrr_infopacket));
11672 }
11673 
11674 static bool
11675 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
11676 				 struct drm_crtc_state *new_crtc_state)
11677 {
11678 	const struct drm_display_mode *old_mode, *new_mode;
11679 
11680 	if (!old_crtc_state || !new_crtc_state)
11681 		return false;
11682 
11683 	old_mode = &old_crtc_state->mode;
11684 	new_mode = &new_crtc_state->mode;
11685 
11686 	if (old_mode->clock       == new_mode->clock &&
11687 	    old_mode->hdisplay    == new_mode->hdisplay &&
11688 	    old_mode->vdisplay    == new_mode->vdisplay &&
11689 	    old_mode->htotal      == new_mode->htotal &&
11690 	    old_mode->vtotal      != new_mode->vtotal &&
11691 	    old_mode->hsync_start == new_mode->hsync_start &&
11692 	    old_mode->vsync_start != new_mode->vsync_start &&
11693 	    old_mode->hsync_end   == new_mode->hsync_end &&
11694 	    old_mode->vsync_end   != new_mode->vsync_end &&
11695 	    old_mode->hskew       == new_mode->hskew &&
11696 	    old_mode->vscan       == new_mode->vscan &&
11697 	    (old_mode->vsync_end - old_mode->vsync_start) ==
11698 	    (new_mode->vsync_end - new_mode->vsync_start))
11699 		return true;
11700 
11701 	return false;
11702 }
11703 
11704 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
11705 {
11706 	u64 num, den, res;
11707 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
11708 
11709 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
11710 
11711 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
11712 	den = (unsigned long long)new_crtc_state->mode.htotal *
11713 	      (unsigned long long)new_crtc_state->mode.vtotal;
11714 
11715 	res = div_u64(num, den);
11716 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
11717 }
11718 
11719 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
11720 			 struct drm_atomic_commit *state,
11721 			 struct drm_crtc *crtc,
11722 			 struct drm_crtc_state *old_crtc_state,
11723 			 struct drm_crtc_state *new_crtc_state,
11724 			 bool enable,
11725 			 bool *lock_and_validation_needed)
11726 {
11727 	struct dm_atomic_state *dm_state = NULL;
11728 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11729 	struct dc_stream_state *new_stream;
11730 	struct amdgpu_device *adev = dm->adev;
11731 	int ret = 0;
11732 
11733 	/*
11734 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
11735 	 * update changed items
11736 	 */
11737 	struct amdgpu_crtc *acrtc = NULL;
11738 	struct drm_connector *connector = NULL;
11739 	struct amdgpu_dm_connector *aconnector = NULL;
11740 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
11741 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
11742 
11743 	new_stream = NULL;
11744 
11745 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11746 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11747 	acrtc = to_amdgpu_crtc(crtc);
11748 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
11749 	if (connector)
11750 		aconnector = to_amdgpu_dm_connector(connector);
11751 
11752 	/* TODO This hack should go away */
11753 	if (connector && enable) {
11754 		/* Make sure fake sink is created in plug-in scenario */
11755 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
11756 									connector);
11757 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
11758 									connector);
11759 
11760 		if (WARN_ON(!drm_new_conn_state)) {
11761 			ret = -EINVAL;
11762 			goto fail;
11763 		}
11764 
11765 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
11766 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
11767 
11768 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11769 			goto skip_modeset;
11770 
11771 		new_stream = create_validate_stream_for_sink(connector,
11772 							     &new_crtc_state->mode,
11773 							     dm_new_conn_state,
11774 							     dm_old_crtc_state->stream);
11775 
11776 		/*
11777 		 * we can have no stream on ACTION_SET if a display
11778 		 * was disconnected during S3, in this case it is not an
11779 		 * error, the OS will be updated after detection, and
11780 		 * will do the right thing on next atomic commit
11781 		 */
11782 
11783 		if (!new_stream) {
11784 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
11785 					__func__, acrtc->base.base.id);
11786 			ret = -ENOMEM;
11787 			goto fail;
11788 		}
11789 
11790 		/*
11791 		 * TODO: Check VSDB bits to decide whether this should
11792 		 * be enabled or not.
11793 		 */
11794 		new_stream->triggered_crtc_reset.enabled =
11795 			dm->force_timing_sync;
11796 
11797 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11798 
11799 		ret = fill_hdr_info_packet(drm_new_conn_state,
11800 					   &new_stream->hdr_static_metadata);
11801 		if (ret)
11802 			goto fail;
11803 
11804 		/*
11805 		 * If we already removed the old stream from the context
11806 		 * (and set the new stream to NULL) then we can't reuse
11807 		 * the old stream even if the stream and scaling are unchanged.
11808 		 * We'll hit the BUG_ON and black screen.
11809 		 *
11810 		 * TODO: Refactor this function to allow this check to work
11811 		 * in all conditions.
11812 		 */
11813 		if (amdgpu_freesync_vid_mode &&
11814 		    dm_new_crtc_state->stream &&
11815 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
11816 			goto skip_modeset;
11817 
11818 		if (dm_new_crtc_state->stream &&
11819 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11820 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
11821 			new_crtc_state->mode_changed = false;
11822 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
11823 					 new_crtc_state->mode_changed);
11824 		}
11825 	}
11826 
11827 	/* mode_changed flag may get updated above, need to check again */
11828 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11829 		goto skip_modeset;
11830 
11831 	drm_dbg_state(state->dev,
11832 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
11833 		acrtc->crtc_id,
11834 		new_crtc_state->enable,
11835 		new_crtc_state->active,
11836 		new_crtc_state->planes_changed,
11837 		new_crtc_state->mode_changed,
11838 		new_crtc_state->active_changed,
11839 		new_crtc_state->connectors_changed);
11840 
11841 	/* Remove stream for any changed/disabled CRTC */
11842 	if (!enable) {
11843 
11844 		if (!dm_old_crtc_state->stream)
11845 			goto skip_modeset;
11846 
11847 		/* Unset freesync video if it was active before */
11848 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
11849 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
11850 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
11851 		}
11852 
11853 		/* Now check if we should set freesync video mode */
11854 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
11855 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11856 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
11857 		    is_timing_unchanged_for_freesync(new_crtc_state,
11858 						     old_crtc_state)) {
11859 			new_crtc_state->mode_changed = false;
11860 			drm_dbg_driver(adev_to_drm(adev),
11861 				"Mode change not required for front porch change, setting mode_changed to %d",
11862 				new_crtc_state->mode_changed);
11863 
11864 			set_freesync_fixed_config(dm_new_crtc_state);
11865 
11866 			goto skip_modeset;
11867 		} else if (amdgpu_freesync_vid_mode && aconnector &&
11868 			   is_freesync_video_mode(&new_crtc_state->mode,
11869 						  aconnector)) {
11870 			struct drm_display_mode *high_mode;
11871 
11872 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
11873 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
11874 				set_freesync_fixed_config(dm_new_crtc_state);
11875 		}
11876 
11877 		ret = dm_atomic_get_state(state, &dm_state);
11878 		if (ret)
11879 			goto fail;
11880 
11881 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
11882 				crtc->base.id);
11883 
11884 		/* i.e. reset mode */
11885 		if (dc_state_remove_stream(
11886 				dm->dc,
11887 				dm_state->context,
11888 				dm_old_crtc_state->stream) != DC_OK) {
11889 			ret = -EINVAL;
11890 			goto fail;
11891 		}
11892 
11893 		dc_stream_release(dm_old_crtc_state->stream);
11894 		dm_new_crtc_state->stream = NULL;
11895 
11896 		reset_freesync_config_for_crtc(dm_new_crtc_state);
11897 
11898 		*lock_and_validation_needed = true;
11899 
11900 	} else {/* Add stream for any updated/enabled CRTC */
11901 		/*
11902 		 * Quick fix to prevent NULL pointer on new_stream when
11903 		 * added MST connectors not found in existing crtc_state in the chained mode
11904 		 * TODO: need to dig out the root cause of that
11905 		 */
11906 		if (!connector)
11907 			goto skip_modeset;
11908 
11909 		if (modereset_required(new_crtc_state))
11910 			goto skip_modeset;
11911 
11912 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
11913 				     dm_old_crtc_state->stream)) {
11914 
11915 			WARN_ON(dm_new_crtc_state->stream);
11916 
11917 			ret = dm_atomic_get_state(state, &dm_state);
11918 			if (ret)
11919 				goto fail;
11920 
11921 			dm_new_crtc_state->stream = new_stream;
11922 
11923 			dc_stream_retain(new_stream);
11924 
11925 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
11926 					 crtc->base.id);
11927 
11928 			if (dc_state_add_stream(
11929 					dm->dc,
11930 					dm_state->context,
11931 					dm_new_crtc_state->stream) != DC_OK) {
11932 				ret = -EINVAL;
11933 				goto fail;
11934 			}
11935 
11936 			*lock_and_validation_needed = true;
11937 		}
11938 	}
11939 
11940 skip_modeset:
11941 	/* Release extra reference */
11942 	if (new_stream)
11943 		dc_stream_release(new_stream);
11944 
11945 	/*
11946 	 * We want to do dc stream updates that do not require a
11947 	 * full modeset below.
11948 	 */
11949 	if (!(enable && connector && new_crtc_state->active))
11950 		return 0;
11951 	/*
11952 	 * Given above conditions, the dc state cannot be NULL because:
11953 	 * 1. We're in the process of enabling CRTCs (just been added
11954 	 *    to the dc context, or already is on the context)
11955 	 * 2. Has a valid connector attached, and
11956 	 * 3. Is currently active and enabled.
11957 	 * => The dc stream state currently exists.
11958 	 */
11959 	BUG_ON(dm_new_crtc_state->stream == NULL);
11960 
11961 	/* Scaling or underscan settings */
11962 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
11963 				drm_atomic_crtc_needs_modeset(new_crtc_state))
11964 		update_stream_scaling_settings(adev_to_drm(adev),
11965 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
11966 
11967 	/* ABM settings */
11968 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11969 
11970 	/*
11971 	 * Color management settings. We also update color properties
11972 	 * when a modeset is needed, to ensure it gets reprogrammed.
11973 	 */
11974 	if (dm_new_crtc_state->base.color_mgmt_changed ||
11975 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11976 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
11977 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
11978 		if (ret)
11979 			goto fail;
11980 	}
11981 
11982 	/* Update Freesync settings. */
11983 	get_freesync_config_for_crtc(dm_new_crtc_state,
11984 				     dm_new_conn_state);
11985 
11986 	return ret;
11987 
11988 fail:
11989 	if (new_stream)
11990 		dc_stream_release(new_stream);
11991 	return ret;
11992 }
11993 
11994 static bool should_reset_plane(struct drm_atomic_commit *state,
11995 			       struct drm_plane *plane,
11996 			       struct drm_plane_state *old_plane_state,
11997 			       struct drm_plane_state *new_plane_state)
11998 {
11999 	struct drm_plane *other;
12000 	struct drm_plane_state *old_other_state, *new_other_state;
12001 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12002 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
12003 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
12004 	struct drm_connector_state *new_con_state;
12005 	struct drm_connector *connector;
12006 	int i;
12007 
12008 	/*
12009 	 * TODO: Remove this hack for all asics once it proves that the
12010 	 * fast updates works fine on DCN3.2+.
12011 	 */
12012 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
12013 	    state->allow_modeset)
12014 		return true;
12015 
12016 	/* Check for writeback commit */
12017 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
12018 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
12019 			continue;
12020 
12021 		if (new_con_state->writeback_job)
12022 			return true;
12023 	}
12024 
12025 	if (amdgpu_in_reset(adev) && state->allow_modeset)
12026 		return true;
12027 
12028 	/* Exit early if we know that we're adding or removing the plane. */
12029 	if (old_plane_state->crtc != new_plane_state->crtc)
12030 		return true;
12031 
12032 	/* old crtc == new_crtc == NULL, plane not in context. */
12033 	if (!new_plane_state->crtc)
12034 		return false;
12035 
12036 	new_crtc_state =
12037 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
12038 	old_crtc_state =
12039 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
12040 
12041 	if (!new_crtc_state)
12042 		return true;
12043 
12044 	/*
12045 	 * A change in cursor mode means a new dc pipe needs to be acquired or
12046 	 * released from the state
12047 	 */
12048 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
12049 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
12050 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
12051 	    old_dm_crtc_state != NULL &&
12052 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
12053 		return true;
12054 	}
12055 
12056 	/* CRTC Degamma changes currently require us to recreate planes. */
12057 	if (new_crtc_state->color_mgmt_changed)
12058 		return true;
12059 
12060 	/*
12061 	 * On zpos change, planes need to be reordered by removing and re-adding
12062 	 * them one by one to the dc state, in order of descending zpos.
12063 	 *
12064 	 * TODO: We can likely skip bandwidth validation if the only thing that
12065 	 * changed about the plane was it'z z-ordering.
12066 	 */
12067 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
12068 		return true;
12069 
12070 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
12071 		return true;
12072 
12073 	/*
12074 	 * If there are any new primary or overlay planes being added or
12075 	 * removed then the z-order can potentially change. To ensure
12076 	 * correct z-order and pipe acquisition the current DC architecture
12077 	 * requires us to remove and recreate all existing planes.
12078 	 *
12079 	 * TODO: Come up with a more elegant solution for this.
12080 	 */
12081 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
12082 		struct amdgpu_framebuffer *old_afb, *new_afb;
12083 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
12084 
12085 		dm_new_other_state = to_dm_plane_state(new_other_state);
12086 		dm_old_other_state = to_dm_plane_state(old_other_state);
12087 
12088 		if (other->type == DRM_PLANE_TYPE_CURSOR)
12089 			continue;
12090 
12091 		if (old_other_state->crtc != new_plane_state->crtc &&
12092 		    new_other_state->crtc != new_plane_state->crtc)
12093 			continue;
12094 
12095 		if (old_other_state->crtc != new_other_state->crtc)
12096 			return true;
12097 
12098 		/* Src/dst size and scaling updates. */
12099 		if (old_other_state->src_w != new_other_state->src_w ||
12100 		    old_other_state->src_h != new_other_state->src_h ||
12101 		    old_other_state->crtc_w != new_other_state->crtc_w ||
12102 		    old_other_state->crtc_h != new_other_state->crtc_h)
12103 			return true;
12104 
12105 		/* Rotation / mirroring updates. */
12106 		if (old_other_state->rotation != new_other_state->rotation)
12107 			return true;
12108 
12109 		/* Blending updates. */
12110 		if (old_other_state->pixel_blend_mode !=
12111 		    new_other_state->pixel_blend_mode)
12112 			return true;
12113 
12114 		/* Alpha updates. */
12115 		if (old_other_state->alpha != new_other_state->alpha)
12116 			return true;
12117 
12118 		/* Colorspace changes. */
12119 		if (old_other_state->color_range != new_other_state->color_range ||
12120 		    old_other_state->color_encoding != new_other_state->color_encoding)
12121 			return true;
12122 
12123 		/* HDR/Transfer Function changes. */
12124 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
12125 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
12126 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
12127 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
12128 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
12129 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
12130 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
12131 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
12132 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
12133 			return true;
12134 
12135 		/* Framebuffer checks fall at the end. */
12136 		if (!old_other_state->fb || !new_other_state->fb)
12137 			continue;
12138 
12139 		/* Pixel format changes can require bandwidth updates. */
12140 		if (old_other_state->fb->format != new_other_state->fb->format)
12141 			return true;
12142 
12143 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
12144 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
12145 
12146 		/* Tiling and DCC changes also require bandwidth updates. */
12147 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
12148 		    old_afb->base.modifier != new_afb->base.modifier)
12149 			return true;
12150 	}
12151 
12152 	return false;
12153 }
12154 
12155 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
12156 			      struct drm_plane_state *new_plane_state,
12157 			      struct drm_framebuffer *fb)
12158 {
12159 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
12160 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
12161 	unsigned int pitch;
12162 	bool linear;
12163 
12164 	if (fb->width > new_acrtc->max_cursor_width ||
12165 	    fb->height > new_acrtc->max_cursor_height) {
12166 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB size %dx%d\n",
12167 				 new_plane_state->fb->width,
12168 				 new_plane_state->fb->height);
12169 		return -EINVAL;
12170 	}
12171 	if (new_plane_state->src_w != fb->width << 16 ||
12172 	    new_plane_state->src_h != fb->height << 16) {
12173 		drm_dbg_atomic(adev_to_drm(adev), "Cropping not supported for cursor plane\n");
12174 		return -EINVAL;
12175 	}
12176 
12177 	/* Pitch in pixels */
12178 	pitch = fb->pitches[0] / fb->format->cpp[0];
12179 
12180 	if (fb->width != pitch) {
12181 		drm_dbg_atomic(adev_to_drm(adev), "Cursor FB width %d doesn't match pitch %d",
12182 				 fb->width, pitch);
12183 		return -EINVAL;
12184 	}
12185 
12186 	switch (pitch) {
12187 	case 64:
12188 	case 128:
12189 	case 256:
12190 		/* FB pitch is supported by cursor plane */
12191 		break;
12192 	default:
12193 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB pitch %d px\n", pitch);
12194 		return -EINVAL;
12195 	}
12196 
12197 	/* Core DRM takes care of checking FB modifiers, so we only need to
12198 	 * check tiling flags when the FB doesn't have a modifier.
12199 	 */
12200 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
12201 		if (adev->family == AMDGPU_FAMILY_GC_12_0_0) {
12202 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
12203 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
12204 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
12205 		} else {
12206 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
12207 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
12208 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
12209 		}
12210 		if (!linear) {
12211 			drm_dbg_atomic(adev_to_drm(adev), "Cursor FB not linear");
12212 			return -EINVAL;
12213 		}
12214 	}
12215 
12216 	return 0;
12217 }
12218 
12219 /*
12220  * Helper function for checking the cursor in native mode
12221  */
12222 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
12223 					struct drm_plane *plane,
12224 					struct drm_plane_state *new_plane_state,
12225 					bool enable)
12226 {
12227 
12228 	struct amdgpu_crtc *new_acrtc;
12229 	int ret;
12230 
12231 	if (!enable || !new_plane_crtc ||
12232 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
12233 		return 0;
12234 
12235 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
12236 
12237 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
12238 		drm_dbg_atomic(new_plane_crtc->dev, "Cropping not supported for cursor plane\n");
12239 		return -EINVAL;
12240 	}
12241 
12242 	if (new_plane_state->fb) {
12243 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
12244 						new_plane_state->fb);
12245 		if (ret)
12246 			return ret;
12247 	}
12248 
12249 	return 0;
12250 }
12251 
12252 static bool dm_should_update_native_cursor(struct drm_atomic_commit *state,
12253 					   struct drm_crtc *old_plane_crtc,
12254 					   struct drm_crtc *new_plane_crtc,
12255 					   bool enable)
12256 {
12257 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12258 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12259 
12260 	if (!enable) {
12261 		if (old_plane_crtc == NULL)
12262 			return true;
12263 
12264 		old_crtc_state = drm_atomic_get_old_crtc_state(
12265 			state, old_plane_crtc);
12266 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12267 
12268 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12269 	} else {
12270 		if (new_plane_crtc == NULL)
12271 			return true;
12272 
12273 		new_crtc_state = drm_atomic_get_new_crtc_state(
12274 			state, new_plane_crtc);
12275 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12276 
12277 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12278 	}
12279 }
12280 
12281 static int dm_update_plane_state(struct dc *dc,
12282 				 struct drm_atomic_commit *state,
12283 				 struct drm_plane *plane,
12284 				 struct drm_plane_state *old_plane_state,
12285 				 struct drm_plane_state *new_plane_state,
12286 				 bool enable,
12287 				 bool *lock_and_validation_needed,
12288 				 bool *is_top_most_overlay)
12289 {
12290 
12291 	struct dm_atomic_state *dm_state = NULL;
12292 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
12293 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12294 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
12295 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
12296 	bool needs_reset, update_native_cursor;
12297 	int ret = 0;
12298 
12299 
12300 	new_plane_crtc = new_plane_state->crtc;
12301 	old_plane_crtc = old_plane_state->crtc;
12302 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
12303 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
12304 
12305 	update_native_cursor = dm_should_update_native_cursor(state,
12306 							      old_plane_crtc,
12307 							      new_plane_crtc,
12308 							      enable);
12309 
12310 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
12311 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12312 						    new_plane_state, enable);
12313 		if (ret)
12314 			return ret;
12315 
12316 		return 0;
12317 	}
12318 
12319 	needs_reset = should_reset_plane(state, plane, old_plane_state,
12320 					 new_plane_state);
12321 
12322 	/* Remove any changed/removed planes */
12323 	if (!enable) {
12324 		if (!needs_reset)
12325 			return 0;
12326 
12327 		if (!old_plane_crtc)
12328 			return 0;
12329 
12330 		old_crtc_state = drm_atomic_get_old_crtc_state(
12331 				state, old_plane_crtc);
12332 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12333 
12334 		if (!dm_old_crtc_state->stream)
12335 			return 0;
12336 
12337 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
12338 				plane->base.id, old_plane_crtc->base.id);
12339 
12340 		ret = dm_atomic_get_state(state, &dm_state);
12341 		if (ret)
12342 			return ret;
12343 
12344 		if (!dc_state_remove_plane(
12345 				dc,
12346 				dm_old_crtc_state->stream,
12347 				dm_old_plane_state->dc_state,
12348 				dm_state->context)) {
12349 
12350 			return -EINVAL;
12351 		}
12352 
12353 		if (dm_old_plane_state->dc_state)
12354 			dc_plane_state_release(dm_old_plane_state->dc_state);
12355 
12356 		dm_new_plane_state->dc_state = NULL;
12357 
12358 		*lock_and_validation_needed = true;
12359 
12360 	} else { /* Add new planes */
12361 		struct dc_plane_state *dc_new_plane_state;
12362 
12363 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
12364 			return 0;
12365 
12366 		if (!new_plane_crtc)
12367 			return 0;
12368 
12369 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
12370 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12371 
12372 		if (!dm_new_crtc_state->stream)
12373 			return 0;
12374 
12375 		if (!needs_reset)
12376 			return 0;
12377 
12378 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
12379 		if (ret)
12380 			goto out;
12381 
12382 		WARN_ON(dm_new_plane_state->dc_state);
12383 
12384 		dc_new_plane_state = dc_create_plane_state(dc);
12385 		if (!dc_new_plane_state) {
12386 			ret = -ENOMEM;
12387 			goto out;
12388 		}
12389 
12390 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
12391 				 plane->base.id, new_plane_crtc->base.id);
12392 
12393 		ret = fill_dc_plane_attributes(
12394 			drm_to_adev(new_plane_crtc->dev),
12395 			dc_new_plane_state,
12396 			new_plane_state,
12397 			new_crtc_state);
12398 		if (ret) {
12399 			dc_plane_state_release(dc_new_plane_state);
12400 			goto out;
12401 		}
12402 
12403 		ret = dm_atomic_get_state(state, &dm_state);
12404 		if (ret) {
12405 			dc_plane_state_release(dc_new_plane_state);
12406 			goto out;
12407 		}
12408 
12409 		/*
12410 		 * Any atomic check errors that occur after this will
12411 		 * not need a release. The plane state will be attached
12412 		 * to the stream, and therefore part of the atomic
12413 		 * state. It'll be released when the atomic state is
12414 		 * cleaned.
12415 		 */
12416 		if (!dc_state_add_plane(
12417 				dc,
12418 				dm_new_crtc_state->stream,
12419 				dc_new_plane_state,
12420 				dm_state->context)) {
12421 
12422 			dc_plane_state_release(dc_new_plane_state);
12423 			ret = -EINVAL;
12424 			goto out;
12425 		}
12426 
12427 		dm_new_plane_state->dc_state = dc_new_plane_state;
12428 
12429 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
12430 
12431 		/* Tell DC to do a full surface update every time there
12432 		 * is a plane change. Inefficient, but works for now.
12433 		 */
12434 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
12435 
12436 		*lock_and_validation_needed = true;
12437 	}
12438 
12439 out:
12440 	/* If enabling cursor overlay failed, attempt fallback to native mode */
12441 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
12442 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12443 						    new_plane_state, enable);
12444 		if (ret)
12445 			return ret;
12446 
12447 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
12448 	}
12449 
12450 	return ret;
12451 }
12452 
12453 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
12454 				       int *src_w, int *src_h)
12455 {
12456 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
12457 	case DRM_MODE_ROTATE_90:
12458 	case DRM_MODE_ROTATE_270:
12459 		*src_w = plane_state->src_h >> 16;
12460 		*src_h = plane_state->src_w >> 16;
12461 		break;
12462 	case DRM_MODE_ROTATE_0:
12463 	case DRM_MODE_ROTATE_180:
12464 	default:
12465 		*src_w = plane_state->src_w >> 16;
12466 		*src_h = plane_state->src_h >> 16;
12467 		break;
12468 	}
12469 }
12470 
12471 static void
12472 dm_get_plane_scale(struct drm_plane_state *plane_state,
12473 		   int *out_plane_scale_w, int *out_plane_scale_h)
12474 {
12475 	int plane_src_w, plane_src_h;
12476 
12477 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
12478 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
12479 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
12480 }
12481 
12482 /*
12483  * The normalized_zpos value cannot be used by this iterator directly. It's only
12484  * calculated for enabled planes, potentially causing normalized_zpos collisions
12485  * between enabled/disabled planes in the atomic state. We need a unique value
12486  * so that the iterator will not generate the same object twice, or loop
12487  * indefinitely.
12488  */
12489 static inline struct __drm_planes_state *__get_next_zpos(
12490 	struct drm_atomic_commit *state,
12491 	struct __drm_planes_state *prev)
12492 {
12493 	unsigned int highest_zpos = 0, prev_zpos = 256;
12494 	uint32_t highest_id = 0, prev_id = UINT_MAX;
12495 	struct drm_plane_state *new_plane_state;
12496 	struct drm_plane *plane;
12497 	int i, highest_i = -1;
12498 
12499 	if (prev != NULL) {
12500 		prev_zpos = prev->new_state->zpos;
12501 		prev_id = prev->ptr->base.id;
12502 	}
12503 
12504 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
12505 		/* Skip planes with higher zpos than the previously returned */
12506 		if (new_plane_state->zpos > prev_zpos ||
12507 		    (new_plane_state->zpos == prev_zpos &&
12508 		     plane->base.id >= prev_id))
12509 			continue;
12510 
12511 		/* Save the index of the plane with highest zpos */
12512 		if (new_plane_state->zpos > highest_zpos ||
12513 		    (new_plane_state->zpos == highest_zpos &&
12514 		     plane->base.id > highest_id)) {
12515 			highest_zpos = new_plane_state->zpos;
12516 			highest_id = plane->base.id;
12517 			highest_i = i;
12518 		}
12519 	}
12520 
12521 	if (highest_i < 0)
12522 		return NULL;
12523 
12524 	return &state->planes[highest_i];
12525 }
12526 
12527 /*
12528  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
12529  * by descending zpos, as read from the new plane state. This is the same
12530  * ordering as defined by drm_atomic_normalize_zpos().
12531  */
12532 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
12533 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
12534 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
12535 		for_each_if(((plane) = __i->ptr,				\
12536 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
12537 			     (old_plane_state) = __i->old_state,		\
12538 			     (new_plane_state) = __i->new_state, 1))
12539 
12540 static int add_affected_mst_dsc_crtcs(struct drm_atomic_commit *state, struct drm_crtc *crtc)
12541 {
12542 	struct drm_connector *connector;
12543 	struct drm_connector_state *conn_state, *old_conn_state;
12544 	struct amdgpu_dm_connector *aconnector = NULL;
12545 	int i;
12546 
12547 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
12548 		if (!conn_state->crtc)
12549 			conn_state = old_conn_state;
12550 
12551 		if (conn_state->crtc != crtc)
12552 			continue;
12553 
12554 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
12555 			continue;
12556 
12557 		aconnector = to_amdgpu_dm_connector(connector);
12558 		if (!aconnector->mst_output_port || !aconnector->mst_root)
12559 			aconnector = NULL;
12560 		else
12561 			break;
12562 	}
12563 
12564 	if (!aconnector)
12565 		return 0;
12566 
12567 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
12568 }
12569 
12570 /**
12571  * DOC: Cursor Modes - Native vs Overlay
12572  *
12573  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
12574  * plane. It does not require a dedicated hw plane to enable, but it is
12575  * subjected to the same z-order and scaling as the hw plane. It also has format
12576  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
12577  * hw plane.
12578  *
12579  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
12580  * own scaling and z-pos. It also has no blending restrictions. It lends to a
12581  * cursor behavior more akin to a DRM client's expectations. However, it does
12582  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
12583  * available.
12584  */
12585 
12586 /**
12587  * dm_plane_color_pipeline_active() - Check if a plane's color pipeline active.
12588  * @state: DRM atomic state
12589  * @plane: DRM plane to check
12590  * @use_old: if true, inspect the old colorop states; otherwise the new ones
12591  *
12592  * A color pipeline may be selected (color_pipeline != NULL) but still is
12593  * inactive if every colorop in the chain is bypassed.  Only return
12594  * true when at least one colorop has bypass == false, meaning the cursor
12595  * would be subjected to the transformation in native mode.
12596  *
12597  * Return: true if the pipeline modifies pixels, false otherwise.
12598  */
12599 static bool dm_plane_color_pipeline_active(struct drm_atomic_commit *state,
12600 					   struct drm_plane *plane,
12601 					   bool use_old)
12602 {
12603 	struct drm_colorop *colorop;
12604 	struct drm_colorop_state *old_colorop_state, *new_colorop_state;
12605 	int i;
12606 
12607 	for_each_oldnew_colorop_in_state(state, colorop, old_colorop_state, new_colorop_state, i) {
12608 		struct drm_colorop_state *cstate = use_old ? old_colorop_state : new_colorop_state;
12609 
12610 		if (cstate->colorop->plane != plane)
12611 			continue;
12612 		if (!cstate->bypass)
12613 			return true;
12614 	}
12615 	return false;
12616 }
12617 
12618 /**
12619  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
12620  * @adev: amdgpu device
12621  * @state: DRM atomic state
12622  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
12623  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
12624  *
12625  * Get whether the cursor should be enabled in native mode, or overlay mode, on
12626  * the dm_crtc_state.
12627  *
12628  * The cursor should be enabled in overlay mode if there exists an underlying
12629  * plane - on which the cursor may be blended - that is either YUV formatted,
12630  * scaled differently from the cursor, or has a color pipeline active.
12631  *
12632  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
12633  * calling this function.
12634  *
12635  * Return: 0 on success, or an error code if getting the cursor plane state
12636  * failed.
12637  */
12638 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
12639 				   struct drm_atomic_commit *state,
12640 				   struct dm_crtc_state *dm_crtc_state,
12641 				   enum amdgpu_dm_cursor_mode *cursor_mode)
12642 {
12643 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
12644 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
12645 	struct drm_plane *plane;
12646 	bool consider_mode_change = false;
12647 	bool entire_crtc_covered = false;
12648 	bool cursor_changed = false;
12649 	int underlying_scale_w, underlying_scale_h;
12650 	int cursor_scale_w, cursor_scale_h;
12651 	int i;
12652 
12653 	/* Overlay cursor not supported on HW before DCN
12654 	 * DCN401/420 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
12655 	 * as previous DCN generations, so enable native mode on DCN401/420
12656 	 */
12657 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1) ||
12658 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0)) {
12659 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12660 		return 0;
12661 	}
12662 
12663 	/* Init cursor_mode to be the same as current */
12664 	*cursor_mode = dm_crtc_state->cursor_mode;
12665 
12666 	/*
12667 	 * Cursor mode can change if a plane's format changes, scale changes, is
12668 	 * enabled/disabled, z-order changes, or color management properties change.
12669 	 */
12670 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
12671 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
12672 
12673 		/* Only care about planes on this CRTC */
12674 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
12675 			continue;
12676 
12677 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
12678 			cursor_changed = true;
12679 
12680 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
12681 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
12682 		    old_plane_state->fb->format != plane_state->fb->format) {
12683 			consider_mode_change = true;
12684 			break;
12685 		}
12686 
12687 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
12688 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
12689 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
12690 			consider_mode_change = true;
12691 			break;
12692 		}
12693 
12694 		if (dm_plane_color_pipeline_active(state, plane, true) !=
12695 		    dm_plane_color_pipeline_active(state, plane, false)) {
12696 			consider_mode_change = true;
12697 			break;
12698 		}
12699 	}
12700 
12701 	if (!consider_mode_change && !crtc_state->zpos_changed)
12702 		return 0;
12703 
12704 	/*
12705 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
12706 	 * no need to set cursor mode. This avoids needlessly locking the cursor
12707 	 * state.
12708 	 */
12709 	if (!cursor_changed &&
12710 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
12711 		return 0;
12712 	}
12713 
12714 	cursor_state = drm_atomic_get_plane_state(state,
12715 						  crtc_state->crtc->cursor);
12716 	if (IS_ERR(cursor_state))
12717 		return PTR_ERR(cursor_state);
12718 
12719 	/* Cursor is disabled */
12720 	if (!cursor_state->fb)
12721 		return 0;
12722 
12723 	/* For all planes in descending z-order (all of which are below cursor
12724 	 * as per zpos definitions), check their scaling and format
12725 	 */
12726 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
12727 
12728 		/* Only care about non-cursor planes on this CRTC */
12729 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
12730 		    plane->type == DRM_PLANE_TYPE_CURSOR)
12731 			continue;
12732 
12733 		/* Underlying plane is YUV format - use overlay cursor */
12734 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
12735 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12736 			return 0;
12737 		}
12738 
12739 		/* Underlying plane has an active color pipeline - cursor would be transformed */
12740 		if (dm_plane_color_pipeline_active(state, plane, false)) {
12741 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12742 			return 0;
12743 		}
12744 
12745 		dm_get_plane_scale(plane_state,
12746 				   &underlying_scale_w, &underlying_scale_h);
12747 		dm_get_plane_scale(cursor_state,
12748 				   &cursor_scale_w, &cursor_scale_h);
12749 
12750 		/* Underlying plane has different scale - use overlay cursor */
12751 		if (cursor_scale_w != underlying_scale_w &&
12752 		    cursor_scale_h != underlying_scale_h) {
12753 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12754 			return 0;
12755 		}
12756 
12757 		/* If this plane covers the whole CRTC, no need to check planes underneath */
12758 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
12759 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
12760 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
12761 			entire_crtc_covered = true;
12762 			break;
12763 		}
12764 	}
12765 
12766 	/* If planes do not cover the entire CRTC, use overlay mode to enable
12767 	 * cursor over holes
12768 	 */
12769 	if (entire_crtc_covered)
12770 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12771 	else
12772 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12773 
12774 	return 0;
12775 }
12776 
12777 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
12778 					    struct drm_atomic_commit *state,
12779 					    struct drm_crtc_state *crtc_state)
12780 {
12781 	struct drm_plane *plane;
12782 	struct drm_plane_state *new_plane_state, *old_plane_state;
12783 
12784 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
12785 		new_plane_state = drm_atomic_get_plane_state(state, plane);
12786 		old_plane_state = drm_atomic_get_plane_state(state, plane);
12787 
12788 		if (IS_ERR(new_plane_state) || IS_ERR(old_plane_state)) {
12789 			drm_err(dev, "Failed to get plane state for plane %s\n", plane->name);
12790 			return false;
12791 		}
12792 
12793 		if (old_plane_state->fb && new_plane_state->fb &&
12794 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
12795 			return true;
12796 	}
12797 
12798 	return false;
12799 }
12800 
12801 /**
12802  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
12803  *
12804  * @dev: The DRM device
12805  * @state: The atomic state to commit
12806  *
12807  * Validate that the given atomic state is programmable by DC into hardware.
12808  * This involves constructing a &struct dc_state reflecting the new hardware
12809  * state we wish to commit, then querying DC to see if it is programmable. It's
12810  * important not to modify the existing DC state. Otherwise, atomic_check
12811  * may unexpectedly commit hardware changes.
12812  *
12813  * When validating the DC state, it's important that the right locks are
12814  * acquired. For full updates case which removes/adds/updates streams on one
12815  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
12816  * that any such full update commit will wait for completion of any outstanding
12817  * flip using DRMs synchronization events.
12818  *
12819  * Note that DM adds the affected connectors for all CRTCs in state, when that
12820  * might not seem necessary. This is because DC stream creation requires the
12821  * DC sink, which is tied to the DRM connector state. Cleaning this up should
12822  * be possible but non-trivial - a possible TODO item.
12823  *
12824  * Return: -Error code if validation failed.
12825  */
12826 static int amdgpu_dm_atomic_check(struct drm_device *dev,
12827 				  struct drm_atomic_commit *state)
12828 {
12829 	struct amdgpu_device *adev = drm_to_adev(dev);
12830 	struct dm_atomic_state *dm_state = NULL;
12831 	struct dc *dc = adev->dm.dc;
12832 	struct drm_connector *connector;
12833 	struct drm_connector_state *old_con_state, *new_con_state;
12834 	struct drm_crtc *crtc;
12835 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12836 	struct drm_plane *plane;
12837 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
12838 	enum dc_status status;
12839 	int ret, i;
12840 	bool lock_and_validation_needed = false;
12841 	bool is_top_most_overlay = true;
12842 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12843 	struct drm_dp_mst_topology_mgr *mgr;
12844 	struct drm_dp_mst_topology_state *mst_state;
12845 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
12846 
12847 	trace_amdgpu_dm_atomic_check_begin(state);
12848 
12849 	ret = drm_atomic_helper_check_modeset(dev, state);
12850 	if (ret) {
12851 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
12852 		goto fail;
12853 	}
12854 
12855 	/* Check connector changes */
12856 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
12857 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
12858 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
12859 
12860 		/* Skip connectors that are disabled or part of modeset already. */
12861 		if (!new_con_state->crtc)
12862 			continue;
12863 
12864 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
12865 		if (IS_ERR(new_crtc_state)) {
12866 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
12867 			ret = PTR_ERR(new_crtc_state);
12868 			goto fail;
12869 		}
12870 
12871 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
12872 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
12873 			new_crtc_state->connectors_changed = true;
12874 	}
12875 
12876 	if (dc_resource_is_dsc_encoding_supported(dc)) {
12877 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12878 			dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12879 			dm_new_crtc_state->mode_changed_independent_from_dsc = new_crtc_state->mode_changed;
12880 		}
12881 
12882 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12883 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
12884 				ret = add_affected_mst_dsc_crtcs(state, crtc);
12885 				if (ret) {
12886 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
12887 					goto fail;
12888 				}
12889 			}
12890 		}
12891 	}
12892 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12893 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12894 
12895 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
12896 		    !new_crtc_state->color_mgmt_changed &&
12897 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
12898 			dm_old_crtc_state->dsc_force_changed == false)
12899 			continue;
12900 
12901 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
12902 		if (ret) {
12903 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
12904 			goto fail;
12905 		}
12906 
12907 		if (!new_crtc_state->enable)
12908 			continue;
12909 
12910 		ret = drm_atomic_add_affected_connectors(state, crtc);
12911 		if (ret) {
12912 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
12913 			goto fail;
12914 		}
12915 
12916 		ret = drm_atomic_add_affected_planes(state, crtc);
12917 		if (ret) {
12918 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
12919 			goto fail;
12920 		}
12921 
12922 		if (dm_old_crtc_state->dsc_force_changed)
12923 			new_crtc_state->mode_changed = true;
12924 	}
12925 
12926 	/*
12927 	 * Add all primary and overlay planes on the CRTC to the state
12928 	 * whenever a plane is enabled to maintain correct z-ordering
12929 	 * and to enable fast surface updates.
12930 	 */
12931 	drm_for_each_crtc(crtc, dev) {
12932 		bool modified = false;
12933 
12934 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
12935 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12936 				continue;
12937 
12938 			if (new_plane_state->crtc == crtc ||
12939 			    old_plane_state->crtc == crtc) {
12940 				modified = true;
12941 				break;
12942 			}
12943 		}
12944 
12945 		if (!modified)
12946 			continue;
12947 
12948 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
12949 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12950 				continue;
12951 
12952 			new_plane_state =
12953 				drm_atomic_get_plane_state(state, plane);
12954 
12955 			if (IS_ERR(new_plane_state)) {
12956 				ret = PTR_ERR(new_plane_state);
12957 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
12958 				goto fail;
12959 			}
12960 		}
12961 	}
12962 
12963 	/*
12964 	 * DC consults the zpos (layer_index in DC terminology) to determine the
12965 	 * hw plane on which to enable the hw cursor (see
12966 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
12967 	 * atomic state, so call drm helper to normalize zpos.
12968 	 */
12969 	ret = drm_atomic_normalize_zpos(dev, state);
12970 	if (ret) {
12971 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
12972 		goto fail;
12973 	}
12974 
12975 	/*
12976 	 * Determine whether cursors on each CRTC should be enabled in native or
12977 	 * overlay mode.
12978 	 */
12979 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12980 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12981 
12982 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
12983 					      &dm_new_crtc_state->cursor_mode);
12984 		if (ret) {
12985 			drm_dbg(dev, "Failed to determine cursor mode\n");
12986 			goto fail;
12987 		}
12988 
12989 		/*
12990 		 * If overlay cursor is needed, DC cannot go through the
12991 		 * native cursor update path. All enabled planes on the CRTC
12992 		 * need to be added for DC to not disable a plane by mistake
12993 		 */
12994 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
12995 			if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
12996 				drm_dbg(dev, "Overlay cursor not supported on DCE\n");
12997 				ret = -EINVAL;
12998 				goto fail;
12999 			}
13000 
13001 			ret = drm_atomic_add_affected_planes(state, crtc);
13002 			if (ret)
13003 				goto fail;
13004 		}
13005 	}
13006 
13007 	/* Remove exiting planes if they are modified */
13008 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13009 
13010 		ret = dm_update_plane_state(dc, state, plane,
13011 					    old_plane_state,
13012 					    new_plane_state,
13013 					    false,
13014 					    &lock_and_validation_needed,
13015 					    &is_top_most_overlay);
13016 		if (ret) {
13017 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13018 			goto fail;
13019 		}
13020 	}
13021 
13022 	/* Disable all crtcs which require disable */
13023 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13024 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
13025 					   old_crtc_state,
13026 					   new_crtc_state,
13027 					   false,
13028 					   &lock_and_validation_needed);
13029 		if (ret) {
13030 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
13031 			goto fail;
13032 		}
13033 	}
13034 
13035 	/* Enable all crtcs which require enable */
13036 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13037 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
13038 					   old_crtc_state,
13039 					   new_crtc_state,
13040 					   true,
13041 					   &lock_and_validation_needed);
13042 		if (ret) {
13043 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
13044 			goto fail;
13045 		}
13046 	}
13047 
13048 	/* Add new/modified planes */
13049 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13050 		ret = dm_update_plane_state(dc, state, plane,
13051 					    old_plane_state,
13052 					    new_plane_state,
13053 					    true,
13054 					    &lock_and_validation_needed,
13055 					    &is_top_most_overlay);
13056 		if (ret) {
13057 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13058 			goto fail;
13059 		}
13060 	}
13061 
13062 #if defined(CONFIG_DRM_AMD_DC_FP)
13063 	if (dc_resource_is_dsc_encoding_supported(dc)) {
13064 		ret = pre_validate_dsc(state, &dm_state, vars);
13065 		if (ret != 0)
13066 			goto fail;
13067 	}
13068 #endif
13069 
13070 	/* Run this here since we want to validate the streams we created */
13071 	ret = drm_atomic_helper_check_planes(dev, state);
13072 	if (ret) {
13073 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
13074 		goto fail;
13075 	}
13076 
13077 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13078 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13079 		if (dm_new_crtc_state->mpo_requested)
13080 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
13081 	}
13082 
13083 	/* Check cursor restrictions */
13084 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13085 		enum amdgpu_dm_cursor_mode required_cursor_mode;
13086 		int is_rotated, is_scaled;
13087 
13088 		/* Overlay cusor not subject to native cursor restrictions */
13089 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13090 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
13091 			continue;
13092 
13093 		/* Check if rotation or scaling is enabled on DCN401 */
13094 		if ((drm_plane_mask(crtc->cursor) & new_crtc_state->plane_mask) &&
13095 		    (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
13096 		    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1))) {
13097 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
13098 
13099 			is_rotated = new_cursor_state &&
13100 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
13101 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
13102 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
13103 
13104 			if (is_rotated || is_scaled) {
13105 				drm_dbg_driver(
13106 					crtc->dev,
13107 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
13108 					crtc->base.id, crtc->name);
13109 				ret = -EINVAL;
13110 				goto fail;
13111 			}
13112 		}
13113 
13114 		/* If HW can only do native cursor, check restrictions again */
13115 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
13116 					      &required_cursor_mode);
13117 		if (ret) {
13118 			drm_dbg_driver(crtc->dev,
13119 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
13120 				       crtc->base.id, crtc->name);
13121 			goto fail;
13122 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
13123 			drm_dbg_driver(crtc->dev,
13124 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling, YUV, or color pipeline restrictions\n",
13125 				       crtc->base.id, crtc->name);
13126 			ret = -EINVAL;
13127 			goto fail;
13128 		}
13129 	}
13130 
13131 	if (state->legacy_cursor_update) {
13132 		/*
13133 		 * This is a fast cursor update coming from the plane update
13134 		 * helper, check if it can be done asynchronously for better
13135 		 * performance.
13136 		 */
13137 		state->async_update =
13138 			!drm_atomic_helper_async_check(dev, state);
13139 
13140 		/*
13141 		 * Skip the remaining global validation if this is an async
13142 		 * update. Cursor updates can be done without affecting
13143 		 * state or bandwidth calcs and this avoids the performance
13144 		 * penalty of locking the private state object and
13145 		 * allocating a new dc_state.
13146 		 */
13147 		if (state->async_update)
13148 			return 0;
13149 	}
13150 
13151 	/* Check scaling and underscan changes*/
13152 	/* TODO Removed scaling changes validation due to inability to commit
13153 	 * new stream into context w\o causing full reset. Need to
13154 	 * decide how to handle.
13155 	 */
13156 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
13157 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
13158 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
13159 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
13160 
13161 		/* Skip any modesets/resets */
13162 		if (!acrtc || drm_atomic_crtc_needs_modeset(
13163 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
13164 			continue;
13165 
13166 		/* Skip any thing not scale or underscan changes */
13167 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
13168 			continue;
13169 
13170 		lock_and_validation_needed = true;
13171 	}
13172 
13173 	/* set the slot info for each mst_state based on the link encoding format */
13174 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
13175 		struct amdgpu_dm_connector *aconnector;
13176 		struct drm_connector *connector;
13177 		struct drm_connector_list_iter iter;
13178 		u8 link_coding_cap;
13179 
13180 		drm_connector_list_iter_begin(dev, &iter);
13181 		drm_for_each_connector_iter(connector, &iter) {
13182 			if (connector->index == mst_state->mgr->conn_base_id) {
13183 				aconnector = to_amdgpu_dm_connector(connector);
13184 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
13185 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
13186 
13187 				break;
13188 			}
13189 		}
13190 		drm_connector_list_iter_end(&iter);
13191 	}
13192 
13193 	/**
13194 	 * Streams and planes are reset when there are changes that affect
13195 	 * bandwidth. Anything that affects bandwidth needs to go through
13196 	 * DC global validation to ensure that the configuration can be applied
13197 	 * to hardware.
13198 	 *
13199 	 * We have to currently stall out here in atomic_check for outstanding
13200 	 * commits to finish in this case because our IRQ handlers reference
13201 	 * DRM state directly - we can end up disabling interrupts too early
13202 	 * if we don't.
13203 	 *
13204 	 * TODO: Remove this stall and drop DM state private objects.
13205 	 */
13206 	if (lock_and_validation_needed) {
13207 		ret = dm_atomic_get_state(state, &dm_state);
13208 		if (ret) {
13209 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
13210 			goto fail;
13211 		}
13212 
13213 		ret = do_aquire_global_lock(dev, state);
13214 		if (ret) {
13215 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
13216 			goto fail;
13217 		}
13218 
13219 #if defined(CONFIG_DRM_AMD_DC_FP)
13220 		if (dc_resource_is_dsc_encoding_supported(dc)) {
13221 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
13222 			if (ret) {
13223 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
13224 				ret = -EINVAL;
13225 				goto fail;
13226 			}
13227 		}
13228 #endif
13229 
13230 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
13231 		if (ret) {
13232 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
13233 			goto fail;
13234 		}
13235 
13236 		/*
13237 		 * Perform validation of MST topology in the state:
13238 		 * We need to perform MST atomic check before calling
13239 		 * dc_validate_global_state(), or there is a chance
13240 		 * to get stuck in an infinite loop and hang eventually.
13241 		 */
13242 		ret = drm_dp_mst_atomic_check(state);
13243 		if (ret) {
13244 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
13245 			goto fail;
13246 		}
13247 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
13248 		if (status != DC_OK) {
13249 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
13250 				       dc_status_to_str(status), status);
13251 			ret = -EINVAL;
13252 			goto fail;
13253 		}
13254 	} else {
13255 		/*
13256 		 * The commit is a fast update. Fast updates shouldn't change
13257 		 * the DC context, affect global validation, and can have their
13258 		 * commit work done in parallel with other commits not touching
13259 		 * the same resource. If we have a new DC context as part of
13260 		 * the DM atomic state from validation we need to free it and
13261 		 * retain the existing one instead.
13262 		 *
13263 		 * Furthermore, since the DM atomic state only contains the DC
13264 		 * context and can safely be annulled, we can free the state
13265 		 * and clear the associated private object now to free
13266 		 * some memory and avoid a possible use-after-free later.
13267 		 */
13268 
13269 		for (i = 0; i < state->num_private_objs; i++) {
13270 			struct drm_private_obj *obj = state->private_objs[i].ptr;
13271 
13272 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
13273 				int j = state->num_private_objs-1;
13274 
13275 				dm_atomic_destroy_state(obj,
13276 						state->private_objs[i].state_to_destroy);
13277 
13278 				/* If i is not at the end of the array then the
13279 				 * last element needs to be moved to where i was
13280 				 * before the array can safely be truncated.
13281 				 */
13282 				if (i != j)
13283 					state->private_objs[i] =
13284 						state->private_objs[j];
13285 
13286 				state->private_objs[j].ptr = NULL;
13287 				state->private_objs[j].state_to_destroy = NULL;
13288 				state->private_objs[j].old_state = NULL;
13289 				state->private_objs[j].new_state = NULL;
13290 
13291 				state->num_private_objs = j;
13292 				break;
13293 			}
13294 		}
13295 	}
13296 
13297 	/* Store the overall update type for use later in atomic check. */
13298 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13299 		struct dm_crtc_state *dm_new_crtc_state =
13300 			to_dm_crtc_state(new_crtc_state);
13301 
13302 		/*
13303 		 * Only allow async flips for fast updates that don't change
13304 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
13305 		 */
13306 		if (new_crtc_state->async_flip &&
13307 		    (lock_and_validation_needed ||
13308 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
13309 			drm_dbg_atomic(crtc->dev,
13310 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
13311 				       crtc->base.id, crtc->name);
13312 			ret = -EINVAL;
13313 			goto fail;
13314 		}
13315 
13316 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
13317 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
13318 	}
13319 
13320 	/* Must be success */
13321 	WARN_ON(ret);
13322 
13323 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13324 
13325 	return ret;
13326 
13327 fail:
13328 	if (ret == -EDEADLK)
13329 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
13330 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
13331 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
13332 	else
13333 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
13334 
13335 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13336 
13337 	return ret;
13338 }
13339 
13340 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
13341 		unsigned int offset,
13342 		unsigned int total_length,
13343 		u8 *data,
13344 		unsigned int length,
13345 		struct amdgpu_hdmi_vsdb_info *vsdb)
13346 {
13347 	bool res;
13348 	union dmub_rb_cmd cmd;
13349 	struct dmub_cmd_send_edid_cea *input;
13350 	struct dmub_cmd_edid_cea_output *output;
13351 
13352 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
13353 		return false;
13354 
13355 	memset(&cmd, 0, sizeof(cmd));
13356 
13357 	input = &cmd.edid_cea.data.input;
13358 
13359 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
13360 	cmd.edid_cea.header.sub_type = 0;
13361 	cmd.edid_cea.header.payload_bytes =
13362 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
13363 	input->offset = offset;
13364 	input->length = length;
13365 	input->cea_total_length = total_length;
13366 	memcpy(input->payload, data, length);
13367 
13368 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
13369 	if (!res) {
13370 		drm_err(adev_to_drm(dm->adev), "EDID CEA parser failed\n");
13371 		return false;
13372 	}
13373 
13374 	output = &cmd.edid_cea.data.output;
13375 
13376 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
13377 		if (!output->ack.success) {
13378 			drm_err(adev_to_drm(dm->adev), "EDID CEA ack failed at offset %d\n",
13379 					output->ack.offset);
13380 		}
13381 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
13382 		if (!output->amd_vsdb.vsdb_found)
13383 			return false;
13384 
13385 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
13386 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
13387 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
13388 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
13389 		vsdb->freesync_mccs_vcp_code = output->amd_vsdb.freesync_mccs_vcp_code;
13390 	} else {
13391 		drm_warn(adev_to_drm(dm->adev), "Unknown EDID CEA parser results\n");
13392 		return false;
13393 	}
13394 
13395 	return true;
13396 }
13397 
13398 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
13399 		u8 *edid_ext, int len,
13400 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13401 {
13402 	int i;
13403 
13404 	/* send extension block to DMCU for parsing */
13405 	for (i = 0; i < len; i += 8) {
13406 		bool res;
13407 		int offset;
13408 
13409 		/* send 8 bytes a time */
13410 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
13411 			return false;
13412 
13413 		if (i+8 == len) {
13414 			/* EDID block sent completed, expect result */
13415 			int version, min_rate, max_rate;
13416 
13417 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
13418 			if (res) {
13419 				/* amd vsdb found */
13420 				vsdb_info->freesync_supported = 1;
13421 				vsdb_info->amd_vsdb_version = version;
13422 				vsdb_info->min_refresh_rate_hz = min_rate;
13423 				vsdb_info->max_refresh_rate_hz = max_rate;
13424 				/* Not enabled on DMCU*/
13425 				vsdb_info->freesync_mccs_vcp_code = 0;
13426 				return true;
13427 			}
13428 			/* not amd vsdb */
13429 			return false;
13430 		}
13431 
13432 		/* check for ack*/
13433 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
13434 		if (!res)
13435 			return false;
13436 	}
13437 
13438 	return false;
13439 }
13440 
13441 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
13442 		u8 *edid_ext, int len,
13443 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13444 {
13445 	int i;
13446 
13447 	/* send extension block to DMCU for parsing */
13448 	for (i = 0; i < len; i += 8) {
13449 		/* send 8 bytes a time */
13450 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
13451 			return false;
13452 	}
13453 
13454 	return vsdb_info->freesync_supported;
13455 }
13456 
13457 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
13458 		u8 *edid_ext, int len,
13459 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13460 {
13461 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
13462 	bool ret;
13463 
13464 	mutex_lock(&adev->dm.dc_lock);
13465 	if (adev->dm.dmub_srv)
13466 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
13467 	else
13468 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
13469 	mutex_unlock(&adev->dm.dc_lock);
13470 	return ret;
13471 }
13472 
13473 static void parse_edid_displayid_vrr(struct drm_connector *connector,
13474 				     const struct edid *edid)
13475 {
13476 	u8 *edid_ext = NULL;
13477 	int i;
13478 	int j = 0;
13479 	u16 min_vfreq;
13480 	u16 max_vfreq;
13481 
13482 	if (!edid || !edid->extensions)
13483 		return;
13484 
13485 	/* Find DisplayID extension */
13486 	for (i = 0; i < edid->extensions; i++) {
13487 		edid_ext = (void *)(edid + (i + 1));
13488 		if (edid_ext[0] == DISPLAYID_EXT)
13489 			break;
13490 	}
13491 
13492 	if (i == edid->extensions)
13493 		return;
13494 
13495 	while (j < EDID_LENGTH) {
13496 		/* Get dynamic video timing range from DisplayID if available */
13497 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
13498 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
13499 			min_vfreq = edid_ext[j+9];
13500 			if (edid_ext[j+1] & 7)
13501 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
13502 			else
13503 				max_vfreq = edid_ext[j+10];
13504 
13505 			if (max_vfreq && min_vfreq) {
13506 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
13507 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
13508 
13509 				return;
13510 			}
13511 		}
13512 		j++;
13513 	}
13514 }
13515 
13516 static int get_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13517 			struct amdgpu_hdmi_vsdb_info *vsdb_info)
13518 {
13519 	struct drm_connector *connector = &aconnector->base;
13520 
13521 	vsdb_info->replay_mode = connector->display_info.amd_vsdb.replay_mode;
13522 	vsdb_info->amd_vsdb_version = connector->display_info.amd_vsdb.version;
13523 
13524 	return connector->display_info.amd_vsdb.version != 0;
13525 }
13526 
13527 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13528 			       const struct edid *edid,
13529 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
13530 {
13531 	u8 *edid_ext = NULL;
13532 	int i;
13533 	bool valid_vsdb_found = false;
13534 
13535 	/*----- drm_find_cea_extension() -----*/
13536 	/* No EDID or EDID extensions */
13537 	if (edid == NULL || edid->extensions == 0)
13538 		return -ENODEV;
13539 
13540 	/* Find CEA extension */
13541 	for (i = 0; i < edid->extensions; i++) {
13542 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
13543 		if (edid_ext[0] == CEA_EXT)
13544 			break;
13545 	}
13546 
13547 	if (i == edid->extensions)
13548 		return -ENODEV;
13549 
13550 	/*----- cea_db_offsets() -----*/
13551 	if (edid_ext[0] != CEA_EXT)
13552 		return -ENODEV;
13553 
13554 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
13555 
13556 	return valid_vsdb_found ? i : -ENODEV;
13557 }
13558 
13559 /**
13560  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
13561  *
13562  * @connector: Connector to query.
13563  * @drm_edid: DRM EDID from monitor
13564  * @do_mccs: Controls whether MCCS (Monitor Control Command Set) over
13565  *	      DDC (Display Data Channel) transactions are performed. When true,
13566  *	      the driver queries the monitor to get or update additional FreeSync
13567  *	      capability information. When false, these transactions are skipped.
13568  *
13569  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
13570  * track of some of the display information in the internal data struct used by
13571  * amdgpu_dm. This function checks which type of connector we need to set the
13572  * FreeSync parameters.
13573  */
13574 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
13575 				    const struct drm_edid *drm_edid, bool do_mccs)
13576 {
13577 	int i = 0;
13578 	struct amdgpu_dm_connector *amdgpu_dm_connector =
13579 			to_amdgpu_dm_connector(connector);
13580 	struct dm_connector_state *dm_con_state = NULL;
13581 	struct dc_sink *sink;
13582 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
13583 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
13584 	const struct edid *edid;
13585 	bool freesync_capable = false;
13586 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
13587 
13588 	if (!connector->state) {
13589 		drm_err(adev_to_drm(adev), "%s - Connector has no state", __func__);
13590 		goto update;
13591 	}
13592 
13593 	sink = amdgpu_dm_connector->dc_sink ?
13594 		amdgpu_dm_connector->dc_sink :
13595 		amdgpu_dm_connector->dc_em_sink;
13596 
13597 	drm_edid_connector_update(connector, drm_edid);
13598 
13599 	if (!drm_edid || !sink) {
13600 		dm_con_state = to_dm_connector_state(connector->state);
13601 
13602 		amdgpu_dm_connector->min_vfreq = 0;
13603 		amdgpu_dm_connector->max_vfreq = 0;
13604 		freesync_capable = false;
13605 
13606 		goto update;
13607 	}
13608 
13609 	dm_con_state = to_dm_connector_state(connector->state);
13610 
13611 	if (!adev->dm.freesync_module || !dc_supports_vrr(sink->ctx->dce_version))
13612 		goto update;
13613 
13614 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
13615 
13616 	/* Some eDP panels only have the refresh rate range info in DisplayID */
13617 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
13618 	     connector->display_info.monitor_range.max_vfreq == 0))
13619 		parse_edid_displayid_vrr(connector, edid);
13620 
13621 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
13622 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
13623 		if (amdgpu_dm_connector->dc_link &&
13624 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
13625 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
13626 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
13627 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13628 				freesync_capable = true;
13629 		}
13630 
13631 		get_amd_vsdb(amdgpu_dm_connector, &vsdb_info);
13632 
13633 		if (vsdb_info.replay_mode) {
13634 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
13635 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
13636 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
13637 		}
13638 
13639 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
13640 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13641 		if (i >= 0) {
13642 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13643 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13644 
13645 			if (vsdb_info.freesync_supported) {
13646 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13647 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13648 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13649 					freesync_capable = true;
13650 
13651 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13652 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13653 			}
13654 		}
13655 	}
13656 
13657 	if (amdgpu_dm_connector->dc_link)
13658 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
13659 
13660 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
13661 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13662 		if (i >= 0) {
13663 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13664 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13665 
13666 			if (vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
13667 				amdgpu_dm_connector->pack_sdp_v1_3 = true;
13668 				amdgpu_dm_connector->as_type = as_type;
13669 
13670 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13671 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13672 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13673 					freesync_capable = true;
13674 
13675 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13676 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13677 			}
13678 		}
13679 	}
13680 
13681 	/* Handle MCCS */
13682 	if (do_mccs)
13683 		dm_helpers_read_mccs_caps(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13684 
13685 	if ((sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
13686 		as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) &&
13687 		(!sink->edid_caps.freesync_vcp_code ||
13688 		(sink->edid_caps.freesync_vcp_code && !sink->mccs_caps.freesync_supported)))
13689 		freesync_capable = false;
13690 
13691 	if (do_mccs && sink->mccs_caps.freesync_supported && freesync_capable)
13692 		dm_helpers_mccs_vcp_set(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13693 
13694 update:
13695 	if (dm_con_state)
13696 		dm_con_state->freesync_capable = freesync_capable;
13697 
13698 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
13699 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
13700 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
13701 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
13702 	}
13703 
13704 	if (connector->vrr_capable_property)
13705 		drm_connector_set_vrr_capable_property(connector,
13706 						       freesync_capable);
13707 }
13708 
13709 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
13710 {
13711 	struct amdgpu_device *adev = drm_to_adev(dev);
13712 	struct dc *dc = adev->dm.dc;
13713 	int i;
13714 
13715 	mutex_lock(&adev->dm.dc_lock);
13716 	if (dc->current_state) {
13717 		for (i = 0; i < dc->current_state->stream_count; ++i)
13718 			dc->current_state->streams[i]
13719 				->triggered_crtc_reset.enabled =
13720 				adev->dm.force_timing_sync;
13721 
13722 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
13723 		dc_trigger_sync(dc, dc->current_state);
13724 	}
13725 	mutex_unlock(&adev->dm.dc_lock);
13726 }
13727 
13728 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
13729 {
13730 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
13731 		dc_exit_ips_for_hw_access(dc);
13732 }
13733 
13734 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
13735 		       u32 value, const char *func_name)
13736 {
13737 #ifdef DM_CHECK_ADDR_0
13738 	if (address == 0) {
13739 		drm_err(adev_to_drm(ctx->driver_context),
13740 			"invalid register write. address = 0");
13741 		return;
13742 	}
13743 #endif
13744 
13745 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13746 	cgs_write_register(ctx->cgs_device, address, value);
13747 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
13748 }
13749 
13750 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
13751 			  const char *func_name)
13752 {
13753 	u32 value;
13754 #ifdef DM_CHECK_ADDR_0
13755 	if (address == 0) {
13756 		drm_err(adev_to_drm(ctx->driver_context),
13757 			"invalid register read; address = 0\n");
13758 		return 0;
13759 	}
13760 #endif
13761 
13762 	if (ctx->dmub_srv &&
13763 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
13764 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
13765 		ASSERT(false);
13766 		return 0;
13767 	}
13768 
13769 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13770 
13771 	value = cgs_read_register(ctx->cgs_device, address);
13772 
13773 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
13774 
13775 	return value;
13776 }
13777 
13778 int amdgpu_dm_process_dmub_aux_transfer_sync(
13779 		struct dc_context *ctx,
13780 		unsigned int link_index,
13781 		struct aux_payload *payload,
13782 		enum aux_return_code_type *operation_result)
13783 {
13784 	struct amdgpu_device *adev = ctx->driver_context;
13785 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
13786 	int ret = -1;
13787 
13788 	mutex_lock(&adev->dm.dpia_aux_lock);
13789 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
13790 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
13791 		goto out;
13792 	}
13793 
13794 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13795 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13796 		*operation_result = AUX_RET_ERROR_TIMEOUT;
13797 		goto out;
13798 	}
13799 
13800 	if (p_notify->result != AUX_RET_SUCCESS) {
13801 		/*
13802 		 * Transient states before tunneling is enabled could
13803 		 * lead to this error. We can ignore this for now.
13804 		 */
13805 		if (p_notify->result == AUX_RET_ERROR_PROTOCOL_ERROR) {
13806 			drm_warn(adev_to_drm(adev), "DPIA AUX failed on 0x%x(%d), error %d\n",
13807 					payload->address, payload->length,
13808 					p_notify->result);
13809 		}
13810 		*operation_result = p_notify->result;
13811 		goto out;
13812 	}
13813 
13814 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command & 0xF;
13815 	if (adev->dm.dmub_notify->aux_reply.command & 0xF0)
13816 		/* The reply is stored in the top nibble of the command. */
13817 		payload->reply[0] = (adev->dm.dmub_notify->aux_reply.command >> 4) & 0xF;
13818 
13819 	/*write req may receive a byte indicating partially written number as well*/
13820 	if (p_notify->aux_reply.length)
13821 		memcpy(payload->data, p_notify->aux_reply.data,
13822 				p_notify->aux_reply.length);
13823 
13824 	/* success */
13825 	ret = p_notify->aux_reply.length;
13826 	*operation_result = p_notify->result;
13827 out:
13828 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
13829 	mutex_unlock(&adev->dm.dpia_aux_lock);
13830 	return ret;
13831 }
13832 
13833 static void abort_fused_io(
13834 		struct dc_context *ctx,
13835 		const struct dmub_cmd_fused_request *request
13836 )
13837 {
13838 	union dmub_rb_cmd command = { 0 };
13839 	struct dmub_rb_cmd_fused_io *io = &command.fused_io;
13840 
13841 	io->header.type = DMUB_CMD__FUSED_IO;
13842 	io->header.sub_type = DMUB_CMD__FUSED_IO_ABORT;
13843 	io->header.payload_bytes = sizeof(*io) - sizeof(io->header);
13844 	io->request = *request;
13845 	dm_execute_dmub_cmd(ctx, &command, DM_DMUB_WAIT_TYPE_NO_WAIT);
13846 }
13847 
13848 static bool execute_fused_io(
13849 		struct amdgpu_device *dev,
13850 		struct dc_context *ctx,
13851 		union dmub_rb_cmd *commands,
13852 		uint8_t count,
13853 		uint32_t timeout_us
13854 )
13855 {
13856 	const uint8_t ddc_line = commands[0].fused_io.request.u.aux.ddc_line;
13857 
13858 	if (ddc_line >= ARRAY_SIZE(dev->dm.fused_io))
13859 		return false;
13860 
13861 	struct fused_io_sync *sync = &dev->dm.fused_io[ddc_line];
13862 	struct dmub_rb_cmd_fused_io *first = &commands[0].fused_io;
13863 	const bool result = dm_execute_dmub_cmd_list(ctx, count, commands, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY)
13864 			&& first->header.ret_status
13865 			&& first->request.status == FUSED_REQUEST_STATUS_SUCCESS;
13866 
13867 	if (!result)
13868 		return false;
13869 
13870 	while (wait_for_completion_timeout(&sync->replied, usecs_to_jiffies(timeout_us))) {
13871 		reinit_completion(&sync->replied);
13872 
13873 		struct dmub_cmd_fused_request *reply = (struct dmub_cmd_fused_request *) sync->reply_data;
13874 
13875 		static_assert(sizeof(*reply) <= sizeof(sync->reply_data), "Size mismatch");
13876 
13877 		if (reply->identifier == first->request.identifier) {
13878 			first->request = *reply;
13879 			return true;
13880 		}
13881 	}
13882 
13883 	reinit_completion(&sync->replied);
13884 	first->request.status = FUSED_REQUEST_STATUS_TIMEOUT;
13885 	abort_fused_io(ctx, &first->request);
13886 	return false;
13887 }
13888 
13889 bool amdgpu_dm_execute_fused_io(
13890 		struct amdgpu_device *dev,
13891 		struct dc_link *link,
13892 		union dmub_rb_cmd *commands,
13893 		uint8_t count,
13894 		uint32_t timeout_us)
13895 {
13896 	struct amdgpu_display_manager *dm = &dev->dm;
13897 
13898 	mutex_lock(&dm->dpia_aux_lock);
13899 
13900 	const bool result = execute_fused_io(dev, link->ctx, commands, count, timeout_us);
13901 
13902 	mutex_unlock(&dm->dpia_aux_lock);
13903 	return result;
13904 }
13905 
13906 int amdgpu_dm_process_dmub_set_config_sync(
13907 		struct dc_context *ctx,
13908 		unsigned int link_index,
13909 		struct set_config_cmd_payload *payload,
13910 		enum set_config_status *operation_result)
13911 {
13912 	struct amdgpu_device *adev = ctx->driver_context;
13913 	bool is_cmd_complete;
13914 	int ret;
13915 
13916 	mutex_lock(&adev->dm.dpia_aux_lock);
13917 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
13918 			link_index, payload, adev->dm.dmub_notify);
13919 
13920 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13921 		ret = 0;
13922 		*operation_result = adev->dm.dmub_notify->sc_status;
13923 	} else {
13924 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13925 		ret = -1;
13926 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
13927 	}
13928 
13929 	if (!is_cmd_complete)
13930 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
13931 	mutex_unlock(&adev->dm.dpia_aux_lock);
13932 	return ret;
13933 }
13934 
13935 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
13936 {
13937 	struct amdgpu_device *adev = ctx->driver_context;
13938 
13939 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
13940 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
13941 }
13942 
13943 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)
13944 {
13945 	struct amdgpu_device *adev = ctx->driver_context;
13946 
13947 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
13948 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
13949 }
13950 
13951 void dm_acpi_process_phy_transition_interlock(
13952 	const struct dc_context *ctx,
13953 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
13954 {
13955 	// Not yet implemented
13956 }
13957