xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision 70ed4679c5129b3a404116dfafa3ddb23a7cfa7a)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright 2015-2026 Advanced Micro Devices, Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  * Authors: AMD
24  *
25  */
26 
27 /* The caprices of the preprocessor require that this be declared right here */
28 #define CREATE_TRACE_POINTS
29 
30 #include "dm_services_types.h"
31 #include "dc.h"
32 #include "link_enc_cfg.h"
33 #include "dc/inc/core_types.h"
34 #include "dal_asic_id.h"
35 #include "dmub/dmub_srv.h"
36 #include "dc/inc/hw/dmcu.h"
37 #include "dc/inc/hw/abm.h"
38 #include "dc/dc_dmub_srv.h"
39 #include "dc/dc_edid_parser.h"
40 #include "dc/dc_stat.h"
41 #include "dc/dc_state.h"
42 #include "amdgpu_dm_trace.h"
43 #include "link/protocols/link_dpcd.h"
44 #include "link_service_types.h"
45 #include "link/protocols/link_dp_capability.h"
46 #include "link/protocols/link_ddc.h"
47 
48 #include "amdgpu.h"
49 #include "amdgpu_display.h"
50 #include "amdgpu_ucode.h"
51 #include "atom.h"
52 #include "amdgpu_dm.h"
53 #include "amdgpu_dm_plane.h"
54 #include "amdgpu_dm_crtc.h"
55 #include "amdgpu_dm_hdcp.h"
56 #include <drm/display/drm_hdcp_helper.h>
57 #include "amdgpu_dm_wb.h"
58 #include "amdgpu_atombios.h"
59 
60 #include "amd_shared.h"
61 #include "amdgpu_dm_irq.h"
62 #include "dm_helpers.h"
63 #include "amdgpu_dm_mst_types.h"
64 #if defined(CONFIG_DEBUG_FS)
65 #include "amdgpu_dm_debugfs.h"
66 #endif
67 #include "amdgpu_dm_psr.h"
68 #include "amdgpu_dm_replay.h"
69 
70 #include "ivsrcid/ivsrcid_vislands30.h"
71 
72 #include <linux/backlight.h>
73 #include <linux/module.h>
74 #include <linux/moduleparam.h>
75 #include <linux/types.h>
76 #include <linux/pm_runtime.h>
77 #include <linux/pci.h>
78 #include <linux/power_supply.h>
79 #include <linux/firmware.h>
80 #include <linux/component.h>
81 #include <linux/sort.h>
82 
83 #include <drm/drm_privacy_screen_consumer.h>
84 #include <drm/display/drm_dp_mst_helper.h>
85 #include <drm/display/drm_hdmi_helper.h>
86 #include <drm/drm_atomic.h>
87 #include <drm/drm_atomic_uapi.h>
88 #include <drm/drm_atomic_helper.h>
89 #include <drm/drm_blend.h>
90 #include <drm/drm_fixed.h>
91 #include <drm/drm_fourcc.h>
92 #include <drm/drm_edid.h>
93 #include <drm/drm_eld.h>
94 #include <drm/drm_mode.h>
95 #include <drm/drm_utils.h>
96 #include <drm/drm_vblank.h>
97 #include <drm/drm_audio_component.h>
98 #include <drm/drm_colorop.h>
99 #include <drm/drm_gem_atomic_helper.h>
100 
101 #include <media/cec-notifier.h>
102 #include <acpi/video.h>
103 
104 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
105 
106 #include "modules/inc/mod_freesync.h"
107 #include "modules/inc/mod_power.h"
108 #include "modules/power/power_helpers.h"
109 
110 static_assert(AMDGPU_DMUB_NOTIFICATION_MAX == DMUB_NOTIFICATION_MAX, "AMDGPU_DMUB_NOTIFICATION_MAX mismatch");
111 
112 #define FIRMWARE_RENOIR_DMUB "amdgpu/renoir_dmcub.bin"
113 MODULE_FIRMWARE(FIRMWARE_RENOIR_DMUB);
114 #define FIRMWARE_SIENNA_CICHLID_DMUB "amdgpu/sienna_cichlid_dmcub.bin"
115 MODULE_FIRMWARE(FIRMWARE_SIENNA_CICHLID_DMUB);
116 #define FIRMWARE_NAVY_FLOUNDER_DMUB "amdgpu/navy_flounder_dmcub.bin"
117 MODULE_FIRMWARE(FIRMWARE_NAVY_FLOUNDER_DMUB);
118 #define FIRMWARE_GREEN_SARDINE_DMUB "amdgpu/green_sardine_dmcub.bin"
119 MODULE_FIRMWARE(FIRMWARE_GREEN_SARDINE_DMUB);
120 #define FIRMWARE_VANGOGH_DMUB "amdgpu/vangogh_dmcub.bin"
121 MODULE_FIRMWARE(FIRMWARE_VANGOGH_DMUB);
122 #define FIRMWARE_DIMGREY_CAVEFISH_DMUB "amdgpu/dimgrey_cavefish_dmcub.bin"
123 MODULE_FIRMWARE(FIRMWARE_DIMGREY_CAVEFISH_DMUB);
124 #define FIRMWARE_BEIGE_GOBY_DMUB "amdgpu/beige_goby_dmcub.bin"
125 MODULE_FIRMWARE(FIRMWARE_BEIGE_GOBY_DMUB);
126 #define FIRMWARE_YELLOW_CARP_DMUB "amdgpu/yellow_carp_dmcub.bin"
127 MODULE_FIRMWARE(FIRMWARE_YELLOW_CARP_DMUB);
128 #define FIRMWARE_DCN_314_DMUB "amdgpu/dcn_3_1_4_dmcub.bin"
129 MODULE_FIRMWARE(FIRMWARE_DCN_314_DMUB);
130 #define FIRMWARE_DCN_315_DMUB "amdgpu/dcn_3_1_5_dmcub.bin"
131 MODULE_FIRMWARE(FIRMWARE_DCN_315_DMUB);
132 #define FIRMWARE_DCN316_DMUB "amdgpu/dcn_3_1_6_dmcub.bin"
133 MODULE_FIRMWARE(FIRMWARE_DCN316_DMUB);
134 
135 #define FIRMWARE_DCN_V3_2_0_DMCUB "amdgpu/dcn_3_2_0_dmcub.bin"
136 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_0_DMCUB);
137 #define FIRMWARE_DCN_V3_2_1_DMCUB "amdgpu/dcn_3_2_1_dmcub.bin"
138 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_1_DMCUB);
139 
140 #define FIRMWARE_RAVEN_DMCU		"amdgpu/raven_dmcu.bin"
141 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
142 
143 #define FIRMWARE_NAVI12_DMCU            "amdgpu/navi12_dmcu.bin"
144 MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
145 
146 #define FIRMWARE_DCN_35_DMUB "amdgpu/dcn_3_5_dmcub.bin"
147 MODULE_FIRMWARE(FIRMWARE_DCN_35_DMUB);
148 
149 #define FIRMWARE_DCN_351_DMUB "amdgpu/dcn_3_5_1_dmcub.bin"
150 MODULE_FIRMWARE(FIRMWARE_DCN_351_DMUB);
151 
152 #define FIRMWARE_DCN_36_DMUB "amdgpu/dcn_3_6_dmcub.bin"
153 MODULE_FIRMWARE(FIRMWARE_DCN_36_DMUB);
154 
155 #define FIRMWARE_DCN_401_DMUB "amdgpu/dcn_4_0_1_dmcub.bin"
156 MODULE_FIRMWARE(FIRMWARE_DCN_401_DMUB);
157 
158 #define FIRMWARE_DCN_42_DMUB "amdgpu/dcn_4_2_dmcub.bin"
159 MODULE_FIRMWARE(FIRMWARE_DCN_42_DMUB);
160 
161 #define FIRMWARE_DCN_42B_DMUB "amdgpu/dcn_4_2_1_dmcub.bin"
162 MODULE_FIRMWARE(FIRMWARE_DCN_42B_DMUB);
163 
164 /**
165  * DOC: overview
166  *
167  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
168  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
169  * requests into DC requests, and DC responses into DRM responses.
170  *
171  * The root control structure is &struct amdgpu_display_manager.
172  */
173 
174 /* basic init/fini API */
175 static int amdgpu_dm_init(struct amdgpu_device *adev);
176 static void amdgpu_dm_fini(struct amdgpu_device *adev);
177 static bool is_freesync_video_mode(const struct drm_display_mode *mode, struct amdgpu_dm_connector *aconnector);
178 static void reset_freesync_config_for_crtc(struct dm_crtc_state *new_crtc_state);
179 static struct amdgpu_i2c_adapter *
180 create_i2c(struct ddc_service *ddc_service, bool oem);
181 
182 static enum drm_mode_subconnector get_subconnector_type(struct dc_link *link)
183 {
184 	switch (link->dpcd_caps.dongle_type) {
185 	case DISPLAY_DONGLE_NONE:
186 		return DRM_MODE_SUBCONNECTOR_Native;
187 	case DISPLAY_DONGLE_DP_VGA_CONVERTER:
188 		return DRM_MODE_SUBCONNECTOR_VGA;
189 	case DISPLAY_DONGLE_DP_DVI_CONVERTER:
190 	case DISPLAY_DONGLE_DP_DVI_DONGLE:
191 		return DRM_MODE_SUBCONNECTOR_DVID;
192 	case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
193 	case DISPLAY_DONGLE_DP_HDMI_DONGLE:
194 		return DRM_MODE_SUBCONNECTOR_HDMIA;
195 	case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
196 	default:
197 		return DRM_MODE_SUBCONNECTOR_Unknown;
198 	}
199 }
200 
201 static void update_subconnector_property(struct amdgpu_dm_connector *aconnector)
202 {
203 	struct dc_link *link = aconnector->dc_link;
204 	struct drm_connector *connector = &aconnector->base;
205 	enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
206 
207 	if (connector->connector_type != DRM_MODE_CONNECTOR_DisplayPort)
208 		return;
209 
210 	if (aconnector->dc_sink)
211 		subconnector = get_subconnector_type(link);
212 
213 	drm_object_property_set_value(&connector->base,
214 			connector->dev->mode_config.dp_subconnector_property,
215 			subconnector);
216 }
217 
218 /*
219  * initializes drm_device display related structures, based on the information
220  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
221  * drm_encoder, drm_mode_config
222  *
223  * Returns 0 on success
224  */
225 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
226 /* removes and deallocates the drm structures, created by the above function */
227 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
228 
229 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
230 				    struct amdgpu_dm_connector *amdgpu_dm_connector,
231 				    u32 link_index,
232 				    struct amdgpu_encoder *amdgpu_encoder);
233 static int amdgpu_dm_encoder_init(struct drm_device *dev,
234 				  struct amdgpu_encoder *aencoder,
235 				  uint32_t link_index);
236 
237 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
238 
239 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state);
240 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state);
241 
242 static int amdgpu_dm_atomic_check(struct drm_device *dev,
243 				  struct drm_atomic_commit *state);
244 
245 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector);
246 static void handle_hpd_rx_irq(void *param);
247 
248 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
249 					 int bl_idx,
250 					 u32 user_brightness);
251 
252 static bool
253 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
254 				 struct drm_crtc_state *new_crtc_state);
255 /*
256  * dm_vblank_get_counter
257  *
258  * @brief
259  * Get counter for number of vertical blanks
260  *
261  * @param
262  * struct amdgpu_device *adev - [in] desired amdgpu device
263  * int disp_idx - [in] which CRTC to get the counter from
264  *
265  * @return
266  * Counter for vertical blanks
267  */
268 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
269 {
270 	struct amdgpu_crtc *acrtc = NULL;
271 
272 	if (crtc >= adev->mode_info.num_crtc)
273 		return 0;
274 
275 	acrtc = adev->mode_info.crtcs[crtc];
276 
277 	if (!acrtc->dm_irq_params.stream) {
278 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
279 			  crtc);
280 		return 0;
281 	}
282 
283 	return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
284 }
285 
286 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
287 				  u32 *vbl, u32 *position)
288 {
289 	u32 v_blank_start = 0, v_blank_end = 0, h_position = 0, v_position = 0;
290 	struct amdgpu_crtc *acrtc = NULL;
291 	struct dc *dc = adev->dm.dc;
292 
293 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
294 		return -EINVAL;
295 
296 	acrtc = adev->mode_info.crtcs[crtc];
297 
298 	if (!acrtc->dm_irq_params.stream) {
299 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
300 			  crtc);
301 		return 0;
302 	}
303 
304 	if (dc && dc->caps.ips_support && dc->idle_optimizations_allowed)
305 		dc_allow_idle_optimizations(dc, false);
306 
307 	/*
308 	 * TODO rework base driver to use values directly.
309 	 * for now parse it back into reg-format
310 	 */
311 	dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
312 				 &v_blank_start,
313 				 &v_blank_end,
314 				 &h_position,
315 				 &v_position);
316 
317 	*position = v_position | (h_position << 16);
318 	*vbl = v_blank_start | (v_blank_end << 16);
319 
320 	return 0;
321 }
322 
323 static bool dm_is_idle(struct amdgpu_ip_block *ip_block)
324 {
325 	/* XXX todo */
326 	return true;
327 }
328 
329 static int dm_wait_for_idle(struct amdgpu_ip_block *ip_block)
330 {
331 	/* XXX todo */
332 	return 0;
333 }
334 
335 static bool dm_check_soft_reset(struct amdgpu_ip_block *ip_block)
336 {
337 	return false;
338 }
339 
340 static int dm_soft_reset(struct amdgpu_ip_block *ip_block)
341 {
342 	/* XXX todo */
343 	return 0;
344 }
345 
346 static struct amdgpu_crtc *
347 get_crtc_by_otg_inst(struct amdgpu_device *adev,
348 		     int otg_inst)
349 {
350 	struct drm_device *dev = adev_to_drm(adev);
351 	struct drm_crtc *crtc;
352 	struct amdgpu_crtc *amdgpu_crtc;
353 
354 	if (WARN_ON(otg_inst == -1))
355 		return adev->mode_info.crtcs[0];
356 
357 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
358 		amdgpu_crtc = to_amdgpu_crtc(crtc);
359 
360 		if (amdgpu_crtc->otg_inst == otg_inst)
361 			return amdgpu_crtc;
362 	}
363 
364 	return NULL;
365 }
366 
367 static inline bool is_dc_timing_adjust_needed(struct dm_crtc_state *old_state,
368 					      struct dm_crtc_state *new_state)
369 {
370 	if (new_state->stream->adjust.timing_adjust_pending)
371 		return true;
372 	if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
373 		return true;
374 	else if (amdgpu_dm_crtc_vrr_active(old_state) != amdgpu_dm_crtc_vrr_active(new_state))
375 		return true;
376 	else
377 		return false;
378 }
379 
380 /*
381  * DC will program planes with their z-order determined by their ordering
382  * in the dc_surface_updates array. This comparator is used to sort them
383  * by descending zpos.
384  */
385 static int dm_plane_layer_index_cmp(const void *a, const void *b)
386 {
387 	const struct dc_surface_update *sa = (struct dc_surface_update *)a;
388 	const struct dc_surface_update *sb = (struct dc_surface_update *)b;
389 
390 	/* Sort by descending dc_plane layer_index (i.e. normalized_zpos) */
391 	return sb->surface->layer_index - sa->surface->layer_index;
392 }
393 
394 /**
395  * update_planes_and_stream_adapter() - Send planes to be updated in DC
396  *
397  * DC has a generic way to update planes and stream via
398  * dc_update_planes_and_stream function; however, DM might need some
399  * adjustments and preparation before calling it. This function is a wrapper
400  * for the dc_update_planes_and_stream that does any required configuration
401  * before passing control to DC.
402  *
403  * @dc: Display Core control structure
404  * @update_type: specify whether it is FULL/MEDIUM/FAST update
405  * @planes_count: planes count to update
406  * @stream: stream state
407  * @stream_update: stream update
408  * @array_of_surface_update: dc surface update pointer
409  *
410  */
411 static inline bool update_planes_and_stream_adapter(struct dc *dc,
412 						    int update_type,
413 						    int planes_count,
414 						    struct dc_stream_state *stream,
415 						    struct dc_stream_update *stream_update,
416 						    struct dc_surface_update *array_of_surface_update)
417 {
418 	sort(array_of_surface_update, planes_count,
419 	     sizeof(*array_of_surface_update), dm_plane_layer_index_cmp, NULL);
420 
421 	/*
422 	 * Previous frame finished and HW is ready for optimization.
423 	 */
424 	dc_post_update_surfaces_to_stream(dc);
425 
426 	return dc_update_planes_and_stream(dc,
427 					   array_of_surface_update,
428 					   planes_count,
429 					   stream,
430 					   stream_update);
431 }
432 
433 /**
434  * dm_pflip_high_irq() - Handle pageflip interrupt
435  * @interrupt_params: ignored
436  *
437  * Handles the pageflip interrupt by notifying all interested parties
438  * that the pageflip has been completed.
439  */
440 static void dm_pflip_high_irq(void *interrupt_params)
441 {
442 	struct amdgpu_crtc *amdgpu_crtc;
443 	struct common_irq_params *irq_params = interrupt_params;
444 	struct amdgpu_device *adev = irq_params->adev;
445 	struct drm_device *dev = adev_to_drm(adev);
446 	unsigned long flags;
447 	struct drm_pending_vblank_event *e;
448 	u32 vpos, hpos, v_blank_start, v_blank_end;
449 	bool vrr_active;
450 
451 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
452 
453 	/* IRQ could occur when in initial stage */
454 	/* TODO work and BO cleanup */
455 	if (amdgpu_crtc == NULL) {
456 		drm_dbg_state(dev, "CRTC is null, returning.\n");
457 		return;
458 	}
459 
460 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
461 
462 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED) {
463 		drm_dbg_state(dev,
464 			      "amdgpu_crtc->pflip_status = %d != AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p]\n",
465 			      amdgpu_crtc->pflip_status, AMDGPU_FLIP_SUBMITTED,
466 			      amdgpu_crtc->crtc_id, amdgpu_crtc);
467 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
468 		return;
469 	}
470 
471 	/* page flip completed. */
472 	e = amdgpu_crtc->event;
473 	amdgpu_crtc->event = NULL;
474 
475 	WARN_ON(!e);
476 
477 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(amdgpu_crtc);
478 
479 	/* Fixed refresh rate, or VRR scanout position outside front-porch? */
480 	if (!vrr_active ||
481 	    !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
482 				      &v_blank_end, &hpos, &vpos) ||
483 	    (vpos < v_blank_start)) {
484 		/* Update to correct count and vblank timestamp if racing with
485 		 * vblank irq. This also updates to the correct vblank timestamp
486 		 * even in VRR mode, as scanout is past the front-porch atm.
487 		 */
488 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
489 
490 		/* Wake up userspace by sending the pageflip event with proper
491 		 * count and timestamp of vblank of flip completion.
492 		 */
493 		if (e) {
494 			drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
495 
496 			/* Event sent, so done with vblank for this flip */
497 			drm_crtc_vblank_put(&amdgpu_crtc->base);
498 		}
499 	} else if (e) {
500 		/* VRR active and inside front-porch: vblank count and
501 		 * timestamp for pageflip event will only be up to date after
502 		 * drm_crtc_handle_vblank() has been executed from late vblank
503 		 * irq handler after start of back-porch (vline 0). We queue the
504 		 * pageflip event for send-out by drm_crtc_handle_vblank() with
505 		 * updated timestamp and count, once it runs after us.
506 		 *
507 		 * We need to open-code this instead of using the helper
508 		 * drm_crtc_arm_vblank_event(), as that helper would
509 		 * call drm_crtc_accurate_vblank_count(), which we must
510 		 * not call in VRR mode while we are in front-porch!
511 		 */
512 
513 		/* sequence will be replaced by real count during send-out. */
514 		e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
515 		e->pipe = amdgpu_crtc->crtc_id;
516 
517 		list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
518 		e = NULL;
519 	}
520 
521 	/* Keep track of vblank of this flip for flip throttling. We use the
522 	 * cooked hw counter, as that one incremented at start of this vblank
523 	 * of pageflip completion, so last_flip_vblank is the forbidden count
524 	 * for queueing new pageflips if vsync + VRR is enabled.
525 	 */
526 	amdgpu_crtc->dm_irq_params.last_flip_vblank =
527 		amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
528 
529 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
530 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
531 
532 	drm_dbg_state(dev,
533 		      "crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
534 		      amdgpu_crtc->crtc_id, amdgpu_crtc, vrr_active, (int)!e);
535 }
536 
537 static void dm_handle_vmin_vmax_update(struct work_struct *offload_work)
538 {
539 	struct vupdate_offload_work *work = container_of(offload_work, struct vupdate_offload_work, work);
540 	struct amdgpu_device *adev = work->adev;
541 	struct dc_stream_state *stream = work->stream;
542 	struct dc_crtc_timing_adjust *adjust = work->adjust;
543 
544 	mutex_lock(&adev->dm.dc_lock);
545 	dc_stream_adjust_vmin_vmax(adev->dm.dc, stream, adjust);
546 	mutex_unlock(&adev->dm.dc_lock);
547 
548 	dc_stream_release(stream);
549 	kfree(work->adjust);
550 	kfree(work);
551 }
552 
553 static void schedule_dc_vmin_vmax(struct amdgpu_device *adev,
554 	struct dc_stream_state *stream,
555 	struct dc_crtc_timing_adjust *adjust)
556 {
557 	struct vupdate_offload_work *offload_work = kzalloc_obj(*offload_work,
558 								GFP_NOWAIT);
559 	if (!offload_work) {
560 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate vupdate_offload_work\n");
561 		return;
562 	}
563 
564 	struct dc_crtc_timing_adjust *adjust_copy = kzalloc_obj(*adjust_copy,
565 								GFP_NOWAIT);
566 	if (!adjust_copy) {
567 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate adjust_copy\n");
568 		kfree(offload_work);
569 		return;
570 	}
571 
572 	dc_stream_retain(stream);
573 	memcpy(adjust_copy, adjust, sizeof(*adjust_copy));
574 
575 	INIT_WORK(&offload_work->work, dm_handle_vmin_vmax_update);
576 	offload_work->adev = adev;
577 	offload_work->stream = stream;
578 	offload_work->adjust = adjust_copy;
579 
580 	queue_work(system_percpu_wq, &offload_work->work);
581 }
582 
583 static void dm_vupdate_high_irq(void *interrupt_params)
584 {
585 	struct common_irq_params *irq_params = interrupt_params;
586 	struct amdgpu_device *adev = irq_params->adev;
587 	struct amdgpu_crtc *acrtc;
588 	struct drm_device *drm_dev;
589 	struct drm_vblank_crtc *vblank;
590 	ktime_t frame_duration_ns, previous_timestamp;
591 	unsigned long flags;
592 	int vrr_active;
593 
594 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
595 
596 	if (acrtc) {
597 		vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
598 		drm_dev = acrtc->base.dev;
599 		vblank = drm_crtc_vblank_crtc(&acrtc->base);
600 		previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
601 		frame_duration_ns = vblank->time - previous_timestamp;
602 
603 		if (frame_duration_ns > 0) {
604 			trace_amdgpu_refresh_rate_track(acrtc->base.index,
605 						frame_duration_ns,
606 						ktime_divns(NSEC_PER_SEC, frame_duration_ns));
607 			atomic64_set(&irq_params->previous_timestamp, vblank->time);
608 		}
609 
610 		drm_dbg_vbl(drm_dev,
611 			    "crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
612 			    vrr_active);
613 
614 		/* Core vblank handling is done here after end of front-porch in
615 		 * vrr mode, as vblank timestamping will give valid results
616 		 * while now done after front-porch. This will also deliver
617 		 * page-flip completion events that have been queued to us
618 		 * if a pageflip happened inside front-porch.
619 		 */
620 		if (vrr_active && acrtc->dm_irq_params.stream) {
621 			bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
622 			bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
623 			bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state
624 				== VRR_STATE_ACTIVE_VARIABLE;
625 
626 			amdgpu_dm_crtc_handle_vblank(acrtc);
627 
628 			/* BTR processing for pre-DCE12 ASICs */
629 			if (adev->family < AMDGPU_FAMILY_AI) {
630 				spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
631 				mod_freesync_handle_v_update(
632 				    adev->dm.freesync_module,
633 				    acrtc->dm_irq_params.stream,
634 				    &acrtc->dm_irq_params.vrr_params);
635 
636 				if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
637 					schedule_dc_vmin_vmax(adev,
638 						acrtc->dm_irq_params.stream,
639 						&acrtc->dm_irq_params.vrr_params.adjust);
640 				}
641 				spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
642 			}
643 		}
644 	}
645 }
646 
647 /**
648  * dm_crtc_high_irq() - Handles CRTC interrupt
649  * @interrupt_params: used for determining the CRTC instance
650  *
651  * Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
652  * event handler.
653  */
654 static void dm_crtc_high_irq(void *interrupt_params)
655 {
656 	struct common_irq_params *irq_params = interrupt_params;
657 	struct amdgpu_device *adev = irq_params->adev;
658 	struct drm_writeback_job *job;
659 	struct amdgpu_crtc *acrtc;
660 	unsigned long flags;
661 	int vrr_active;
662 
663 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
664 	if (!acrtc)
665 		return;
666 
667 	if (acrtc->wb_conn) {
668 		spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
669 
670 		if (acrtc->wb_pending) {
671 			job = list_first_entry_or_null(&acrtc->wb_conn->job_queue,
672 						       struct drm_writeback_job,
673 						       list_entry);
674 			acrtc->wb_pending = false;
675 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
676 
677 			if (job) {
678 				unsigned int v_total, refresh_hz;
679 				struct dc_stream_state *stream = acrtc->dm_irq_params.stream;
680 
681 				v_total = stream->adjust.v_total_max ?
682 					  stream->adjust.v_total_max : stream->timing.v_total;
683 				refresh_hz = div_u64((uint64_t) stream->timing.pix_clk_100hz *
684 					     100LL, (v_total * stream->timing.h_total));
685 				mdelay(1000 / refresh_hz);
686 
687 				drm_writeback_signal_completion(acrtc->wb_conn, 0);
688 				dc_stream_fc_disable_writeback(adev->dm.dc,
689 							       acrtc->dm_irq_params.stream, 0);
690 			}
691 		} else
692 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
693 	}
694 
695 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
696 
697 	drm_dbg_vbl(adev_to_drm(adev),
698 		    "crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
699 		    vrr_active, acrtc->dm_irq_params.active_planes);
700 
701 	/**
702 	 * Core vblank handling at start of front-porch is only possible
703 	 * in non-vrr mode, as only there vblank timestamping will give
704 	 * valid results while done in front-porch. Otherwise defer it
705 	 * to dm_vupdate_high_irq after end of front-porch.
706 	 */
707 	if (!vrr_active)
708 		amdgpu_dm_crtc_handle_vblank(acrtc);
709 
710 	/**
711 	 * Following stuff must happen at start of vblank, for crc
712 	 * computation and below-the-range btr support in vrr mode.
713 	 */
714 	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
715 
716 	/* BTR updates need to happen before VUPDATE on Vega and above. */
717 	if (adev->family < AMDGPU_FAMILY_AI)
718 		return;
719 
720 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
721 
722 	if (acrtc->dm_irq_params.stream &&
723 		acrtc->dm_irq_params.vrr_params.supported) {
724 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
725 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
726 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state == VRR_STATE_ACTIVE_VARIABLE;
727 
728 		mod_freesync_handle_v_update(adev->dm.freesync_module,
729 					     acrtc->dm_irq_params.stream,
730 					     &acrtc->dm_irq_params.vrr_params);
731 
732 		/* update vmin_vmax only if freesync is enabled, or only if PSR and REPLAY are disabled */
733 		if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
734 			schedule_dc_vmin_vmax(adev, acrtc->dm_irq_params.stream,
735 					&acrtc->dm_irq_params.vrr_params.adjust);
736 		}
737 	}
738 
739 	/*
740 	 * If there aren't any active_planes then DCH HUBP may be clock-gated.
741 	 * In that case, pageflip completion interrupts won't fire and pageflip
742 	 * completion events won't get delivered. Prevent this by sending
743 	 * pending pageflip events from here if a flip is still pending.
744 	 *
745 	 * If any planes are enabled, use dm_pflip_high_irq() instead, to
746 	 * avoid race conditions between flip programming and completion,
747 	 * which could cause too early flip completion events.
748 	 */
749 	if (adev->family >= AMDGPU_FAMILY_RV &&
750 	    acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
751 	    acrtc->dm_irq_params.active_planes == 0) {
752 		if (acrtc->event) {
753 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
754 			acrtc->event = NULL;
755 			drm_crtc_vblank_put(&acrtc->base);
756 		}
757 		acrtc->pflip_status = AMDGPU_FLIP_NONE;
758 	}
759 
760 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
761 }
762 
763 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
764 /**
765  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
766  * DCN generation ASICs
767  * @interrupt_params: interrupt parameters
768  *
769  * Used to set crc window/read out crc value at vertical line 0 position
770  */
771 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
772 {
773 	struct common_irq_params *irq_params = interrupt_params;
774 	struct amdgpu_device *adev = irq_params->adev;
775 	struct amdgpu_crtc *acrtc;
776 
777 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
778 
779 	if (!acrtc)
780 		return;
781 
782 	amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
783 }
784 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
785 
786 /**
787  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
788  * @adev: amdgpu_device pointer
789  * @notify: dmub notification structure
790  *
791  * Dmub AUX or SET_CONFIG command completion processing callback
792  * Copies dmub notification to DM which is to be read by AUX command.
793  * issuing thread and also signals the event to wake up the thread.
794  */
795 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
796 					struct dmub_notification *notify)
797 {
798 	if (adev->dm.dmub_notify)
799 		memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
800 	if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
801 		complete(&adev->dm.dmub_aux_transfer_done);
802 }
803 
804 static void dmub_aux_fused_io_callback(struct amdgpu_device *adev,
805 					struct dmub_notification *notify)
806 {
807 	if (!adev || !notify) {
808 		ASSERT(false);
809 		return;
810 	}
811 
812 	const struct dmub_cmd_fused_request *req = &notify->fused_request;
813 	const uint8_t ddc_line = req->u.aux.ddc_line;
814 
815 	if (ddc_line >= ARRAY_SIZE(adev->dm.fused_io)) {
816 		ASSERT(false);
817 		return;
818 	}
819 
820 	struct fused_io_sync *sync = &adev->dm.fused_io[ddc_line];
821 
822 	static_assert(sizeof(*req) <= sizeof(sync->reply_data), "Size mismatch");
823 	memcpy(sync->reply_data, req, sizeof(*req));
824 	complete(&sync->replied);
825 }
826 
827 /**
828  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
829  * @adev: amdgpu_device pointer
830  * @notify: dmub notification structure
831  *
832  * Dmub Hpd interrupt processing callback. Gets displayindex through the
833  * ink index and calls helper to do the processing.
834  */
835 static void dmub_hpd_callback(struct amdgpu_device *adev,
836 			      struct dmub_notification *notify)
837 {
838 	struct amdgpu_dm_connector *aconnector;
839 	struct amdgpu_dm_connector *hpd_aconnector = NULL;
840 	struct drm_connector *connector;
841 	struct drm_connector_list_iter iter;
842 	struct dc_link *link;
843 	u8 link_index = 0;
844 	struct drm_device *dev;
845 
846 	if (adev == NULL)
847 		return;
848 
849 	if (notify == NULL) {
850 		drm_err(adev_to_drm(adev), "DMUB HPD callback notification was NULL");
851 		return;
852 	}
853 
854 	if (notify->link_index > adev->dm.dc->link_count) {
855 		drm_err(adev_to_drm(adev), "DMUB HPD index (%u)is abnormal", notify->link_index);
856 		return;
857 	}
858 
859 	/* Skip DMUB HPD IRQ in suspend/resume. We will probe them later. */
860 	if (notify->type == DMUB_NOTIFICATION_HPD && adev->in_suspend) {
861 		drm_info(adev_to_drm(adev), "Skip DMUB HPD IRQ callback in suspend/resume\n");
862 		return;
863 	}
864 
865 	link_index = notify->link_index;
866 	link = adev->dm.dc->links[link_index];
867 	dev = adev->dm.ddev;
868 
869 	drm_connector_list_iter_begin(dev, &iter);
870 	drm_for_each_connector_iter(connector, &iter) {
871 
872 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
873 			continue;
874 
875 		aconnector = to_amdgpu_dm_connector(connector);
876 		if (link && aconnector->dc_link == link) {
877 			if (notify->type == DMUB_NOTIFICATION_HPD)
878 				drm_info(adev_to_drm(adev), "DMUB HPD IRQ callback: link_index=%u\n", link_index);
879 			else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
880 				drm_info(adev_to_drm(adev), "DMUB HPD RX IRQ callback: link_index=%u\n", link_index);
881 			else
882 				drm_warn(adev_to_drm(adev), "DMUB Unknown HPD callback type %d, link_index=%u\n",
883 						notify->type, link_index);
884 
885 			hpd_aconnector = aconnector;
886 			break;
887 		}
888 	}
889 	drm_connector_list_iter_end(&iter);
890 
891 	if (hpd_aconnector) {
892 		if (notify->type == DMUB_NOTIFICATION_HPD) {
893 			if (hpd_aconnector->dc_link->hpd_status == (notify->hpd_status == DP_HPD_PLUG))
894 				drm_warn(adev_to_drm(adev), "DMUB reported hpd status unchanged. link_index=%u\n", link_index);
895 			handle_hpd_irq_helper(hpd_aconnector);
896 		} else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ) {
897 			handle_hpd_rx_irq(hpd_aconnector);
898 		}
899 	}
900 }
901 
902 /**
903  * dmub_hpd_sense_callback - DMUB HPD sense processing callback.
904  * @adev: amdgpu_device pointer
905  * @notify: dmub notification structure
906  *
907  * HPD sense changes can occur during low power states and need to be
908  * notified from firmware to driver.
909  */
910 static void dmub_hpd_sense_callback(struct amdgpu_device *adev,
911 			      struct dmub_notification *notify)
912 {
913 	drm_dbg_driver(adev_to_drm(adev), "DMUB HPD SENSE callback.\n");
914 }
915 
916 /**
917  * register_dmub_notify_callback - Sets callback for DMUB notify
918  * @adev: amdgpu_device pointer
919  * @type: Type of dmub notification
920  * @callback: Dmub interrupt callback function
921  * @dmub_int_thread_offload: offload indicator
922  *
923  * API to register a dmub callback handler for a dmub notification
924  * Also sets indicator whether callback processing to be offloaded.
925  * to dmub interrupt handling thread
926  * Return: true if successfully registered, false if there is existing registration
927  */
928 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
929 					  enum dmub_notification_type type,
930 					  dmub_notify_interrupt_callback_t callback,
931 					  bool dmub_int_thread_offload)
932 {
933 	if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
934 		adev->dm.dmub_callback[type] = callback;
935 		adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
936 	} else
937 		return false;
938 
939 	return true;
940 }
941 
942 static void dm_handle_hpd_work(struct work_struct *work)
943 {
944 	struct dmub_hpd_work *dmub_hpd_wrk;
945 
946 	dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
947 
948 	if (!dmub_hpd_wrk->dmub_notify) {
949 		drm_err(adev_to_drm(dmub_hpd_wrk->adev), "dmub_hpd_wrk dmub_notify is NULL");
950 		return;
951 	}
952 
953 	if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
954 		dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
955 		dmub_hpd_wrk->dmub_notify);
956 	}
957 
958 	kfree(dmub_hpd_wrk->dmub_notify);
959 	kfree(dmub_hpd_wrk);
960 
961 }
962 
963 static const char *dmub_notification_type_str(enum dmub_notification_type e)
964 {
965 	switch (e) {
966 	case DMUB_NOTIFICATION_NO_DATA:
967 		return "NO_DATA";
968 	case DMUB_NOTIFICATION_AUX_REPLY:
969 		return "AUX_REPLY";
970 	case DMUB_NOTIFICATION_HPD:
971 		return "HPD";
972 	case DMUB_NOTIFICATION_HPD_IRQ:
973 		return "HPD_IRQ";
974 	case DMUB_NOTIFICATION_SET_CONFIG_REPLY:
975 		return "SET_CONFIG_REPLY";
976 	case DMUB_NOTIFICATION_DPIA_NOTIFICATION:
977 		return "DPIA_NOTIFICATION";
978 	case DMUB_NOTIFICATION_HPD_SENSE_NOTIFY:
979 		return "HPD_SENSE_NOTIFY";
980 	case DMUB_NOTIFICATION_FUSED_IO:
981 		return "FUSED_IO";
982 	default:
983 		return "<unknown>";
984 	}
985 }
986 
987 #define DMUB_TRACE_MAX_READ 64
988 /**
989  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
990  * @interrupt_params: used for determining the Outbox instance
991  *
992  * Handles the Outbox Interrupt
993  * event handler.
994  */
995 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
996 {
997 	struct dmub_notification notify = {0};
998 	struct common_irq_params *irq_params = interrupt_params;
999 	struct amdgpu_device *adev = irq_params->adev;
1000 	struct amdgpu_display_manager *dm = &adev->dm;
1001 	struct dmcub_trace_buf_entry entry = { 0 };
1002 	u32 count = 0;
1003 	struct dmub_hpd_work *dmub_hpd_wrk;
1004 
1005 	do {
1006 		if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
1007 			trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
1008 							entry.param0, entry.param1);
1009 
1010 			drm_dbg_driver(adev_to_drm(adev), "trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
1011 				 entry.trace_code, entry.tick_count, entry.param0, entry.param1);
1012 		} else
1013 			break;
1014 
1015 		count++;
1016 
1017 	} while (count <= DMUB_TRACE_MAX_READ);
1018 
1019 	if (count > DMUB_TRACE_MAX_READ)
1020 		drm_dbg_driver(adev_to_drm(adev), "Warning : count > DMUB_TRACE_MAX_READ");
1021 
1022 	if (dc_enable_dmub_notifications(adev->dm.dc) &&
1023 		irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
1024 
1025 		do {
1026 			dc_stat_get_dmub_notification(adev->dm.dc, &notify);
1027 			if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
1028 				drm_err(adev_to_drm(adev), "DM: notify type %d invalid!", notify.type);
1029 				continue;
1030 			}
1031 			if (!dm->dmub_callback[notify.type]) {
1032 				drm_warn(adev_to_drm(adev), "DMUB notification skipped due to no handler: type=%s\n",
1033 					dmub_notification_type_str(notify.type));
1034 				continue;
1035 			}
1036 			if (dm->dmub_thread_offload[notify.type] == true) {
1037 				dmub_hpd_wrk = kzalloc_obj(*dmub_hpd_wrk,
1038 							   GFP_ATOMIC);
1039 				if (!dmub_hpd_wrk) {
1040 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk");
1041 					return;
1042 				}
1043 				dmub_hpd_wrk->dmub_notify = kmemdup(&notify, sizeof(struct dmub_notification),
1044 								    GFP_ATOMIC);
1045 				if (!dmub_hpd_wrk->dmub_notify) {
1046 					kfree(dmub_hpd_wrk);
1047 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk->dmub_notify");
1048 					return;
1049 				}
1050 				INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
1051 				dmub_hpd_wrk->adev = adev;
1052 				queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
1053 			} else {
1054 				dm->dmub_callback[notify.type](adev, &notify);
1055 			}
1056 		} while (notify.pending_notification);
1057 	}
1058 }
1059 
1060 static int dm_set_clockgating_state(struct amdgpu_ip_block *ip_block,
1061 		  enum amd_clockgating_state state)
1062 {
1063 	return 0;
1064 }
1065 
1066 static int dm_set_powergating_state(struct amdgpu_ip_block *ip_block,
1067 		  enum amd_powergating_state state)
1068 {
1069 	return 0;
1070 }
1071 
1072 /* Prototypes of private functions */
1073 static int dm_early_init(struct amdgpu_ip_block *ip_block);
1074 
1075 /* Allocate memory for FBC compressed data  */
1076 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
1077 {
1078 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
1079 	struct dm_compressor_info *compressor = &adev->dm.compressor;
1080 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
1081 	struct drm_display_mode *mode;
1082 	unsigned long max_size = 0;
1083 
1084 	if (adev->dm.dc->fbc_compressor == NULL)
1085 		return;
1086 
1087 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
1088 		return;
1089 
1090 	if (compressor->bo_ptr)
1091 		return;
1092 
1093 
1094 	list_for_each_entry(mode, &connector->modes, head) {
1095 		if (max_size < (unsigned long) mode->htotal * mode->vtotal)
1096 			max_size = (unsigned long) mode->htotal * mode->vtotal;
1097 	}
1098 
1099 	if (max_size) {
1100 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
1101 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
1102 			    &compressor->gpu_addr, &compressor->cpu_addr);
1103 
1104 		if (r)
1105 			drm_err(adev_to_drm(adev), "DM: Failed to initialize FBC\n");
1106 		else {
1107 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
1108 			drm_info(adev_to_drm(adev), "DM: FBC alloc %lu\n", max_size*4);
1109 		}
1110 
1111 	}
1112 
1113 }
1114 
1115 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
1116 					  int pipe, bool *enabled,
1117 					  unsigned char *buf, int max_bytes)
1118 {
1119 	struct drm_device *dev = dev_get_drvdata(kdev);
1120 	struct amdgpu_device *adev = drm_to_adev(dev);
1121 	struct drm_connector *connector;
1122 	struct drm_connector_list_iter conn_iter;
1123 	struct amdgpu_dm_connector *aconnector;
1124 	int ret = 0;
1125 
1126 	*enabled = false;
1127 
1128 	mutex_lock(&adev->dm.audio_lock);
1129 
1130 	drm_connector_list_iter_begin(dev, &conn_iter);
1131 	drm_for_each_connector_iter(connector, &conn_iter) {
1132 
1133 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1134 			continue;
1135 
1136 		aconnector = to_amdgpu_dm_connector(connector);
1137 		if (aconnector->audio_inst != port)
1138 			continue;
1139 
1140 		*enabled = true;
1141 		mutex_lock(&connector->eld_mutex);
1142 		ret = drm_eld_size(connector->eld);
1143 		memcpy(buf, connector->eld, min(max_bytes, ret));
1144 		mutex_unlock(&connector->eld_mutex);
1145 
1146 		break;
1147 	}
1148 	drm_connector_list_iter_end(&conn_iter);
1149 
1150 	mutex_unlock(&adev->dm.audio_lock);
1151 
1152 	drm_dbg_kms(adev_to_drm(adev), "Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
1153 
1154 	return ret;
1155 }
1156 
1157 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
1158 	.get_eld = amdgpu_dm_audio_component_get_eld,
1159 };
1160 
1161 static int amdgpu_dm_audio_component_bind(struct device *kdev,
1162 				       struct device *hda_kdev, void *data)
1163 {
1164 	struct drm_device *dev = dev_get_drvdata(kdev);
1165 	struct amdgpu_device *adev = drm_to_adev(dev);
1166 	struct drm_audio_component *acomp = data;
1167 
1168 	acomp->ops = &amdgpu_dm_audio_component_ops;
1169 	acomp->dev = kdev;
1170 	adev->dm.audio_component = acomp;
1171 
1172 	return 0;
1173 }
1174 
1175 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
1176 					  struct device *hda_kdev, void *data)
1177 {
1178 	struct amdgpu_device *adev = drm_to_adev(dev_get_drvdata(kdev));
1179 	struct drm_audio_component *acomp = data;
1180 
1181 	acomp->ops = NULL;
1182 	acomp->dev = NULL;
1183 	adev->dm.audio_component = NULL;
1184 }
1185 
1186 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
1187 	.bind	= amdgpu_dm_audio_component_bind,
1188 	.unbind	= amdgpu_dm_audio_component_unbind,
1189 };
1190 
1191 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
1192 {
1193 	int i, ret;
1194 
1195 	if (!amdgpu_audio)
1196 		return 0;
1197 
1198 	adev->mode_info.audio.enabled = true;
1199 
1200 	adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
1201 
1202 	for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
1203 		adev->mode_info.audio.pin[i].channels = -1;
1204 		adev->mode_info.audio.pin[i].rate = -1;
1205 		adev->mode_info.audio.pin[i].bits_per_sample = -1;
1206 		adev->mode_info.audio.pin[i].status_bits = 0;
1207 		adev->mode_info.audio.pin[i].category_code = 0;
1208 		adev->mode_info.audio.pin[i].connected = false;
1209 		adev->mode_info.audio.pin[i].id =
1210 			adev->dm.dc->res_pool->audios[i]->inst;
1211 		adev->mode_info.audio.pin[i].offset = 0;
1212 	}
1213 
1214 	ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1215 	if (ret < 0)
1216 		return ret;
1217 
1218 	adev->dm.audio_registered = true;
1219 
1220 	return 0;
1221 }
1222 
1223 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
1224 {
1225 	if (!amdgpu_audio)
1226 		return;
1227 
1228 	if (!adev->mode_info.audio.enabled)
1229 		return;
1230 
1231 	if (adev->dm.audio_registered) {
1232 		component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1233 		adev->dm.audio_registered = false;
1234 	}
1235 
1236 	/* TODO: Disable audio? */
1237 
1238 	adev->mode_info.audio.enabled = false;
1239 }
1240 
1241 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
1242 {
1243 	struct drm_audio_component *acomp = adev->dm.audio_component;
1244 
1245 	if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
1246 		drm_dbg_kms(adev_to_drm(adev), "Notify ELD: %d\n", pin);
1247 
1248 		acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1249 						 pin, -1);
1250 	}
1251 }
1252 
1253 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1254 {
1255 	const struct dmcub_firmware_header_v1_0 *hdr;
1256 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1257 	struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1258 	const struct firmware *dmub_fw = adev->dm.dmub_fw;
1259 	struct dc *dc = adev->dm.dc;
1260 	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1261 	struct abm *abm = adev->dm.dc->res_pool->abm;
1262 	struct dc_context *ctx = adev->dm.dc->ctx;
1263 	struct dmub_srv_hw_params hw_params;
1264 	enum dmub_status status;
1265 	const unsigned char *fw_inst_const, *fw_bss_data;
1266 	u32 i, fw_inst_const_size, fw_bss_data_size;
1267 	bool has_hw_support;
1268 
1269 	if (!dmub_srv)
1270 		/* DMUB isn't supported on the ASIC. */
1271 		return 0;
1272 
1273 	if (!fb_info) {
1274 		drm_err(adev_to_drm(adev), "No framebuffer info for DMUB service.\n");
1275 		return -EINVAL;
1276 	}
1277 
1278 	if (!dmub_fw) {
1279 		/* Firmware required for DMUB support. */
1280 		drm_err(adev_to_drm(adev), "No firmware provided for DMUB.\n");
1281 		return -EINVAL;
1282 	}
1283 
1284 	/* initialize register offsets for ASICs with runtime initialization available */
1285 	if (dmub_srv->hw_funcs.init_reg_offsets)
1286 		dmub_srv->hw_funcs.init_reg_offsets(dmub_srv, ctx);
1287 
1288 	status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1289 	if (status != DMUB_STATUS_OK) {
1290 		drm_err(adev_to_drm(adev), "Error checking HW support for DMUB: %d\n", status);
1291 		return -EINVAL;
1292 	}
1293 
1294 	if (!has_hw_support) {
1295 		drm_info(adev_to_drm(adev), "DMUB unsupported on ASIC\n");
1296 		return 0;
1297 	}
1298 
1299 	/* Reset DMCUB if it was previously running - before we overwrite its memory. */
1300 	status = dmub_srv_hw_reset(dmub_srv);
1301 	if (status != DMUB_STATUS_OK)
1302 		drm_warn(adev_to_drm(adev), "Error resetting DMUB HW: %d\n", status);
1303 
1304 	hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1305 
1306 	fw_inst_const = dmub_fw->data +
1307 			le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1308 			PSP_HEADER_BYTES_256;
1309 
1310 	fw_bss_data = dmub_fw->data +
1311 		      le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1312 		      le32_to_cpu(hdr->inst_const_bytes);
1313 
1314 	/* Copy firmware and bios info into FB memory. */
1315 	fw_inst_const_size = adev->dm.fw_inst_size;
1316 
1317 	fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1318 
1319 	/* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1320 	 * amdgpu_ucode_init_single_fw will load dmub firmware
1321 	 * fw_inst_const part to cw0; otherwise, the firmware back door load
1322 	 * will be done by dm_dmub_hw_init
1323 	 */
1324 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1325 		memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1326 				fw_inst_const_size);
1327 	}
1328 
1329 	if (fw_bss_data_size)
1330 		memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1331 		       fw_bss_data, fw_bss_data_size);
1332 
1333 	/* Copy firmware bios info into FB memory. */
1334 	memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1335 	       adev->bios_size);
1336 
1337 	/* Reset regions that need to be reset. */
1338 	memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1339 	fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1340 
1341 	memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1342 	       fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1343 
1344 	memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1345 	       fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1346 
1347 	memset(fb_info->fb[DMUB_WINDOW_SHARED_STATE].cpu_addr, 0,
1348 	       fb_info->fb[DMUB_WINDOW_SHARED_STATE].size);
1349 
1350 	/* Initialize hardware. */
1351 	memset(&hw_params, 0, sizeof(hw_params));
1352 	hw_params.soc_fb_info.fb_base = adev->gmc.fb_start;
1353 	hw_params.soc_fb_info.fb_offset = adev->vm_manager.vram_base_offset;
1354 
1355 	/* backdoor load firmware and trigger dmub running */
1356 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1357 		hw_params.load_inst_const = true;
1358 
1359 	if (dmcu)
1360 		hw_params.psp_version = dmcu->psp_version;
1361 
1362 	for (i = 0; i < fb_info->num_fb; ++i)
1363 		hw_params.fb[i] = &fb_info->fb[i];
1364 
1365 	/* Enable usb4 dpia in the FW APU */
1366 	if (dc->caps.is_apu &&
1367 		dc->res_pool->usb4_dpia_count != 0 &&
1368 		!dc->debug.dpia_debug.bits.disable_dpia) {
1369 		hw_params.dpia_supported = true;
1370 		hw_params.disable_dpia = dc->debug.dpia_debug.bits.disable_dpia;
1371 		hw_params.dpia_hpd_int_enable_supported = false;
1372 		hw_params.enable_non_transparent_setconfig = dc->config.consolidated_dpia_dp_lt;
1373 		hw_params.disable_dpia_bw_allocation = !dc->config.usb4_bw_alloc_support;
1374 	}
1375 
1376 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1377 	case IP_VERSION(3, 5, 0):
1378 	case IP_VERSION(3, 5, 1):
1379 	case IP_VERSION(3, 6, 0):
1380 	case IP_VERSION(4, 2, 0):
1381 	case IP_VERSION(4, 2, 1):
1382 		hw_params.ips_sequential_ono = adev->external_rev_id > 0x10;
1383 		hw_params.lower_hbr3_phy_ssc = true;
1384 		break;
1385 	default:
1386 		break;
1387 	}
1388 
1389 	status = dmub_srv_hw_init(dmub_srv, &hw_params);
1390 	if (status != DMUB_STATUS_OK) {
1391 		drm_err(adev_to_drm(adev), "Error initializing DMUB HW: %d\n", status);
1392 		return -EINVAL;
1393 	}
1394 
1395 	/* Wait for firmware load to finish. */
1396 	status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1397 	if (status != DMUB_STATUS_OK)
1398 		drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1399 
1400 	/* Init DMCU and ABM if available. */
1401 	if (dmcu && abm) {
1402 		dmcu->funcs->dmcu_init(dmcu);
1403 		abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1404 	}
1405 
1406 	if (!adev->dm.dc->ctx->dmub_srv)
1407 		adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1408 	if (!adev->dm.dc->ctx->dmub_srv) {
1409 		drm_err(adev_to_drm(adev), "Couldn't allocate DC DMUB server!\n");
1410 		return -ENOMEM;
1411 	}
1412 
1413 	drm_info(adev_to_drm(adev), "DMUB hardware initialized: version=0x%08X\n",
1414 		 adev->dm.dmcub_fw_version);
1415 
1416 	/* Keeping sanity checks off if
1417 	 * DCN31 >= 4.0.59.0
1418 	 * DCN314 >= 8.0.16.0
1419 	 * Otherwise, turn on sanity checks
1420 	 */
1421 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1422 	case IP_VERSION(3, 1, 2):
1423 	case IP_VERSION(3, 1, 3):
1424 		if (adev->dm.dmcub_fw_version &&
1425 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1426 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(4, 0, 59))
1427 				adev->dm.dc->debug.sanity_checks = true;
1428 		break;
1429 	case IP_VERSION(3, 1, 4):
1430 		if (adev->dm.dmcub_fw_version &&
1431 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1432 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(8, 0, 16))
1433 				adev->dm.dc->debug.sanity_checks = true;
1434 		break;
1435 	default:
1436 		break;
1437 	}
1438 
1439 	return 0;
1440 }
1441 
1442 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1443 {
1444 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1445 	enum dmub_status status;
1446 	bool init;
1447 	int r;
1448 
1449 	if (!dmub_srv) {
1450 		/* DMUB isn't supported on the ASIC. */
1451 		return;
1452 	}
1453 
1454 	status = dmub_srv_is_hw_init(dmub_srv, &init);
1455 	if (status != DMUB_STATUS_OK)
1456 		drm_warn(adev_to_drm(adev), "DMUB hardware init check failed: %d\n", status);
1457 
1458 	if (status == DMUB_STATUS_OK && init) {
1459 		/* Wait for firmware load to finish. */
1460 		status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1461 		if (status != DMUB_STATUS_OK)
1462 			drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1463 	} else {
1464 		/* Perform the full hardware initialization. */
1465 		r = dm_dmub_hw_init(adev);
1466 		if (r)
1467 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
1468 	}
1469 }
1470 
1471 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1472 {
1473 	u64 pt_base;
1474 	u32 logical_addr_low;
1475 	u32 logical_addr_high;
1476 	u32 agp_base, agp_bot, agp_top;
1477 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1478 
1479 	memset(pa_config, 0, sizeof(*pa_config));
1480 
1481 	agp_base = 0;
1482 	agp_bot = adev->gmc.agp_start >> 24;
1483 	agp_top = adev->gmc.agp_end >> 24;
1484 
1485 	/* AGP aperture is disabled */
1486 	if (agp_bot > agp_top) {
1487 		logical_addr_low = adev->gmc.fb_start >> 18;
1488 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1489 				       AMD_APU_IS_RENOIR |
1490 				       AMD_APU_IS_GREEN_SARDINE))
1491 			/*
1492 			 * Raven2 has a HW issue that it is unable to use the vram which
1493 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1494 			 * workaround that increase system aperture high address (add 1)
1495 			 * to get rid of the VM fault and hardware hang.
1496 			 */
1497 			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
1498 		else
1499 			logical_addr_high = adev->gmc.fb_end >> 18;
1500 	} else {
1501 		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1502 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1503 				       AMD_APU_IS_RENOIR |
1504 				       AMD_APU_IS_GREEN_SARDINE))
1505 			/*
1506 			 * Raven2 has a HW issue that it is unable to use the vram which
1507 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1508 			 * workaround that increase system aperture high address (add 1)
1509 			 * to get rid of the VM fault and hardware hang.
1510 			 */
1511 			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1512 		else
1513 			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1514 	}
1515 
1516 	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1517 
1518 	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
1519 						   AMDGPU_GPU_PAGE_SHIFT);
1520 	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
1521 						  AMDGPU_GPU_PAGE_SHIFT);
1522 	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
1523 						 AMDGPU_GPU_PAGE_SHIFT);
1524 	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
1525 						AMDGPU_GPU_PAGE_SHIFT);
1526 	page_table_base.high_part = upper_32_bits(pt_base);
1527 	page_table_base.low_part = lower_32_bits(pt_base);
1528 
1529 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1530 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1531 
1532 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
1533 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1534 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1535 
1536 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1537 	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
1538 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1539 
1540 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1541 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1542 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1543 
1544 	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
1545 
1546 }
1547 
1548 static void force_connector_state(
1549 	struct amdgpu_dm_connector *aconnector,
1550 	enum drm_connector_force force_state)
1551 {
1552 	struct drm_connector *connector = &aconnector->base;
1553 
1554 	mutex_lock(&connector->dev->mode_config.mutex);
1555 	aconnector->base.force = force_state;
1556 	mutex_unlock(&connector->dev->mode_config.mutex);
1557 
1558 	mutex_lock(&aconnector->hpd_lock);
1559 	drm_kms_helper_connector_hotplug_event(connector);
1560 	mutex_unlock(&aconnector->hpd_lock);
1561 }
1562 
1563 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1564 {
1565 	struct hpd_rx_irq_offload_work *offload_work;
1566 	struct amdgpu_dm_connector *aconnector;
1567 	struct dc_link *dc_link;
1568 	struct amdgpu_device *adev;
1569 	enum dc_connection_type new_connection_type = dc_connection_none;
1570 	unsigned long flags;
1571 	union test_response test_response;
1572 
1573 	memset(&test_response, 0, sizeof(test_response));
1574 
1575 	offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1576 	aconnector = offload_work->offload_wq->aconnector;
1577 	adev = offload_work->adev;
1578 
1579 	if (!aconnector) {
1580 		drm_err(adev_to_drm(adev), "Can't retrieve aconnector in hpd_rx_irq_offload_work");
1581 		goto skip;
1582 	}
1583 
1584 	dc_link = aconnector->dc_link;
1585 
1586 	mutex_lock(&aconnector->hpd_lock);
1587 	if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
1588 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
1589 	mutex_unlock(&aconnector->hpd_lock);
1590 
1591 	if (new_connection_type == dc_connection_none)
1592 		goto skip;
1593 
1594 	if (amdgpu_in_reset(adev))
1595 		goto skip;
1596 
1597 	if (offload_work->data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
1598 		offload_work->data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
1599 		dm_handle_mst_sideband_msg_ready_event(&aconnector->mst_mgr, DOWN_OR_UP_MSG_RDY_EVENT);
1600 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1601 		offload_work->offload_wq->is_handling_mst_msg_rdy_event = false;
1602 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1603 		goto skip;
1604 	}
1605 
1606 	mutex_lock(&adev->dm.dc_lock);
1607 	if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
1608 		dc_link_dp_handle_automated_test(dc_link);
1609 
1610 		if (aconnector->timing_changed) {
1611 			/* force connector disconnect and reconnect */
1612 			force_connector_state(aconnector, DRM_FORCE_OFF);
1613 			msleep(100);
1614 			force_connector_state(aconnector, DRM_FORCE_UNSPECIFIED);
1615 		}
1616 
1617 		test_response.bits.ACK = 1;
1618 
1619 		core_link_write_dpcd(
1620 		dc_link,
1621 		DP_TEST_RESPONSE,
1622 		&test_response.raw,
1623 		sizeof(test_response));
1624 	} else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1625 			dc_link_check_link_loss_status(dc_link, &offload_work->data) &&
1626 			dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1627 		/* offload_work->data is from handle_hpd_rx_irq->
1628 		 * schedule_hpd_rx_offload_work.this is defer handle
1629 		 * for hpd short pulse. upon here, link status may be
1630 		 * changed, need get latest link status from dpcd
1631 		 * registers. if link status is good, skip run link
1632 		 * training again.
1633 		 */
1634 		union hpd_irq_data irq_data;
1635 
1636 		memset(&irq_data, 0, sizeof(irq_data));
1637 
1638 		/* before dc_link_dp_handle_link_loss, allow new link lost handle
1639 		 * request be added to work queue if link lost at end of dc_link_
1640 		 * dp_handle_link_loss
1641 		 */
1642 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1643 		offload_work->offload_wq->is_handling_link_loss = false;
1644 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1645 
1646 		if ((dc_link_dp_read_hpd_rx_irq_data(dc_link, &irq_data) == DC_OK) &&
1647 			dc_link_check_link_loss_status(dc_link, &irq_data))
1648 			dc_link_dp_handle_link_loss(dc_link);
1649 	}
1650 	mutex_unlock(&adev->dm.dc_lock);
1651 
1652 skip:
1653 	kfree(offload_work);
1654 
1655 }
1656 
1657 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct amdgpu_device *adev)
1658 {
1659 	struct dc *dc = adev->dm.dc;
1660 	int max_caps = dc->caps.max_links;
1661 	int i = 0;
1662 	struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1663 
1664 	hpd_rx_offload_wq = kzalloc_objs(*hpd_rx_offload_wq, max_caps);
1665 
1666 	if (!hpd_rx_offload_wq)
1667 		return NULL;
1668 
1669 
1670 	for (i = 0; i < max_caps; i++) {
1671 		hpd_rx_offload_wq[i].wq =
1672 				    create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1673 
1674 		if (hpd_rx_offload_wq[i].wq == NULL) {
1675 			drm_err(adev_to_drm(adev), "create amdgpu_dm_hpd_rx_offload_wq fail!");
1676 			goto out_err;
1677 		}
1678 
1679 		spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
1680 	}
1681 
1682 	return hpd_rx_offload_wq;
1683 
1684 out_err:
1685 	for (i = 0; i < max_caps; i++) {
1686 		if (hpd_rx_offload_wq[i].wq)
1687 			destroy_workqueue(hpd_rx_offload_wq[i].wq);
1688 	}
1689 	kfree(hpd_rx_offload_wq);
1690 	return NULL;
1691 }
1692 
1693 struct amdgpu_stutter_quirk {
1694 	u16 chip_vendor;
1695 	u16 chip_device;
1696 	u16 subsys_vendor;
1697 	u16 subsys_device;
1698 	u8 revision;
1699 };
1700 
1701 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1702 	/* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1703 	{ 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1704 	{ 0, 0, 0, 0, 0 },
1705 };
1706 
1707 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1708 {
1709 	const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1710 
1711 	while (p && p->chip_device != 0) {
1712 		if (pdev->vendor == p->chip_vendor &&
1713 		    pdev->device == p->chip_device &&
1714 		    pdev->subsystem_vendor == p->subsys_vendor &&
1715 		    pdev->subsystem_device == p->subsys_device &&
1716 		    pdev->revision == p->revision) {
1717 			return true;
1718 		}
1719 		++p;
1720 	}
1721 	return false;
1722 }
1723 
1724 
1725 void*
1726 dm_allocate_gpu_mem(
1727 		struct amdgpu_device *adev,
1728 		enum dc_gpu_mem_alloc_type type,
1729 		size_t size,
1730 		long long *addr)
1731 {
1732 	struct dal_allocation *da;
1733 	u32 domain = (type == DC_MEM_ALLOC_TYPE_GART) ?
1734 		AMDGPU_GEM_DOMAIN_GTT : AMDGPU_GEM_DOMAIN_VRAM;
1735 	int ret;
1736 
1737 	da = kzalloc_obj(struct dal_allocation);
1738 	if (!da)
1739 		return NULL;
1740 
1741 	ret = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
1742 				      domain, &da->bo,
1743 				      &da->gpu_addr, &da->cpu_ptr);
1744 
1745 	*addr = da->gpu_addr;
1746 
1747 	if (ret) {
1748 		kfree(da);
1749 		return NULL;
1750 	}
1751 
1752 	/* add da to list in dm */
1753 	list_add(&da->list, &adev->dm.da_list);
1754 
1755 	return da->cpu_ptr;
1756 }
1757 
1758 void
1759 dm_free_gpu_mem(
1760 		struct amdgpu_device *adev,
1761 		enum dc_gpu_mem_alloc_type type,
1762 		void *pvMem)
1763 {
1764 	struct dal_allocation *da;
1765 
1766 	/* walk the da list in DM */
1767 	list_for_each_entry(da, &adev->dm.da_list, list) {
1768 		if (pvMem == da->cpu_ptr) {
1769 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
1770 			list_del(&da->list);
1771 			kfree(da);
1772 			break;
1773 		}
1774 	}
1775 
1776 }
1777 
1778 static enum dmub_status
1779 dm_dmub_send_vbios_gpint_command(struct amdgpu_device *adev,
1780 				 enum dmub_gpint_command command_code,
1781 				 uint16_t param,
1782 				 uint32_t timeout_us)
1783 {
1784 	union dmub_gpint_data_register reg, test;
1785 	uint32_t i;
1786 
1787 	/* Assume that VBIOS DMUB is ready to take commands */
1788 
1789 	reg.bits.status = 1;
1790 	reg.bits.command_code = command_code;
1791 	reg.bits.param = param;
1792 
1793 	cgs_write_register(adev->dm.cgs_device, 0x34c0 + 0x01f8, reg.all);
1794 
1795 	for (i = 0; i < timeout_us; ++i) {
1796 		udelay(1);
1797 
1798 		/* Check if our GPINT got acked */
1799 		reg.bits.status = 0;
1800 		test = (union dmub_gpint_data_register)
1801 			cgs_read_register(adev->dm.cgs_device, 0x34c0 + 0x01f8);
1802 
1803 		if (test.all == reg.all)
1804 			return DMUB_STATUS_OK;
1805 	}
1806 
1807 	return DMUB_STATUS_TIMEOUT;
1808 }
1809 
1810 static void *dm_dmub_get_vbios_bounding_box(struct amdgpu_device *adev)
1811 {
1812 	void *bb;
1813 	long long addr;
1814 	unsigned int bb_size;
1815 	int i = 0;
1816 	uint16_t chunk;
1817 	enum dmub_gpint_command send_addrs[] = {
1818 		DMUB_GPINT__SET_BB_ADDR_WORD0,
1819 		DMUB_GPINT__SET_BB_ADDR_WORD1,
1820 		DMUB_GPINT__SET_BB_ADDR_WORD2,
1821 		DMUB_GPINT__SET_BB_ADDR_WORD3,
1822 	};
1823 	enum dmub_status ret;
1824 
1825 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1826 	case IP_VERSION(4, 0, 1):
1827 		bb_size = sizeof(struct dml2_soc_bb);
1828 		break;
1829 	case IP_VERSION(4, 2, 0):
1830 	case IP_VERSION(4, 2, 1):
1831 		bb_size = sizeof(struct dml2_soc_bb);
1832 		break;
1833 	default:
1834 		return NULL;
1835 	}
1836 
1837 	bb =  dm_allocate_gpu_mem(adev,
1838 				  DC_MEM_ALLOC_TYPE_GART,
1839 				  bb_size,
1840 				  &addr);
1841 	if (!bb)
1842 		return NULL;
1843 
1844 	for (i = 0; i < 4; i++) {
1845 		/* Extract 16-bit chunk */
1846 		chunk = ((uint64_t) addr >> (i * 16)) & 0xFFFF;
1847 		/* Send the chunk */
1848 		ret = dm_dmub_send_vbios_gpint_command(adev, send_addrs[i], chunk, 30000);
1849 		if (ret != DMUB_STATUS_OK)
1850 			goto free_bb;
1851 	}
1852 
1853 	/* Now ask DMUB to copy the bb */
1854 	ret = dm_dmub_send_vbios_gpint_command(adev, DMUB_GPINT__BB_COPY, 1, 200000);
1855 	if (ret != DMUB_STATUS_OK)
1856 		goto free_bb;
1857 
1858 	return bb;
1859 
1860 free_bb:
1861 	dm_free_gpu_mem(adev, DC_MEM_ALLOC_TYPE_GART, (void *) bb);
1862 	return NULL;
1863 
1864 }
1865 
1866 static enum dmub_ips_disable_type dm_get_default_ips_mode(
1867 	struct amdgpu_device *adev)
1868 {
1869 	enum dmub_ips_disable_type ret = DMUB_IPS_ENABLE;
1870 
1871 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1872 	case IP_VERSION(3, 5, 0):
1873 	case IP_VERSION(3, 6, 0):
1874 	case IP_VERSION(3, 5, 1):
1875 		ret =  DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
1876 		break;
1877 	case IP_VERSION(4, 2, 0):
1878 	case IP_VERSION(4, 2, 1):
1879 		ret =  DMUB_IPS_ENABLE;
1880 		break;
1881 	default:
1882 		/* ASICs older than DCN35 do not have IPSs */
1883 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 5, 0))
1884 			ret = DMUB_IPS_DISABLE_ALL;
1885 		break;
1886 	}
1887 
1888 	return ret;
1889 }
1890 
1891 static int amdgpu_dm_init_power_module(struct amdgpu_display_manager *dm)
1892 {
1893 	struct mod_power_init_params init_data[MAX_NUM_EDP];
1894 
1895 	if (dm->num_of_edps == 0) {
1896 		drm_dbg_driver(
1897 			dm->ddev,
1898 			"amdgpu: No eDP detected, skip initializing power module\n");
1899 		return 0;
1900 	}
1901 
1902 	/* Initialize all the power module parameters */
1903 	for (int i = 0; i < dm->num_of_edps; i++) {
1904 		init_data[i].allow_psr_smu_optimizations =
1905 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_SMU_OPT);
1906 		init_data[i].allow_psr_multi_disp_optimizations =
1907 			!!(amdgpu_dc_feature_mask & DC_PSR_ALLOW_MULTI_DISP_OPT);
1908 		/* See dm_late_init */
1909 		init_data[i].backlight_ramping_override = false;
1910 		init_data[i].backlight_ramping_start = 0xCCCC;
1911 		init_data[i].backlight_ramping_reduction = 0xCCCCCCCC;
1912 		init_data[i].def_varibright_level = 0;
1913 		init_data[i].abm_config_setting = 0;
1914 		init_data[i].num_backlight_levels = 101;
1915 		init_data[i].use_nits_based_brightness = false;
1916 		init_data[i].panel_max_millinits = 0;
1917 		init_data[i].panel_min_millinits = 0;
1918 		init_data[i].disable_fractional_pwm =
1919 			!(amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK);
1920 		init_data[i].use_custom_backlight_caps = false;
1921 		init_data[i].custom_backlight_caps_config_no = 0;
1922 		init_data[i].use_linear_backlight_curve = false;
1923 		init_data[i].def_varibright_enable = 0;
1924 		init_data[i].varibright_level = 0;
1925 		/*
1926 		 * Power module uses 16-bit backlight levels (0xFFFF max) rather
1927 		 * than 8-bit(0XFF max)
1928 		 */
1929 		init_data[i].min_backlight_pwm =
1930 			dm->backlight_caps[i].min_input_signal * 0x101;
1931 		init_data[i].max_backlight_pwm =
1932 			dm->backlight_caps[i].max_input_signal * 0x101;
1933 		init_data[i].min_abm_backlight =
1934 			dm->backlight_caps[i].min_input_signal * 0x101;
1935 
1936 		/* Min backlight level after ABM reduction,  Don't allow below 1%
1937 		 * 0xFFFF x 0.01 = 0x28F
1938 		 */
1939 		init_data[i].min_abm_backlight = (init_data[i].min_abm_backlight < 0x28F) ?
1940 			0x28F : init_data[i].min_abm_backlight;
1941 	}
1942 
1943 	dm->power_module = mod_power_create(dm->dc, init_data, dm->num_of_edps);
1944 	if (!dm->power_module) {
1945 		drm_err(dm->ddev, "amdgpu: Error allocating memory for power module\n");
1946 		return -ENOMEM;
1947 	}
1948 
1949 	mod_power_hw_init(dm->power_module);
1950 	drm_dbg_driver(dm->ddev, "amdgpu: Power module init done\n");
1951 
1952 	return 0;
1953 }
1954 
1955 static int amdgpu_dm_init(struct amdgpu_device *adev)
1956 {
1957 	struct dc_init_data init_data;
1958 	struct dc_callback_init init_params;
1959 	int r;
1960 
1961 	adev->dm.ddev = adev_to_drm(adev);
1962 	adev->dm.adev = adev;
1963 
1964 	/* Zero all the fields */
1965 	memset(&init_data, 0, sizeof(init_data));
1966 	memset(&init_params, 0, sizeof(init_params));
1967 
1968 	mutex_init(&adev->dm.dpia_aux_lock);
1969 	mutex_init(&adev->dm.dc_lock);
1970 	mutex_init(&adev->dm.audio_lock);
1971 
1972 	spin_lock_init(&adev->dm.dmub_lock);
1973 
1974 	if (amdgpu_dm_irq_init(adev)) {
1975 		drm_err(adev_to_drm(adev), "failed to initialize DM IRQ support.\n");
1976 		goto error;
1977 	}
1978 
1979 	/* special handling for early revisions of GC 11.5.4 */
1980 	if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(11, 5, 4))
1981 		init_data.asic_id.chip_family = AMDGPU_FAMILY_GC_11_5_4;
1982 	else
1983 		init_data.asic_id.chip_family = adev->family;
1984 
1985 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
1986 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
1987 	init_data.asic_id.chip_id = adev->pdev->device;
1988 
1989 	init_data.asic_id.vram_width = adev->gmc.vram_width;
1990 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
1991 	init_data.asic_id.atombios_base_address =
1992 		adev->mode_info.atom_context->bios;
1993 
1994 	init_data.driver = adev;
1995 
1996 	/* cgs_device was created in dm_sw_init() */
1997 	init_data.cgs_device = adev->dm.cgs_device;
1998 
1999 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
2000 
2001 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2002 	case IP_VERSION(2, 1, 0):
2003 		switch (adev->dm.dmcub_fw_version) {
2004 		case 0: /* development */
2005 		case 0x1: /* linux-firmware.git hash 6d9f399 */
2006 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
2007 			init_data.flags.disable_dmcu = false;
2008 			break;
2009 		default:
2010 			init_data.flags.disable_dmcu = true;
2011 		}
2012 		break;
2013 	case IP_VERSION(2, 0, 3):
2014 		init_data.flags.disable_dmcu = true;
2015 		break;
2016 	default:
2017 		break;
2018 	}
2019 
2020 	/* APU support S/G display by default except:
2021 	 * ASICs before Carrizo,
2022 	 * RAVEN1 (Users reported stability issue)
2023 	 */
2024 
2025 	if (adev->asic_type < CHIP_CARRIZO) {
2026 		init_data.flags.gpu_vm_support = false;
2027 	} else if (adev->asic_type == CHIP_RAVEN) {
2028 		if (adev->apu_flags & AMD_APU_IS_RAVEN)
2029 			init_data.flags.gpu_vm_support = false;
2030 		else
2031 			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
2032 	} else {
2033 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(2, 0, 3))
2034 			init_data.flags.gpu_vm_support = (amdgpu_sg_display == 1);
2035 		else
2036 			init_data.flags.gpu_vm_support =
2037 				(amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
2038 	}
2039 
2040 	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
2041 
2042 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
2043 		init_data.flags.fbc_support = true;
2044 
2045 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
2046 		init_data.flags.multi_mon_pp_mclk_switch = true;
2047 
2048 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
2049 		init_data.flags.disable_fractional_pwm = true;
2050 
2051 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
2052 		init_data.flags.edp_no_power_sequencing = true;
2053 
2054 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
2055 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
2056 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
2057 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
2058 
2059 	init_data.flags.seamless_boot_edp_requested = false;
2060 
2061 	if (amdgpu_device_seamless_boot_supported(adev)) {
2062 		init_data.flags.seamless_boot_edp_requested = true;
2063 		init_data.flags.allow_seamless_boot_optimization = true;
2064 		drm_dbg(adev->dm.ddev, "Seamless boot requested\n");
2065 	}
2066 
2067 	init_data.flags.enable_mipi_converter_optimization = true;
2068 
2069 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
2070 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
2071 	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
2072 
2073 	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
2074 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
2075 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS_DYNAMIC)
2076 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_DYNAMIC;
2077 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS2_DYNAMIC)
2078 		init_data.flags.disable_ips = DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
2079 	else if (amdgpu_dc_debug_mask & DC_FORCE_IPS_ENABLE)
2080 		init_data.flags.disable_ips = DMUB_IPS_ENABLE;
2081 	else
2082 		init_data.flags.disable_ips = dm_get_default_ips_mode(adev);
2083 
2084 	init_data.flags.disable_ips_in_vpb = 0;
2085 
2086 	/* DCN35 and above supports dynamic DTBCLK switch */
2087 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 5, 0))
2088 		init_data.flags.allow_0_dtb_clk = true;
2089 
2090 	/* Enable DWB for tested platforms only */
2091 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
2092 		init_data.num_virtual_links = 1;
2093 
2094 	/* DCN42 and above dpia switch to unified link training path */
2095 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 2, 0)) {
2096 		init_data.flags.consolidated_dpia_dp_lt = true;
2097 		init_data.flags.enable_dpia_pre_training = true;
2098 		init_data.flags.unify_link_enc_assignment = true;
2099 		init_data.flags.usb4_bw_alloc_support = true;
2100 	}
2101 	retrieve_dmi_info(&adev->dm);
2102 	if (adev->dm.edp0_on_dp1_quirk)
2103 		init_data.flags.support_edp0_on_dp1 = true;
2104 
2105 	if (adev->dm.bb_from_dmub)
2106 		init_data.bb_from_dmub = adev->dm.bb_from_dmub;
2107 	else
2108 		init_data.bb_from_dmub = NULL;
2109 
2110 	/* Display Core create. */
2111 	adev->dm.dc = dc_create(&init_data);
2112 
2113 	if (adev->dm.dc) {
2114 		drm_info(adev_to_drm(adev), "Display Core v%s initialized on %s\n", DC_VER,
2115 			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
2116 	} else {
2117 		drm_info(adev_to_drm(adev), "Display Core failed to initialize with v%s!\n", DC_VER);
2118 		goto error;
2119 	}
2120 
2121 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
2122 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
2123 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
2124 	}
2125 
2126 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2127 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2128 	if (dm_should_disable_stutter(adev->pdev))
2129 		adev->dm.dc->debug.disable_stutter = true;
2130 
2131 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
2132 		adev->dm.dc->debug.disable_stutter = true;
2133 
2134 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
2135 		adev->dm.dc->debug.disable_dsc = true;
2136 
2137 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
2138 		adev->dm.dc->debug.disable_clock_gate = true;
2139 
2140 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
2141 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
2142 
2143 	if (amdgpu_dc_debug_mask & DC_DISABLE_SUBVP_FAMS) {
2144 		adev->dm.dc->debug.force_disable_subvp = true;
2145 		adev->dm.dc->debug.fams2_config.bits.enable = false;
2146 	}
2147 
2148 	if (amdgpu_dc_debug_mask & DC_ENABLE_DML2) {
2149 		adev->dm.dc->debug.using_dml2 = true;
2150 		adev->dm.dc->debug.using_dml21 = true;
2151 	}
2152 
2153 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_FORCE_FW_ENABLE)
2154 		adev->dm.dc->debug.hdcp_lc_force_fw_enable = true;
2155 
2156 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_ENABLE_SW_FALLBACK)
2157 		adev->dm.dc->debug.hdcp_lc_enable_sw_fallback = true;
2158 
2159 	if (amdgpu_dc_debug_mask & DC_SKIP_DETECTION_LT)
2160 		adev->dm.dc->debug.skip_detection_link_training = true;
2161 
2162 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
2163 
2164 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
2165 	adev->dm.dc->debug.ignore_cable_id = true;
2166 
2167 	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
2168 		drm_info(adev_to_drm(adev), "DP-HDMI FRL PCON supported\n");
2169 
2170 	r = dm_dmub_hw_init(adev);
2171 	if (r) {
2172 		drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
2173 		goto error;
2174 	}
2175 
2176 	dc_hardware_init(adev->dm.dc);
2177 
2178 	adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev);
2179 	if (!adev->dm.hpd_rx_offload_wq) {
2180 		drm_err(adev_to_drm(adev), "failed to create hpd rx offload workqueue.\n");
2181 		goto error;
2182 	}
2183 
2184 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
2185 		struct dc_phy_addr_space_config pa_config;
2186 
2187 		mmhub_read_system_context(adev, &pa_config);
2188 
2189 		// Call the DC init_memory func
2190 		dc_setup_system_context(adev->dm.dc, &pa_config);
2191 	}
2192 
2193 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
2194 	if (!adev->dm.freesync_module) {
2195 		drm_err(adev_to_drm(adev),
2196 		"failed to initialize freesync_module.\n");
2197 	} else
2198 		drm_dbg_driver(adev_to_drm(adev), "freesync_module init done %p.\n",
2199 				adev->dm.freesync_module);
2200 
2201 	amdgpu_dm_init_color_mod();
2202 
2203 	if (adev->dm.dc->caps.max_links > 0) {
2204 		adev->dm.vblank_control_workqueue =
2205 			create_singlethread_workqueue("dm_vblank_control_workqueue");
2206 		if (!adev->dm.vblank_control_workqueue)
2207 			drm_err(adev_to_drm(adev), "failed to initialize vblank_workqueue.\n");
2208 	}
2209 
2210 	if (adev->dm.dc->caps.ips_support &&
2211 	    adev->dm.dc->config.disable_ips != DMUB_IPS_DISABLE_ALL)
2212 		adev->dm.idle_workqueue = idle_create_workqueue(adev);
2213 
2214 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
2215 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
2216 
2217 		if (!adev->dm.hdcp_workqueue)
2218 			drm_err(adev_to_drm(adev), "failed to initialize hdcp_workqueue.\n");
2219 		else
2220 			drm_dbg_driver(adev_to_drm(adev),
2221 				       "hdcp_workqueue init done %p.\n",
2222 				       adev->dm.hdcp_workqueue);
2223 
2224 		dc_init_callbacks(adev->dm.dc, &init_params);
2225 	}
2226 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2227 		init_completion(&adev->dm.dmub_aux_transfer_done);
2228 		adev->dm.dmub_notify = kzalloc_obj(struct dmub_notification);
2229 		if (!adev->dm.dmub_notify) {
2230 			drm_info(adev_to_drm(adev), "fail to allocate adev->dm.dmub_notify");
2231 			goto error;
2232 		}
2233 
2234 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
2235 		if (!adev->dm.delayed_hpd_wq) {
2236 			drm_err(adev_to_drm(adev), "failed to create hpd offload workqueue.\n");
2237 			goto error;
2238 		}
2239 
2240 		amdgpu_dm_outbox_init(adev);
2241 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
2242 			dmub_aux_setconfig_callback, false)) {
2243 			drm_err(adev_to_drm(adev), "fail to register dmub aux callback");
2244 			goto error;
2245 		}
2246 
2247 		for (size_t i = 0; i < ARRAY_SIZE(adev->dm.fused_io); i++)
2248 			init_completion(&adev->dm.fused_io[i].replied);
2249 
2250 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_FUSED_IO,
2251 			dmub_aux_fused_io_callback, false)) {
2252 			drm_err(adev_to_drm(adev), "fail to register dmub fused io callback");
2253 			goto error;
2254 		}
2255 		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
2256 		 * It is expected that DMUB will resend any pending notifications at this point. Note
2257 		 * that hpd and hpd_irq handler registration are deferred to register_hpd_handlers() to
2258 		 * align legacy interface initialization sequence. Connection status will be proactivly
2259 		 * detected once in the amdgpu_dm_initialize_drm_device.
2260 		 */
2261 		dc_enable_dmub_outbox(adev->dm.dc);
2262 
2263 		/* DPIA trace goes to dmesg logs only if outbox is enabled */
2264 		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
2265 			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
2266 	}
2267 
2268 	if (amdgpu_dm_initialize_drm_device(adev)) {
2269 		drm_err(adev_to_drm(adev),
2270 		"failed to initialize sw for display support.\n");
2271 		goto error;
2272 	}
2273 
2274 	if (amdgpu_dm_init_power_module(&adev->dm))
2275 		goto error;
2276 
2277 	/* create fake encoders for MST */
2278 	dm_dp_create_fake_mst_encoders(adev);
2279 
2280 	/* TODO: Add_display_info? */
2281 
2282 	/* TODO use dynamic cursor width */
2283 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
2284 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
2285 
2286 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
2287 		drm_err(adev_to_drm(adev),
2288 		"failed to initialize vblank for display support.\n");
2289 		goto error;
2290 	}
2291 
2292 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2293 	amdgpu_dm_crtc_secure_display_create_contexts(adev);
2294 	if (!adev->dm.secure_display_ctx.crtc_ctx)
2295 		drm_err(adev_to_drm(adev), "failed to initialize secure display contexts.\n");
2296 
2297 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))
2298 		adev->dm.secure_display_ctx.support_mul_roi = true;
2299 
2300 #endif
2301 
2302 	drm_dbg_driver(adev_to_drm(adev), "KMS initialized.\n");
2303 
2304 	return 0;
2305 error:
2306 	amdgpu_dm_fini(adev);
2307 
2308 	return -EINVAL;
2309 }
2310 
2311 static int amdgpu_dm_early_fini(struct amdgpu_ip_block *ip_block)
2312 {
2313 	struct amdgpu_device *adev = ip_block->adev;
2314 
2315 	amdgpu_dm_audio_fini(adev);
2316 
2317 	return 0;
2318 }
2319 
2320 static void amdgpu_dm_fini(struct amdgpu_device *adev)
2321 {
2322 	int i;
2323 
2324 	if (adev->dm.vblank_control_workqueue) {
2325 		destroy_workqueue(adev->dm.vblank_control_workqueue);
2326 		adev->dm.vblank_control_workqueue = NULL;
2327 	}
2328 
2329 	if (adev->dm.idle_workqueue) {
2330 		if (adev->dm.idle_workqueue->running) {
2331 			adev->dm.idle_workqueue->enable = false;
2332 			flush_work(&adev->dm.idle_workqueue->work);
2333 		}
2334 
2335 		kfree(adev->dm.idle_workqueue);
2336 		adev->dm.idle_workqueue = NULL;
2337 	}
2338 
2339 	/*
2340 	 * Disable ISM before dc_destroy() invalidates dm->dc.
2341 	 *
2342 	 * Quiesce workers first without dc_lock (they take dc_lock
2343 	 * themselves, so syncing under it would deadlock), then drive the
2344 	 * FSM back to FULL_POWER_RUNNING under dc_lock.
2345 	 */
2346 	amdgpu_dm_ism_disable(&adev->dm);
2347 	scoped_guard(mutex, &adev->dm.dc_lock)
2348 		amdgpu_dm_ism_force_full_power(&adev->dm);
2349 
2350 	amdgpu_dm_destroy_drm_device(&adev->dm);
2351 
2352 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2353 	if (adev->dm.secure_display_ctx.crtc_ctx) {
2354 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
2355 			if (adev->dm.secure_display_ctx.crtc_ctx[i].crtc) {
2356 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].notify_ta_work);
2357 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].forward_roi_work);
2358 			}
2359 		}
2360 		kfree(adev->dm.secure_display_ctx.crtc_ctx);
2361 		adev->dm.secure_display_ctx.crtc_ctx = NULL;
2362 	}
2363 #endif
2364 	if (adev->dm.hdcp_workqueue) {
2365 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
2366 		adev->dm.hdcp_workqueue = NULL;
2367 	}
2368 
2369 	if (adev->dm.dc) {
2370 		dc_deinit_callbacks(adev->dm.dc);
2371 		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
2372 		if (dc_enable_dmub_notifications(adev->dm.dc)) {
2373 			kfree(adev->dm.dmub_notify);
2374 			adev->dm.dmub_notify = NULL;
2375 			destroy_workqueue(adev->dm.delayed_hpd_wq);
2376 			adev->dm.delayed_hpd_wq = NULL;
2377 		}
2378 	}
2379 
2380 	if (adev->dm.dmub_bo)
2381 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
2382 				      &adev->dm.dmub_bo_gpu_addr,
2383 				      &adev->dm.dmub_bo_cpu_addr);
2384 
2385 	if (adev->dm.boot_time_crc_info.bo_ptr)
2386 		amdgpu_bo_free_kernel(&adev->dm.boot_time_crc_info.bo_ptr,
2387 					&adev->dm.boot_time_crc_info.gpu_addr,
2388 					&adev->dm.boot_time_crc_info.cpu_addr);
2389 
2390 	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
2391 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
2392 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
2393 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
2394 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
2395 			}
2396 		}
2397 
2398 		kfree(adev->dm.hpd_rx_offload_wq);
2399 		adev->dm.hpd_rx_offload_wq = NULL;
2400 	}
2401 
2402 	/* DC Destroy TODO: Replace destroy DAL */
2403 	if (adev->dm.dc)
2404 		dc_destroy(&adev->dm.dc);
2405 	/*
2406 	 * TODO: pageflip, vlank interrupt
2407 	 *
2408 	 * amdgpu_dm_irq_fini(adev);
2409 	 */
2410 
2411 	if (adev->dm.cgs_device) {
2412 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
2413 		adev->dm.cgs_device = NULL;
2414 	}
2415 	if (adev->dm.freesync_module) {
2416 		mod_freesync_destroy(adev->dm.freesync_module);
2417 		adev->dm.freesync_module = NULL;
2418 	}
2419 
2420 	if (adev->dm.power_module) {
2421 		mod_power_destroy(adev->dm.power_module);
2422 		adev->dm.power_module = NULL;
2423 	}
2424 	mutex_destroy(&adev->dm.audio_lock);
2425 	mutex_destroy(&adev->dm.dc_lock);
2426 	mutex_destroy(&adev->dm.dpia_aux_lock);
2427 }
2428 
2429 static int load_dmcu_fw(struct amdgpu_device *adev)
2430 {
2431 	const char *fw_name_dmcu = NULL;
2432 	int r;
2433 	const struct dmcu_firmware_header_v1_0 *hdr;
2434 
2435 	switch (adev->asic_type) {
2436 #if defined(CONFIG_DRM_AMD_DC_SI)
2437 	case CHIP_TAHITI:
2438 	case CHIP_PITCAIRN:
2439 	case CHIP_VERDE:
2440 	case CHIP_OLAND:
2441 #endif
2442 	case CHIP_BONAIRE:
2443 	case CHIP_HAWAII:
2444 	case CHIP_KAVERI:
2445 	case CHIP_KABINI:
2446 	case CHIP_MULLINS:
2447 	case CHIP_TONGA:
2448 	case CHIP_FIJI:
2449 	case CHIP_CARRIZO:
2450 	case CHIP_STONEY:
2451 	case CHIP_POLARIS11:
2452 	case CHIP_POLARIS10:
2453 	case CHIP_POLARIS12:
2454 	case CHIP_VEGAM:
2455 	case CHIP_VEGA10:
2456 	case CHIP_VEGA12:
2457 	case CHIP_VEGA20:
2458 		return 0;
2459 	case CHIP_NAVI12:
2460 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
2461 		break;
2462 	case CHIP_RAVEN:
2463 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
2464 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2465 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
2466 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2467 		else
2468 			return 0;
2469 		break;
2470 	default:
2471 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2472 		case IP_VERSION(2, 0, 2):
2473 		case IP_VERSION(2, 0, 3):
2474 		case IP_VERSION(2, 0, 0):
2475 		case IP_VERSION(2, 1, 0):
2476 		case IP_VERSION(3, 0, 0):
2477 		case IP_VERSION(3, 0, 2):
2478 		case IP_VERSION(3, 0, 3):
2479 		case IP_VERSION(3, 0, 1):
2480 		case IP_VERSION(3, 1, 2):
2481 		case IP_VERSION(3, 1, 3):
2482 		case IP_VERSION(3, 1, 4):
2483 		case IP_VERSION(3, 1, 5):
2484 		case IP_VERSION(3, 1, 6):
2485 		case IP_VERSION(3, 2, 0):
2486 		case IP_VERSION(3, 2, 1):
2487 		case IP_VERSION(3, 5, 0):
2488 		case IP_VERSION(3, 5, 1):
2489 		case IP_VERSION(3, 6, 0):
2490 		case IP_VERSION(4, 0, 1):
2491 		case IP_VERSION(4, 2, 0):
2492 		case IP_VERSION(4, 2, 1):
2493 			return 0;
2494 		default:
2495 			break;
2496 		}
2497 		drm_err(adev_to_drm(adev), "Unsupported ASIC type: 0x%X\n", adev->asic_type);
2498 		return -EINVAL;
2499 	}
2500 
2501 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
2502 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not supported on direct or SMU loading\n");
2503 		return 0;
2504 	}
2505 
2506 	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, AMDGPU_UCODE_REQUIRED,
2507 				 "%s", fw_name_dmcu);
2508 	if (r == -ENODEV) {
2509 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
2510 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not found\n");
2511 		adev->dm.fw_dmcu = NULL;
2512 		return 0;
2513 	}
2514 	if (r) {
2515 		drm_err(adev_to_drm(adev), "amdgpu_dm: Can't validate firmware \"%s\"\n",
2516 			fw_name_dmcu);
2517 		amdgpu_ucode_release(&adev->dm.fw_dmcu);
2518 		return r;
2519 	}
2520 
2521 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
2522 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
2523 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
2524 	adev->firmware.fw_size +=
2525 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2526 
2527 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
2528 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
2529 	adev->firmware.fw_size +=
2530 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2531 
2532 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
2533 
2534 	drm_dbg_kms(adev_to_drm(adev), "PSP loading DMCU firmware\n");
2535 
2536 	return 0;
2537 }
2538 
2539 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
2540 {
2541 	struct amdgpu_device *adev = ctx;
2542 
2543 	return dm_read_reg(adev->dm.dc->ctx, address);
2544 }
2545 
2546 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
2547 				     uint32_t value)
2548 {
2549 	struct amdgpu_device *adev = ctx;
2550 
2551 	return dm_write_reg(adev->dm.dc->ctx, address, value);
2552 }
2553 
2554 static int dm_dmub_sw_init(struct amdgpu_device *adev)
2555 {
2556 	struct dmub_srv_create_params create_params;
2557 	struct dmub_srv_fw_meta_info_params fw_meta_info_params;
2558 	struct dmub_srv_region_params region_params;
2559 	struct dmub_srv_region_info region_info;
2560 	struct dmub_srv_memory_params memory_params;
2561 	struct dmub_fw_meta_info fw_info;
2562 	struct dmub_srv_fb_info *fb_info;
2563 	struct dmub_srv *dmub_srv;
2564 	const struct dmcub_firmware_header_v1_0 *hdr;
2565 	enum dmub_asic dmub_asic;
2566 	enum dmub_status status;
2567 	static enum dmub_window_memory_type window_memory_type[DMUB_WINDOW_TOTAL] = {
2568 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_0_INST_CONST
2569 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_1_STACK
2570 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_2_BSS_DATA
2571 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_3_VBIOS
2572 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_4_MAILBOX
2573 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_5_TRACEBUFF
2574 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_6_FW_STATE
2575 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_7_SCRATCH_MEM
2576 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_IB_MEM
2577 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_SHARED_STATE
2578 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_LSDMA_BUFFER
2579 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_CURSOR_OFFLOAD
2580 	};
2581 	int r;
2582 
2583 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2584 	case IP_VERSION(2, 1, 0):
2585 		dmub_asic = DMUB_ASIC_DCN21;
2586 		break;
2587 	case IP_VERSION(3, 0, 0):
2588 		dmub_asic = DMUB_ASIC_DCN30;
2589 		break;
2590 	case IP_VERSION(3, 0, 1):
2591 		dmub_asic = DMUB_ASIC_DCN301;
2592 		break;
2593 	case IP_VERSION(3, 0, 2):
2594 		dmub_asic = DMUB_ASIC_DCN302;
2595 		break;
2596 	case IP_VERSION(3, 0, 3):
2597 		dmub_asic = DMUB_ASIC_DCN303;
2598 		break;
2599 	case IP_VERSION(3, 1, 2):
2600 	case IP_VERSION(3, 1, 3):
2601 		dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
2602 		break;
2603 	case IP_VERSION(3, 1, 4):
2604 		dmub_asic = DMUB_ASIC_DCN314;
2605 		break;
2606 	case IP_VERSION(3, 1, 5):
2607 		dmub_asic = DMUB_ASIC_DCN315;
2608 		break;
2609 	case IP_VERSION(3, 1, 6):
2610 		dmub_asic = DMUB_ASIC_DCN316;
2611 		break;
2612 	case IP_VERSION(3, 2, 0):
2613 		dmub_asic = DMUB_ASIC_DCN32;
2614 		break;
2615 	case IP_VERSION(3, 2, 1):
2616 		dmub_asic = DMUB_ASIC_DCN321;
2617 		break;
2618 	case IP_VERSION(3, 5, 0):
2619 	case IP_VERSION(3, 5, 1):
2620 		dmub_asic = DMUB_ASIC_DCN35;
2621 		break;
2622 	case IP_VERSION(3, 6, 0):
2623 		dmub_asic = DMUB_ASIC_DCN36;
2624 		break;
2625 	case IP_VERSION(4, 0, 1):
2626 		dmub_asic = DMUB_ASIC_DCN401;
2627 		break;
2628 	case IP_VERSION(4, 2, 0):
2629 		dmub_asic = DMUB_ASIC_DCN42;
2630 		break;
2631 	case IP_VERSION(4, 2, 1):
2632 		dmub_asic = DMUB_ASIC_DCN42B;
2633 		break;
2634 	default:
2635 		/* ASIC doesn't support DMUB. */
2636 		return 0;
2637 	}
2638 
2639 	hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
2640 	adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
2641 
2642 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
2643 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
2644 			AMDGPU_UCODE_ID_DMCUB;
2645 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
2646 			adev->dm.dmub_fw;
2647 		adev->firmware.fw_size +=
2648 			ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
2649 
2650 		drm_info(adev_to_drm(adev), "Loading DMUB firmware via PSP: version=0x%08X\n",
2651 			 adev->dm.dmcub_fw_version);
2652 	}
2653 
2654 
2655 	adev->dm.dmub_srv = kzalloc_obj(*adev->dm.dmub_srv);
2656 	dmub_srv = adev->dm.dmub_srv;
2657 
2658 	if (!dmub_srv) {
2659 		drm_err(adev_to_drm(adev), "Failed to allocate DMUB service!\n");
2660 		return -ENOMEM;
2661 	}
2662 
2663 	memset(&create_params, 0, sizeof(create_params));
2664 	create_params.user_ctx = adev;
2665 	create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2666 	create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2667 	create_params.asic = dmub_asic;
2668 
2669 	/* Create the DMUB service. */
2670 	status = dmub_srv_create(dmub_srv, &create_params);
2671 	if (status != DMUB_STATUS_OK) {
2672 		drm_err(adev_to_drm(adev), "Error creating DMUB service: %d\n", status);
2673 		return -EINVAL;
2674 	}
2675 
2676 	/* Extract the FW meta info. */
2677 	memset(&fw_meta_info_params, 0, sizeof(fw_meta_info_params));
2678 
2679 	fw_meta_info_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2680 					      PSP_HEADER_BYTES_256;
2681 	fw_meta_info_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2682 	fw_meta_info_params.fw_inst_const = adev->dm.dmub_fw->data +
2683 					    le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2684 					    PSP_HEADER_BYTES_256;
2685 	fw_meta_info_params.fw_bss_data = fw_meta_info_params.bss_data_size ? adev->dm.dmub_fw->data +
2686 					  le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2687 					  le32_to_cpu(hdr->inst_const_bytes) : NULL;
2688 	fw_meta_info_params.custom_psp_footer_size = 0;
2689 
2690 	status = dmub_srv_get_fw_meta_info_from_raw_fw(&fw_meta_info_params, &fw_info);
2691 	if (status != DMUB_STATUS_OK) {
2692 		/* Skip returning early, just log the error. */
2693 		drm_err(adev_to_drm(adev), "Error getting DMUB FW meta info: %d\n", status);
2694 		// return -EINVAL;
2695 	}
2696 
2697 	/* Calculate the size of all the regions for the DMUB service. */
2698 	memset(&region_params, 0, sizeof(region_params));
2699 
2700 	region_params.inst_const_size = fw_meta_info_params.inst_const_size;
2701 	region_params.bss_data_size = fw_meta_info_params.bss_data_size;
2702 	region_params.vbios_size = adev->bios_size;
2703 	region_params.fw_bss_data = fw_meta_info_params.fw_bss_data;
2704 	region_params.fw_inst_const = fw_meta_info_params.fw_inst_const;
2705 	region_params.window_memory_type = window_memory_type;
2706 	region_params.fw_info = (status == DMUB_STATUS_OK) ? &fw_info : NULL;
2707 
2708 	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2709 					   &region_info);
2710 
2711 	if (status != DMUB_STATUS_OK) {
2712 		drm_err(adev_to_drm(adev), "Error calculating DMUB region info: %d\n", status);
2713 		return -EINVAL;
2714 	}
2715 
2716 	/*
2717 	 * Allocate a framebuffer based on the total size of all the regions.
2718 	 * TODO: Move this into GART.
2719 	 */
2720 	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2721 				    AMDGPU_GEM_DOMAIN_VRAM |
2722 				    AMDGPU_GEM_DOMAIN_GTT,
2723 				    &adev->dm.dmub_bo,
2724 				    &adev->dm.dmub_bo_gpu_addr,
2725 				    &adev->dm.dmub_bo_cpu_addr);
2726 	if (r)
2727 		return r;
2728 
2729 	/* Rebase the regions on the framebuffer address. */
2730 	memset(&memory_params, 0, sizeof(memory_params));
2731 	memory_params.cpu_fb_addr = adev->dm.dmub_bo_cpu_addr;
2732 	memory_params.gpu_fb_addr = adev->dm.dmub_bo_gpu_addr;
2733 	memory_params.region_info = &region_info;
2734 	memory_params.window_memory_type = window_memory_type;
2735 
2736 	adev->dm.dmub_fb_info = kzalloc_obj(*adev->dm.dmub_fb_info);
2737 	fb_info = adev->dm.dmub_fb_info;
2738 
2739 	if (!fb_info) {
2740 		drm_err(adev_to_drm(adev),
2741 			"Failed to allocate framebuffer info for DMUB service!\n");
2742 		return -ENOMEM;
2743 	}
2744 
2745 	status = dmub_srv_calc_mem_info(dmub_srv, &memory_params, fb_info);
2746 	if (status != DMUB_STATUS_OK) {
2747 		drm_err(adev_to_drm(adev), "Error calculating DMUB FB info: %d\n", status);
2748 		return -EINVAL;
2749 	}
2750 
2751 	adev->dm.bb_from_dmub = dm_dmub_get_vbios_bounding_box(adev);
2752 	adev->dm.fw_inst_size = fw_meta_info_params.inst_const_size;
2753 
2754 	return 0;
2755 }
2756 
2757 static int dm_sw_init(struct amdgpu_ip_block *ip_block)
2758 {
2759 	struct amdgpu_device *adev = ip_block->adev;
2760 	int r;
2761 
2762 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
2763 
2764 	if (!adev->dm.cgs_device) {
2765 		drm_err(adev_to_drm(adev), "failed to create cgs device.\n");
2766 		return -EINVAL;
2767 	}
2768 
2769 	/* Moved from dm init since we need to use allocations for storing bounding box data */
2770 	INIT_LIST_HEAD(&adev->dm.da_list);
2771 
2772 	r = dm_dmub_sw_init(adev);
2773 	if (r)
2774 		return r;
2775 
2776 	return load_dmcu_fw(adev);
2777 }
2778 
2779 static int dm_sw_fini(struct amdgpu_ip_block *ip_block)
2780 {
2781 	struct amdgpu_device *adev = ip_block->adev;
2782 	struct dal_allocation *da;
2783 
2784 	list_for_each_entry(da, &adev->dm.da_list, list) {
2785 		if (adev->dm.bb_from_dmub == (void *) da->cpu_ptr) {
2786 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
2787 			list_del(&da->list);
2788 			kfree(da);
2789 			adev->dm.bb_from_dmub = NULL;
2790 			break;
2791 		}
2792 	}
2793 
2794 
2795 	kfree(adev->dm.dmub_fb_info);
2796 	adev->dm.dmub_fb_info = NULL;
2797 
2798 	if (adev->dm.dmub_srv) {
2799 		dmub_srv_destroy(adev->dm.dmub_srv);
2800 		kfree(adev->dm.dmub_srv);
2801 		adev->dm.dmub_srv = NULL;
2802 	}
2803 
2804 	amdgpu_ucode_release(&adev->dm.dmub_fw);
2805 	amdgpu_ucode_release(&adev->dm.fw_dmcu);
2806 
2807 	return 0;
2808 }
2809 
2810 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2811 {
2812 	struct amdgpu_dm_connector *aconnector;
2813 	struct drm_connector *connector;
2814 	struct drm_connector_list_iter iter;
2815 	int ret = 0;
2816 
2817 	drm_connector_list_iter_begin(dev, &iter);
2818 	drm_for_each_connector_iter(connector, &iter) {
2819 
2820 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2821 			continue;
2822 
2823 		aconnector = to_amdgpu_dm_connector(connector);
2824 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
2825 		    aconnector->mst_mgr.aux) {
2826 			drm_dbg_kms(dev, "DM_MST: starting TM on aconnector: %p [id: %d]\n",
2827 					 aconnector,
2828 					 aconnector->base.base.id);
2829 
2830 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2831 			if (ret < 0) {
2832 				drm_err(dev, "DM_MST: Failed to start MST\n");
2833 				aconnector->dc_link->type =
2834 					dc_connection_single;
2835 				ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2836 								     aconnector->dc_link);
2837 				break;
2838 			}
2839 		}
2840 	}
2841 	drm_connector_list_iter_end(&iter);
2842 
2843 	return ret;
2844 }
2845 
2846 static void amdgpu_dm_boot_time_crc_init(struct amdgpu_device *adev)
2847 {
2848 	struct dm_boot_time_crc_info *bootcrc_info = NULL;
2849 	struct dmub_srv *dmub = NULL;
2850 	union dmub_fw_boot_options option = {0};
2851 	int ret = 0;
2852 	const uint32_t fb_size = 3 * 1024 * 1024;	/* 3MB for DCC pattern */
2853 
2854 	if (!adev || !adev->dm.dc || !adev->dm.dc->ctx ||
2855 		!adev->dm.dc->ctx->dmub_srv) {
2856 		return;
2857 	}
2858 
2859 	dmub = adev->dm.dc->ctx->dmub_srv->dmub;
2860 	bootcrc_info = &adev->dm.boot_time_crc_info;
2861 
2862 	if (!dmub || !dmub->hw_funcs.get_fw_boot_option) {
2863 		drm_dbg(adev_to_drm(adev), "failed to init boot time crc buffer\n");
2864 		return;
2865 	}
2866 
2867 	option = dmub->hw_funcs.get_fw_boot_option(dmub);
2868 
2869 	/* Return if boot time CRC is not enabled */
2870 	if (option.bits.bootcrc_en_at_S0i3 == 0)
2871 		return;
2872 
2873 	/* Create a buffer for boot time CRC */
2874 	ret = amdgpu_bo_create_kernel(adev, fb_size, PAGE_SIZE,
2875 		AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT,
2876 		&bootcrc_info->bo_ptr,
2877 		&bootcrc_info->gpu_addr,
2878 		&bootcrc_info->cpu_addr);
2879 
2880 	if (ret) {
2881 		drm_dbg(adev_to_drm(adev), "failed to create boot time crc buffer\n");
2882 	} else {
2883 		bootcrc_info->size = fb_size;
2884 
2885 		drm_dbg(adev_to_drm(adev), "boot time crc buffer created addr 0x%llx, size %u\n",
2886 			bootcrc_info->gpu_addr, bootcrc_info->size);
2887 
2888 		/* Send the buffer info to DMUB */
2889 		dc_dmub_srv_boot_time_crc_init(adev->dm.dc,
2890 			bootcrc_info->gpu_addr, bootcrc_info->size);
2891 	}
2892 }
2893 
2894 static int dm_late_init(struct amdgpu_ip_block *ip_block)
2895 {
2896 	struct amdgpu_device *adev = ip_block->adev;
2897 
2898 	struct dmcu_iram_parameters params;
2899 	unsigned int linear_lut[16];
2900 	int i;
2901 	struct dmcu *dmcu = NULL;
2902 
2903 	dmcu = adev->dm.dc->res_pool->dmcu;
2904 
2905 	/* Init the boot time CRC (skip in resume) */
2906 	if ((adev->in_suspend == 0) &&
2907 		(amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(3, 6, 0)))
2908 		amdgpu_dm_boot_time_crc_init(adev);
2909 
2910 	for (i = 0; i < 16; i++)
2911 		linear_lut[i] = 0xFFFF * i / 15;
2912 
2913 	params.set = 0;
2914 	params.backlight_ramping_override = false;
2915 	params.backlight_ramping_start = 0xCCCC;
2916 	params.backlight_ramping_reduction = 0xCCCCCCCC;
2917 	params.backlight_lut_array_size = 16;
2918 	params.backlight_lut_array = linear_lut;
2919 
2920 	/* Min backlight level after ABM reduction,  Don't allow below 1%
2921 	 * 0xFFFF x 0.01 = 0x28F
2922 	 */
2923 	params.min_abm_backlight = 0x28F;
2924 	/* In the case where abm is implemented on dmcub,
2925 	 * dmcu object will be null.
2926 	 * ABM 2.4 and up are implemented on dmcub.
2927 	 */
2928 	if (dmcu) {
2929 		if (!dmcu_load_iram(dmcu, params))
2930 			return -EINVAL;
2931 	} else if (adev->dm.dc->ctx->dmub_srv) {
2932 		struct dc_link *edp_links[MAX_NUM_EDP];
2933 		int edp_num;
2934 
2935 		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
2936 		for (i = 0; i < edp_num; i++) {
2937 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
2938 				return -EINVAL;
2939 		}
2940 	}
2941 
2942 	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
2943 }
2944 
2945 static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
2946 {
2947 	u8 buf[UUID_SIZE];
2948 	guid_t guid;
2949 	int ret;
2950 
2951 	mutex_lock(&mgr->lock);
2952 	if (!mgr->mst_primary)
2953 		goto out_fail;
2954 
2955 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
2956 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2957 		goto out_fail;
2958 	}
2959 
2960 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
2961 				 DP_MST_EN |
2962 				 DP_UP_REQ_EN |
2963 				 DP_UPSTREAM_IS_SRC);
2964 	if (ret < 0) {
2965 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
2966 		goto out_fail;
2967 	}
2968 
2969 	/* Some hubs forget their guids after they resume */
2970 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, buf, sizeof(buf));
2971 	if (ret != sizeof(buf)) {
2972 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2973 		goto out_fail;
2974 	}
2975 
2976 	import_guid(&guid, buf);
2977 
2978 	if (guid_is_null(&guid)) {
2979 		guid_gen(&guid);
2980 		export_guid(buf, &guid);
2981 
2982 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, buf, sizeof(buf));
2983 
2984 		if (ret != sizeof(buf)) {
2985 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
2986 			goto out_fail;
2987 		}
2988 	}
2989 
2990 	guid_copy(&mgr->mst_primary->guid, &guid);
2991 
2992 out_fail:
2993 	mutex_unlock(&mgr->lock);
2994 }
2995 
2996 void hdmi_cec_unset_edid(struct amdgpu_dm_connector *aconnector)
2997 {
2998 	struct cec_notifier *n = aconnector->notifier;
2999 
3000 	if (!n)
3001 		return;
3002 
3003 	cec_notifier_phys_addr_invalidate(n);
3004 }
3005 
3006 void hdmi_cec_set_edid(struct amdgpu_dm_connector *aconnector)
3007 {
3008 	struct drm_connector *connector = &aconnector->base;
3009 	struct cec_notifier *n = aconnector->notifier;
3010 
3011 	if (!n)
3012 		return;
3013 
3014 	cec_notifier_set_phys_addr(n,
3015 				   connector->display_info.source_physical_address);
3016 }
3017 
3018 static void s3_handle_hdmi_cec(struct drm_device *ddev, bool suspend)
3019 {
3020 	struct amdgpu_dm_connector *aconnector;
3021 	struct drm_connector *connector;
3022 	struct drm_connector_list_iter conn_iter;
3023 
3024 	drm_connector_list_iter_begin(ddev, &conn_iter);
3025 	drm_for_each_connector_iter(connector, &conn_iter) {
3026 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3027 			continue;
3028 
3029 		aconnector = to_amdgpu_dm_connector(connector);
3030 		if (suspend)
3031 			hdmi_cec_unset_edid(aconnector);
3032 		else
3033 			hdmi_cec_set_edid(aconnector);
3034 	}
3035 	drm_connector_list_iter_end(&conn_iter);
3036 }
3037 
3038 static void s3_handle_mst(struct drm_device *dev, bool suspend)
3039 {
3040 	struct amdgpu_dm_connector *aconnector;
3041 	struct drm_connector *connector;
3042 	struct drm_connector_list_iter iter;
3043 	struct drm_dp_mst_topology_mgr *mgr;
3044 
3045 	drm_connector_list_iter_begin(dev, &iter);
3046 	drm_for_each_connector_iter(connector, &iter) {
3047 
3048 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3049 			continue;
3050 
3051 		aconnector = to_amdgpu_dm_connector(connector);
3052 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3053 		    aconnector->mst_root)
3054 			continue;
3055 
3056 		mgr = &aconnector->mst_mgr;
3057 
3058 		if (suspend) {
3059 			drm_dp_mst_topology_mgr_suspend(mgr);
3060 		} else {
3061 			/* if extended timeout is supported in hardware,
3062 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
3063 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
3064 			 */
3065 			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
3066 			if (!dp_is_lttpr_present(aconnector->dc_link))
3067 				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
3068 
3069 			/* TODO: move resume_mst_branch_status() into drm mst resume again
3070 			 * once topology probing work is pulled out from mst resume into mst
3071 			 * resume 2nd step. mst resume 2nd step should be called after old
3072 			 * state getting restored (i.e. drm_atomic_helper_resume()).
3073 			 */
3074 			resume_mst_branch_status(mgr);
3075 		}
3076 	}
3077 	drm_connector_list_iter_end(&iter);
3078 }
3079 
3080 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
3081 {
3082 	int ret = 0;
3083 
3084 	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
3085 	 * on window driver dc implementation.
3086 	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
3087 	 * should be passed to smu during boot up and resume from s3.
3088 	 * boot up: dc calculate dcn watermark clock settings within dc_create,
3089 	 * dcn20_resource_construct
3090 	 * then call pplib functions below to pass the settings to smu:
3091 	 * smu_set_watermarks_for_clock_ranges
3092 	 * smu_set_watermarks_table
3093 	 * navi10_set_watermarks_table
3094 	 * smu_write_watermarks_table
3095 	 *
3096 	 * For Renoir, clock settings of dcn watermark are also fixed values.
3097 	 * dc has implemented different flow for window driver:
3098 	 * dc_hardware_init / dc_set_power_state
3099 	 * dcn10_init_hw
3100 	 * notify_wm_ranges
3101 	 * set_wm_ranges
3102 	 * -- Linux
3103 	 * smu_set_watermarks_for_clock_ranges
3104 	 * renoir_set_watermarks_table
3105 	 * smu_write_watermarks_table
3106 	 *
3107 	 * For Linux,
3108 	 * dc_hardware_init -> amdgpu_dm_init
3109 	 * dc_set_power_state --> dm_resume
3110 	 *
3111 	 * therefore, this function apply to navi10/12/14 but not Renoir
3112 	 * *
3113 	 */
3114 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
3115 	case IP_VERSION(2, 0, 2):
3116 	case IP_VERSION(2, 0, 0):
3117 		break;
3118 	default:
3119 		return 0;
3120 	}
3121 
3122 	ret = amdgpu_dpm_write_watermarks_table(adev);
3123 	if (ret) {
3124 		drm_err(adev_to_drm(adev), "Failed to update WMTABLE!\n");
3125 		return ret;
3126 	}
3127 
3128 	return 0;
3129 }
3130 
3131 static int dm_oem_i2c_hw_init(struct amdgpu_device *adev)
3132 {
3133 	struct amdgpu_display_manager *dm = &adev->dm;
3134 	struct amdgpu_i2c_adapter *oem_i2c;
3135 	struct ddc_service *oem_ddc_service;
3136 	int r;
3137 
3138 	oem_ddc_service = dc_get_oem_i2c_device(adev->dm.dc);
3139 	if (oem_ddc_service) {
3140 		oem_i2c = create_i2c(oem_ddc_service, true);
3141 		if (!oem_i2c) {
3142 			drm_info(adev_to_drm(adev), "Failed to create oem i2c adapter data\n");
3143 			return -ENOMEM;
3144 		}
3145 
3146 		r = devm_i2c_add_adapter(adev->dev, &oem_i2c->base);
3147 		if (r) {
3148 			drm_info(adev_to_drm(adev), "Failed to register oem i2c\n");
3149 			kfree(oem_i2c);
3150 			return r;
3151 		}
3152 		dm->oem_i2c = oem_i2c;
3153 	}
3154 
3155 	return 0;
3156 }
3157 
3158 /**
3159  * dm_hw_init() - Initialize DC device
3160  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3161  *
3162  * Initialize the &struct amdgpu_display_manager device. This involves calling
3163  * the initializers of each DM component, then populating the struct with them.
3164  *
3165  * Although the function implies hardware initialization, both hardware and
3166  * software are initialized here. Splitting them out to their relevant init
3167  * hooks is a future TODO item.
3168  *
3169  * Some notable things that are initialized here:
3170  *
3171  * - Display Core, both software and hardware
3172  * - DC modules that we need (freesync and color management)
3173  * - DRM software states
3174  * - Interrupt sources and handlers
3175  * - Vblank support
3176  * - Debug FS entries, if enabled
3177  */
3178 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
3179 {
3180 	struct amdgpu_device *adev = ip_block->adev;
3181 	int r;
3182 
3183 	/* Create DAL display manager */
3184 	r = amdgpu_dm_init(adev);
3185 	if (r)
3186 		return r;
3187 	amdgpu_dm_hpd_init(adev);
3188 
3189 	r = dm_oem_i2c_hw_init(adev);
3190 	if (r)
3191 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
3192 
3193 	return 0;
3194 }
3195 
3196 /**
3197  * dm_hw_fini() - Teardown DC device
3198  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3199  *
3200  * Teardown components within &struct amdgpu_display_manager that require
3201  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
3202  * were loaded. Also flush IRQ workqueues and disable them.
3203  */
3204 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
3205 {
3206 	struct amdgpu_device *adev = ip_block->adev;
3207 
3208 	amdgpu_dm_hpd_fini(adev);
3209 
3210 	amdgpu_dm_irq_fini(adev);
3211 	amdgpu_dm_fini(adev);
3212 	return 0;
3213 }
3214 
3215 
3216 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
3217 				 struct dc_state *state, bool enable)
3218 {
3219 	enum dc_irq_source irq_source;
3220 	struct amdgpu_crtc *acrtc;
3221 	int rc = -EBUSY;
3222 	int i = 0;
3223 
3224 	for (i = 0; i < state->stream_count; i++) {
3225 		acrtc = get_crtc_by_otg_inst(
3226 				adev, state->stream_status[i].primary_otg_inst);
3227 
3228 		if (acrtc && state->stream_status[i].plane_count != 0) {
3229 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
3230 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3231 			if (rc)
3232 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
3233 					 enable ? "enable" : "disable");
3234 
3235 			if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
3236 				if (enable) {
3237 					if (amdgpu_dm_crtc_vrr_active(
3238 							to_dm_crtc_state(acrtc->base.state)))
3239 						rc = amdgpu_dm_crtc_set_vupdate_irq(
3240 							&acrtc->base, true);
3241 				} else
3242 					rc = amdgpu_dm_crtc_set_vupdate_irq(
3243 							&acrtc->base, false);
3244 
3245 				if (rc)
3246 					drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
3247 						enable ? "en" : "dis");
3248 			}
3249 
3250 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3251 			/* During gpu-reset we disable and then enable vblank irq, so
3252 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
3253 			 */
3254 			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
3255 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
3256 		}
3257 	}
3258 
3259 }
3260 
3261 DEFINE_FREE(state_release, struct dc_state *, if (_T) dc_state_release(_T))
3262 
3263 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
3264 {
3265 	struct dc_state *context __free(state_release) = NULL;
3266 	int i;
3267 	struct dc_stream_state *del_streams[MAX_PIPES];
3268 	int del_streams_count = 0;
3269 	struct dc_commit_streams_params params = {};
3270 
3271 	memset(del_streams, 0, sizeof(del_streams));
3272 
3273 	context = dc_state_create_current_copy(dc);
3274 	if (context == NULL)
3275 		return DC_ERROR_UNEXPECTED;
3276 
3277 	/* First remove from context all streams */
3278 	for (i = 0; i < context->stream_count; i++) {
3279 		struct dc_stream_state *stream = context->streams[i];
3280 
3281 		del_streams[del_streams_count++] = stream;
3282 	}
3283 
3284 	/* Remove all planes for removed streams and then remove the streams */
3285 	for (i = 0; i < del_streams_count; i++) {
3286 		enum dc_status res;
3287 
3288 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
3289 			return DC_FAIL_DETACH_SURFACES;
3290 
3291 		res = dc_state_remove_stream(dc, context, del_streams[i]);
3292 		if (res != DC_OK)
3293 			return res;
3294 	}
3295 
3296 	params.streams = context->streams;
3297 	params.stream_count = context->stream_count;
3298 
3299 	return dc_commit_streams(dc, &params);
3300 }
3301 
3302 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
3303 {
3304 	int i;
3305 
3306 	if (dm->hpd_rx_offload_wq) {
3307 		for (i = 0; i < dm->dc->caps.max_links; i++)
3308 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
3309 	}
3310 }
3311 
3312 static int dm_cache_state(struct amdgpu_device *adev)
3313 {
3314 	int r;
3315 
3316 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
3317 	if (IS_ERR(adev->dm.cached_state)) {
3318 		r = PTR_ERR(adev->dm.cached_state);
3319 		adev->dm.cached_state = NULL;
3320 	}
3321 
3322 	return adev->dm.cached_state ? 0 : r;
3323 }
3324 
3325 static void dm_destroy_cached_state(struct amdgpu_device *adev)
3326 {
3327 	struct amdgpu_display_manager *dm = &adev->dm;
3328 	struct drm_device *ddev = adev_to_drm(adev);
3329 	struct dm_plane_state *dm_new_plane_state;
3330 	struct drm_plane_state *new_plane_state;
3331 	struct dm_crtc_state *dm_new_crtc_state;
3332 	struct drm_crtc_state *new_crtc_state;
3333 	struct drm_plane *plane;
3334 	struct drm_crtc *crtc;
3335 	int i;
3336 
3337 	if (!dm->cached_state)
3338 		return;
3339 
3340 	/* Force mode set in atomic commit */
3341 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3342 		new_crtc_state->active_changed = true;
3343 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3344 		reset_freesync_config_for_crtc(dm_new_crtc_state);
3345 	}
3346 
3347 	/*
3348 	 * atomic_check is expected to create the dc states. We need to release
3349 	 * them here, since they were duplicated as part of the suspend
3350 	 * procedure.
3351 	 */
3352 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3353 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3354 		if (dm_new_crtc_state->stream) {
3355 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
3356 			dc_stream_release(dm_new_crtc_state->stream);
3357 			dm_new_crtc_state->stream = NULL;
3358 		}
3359 		dm_new_crtc_state->base.color_mgmt_changed = true;
3360 	}
3361 
3362 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
3363 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
3364 		if (dm_new_plane_state->dc_state) {
3365 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
3366 			dc_plane_state_release(dm_new_plane_state->dc_state);
3367 			dm_new_plane_state->dc_state = NULL;
3368 		}
3369 	}
3370 
3371 	drm_atomic_helper_resume(ddev, dm->cached_state);
3372 
3373 	dm->cached_state = NULL;
3374 }
3375 
3376 static int dm_suspend(struct amdgpu_ip_block *ip_block)
3377 {
3378 	struct amdgpu_device *adev = ip_block->adev;
3379 	struct amdgpu_display_manager *dm = &adev->dm;
3380 
3381 	if (amdgpu_in_reset(adev)) {
3382 		enum dc_status res;
3383 
3384 		/* Quiesce ISM workers before taking dc_lock (workers take
3385 		 * dc_lock themselves; syncing under it would deadlock).
3386 		 */
3387 		amdgpu_dm_ism_disable(dm);
3388 
3389 		mutex_lock(&dm->dc_lock);
3390 
3391 		amdgpu_dm_ism_force_full_power(dm);
3392 		dc_allow_idle_optimizations(adev->dm.dc, false);
3393 
3394 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
3395 
3396 		if (dm->cached_dc_state)
3397 			dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
3398 
3399 		res = amdgpu_dm_commit_zero_streams(dm->dc);
3400 		if (res != DC_OK) {
3401 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
3402 			return -EINVAL;
3403 		}
3404 
3405 		amdgpu_dm_irq_suspend(adev);
3406 
3407 		hpd_rx_irq_work_suspend(dm);
3408 
3409 		return 0;
3410 	}
3411 
3412 	if (!adev->dm.cached_state) {
3413 		int r = dm_cache_state(adev);
3414 
3415 		if (r)
3416 			return r;
3417 	}
3418 
3419 	s3_handle_hdmi_cec(adev_to_drm(adev), true);
3420 
3421 	s3_handle_mst(adev_to_drm(adev), true);
3422 
3423 	amdgpu_dm_irq_suspend(adev);
3424 
3425 	/*
3426 	 * Quiesce ISM workers before taking dc_lock (workers take dc_lock
3427 	 * themselves; syncing under it would deadlock).
3428 	 */
3429 	amdgpu_dm_ism_disable(dm);
3430 	scoped_guard(mutex, &dm->dc_lock)
3431 		amdgpu_dm_ism_force_full_power(dm);
3432 
3433 	hpd_rx_irq_work_suspend(dm);
3434 
3435 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
3436 
3437 	if (dm->dc->caps.ips_support && adev->in_s0ix)
3438 		dc_allow_idle_optimizations(dm->dc, true);
3439 
3440 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
3441 
3442 	return 0;
3443 }
3444 
3445 struct drm_connector *
3446 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_commit *state,
3447 					     struct drm_crtc *crtc)
3448 {
3449 	u32 i;
3450 	struct drm_connector_state *new_con_state;
3451 	struct drm_connector *connector;
3452 	struct drm_crtc *crtc_from_state;
3453 
3454 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3455 		crtc_from_state = new_con_state->crtc;
3456 
3457 		if (crtc_from_state == crtc)
3458 			return connector;
3459 	}
3460 
3461 	return NULL;
3462 }
3463 
3464 static void emulated_link_detect(struct dc_link *link)
3465 {
3466 	struct dc_sink_init_data sink_init_data = { 0 };
3467 	struct display_sink_capability sink_caps = { 0 };
3468 	enum dc_edid_status edid_status;
3469 	struct dc_context *dc_ctx = link->ctx;
3470 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
3471 	struct dc_sink *sink = NULL;
3472 	struct dc_sink *prev_sink = NULL;
3473 
3474 	link->type = dc_connection_none;
3475 	prev_sink = link->local_sink;
3476 
3477 	if (prev_sink)
3478 		dc_sink_release(prev_sink);
3479 
3480 	switch (link->connector_signal) {
3481 	case SIGNAL_TYPE_HDMI_TYPE_A: {
3482 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3483 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
3484 		break;
3485 	}
3486 
3487 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
3488 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3489 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
3490 		break;
3491 	}
3492 
3493 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
3494 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3495 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
3496 		break;
3497 	}
3498 
3499 	case SIGNAL_TYPE_LVDS: {
3500 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3501 		sink_caps.signal = SIGNAL_TYPE_LVDS;
3502 		break;
3503 	}
3504 
3505 	case SIGNAL_TYPE_EDP: {
3506 		sink_caps.transaction_type =
3507 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3508 		sink_caps.signal = SIGNAL_TYPE_EDP;
3509 		break;
3510 	}
3511 
3512 	case SIGNAL_TYPE_DISPLAY_PORT: {
3513 		sink_caps.transaction_type =
3514 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3515 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
3516 		break;
3517 	}
3518 
3519 	default:
3520 		drm_err(dev, "Invalid connector type! signal:%d\n",
3521 			link->connector_signal);
3522 		return;
3523 	}
3524 
3525 	sink_init_data.link = link;
3526 	sink_init_data.sink_signal = sink_caps.signal;
3527 
3528 	sink = dc_sink_create(&sink_init_data);
3529 	if (!sink) {
3530 		drm_err(dev, "Failed to create sink!\n");
3531 		return;
3532 	}
3533 
3534 	/* dc_sink_create returns a new reference */
3535 	link->local_sink = sink;
3536 
3537 	edid_status = dm_helpers_read_local_edid(
3538 			link->ctx,
3539 			link,
3540 			sink);
3541 
3542 	if (edid_status != EDID_OK)
3543 		drm_err(dev, "Failed to read EDID\n");
3544 
3545 }
3546 
3547 static void dm_gpureset_commit_state(struct dc_state *dc_state,
3548 				     struct amdgpu_display_manager *dm)
3549 {
3550 	struct {
3551 		struct dc_surface_update surface_updates[MAX_SURFACES];
3552 		struct dc_plane_info plane_infos[MAX_SURFACES];
3553 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3554 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3555 		struct dc_stream_update stream_update;
3556 	} *bundle __free(kfree);
3557 	int k, m;
3558 
3559 	bundle = kzalloc_obj(*bundle);
3560 
3561 	if (!bundle) {
3562 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
3563 		return;
3564 	}
3565 
3566 	for (k = 0; k < dc_state->stream_count; k++) {
3567 		bundle->stream_update.stream = dc_state->streams[k];
3568 
3569 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
3570 			bundle->surface_updates[m].surface =
3571 				dc_state->stream_status[k].plane_states[m];
3572 			bundle->surface_updates[m].surface->force_full_update =
3573 				true;
3574 		}
3575 
3576 		update_planes_and_stream_adapter(dm->dc,
3577 					 UPDATE_TYPE_FULL,
3578 					 dc_state->stream_status[k].plane_count,
3579 					 dc_state->streams[k],
3580 					 &bundle->stream_update,
3581 					 bundle->surface_updates);
3582 	}
3583 }
3584 
3585 static void apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
3586 					    struct dc_sink *sink)
3587 {
3588 	struct dc_panel_patch *ppatch = NULL;
3589 
3590 	if (!sink)
3591 		return;
3592 
3593 	ppatch = &sink->edid_caps.panel_patch;
3594 	if (ppatch->wait_after_dpcd_poweroff_ms) {
3595 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
3596 		drm_dbg_driver(adev_to_drm(adev),
3597 			       "%s: adding a %ds delay as w/a for panel\n",
3598 			       __func__,
3599 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
3600 	}
3601 }
3602 
3603 /**
3604  * amdgpu_dm_dump_links_and_sinks - Debug dump of all DC links and their sinks
3605  * @adev: amdgpu device pointer
3606  *
3607  * Iterates through all DC links and dumps information about local and remote
3608  * (MST) sinks. Should be called after connector detection is complete to see
3609  * the final state of all links.
3610  */
3611 static void amdgpu_dm_dump_links_and_sinks(struct amdgpu_device *adev)
3612 {
3613 	struct dc *dc = adev->dm.dc;
3614 	struct drm_device *dev = adev_to_drm(adev);
3615 	int li;
3616 
3617 	if (!dc)
3618 		return;
3619 
3620 	for (li = 0; li < dc->link_count; li++) {
3621 		struct dc_link *l = dc->links[li];
3622 		const char *name = NULL;
3623 		int rs;
3624 
3625 		if (!l)
3626 			continue;
3627 		if (l->local_sink && l->local_sink->edid_caps.display_name[0])
3628 			name = l->local_sink->edid_caps.display_name;
3629 		else
3630 			name = "n/a";
3631 
3632 		drm_dbg_kms(dev,
3633 			"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",
3634 			li,
3635 			l->local_sink,
3636 			l->type,
3637 			l->local_sink ? l->local_sink->sink_signal : SIGNAL_TYPE_NONE,
3638 			l->sink_count,
3639 			name,
3640 			l->dpcd_caps.is_mst_capable,
3641 			l->mst_stream_alloc_table.stream_count);
3642 
3643 		/* Dump remote (MST) sinks if any */
3644 		for (rs = 0; rs < l->sink_count; rs++) {
3645 			struct dc_sink *rsink = l->remote_sinks[rs];
3646 			const char *rname = NULL;
3647 
3648 			if (!rsink)
3649 				continue;
3650 			if (rsink->edid_caps.display_name[0])
3651 				rname = rsink->edid_caps.display_name;
3652 			else
3653 				rname = "n/a";
3654 			drm_dbg_kms(dev,
3655 				"  REMOTE_SINK[%d:%d]: sink=%p signal=%d edid_name=%s\n",
3656 				li, rs,
3657 				rsink,
3658 				rsink->sink_signal,
3659 				rname);
3660 		}
3661 	}
3662 }
3663 
3664 static int dm_resume(struct amdgpu_ip_block *ip_block)
3665 {
3666 	struct amdgpu_device *adev = ip_block->adev;
3667 	struct drm_device *ddev = adev_to_drm(adev);
3668 	struct amdgpu_display_manager *dm = &adev->dm;
3669 	struct amdgpu_dm_connector *aconnector;
3670 	struct drm_connector *connector;
3671 	struct drm_connector_list_iter iter;
3672 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
3673 	enum dc_connection_type new_connection_type = dc_connection_none;
3674 	struct dc_state *dc_state;
3675 	int i, r, j;
3676 	struct dc_commit_streams_params commit_params = {};
3677 
3678 	if (dm->dc->caps.ips_support) {
3679 		if (!amdgpu_in_reset(adev))
3680 			mutex_lock(&dm->dc_lock);
3681 
3682 		/* Need to set POWER_STATE_D0 first or it will not execute
3683 		 * idle_power_optimizations command to DMUB.
3684 		 */
3685 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3686 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
3687 
3688 		if (!amdgpu_in_reset(adev))
3689 			mutex_unlock(&dm->dc_lock);
3690 	}
3691 
3692 	if (amdgpu_in_reset(adev)) {
3693 		dc_state = dm->cached_dc_state;
3694 
3695 		/*
3696 		 * The dc->current_state is backed up into dm->cached_dc_state
3697 		 * before we commit 0 streams.
3698 		 *
3699 		 * DC will clear link encoder assignments on the real state
3700 		 * but the changes won't propagate over to the copy we made
3701 		 * before the 0 streams commit.
3702 		 *
3703 		 * DC expects that link encoder assignments are *not* valid
3704 		 * when committing a state, so as a workaround we can copy
3705 		 * off of the current state.
3706 		 *
3707 		 * We lose the previous assignments, but we had already
3708 		 * commit 0 streams anyway.
3709 		 */
3710 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
3711 
3712 		r = dm_dmub_hw_init(adev);
3713 		if (r) {
3714 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
3715 			return r;
3716 		}
3717 
3718 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3719 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3720 
3721 		dc_resume(dm->dc);
3722 
3723 		amdgpu_dm_ism_enable(dm);
3724 		amdgpu_dm_irq_resume_early(adev);
3725 
3726 		for (i = 0; i < dc_state->stream_count; i++) {
3727 			dc_state->streams[i]->mode_changed = true;
3728 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
3729 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
3730 					= 0xffffffff;
3731 			}
3732 		}
3733 
3734 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3735 			amdgpu_dm_outbox_init(adev);
3736 			dc_enable_dmub_outbox(adev->dm.dc);
3737 		}
3738 
3739 		commit_params.streams = dc_state->streams;
3740 		commit_params.stream_count = dc_state->stream_count;
3741 		dc_exit_ips_for_hw_access(dm->dc);
3742 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
3743 
3744 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
3745 
3746 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
3747 
3748 		dc_state_release(dm->cached_dc_state);
3749 		dm->cached_dc_state = NULL;
3750 
3751 		amdgpu_dm_irq_resume_late(adev);
3752 
3753 		mutex_unlock(&dm->dc_lock);
3754 
3755 		/* set the backlight after a reset */
3756 		for (i = 0; i < dm->num_of_edps; i++) {
3757 			if (dm->backlight_dev[i])
3758 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
3759 		}
3760 
3761 		return 0;
3762 	}
3763 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
3764 	dc_state_release(dm_state->context);
3765 	dm_state->context = dc_state_create(dm->dc, NULL);
3766 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
3767 
3768 	/* Before powering on DC we need to re-initialize DMUB. */
3769 	dm_dmub_hw_resume(adev);
3770 
3771 	/* Re-enable outbox interrupts for DPIA. */
3772 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3773 		amdgpu_dm_outbox_init(adev);
3774 		dc_enable_dmub_outbox(adev->dm.dc);
3775 	}
3776 
3777 	/* power on hardware */
3778 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3779 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3780 
3781 	/* program HPD filter */
3782 	dc_resume(dm->dc);
3783 
3784 	scoped_guard(mutex, &dm->dc_lock)
3785 		amdgpu_dm_ism_enable(dm);
3786 
3787 	/*
3788 	 * early enable HPD Rx IRQ, should be done before set mode as short
3789 	 * pulse interrupts are used for MST
3790 	 */
3791 	amdgpu_dm_irq_resume_early(adev);
3792 
3793 	s3_handle_hdmi_cec(ddev, false);
3794 
3795 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
3796 	s3_handle_mst(ddev, false);
3797 
3798 	/* Do detection*/
3799 	drm_connector_list_iter_begin(ddev, &iter);
3800 	drm_for_each_connector_iter(connector, &iter) {
3801 		bool ret;
3802 
3803 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3804 			continue;
3805 
3806 		aconnector = to_amdgpu_dm_connector(connector);
3807 
3808 		if (!aconnector->dc_link)
3809 			continue;
3810 
3811 		/*
3812 		 * this is the case when traversing through already created end sink
3813 		 * MST connectors, should be skipped
3814 		 */
3815 		if (aconnector->mst_root)
3816 			continue;
3817 
3818 		/* Skip eDP detection, when there is no sink present */
3819 		if (aconnector->dc_link->connector_signal == SIGNAL_TYPE_EDP &&
3820 		    !aconnector->dc_link->edp_sink_present)
3821 			continue;
3822 
3823 		guard(mutex)(&aconnector->hpd_lock);
3824 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3825 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3826 
3827 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3828 			emulated_link_detect(aconnector->dc_link);
3829 		} else {
3830 			guard(mutex)(&dm->dc_lock);
3831 			dc_exit_ips_for_hw_access(dm->dc);
3832 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
3833 			if (ret) {
3834 				/* w/a delay for certain panels */
3835 				apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3836 			}
3837 		}
3838 
3839 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
3840 			aconnector->fake_enable = false;
3841 
3842 		if (aconnector->dc_sink)
3843 			dc_sink_release(aconnector->dc_sink);
3844 		aconnector->dc_sink = NULL;
3845 		amdgpu_dm_update_connector_after_detect(aconnector);
3846 	}
3847 	drm_connector_list_iter_end(&iter);
3848 
3849 	dm_destroy_cached_state(adev);
3850 
3851 	/* Do mst topology probing after resuming cached state*/
3852 	drm_connector_list_iter_begin(ddev, &iter);
3853 	drm_for_each_connector_iter(connector, &iter) {
3854 		bool init = false;
3855 
3856 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3857 			continue;
3858 
3859 		aconnector = to_amdgpu_dm_connector(connector);
3860 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3861 		    aconnector->mst_root)
3862 			continue;
3863 
3864 		scoped_guard(mutex, &aconnector->mst_mgr.lock) {
3865 			init = !aconnector->mst_mgr.mst_primary;
3866 		}
3867 		if (init)
3868 			dm_helpers_dp_mst_start_top_mgr(aconnector->dc_link->ctx,
3869 				aconnector->dc_link, false);
3870 		else
3871 			drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
3872 	}
3873 	drm_connector_list_iter_end(&iter);
3874 
3875 	/* Debug dump: list all DC links and their associated sinks after detection
3876 	 * is complete for all connectors. This provides a comprehensive view of the
3877 	 * final state without repeating the dump for each connector.
3878 	 */
3879 	amdgpu_dm_dump_links_and_sinks(adev);
3880 
3881 	amdgpu_dm_irq_resume_late(adev);
3882 
3883 	amdgpu_dm_smu_write_watermarks_table(adev);
3884 
3885 	drm_kms_helper_hotplug_event(ddev);
3886 
3887 	return 0;
3888 }
3889 
3890 /**
3891  * DOC: DM Lifecycle
3892  *
3893  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
3894  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
3895  * the base driver's device list to be initialized and torn down accordingly.
3896  *
3897  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
3898  */
3899 
3900 static const struct amd_ip_funcs amdgpu_dm_funcs = {
3901 	.name = "dm",
3902 	.early_init = dm_early_init,
3903 	.late_init = dm_late_init,
3904 	.sw_init = dm_sw_init,
3905 	.sw_fini = dm_sw_fini,
3906 	.early_fini = amdgpu_dm_early_fini,
3907 	.hw_init = dm_hw_init,
3908 	.hw_fini = dm_hw_fini,
3909 	.suspend = dm_suspend,
3910 	.resume = dm_resume,
3911 	.is_idle = dm_is_idle,
3912 	.wait_for_idle = dm_wait_for_idle,
3913 	.check_soft_reset = dm_check_soft_reset,
3914 	.soft_reset = dm_soft_reset,
3915 	.set_clockgating_state = dm_set_clockgating_state,
3916 	.set_powergating_state = dm_set_powergating_state,
3917 };
3918 
3919 const struct amdgpu_ip_block_version dm_ip_block = {
3920 	.type = AMD_IP_BLOCK_TYPE_DCE,
3921 	.major = 1,
3922 	.minor = 0,
3923 	.rev = 0,
3924 	.funcs = &amdgpu_dm_funcs,
3925 };
3926 
3927 
3928 /**
3929  * DOC: atomic
3930  *
3931  * *WIP*
3932  */
3933 
3934 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
3935 	.fb_create = amdgpu_display_user_framebuffer_create,
3936 	.get_format_info = amdgpu_dm_plane_get_format_info,
3937 	.atomic_check = amdgpu_dm_atomic_check,
3938 	.atomic_commit = drm_atomic_helper_commit,
3939 };
3940 
3941 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
3942 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
3943 	.atomic_commit_setup = amdgpu_dm_atomic_setup_commit,
3944 };
3945 
3946 #define DDC_MANUFACTURERNAME_SAMSUNG 0x2D4C
3947 
3948 static void dm_set_panel_type(struct amdgpu_dm_connector *aconnector)
3949 {
3950 	struct drm_connector *connector = &aconnector->base;
3951 	struct drm_display_info *display_info = &connector->display_info;
3952 	struct dc_link *link = aconnector->dc_link;
3953 	struct amdgpu_device *adev;
3954 
3955 	adev = drm_to_adev(connector->dev);
3956 
3957 	link->panel_type = PANEL_TYPE_NONE;
3958 
3959 	switch (display_info->amd_vsdb.panel_type) {
3960 	case AMD_VSDB_PANEL_TYPE_OLED:
3961 		link->panel_type = PANEL_TYPE_OLED;
3962 		break;
3963 	case AMD_VSDB_PANEL_TYPE_MINILED:
3964 		link->panel_type = PANEL_TYPE_MINILED;
3965 		break;
3966 	}
3967 
3968 	/* If VSDB didn't determine panel type, check DPCD ext caps */
3969 	if (link->panel_type == PANEL_TYPE_NONE) {
3970 		if (link->dpcd_sink_ext_caps.bits.miniled == 1)
3971 			link->panel_type = PANEL_TYPE_MINILED;
3972 		if (link->dpcd_sink_ext_caps.bits.oled == 1)
3973 			link->panel_type = PANEL_TYPE_OLED;
3974 	}
3975 
3976 	/*
3977 	 * TODO: get panel type from DID2 that has device technology field
3978 	 * to specify if it's OLED or not. But we need to wait for DID2
3979 	 * support in DC and EDID parser to be able to use it here.
3980 	 */
3981 
3982 	if (link->panel_type == PANEL_TYPE_NONE) {
3983 		struct drm_amd_vsdb_info *vsdb = &display_info->amd_vsdb;
3984 		u32 lum1_max = vsdb->luminance_range1.max_luminance;
3985 		u32 lum2_max = vsdb->luminance_range2.max_luminance;
3986 
3987 		if (vsdb->version && link->local_sink &&
3988 		    link->local_sink->edid_caps.manufacturer_id ==
3989 		    DDC_MANUFACTURERNAME_SAMSUNG &&
3990 		    lum1_max >= ((lum2_max * 3) / 2))
3991 			link->panel_type = PANEL_TYPE_MINILED;
3992 	}
3993 
3994 	if (link->panel_type == PANEL_TYPE_OLED)
3995 		drm_object_property_set_value(&connector->base,
3996 		    adev_to_drm(adev)->mode_config.panel_type_property,
3997 		    DRM_MODE_PANEL_TYPE_OLED);
3998 	else
3999 		drm_object_property_set_value(&connector->base,
4000 		    adev_to_drm(adev)->mode_config.panel_type_property,
4001 		    DRM_MODE_PANEL_TYPE_UNKNOWN);
4002 
4003 	drm_dbg_kms(aconnector->base.dev, "Panel type: %d\n", link->panel_type);
4004 }
4005 
4006 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
4007 {
4008 	const struct drm_panel_backlight_quirk *panel_backlight_quirk;
4009 	struct amdgpu_dm_backlight_caps *caps;
4010 	struct drm_connector *conn_base;
4011 	struct amdgpu_device *adev;
4012 	struct drm_luminance_range_info *luminance_range;
4013 	struct drm_device *drm;
4014 
4015 	if (aconnector->bl_idx == -1 ||
4016 	    aconnector->dc_link->connector_signal != SIGNAL_TYPE_EDP)
4017 		return;
4018 
4019 	conn_base = &aconnector->base;
4020 	drm = conn_base->dev;
4021 	adev = drm_to_adev(drm);
4022 
4023 	caps = &adev->dm.backlight_caps[aconnector->bl_idx];
4024 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
4025 	caps->aux_support = false;
4026 
4027 	if (caps->ext_caps->bits.oled == 1
4028 	    /*
4029 	     * ||
4030 	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
4031 	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
4032 	     */)
4033 		caps->aux_support = true;
4034 
4035 	if (amdgpu_backlight == 0)
4036 		caps->aux_support = false;
4037 	else if (amdgpu_backlight == 1)
4038 		caps->aux_support = true;
4039 	if (caps->aux_support)
4040 		aconnector->dc_link->backlight_control_type = BACKLIGHT_CONTROL_AMD_AUX;
4041 
4042 	luminance_range = &conn_base->display_info.luminance_range;
4043 
4044 	if (luminance_range->max_luminance)
4045 		caps->aux_max_input_signal = luminance_range->max_luminance;
4046 	else
4047 		caps->aux_max_input_signal = 512;
4048 
4049 	if (luminance_range->min_luminance)
4050 		caps->aux_min_input_signal = luminance_range->min_luminance;
4051 	else
4052 		caps->aux_min_input_signal = 1;
4053 
4054 	panel_backlight_quirk =
4055 		drm_get_panel_backlight_quirk(aconnector->drm_edid);
4056 	if (!IS_ERR_OR_NULL(panel_backlight_quirk)) {
4057 		if (panel_backlight_quirk->min_brightness) {
4058 			caps->min_input_signal =
4059 				panel_backlight_quirk->min_brightness - 1;
4060 			drm_info(drm,
4061 				 "Applying panel backlight quirk, min_brightness: %d\n",
4062 				 caps->min_input_signal);
4063 		}
4064 		if (panel_backlight_quirk->brightness_mask) {
4065 			drm_info(drm,
4066 				 "Applying panel backlight quirk, brightness_mask: 0x%X\n",
4067 				 panel_backlight_quirk->brightness_mask);
4068 			caps->brightness_mask =
4069 				panel_backlight_quirk->brightness_mask;
4070 		}
4071 	}
4072 }
4073 
4074 DEFINE_FREE(sink_release, struct dc_sink *, if (_T) dc_sink_release(_T))
4075 
4076 void amdgpu_dm_update_connector_after_detect(
4077 		struct amdgpu_dm_connector *aconnector)
4078 {
4079 	struct drm_connector *connector = &aconnector->base;
4080 	struct dc_sink *sink __free(sink_release) = NULL;
4081 	struct drm_device *dev = connector->dev;
4082 
4083 	/* MST handled by drm_mst framework */
4084 	if (aconnector->mst_mgr.mst_state == true)
4085 		return;
4086 
4087 	sink = aconnector->dc_link->local_sink;
4088 	if (sink)
4089 		dc_sink_retain(sink);
4090 
4091 	/*
4092 	 * Edid mgmt connector gets first update only in mode_valid hook and then
4093 	 * the connector sink is set to either fake or physical sink depends on link status.
4094 	 * Skip if already done during boot.
4095 	 */
4096 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
4097 			&& aconnector->dc_em_sink) {
4098 
4099 		/*
4100 		 * For S3 resume with headless use eml_sink to fake stream
4101 		 * because on resume connector->sink is set to NULL
4102 		 */
4103 		guard(mutex)(&dev->mode_config.mutex);
4104 
4105 		if (sink) {
4106 			if (aconnector->dc_sink) {
4107 				amdgpu_dm_update_freesync_caps(connector, NULL, true);
4108 				/*
4109 				 * retain and release below are used to
4110 				 * bump up refcount for sink because the link doesn't point
4111 				 * to it anymore after disconnect, so on next crtc to connector
4112 				 * reshuffle by UMD we will get into unwanted dc_sink release
4113 				 */
4114 				dc_sink_release(aconnector->dc_sink);
4115 			}
4116 			aconnector->dc_sink = sink;
4117 			dc_sink_retain(aconnector->dc_sink);
4118 			amdgpu_dm_update_freesync_caps(connector,
4119 					aconnector->drm_edid, true);
4120 		} else {
4121 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4122 			if (!aconnector->dc_sink) {
4123 				aconnector->dc_sink = aconnector->dc_em_sink;
4124 				dc_sink_retain(aconnector->dc_sink);
4125 			}
4126 		}
4127 
4128 		return;
4129 	}
4130 
4131 	/*
4132 	 * TODO: temporary guard to look for proper fix
4133 	 * if this sink is MST sink, we should not do anything
4134 	 */
4135 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
4136 		return;
4137 
4138 	if (aconnector->dc_sink == sink) {
4139 		/*
4140 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
4141 		 * Do nothing!!
4142 		 */
4143 		drm_dbg_kms(dev, "DCHPD: connector_id=%d: dc_sink didn't change.\n",
4144 				 aconnector->connector_id);
4145 		return;
4146 	}
4147 
4148 	drm_dbg_kms(dev, "DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
4149 		    aconnector->connector_id, aconnector->dc_sink, sink);
4150 
4151 	/* When polling, DRM has already locked the mutex for us. */
4152 	if (!drm_kms_helper_is_poll_worker())
4153 		mutex_lock(&dev->mode_config.mutex);
4154 
4155 	/*
4156 	 * 1. Update status of the drm connector
4157 	 * 2. Send an event and let userspace tell us what to do
4158 	 */
4159 	if (sink) {
4160 		/*
4161 		 * TODO: check if we still need the S3 mode update workaround.
4162 		 * If yes, put it here.
4163 		 */
4164 		if (aconnector->dc_sink) {
4165 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4166 			dc_sink_release(aconnector->dc_sink);
4167 		}
4168 
4169 		aconnector->dc_sink = sink;
4170 		dc_sink_retain(aconnector->dc_sink);
4171 		drm_edid_free(aconnector->drm_edid);
4172 		aconnector->drm_edid = NULL;
4173 		if (sink->dc_edid.length == 0) {
4174 			hdmi_cec_unset_edid(aconnector);
4175 			if (aconnector->dc_link->aux_mode) {
4176 				drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4177 			}
4178 		} else {
4179 			const struct edid *edid = (const struct edid *)sink->dc_edid.raw_edid;
4180 
4181 			aconnector->drm_edid = drm_edid_alloc(edid, sink->dc_edid.length);
4182 			drm_edid_connector_update(connector, aconnector->drm_edid);
4183 
4184 			hdmi_cec_set_edid(aconnector);
4185 			if (aconnector->dc_link->aux_mode)
4186 				drm_dp_cec_attach(&aconnector->dm_dp_aux.aux,
4187 						  connector->display_info.source_physical_address);
4188 		}
4189 
4190 		if (!aconnector->timing_requested) {
4191 			aconnector->timing_requested =
4192 				kzalloc_obj(struct dc_crtc_timing);
4193 			if (!aconnector->timing_requested)
4194 				drm_err(dev,
4195 					"failed to create aconnector->requested_timing\n");
4196 		}
4197 
4198 		amdgpu_dm_update_freesync_caps(connector, aconnector->drm_edid, true);
4199 		update_connector_ext_caps(aconnector);
4200 		dm_set_panel_type(aconnector);
4201 	} else {
4202 		hdmi_cec_unset_edid(aconnector);
4203 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4204 		amdgpu_dm_update_freesync_caps(connector, NULL, true);
4205 		aconnector->num_modes = 0;
4206 		dc_sink_release(aconnector->dc_sink);
4207 		aconnector->dc_sink = NULL;
4208 		drm_edid_free(aconnector->drm_edid);
4209 		aconnector->drm_edid = NULL;
4210 		kfree(aconnector->timing_requested);
4211 		aconnector->timing_requested = NULL;
4212 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
4213 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
4214 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
4215 	}
4216 
4217 	update_subconnector_property(aconnector);
4218 
4219 	/* When polling, the mutex will be unlocked for us by DRM. */
4220 	if (!drm_kms_helper_is_poll_worker())
4221 		mutex_unlock(&dev->mode_config.mutex);
4222 }
4223 
4224 static bool are_sinks_equal(const struct dc_sink *sink1, const struct dc_sink *sink2)
4225 {
4226 	if (!sink1 || !sink2)
4227 		return false;
4228 	if (sink1->sink_signal != sink2->sink_signal)
4229 		return false;
4230 
4231 	if (sink1->dc_edid.length != sink2->dc_edid.length)
4232 		return false;
4233 
4234 	if (memcmp(sink1->dc_edid.raw_edid, sink2->dc_edid.raw_edid,
4235 		   sink1->dc_edid.length) != 0)
4236 		return false;
4237 	return true;
4238 }
4239 
4240 
4241 /**
4242  * DOC: hdmi_hpd_debounce_work
4243  *
4244  * HDMI HPD debounce delay in milliseconds. When an HDMI display toggles HPD
4245  * (such as during power save transitions), this delay determines how long to
4246  * wait before processing the HPD event. This allows distinguishing between a
4247  * physical unplug (>hdmi_hpd_debounce_delay)
4248  * and a spontaneous RX HPD toggle (<hdmi_hpd_debounce_delay).
4249  *
4250  * If the toggle is less than this delay, the driver compares sink capabilities
4251  * and permits a hotplug event if they changed.
4252  *
4253  * The default value of 1500ms was chosen based on experimental testing with
4254  * various monitors that exhibit spontaneous HPD toggling behavior.
4255  */
4256 static void hdmi_hpd_debounce_work(struct work_struct *work)
4257 {
4258 	struct amdgpu_dm_connector *aconnector =
4259 		container_of(to_delayed_work(work), struct amdgpu_dm_connector,
4260 			     hdmi_hpd_debounce_work);
4261 	struct drm_connector *connector = &aconnector->base;
4262 	struct drm_device *dev = connector->dev;
4263 	struct amdgpu_device *adev = drm_to_adev(dev);
4264 	struct dc *dc = aconnector->dc_link->ctx->dc;
4265 	bool fake_reconnect = false;
4266 	bool reallow_idle = false;
4267 	bool ret = false;
4268 	guard(mutex)(&aconnector->hpd_lock);
4269 
4270 	/* Re-detect the display */
4271 	scoped_guard(mutex, &adev->dm.dc_lock) {
4272 		if (dc->caps.ips_support && dc->ctx->dmub_srv->idle_allowed) {
4273 			dc_allow_idle_optimizations(dc, false);
4274 			reallow_idle = true;
4275 		}
4276 		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4277 	}
4278 
4279 	if (ret) {
4280 		/* Apply workaround delay for certain panels */
4281 		apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4282 		/* Compare sinks to determine if this was a spontaneous HPD toggle */
4283 		if (are_sinks_equal(aconnector->dc_link->local_sink, aconnector->hdmi_prev_sink)) {
4284 			/*
4285 			* Sinks match - this was a spontaneous HDMI HPD toggle.
4286 			*/
4287 			drm_dbg_kms(dev, "HDMI HPD: Sink unchanged after debounce, internal re-enable\n");
4288 			fake_reconnect = true;
4289 		}
4290 
4291 		/* Update connector state */
4292 		amdgpu_dm_update_connector_after_detect(aconnector);
4293 
4294 		drm_modeset_lock_all(dev);
4295 		dm_restore_drm_connector_state(dev, connector);
4296 		drm_modeset_unlock_all(dev);
4297 
4298 		/* Only notify OS if sink actually changed */
4299 		if (!fake_reconnect && aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4300 			drm_kms_helper_hotplug_event(dev);
4301 	}
4302 
4303 	/* Release the cached sink reference */
4304 	if (aconnector->hdmi_prev_sink) {
4305 		dc_sink_release(aconnector->hdmi_prev_sink);
4306 		aconnector->hdmi_prev_sink = NULL;
4307 	}
4308 
4309 	scoped_guard(mutex, &adev->dm.dc_lock) {
4310 		if (reallow_idle && dc->caps.ips_support)
4311 			dc_allow_idle_optimizations(dc, true);
4312 	}
4313 }
4314 
4315 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
4316 {
4317 	struct drm_connector *connector = &aconnector->base;
4318 	struct drm_device *dev = connector->dev;
4319 	enum dc_connection_type new_connection_type = dc_connection_none;
4320 	struct amdgpu_device *adev = drm_to_adev(dev);
4321 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
4322 	struct dc *dc = aconnector->dc_link->ctx->dc;
4323 	bool ret = false;
4324 	bool debounce_required = false;
4325 
4326 	if (adev->dm.disable_hpd_irq)
4327 		return;
4328 
4329 	/*
4330 	 * In case of failure or MST no need to update connector status or notify the OS
4331 	 * since (for MST case) MST does this in its own context.
4332 	 */
4333 	guard(mutex)(&aconnector->hpd_lock);
4334 
4335 	if (adev->dm.hdcp_workqueue) {
4336 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
4337 		dm_con_state->update_hdcp = true;
4338 	}
4339 	if (aconnector->fake_enable)
4340 		aconnector->fake_enable = false;
4341 
4342 	aconnector->timing_changed = false;
4343 
4344 	if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
4345 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4346 
4347 	/*
4348 	 * Check for HDMI disconnect with debounce enabled.
4349 	 */
4350 	debounce_required = (aconnector->hdmi_hpd_debounce_delay_ms > 0 &&
4351 			      dc_is_hdmi_signal(aconnector->dc_link->connector_signal) &&
4352 			      new_connection_type == dc_connection_none &&
4353 			      aconnector->dc_link->local_sink != NULL);
4354 
4355 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
4356 		emulated_link_detect(aconnector->dc_link);
4357 
4358 		drm_modeset_lock_all(dev);
4359 		dm_restore_drm_connector_state(dev, connector);
4360 		drm_modeset_unlock_all(dev);
4361 
4362 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4363 			drm_kms_helper_connector_hotplug_event(connector);
4364 	} else if (debounce_required) {
4365 		/*
4366 		 * HDMI disconnect detected - schedule delayed work instead of
4367 		 * processing immediately. This allows us to coalesce spurious
4368 		 * HDMI signals from physical unplugs.
4369 		 */
4370 		drm_dbg_kms(dev, "HDMI HPD: Disconnect detected, scheduling debounce work (%u ms)\n",
4371 			    aconnector->hdmi_hpd_debounce_delay_ms);
4372 
4373 		/* Cache the current sink for later comparison */
4374 		if (aconnector->hdmi_prev_sink)
4375 			dc_sink_release(aconnector->hdmi_prev_sink);
4376 		aconnector->hdmi_prev_sink = aconnector->dc_link->local_sink;
4377 		if (aconnector->hdmi_prev_sink)
4378 			dc_sink_retain(aconnector->hdmi_prev_sink);
4379 
4380 		/* Schedule delayed detection. */
4381 		if (mod_delayed_work(system_percpu_wq,
4382 				 &aconnector->hdmi_hpd_debounce_work,
4383 				 msecs_to_jiffies(aconnector->hdmi_hpd_debounce_delay_ms)))
4384 			drm_dbg_kms(dev, "HDMI HPD: Re-scheduled debounce work\n");
4385 
4386 	} else {
4387 
4388 		/* If the aconnector->hdmi_hpd_debounce_work is scheduled, exit early */
4389 		if (delayed_work_pending(&aconnector->hdmi_hpd_debounce_work))
4390 			return;
4391 
4392 		scoped_guard(mutex, &adev->dm.dc_lock) {
4393 			dc_exit_ips_for_hw_access(dc);
4394 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4395 		}
4396 		if (ret) {
4397 			/* w/a delay for certain panels */
4398 			apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4399 			amdgpu_dm_update_connector_after_detect(aconnector);
4400 
4401 			drm_modeset_lock_all(dev);
4402 			dm_restore_drm_connector_state(dev, connector);
4403 			drm_modeset_unlock_all(dev);
4404 
4405 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4406 				drm_kms_helper_connector_hotplug_event(connector);
4407 		}
4408 	}
4409 }
4410 
4411 static void handle_hpd_irq(void *param)
4412 {
4413 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4414 
4415 	handle_hpd_irq_helper(aconnector);
4416 
4417 }
4418 
4419 static void schedule_hpd_rx_offload_work(struct amdgpu_device *adev, struct hpd_rx_irq_offload_work_queue *offload_wq,
4420 							union hpd_irq_data hpd_irq_data)
4421 {
4422 	struct hpd_rx_irq_offload_work *offload_work = kzalloc_obj(*offload_work);
4423 
4424 	if (!offload_work) {
4425 		drm_err(adev_to_drm(adev), "Failed to allocate hpd_rx_irq_offload_work.\n");
4426 		return;
4427 	}
4428 
4429 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
4430 	offload_work->data = hpd_irq_data;
4431 	offload_work->offload_wq = offload_wq;
4432 	offload_work->adev = adev;
4433 
4434 	queue_work(offload_wq->wq, &offload_work->work);
4435 	drm_dbg_kms(adev_to_drm(adev), "queue work to handle hpd_rx offload work");
4436 }
4437 
4438 static void handle_hpd_rx_irq(void *param)
4439 {
4440 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4441 	struct drm_connector *connector = &aconnector->base;
4442 	struct drm_device *dev = connector->dev;
4443 	struct dc_link *dc_link = aconnector->dc_link;
4444 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
4445 	bool result = false;
4446 	enum dc_connection_type new_connection_type = dc_connection_none;
4447 	struct amdgpu_device *adev = drm_to_adev(dev);
4448 	union hpd_irq_data hpd_irq_data;
4449 	bool link_loss = false;
4450 	bool has_left_work = false;
4451 	int idx = dc_link->link_index;
4452 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
4453 	struct dc *dc = aconnector->dc_link->ctx->dc;
4454 
4455 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
4456 
4457 	if (adev->dm.disable_hpd_irq)
4458 		return;
4459 
4460 	/*
4461 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
4462 	 * conflict, after implement i2c helper, this mutex should be
4463 	 * retired.
4464 	 */
4465 	mutex_lock(&aconnector->hpd_lock);
4466 
4467 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
4468 						&link_loss, true, &has_left_work);
4469 
4470 	if (!has_left_work)
4471 		goto out;
4472 
4473 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
4474 		schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4475 		goto out;
4476 	}
4477 
4478 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
4479 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
4480 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
4481 			bool skip = false;
4482 
4483 			/*
4484 			 * DOWN_REP_MSG_RDY is also handled by polling method
4485 			 * mgr->cbs->poll_hpd_irq()
4486 			 */
4487 			spin_lock(&offload_wq->offload_lock);
4488 			skip = offload_wq->is_handling_mst_msg_rdy_event;
4489 
4490 			if (!skip)
4491 				offload_wq->is_handling_mst_msg_rdy_event = true;
4492 
4493 			spin_unlock(&offload_wq->offload_lock);
4494 
4495 			if (!skip)
4496 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4497 
4498 			goto out;
4499 		}
4500 
4501 		if (link_loss) {
4502 			bool skip = false;
4503 
4504 			spin_lock(&offload_wq->offload_lock);
4505 			skip = offload_wq->is_handling_link_loss;
4506 
4507 			if (!skip)
4508 				offload_wq->is_handling_link_loss = true;
4509 
4510 			spin_unlock(&offload_wq->offload_lock);
4511 
4512 			if (!skip)
4513 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4514 
4515 			goto out;
4516 		}
4517 	}
4518 
4519 out:
4520 	if (result && !is_mst_root_connector) {
4521 		/* Downstream Port status changed. */
4522 		if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
4523 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4524 
4525 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4526 			emulated_link_detect(dc_link);
4527 
4528 			if (aconnector->fake_enable)
4529 				aconnector->fake_enable = false;
4530 
4531 			amdgpu_dm_update_connector_after_detect(aconnector);
4532 
4533 
4534 			drm_modeset_lock_all(dev);
4535 			dm_restore_drm_connector_state(dev, connector);
4536 			drm_modeset_unlock_all(dev);
4537 
4538 			drm_kms_helper_connector_hotplug_event(connector);
4539 		} else {
4540 			bool ret = false;
4541 
4542 			mutex_lock(&adev->dm.dc_lock);
4543 			dc_exit_ips_for_hw_access(dc);
4544 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
4545 			mutex_unlock(&adev->dm.dc_lock);
4546 
4547 			if (ret) {
4548 				if (aconnector->fake_enable)
4549 					aconnector->fake_enable = false;
4550 
4551 				amdgpu_dm_update_connector_after_detect(aconnector);
4552 
4553 				drm_modeset_lock_all(dev);
4554 				dm_restore_drm_connector_state(dev, connector);
4555 				drm_modeset_unlock_all(dev);
4556 
4557 				drm_kms_helper_connector_hotplug_event(connector);
4558 			}
4559 		}
4560 	}
4561 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
4562 		if (adev->dm.hdcp_workqueue)
4563 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
4564 	}
4565 
4566 	if (dc_link->type != dc_connection_mst_branch)
4567 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
4568 
4569 	mutex_unlock(&aconnector->hpd_lock);
4570 }
4571 
4572 static int register_hpd_handlers(struct amdgpu_device *adev)
4573 {
4574 	struct drm_device *dev = adev_to_drm(adev);
4575 	struct drm_connector *connector;
4576 	struct amdgpu_dm_connector *aconnector;
4577 	const struct dc_link *dc_link;
4578 	struct dc_interrupt_params int_params = {0};
4579 
4580 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4581 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4582 
4583 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
4584 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD,
4585 			dmub_hpd_callback, true)) {
4586 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4587 			return -EINVAL;
4588 		}
4589 
4590 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ,
4591 			dmub_hpd_callback, true)) {
4592 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4593 			return -EINVAL;
4594 		}
4595 
4596 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_SENSE_NOTIFY,
4597 			dmub_hpd_sense_callback, true)) {
4598 			drm_err(adev_to_drm(adev), "fail to register dmub hpd sense callback");
4599 			return -EINVAL;
4600 		}
4601 	}
4602 
4603 	list_for_each_entry(connector,
4604 			&dev->mode_config.connector_list, head)	{
4605 
4606 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
4607 			continue;
4608 
4609 		aconnector = to_amdgpu_dm_connector(connector);
4610 		dc_link = aconnector->dc_link;
4611 
4612 		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
4613 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4614 			int_params.irq_source = dc_link->irq_source_hpd;
4615 
4616 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4617 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1 ||
4618 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6) {
4619 				drm_err(adev_to_drm(adev), "Failed to register hpd irq!\n");
4620 				return -EINVAL;
4621 			}
4622 
4623 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4624 				handle_hpd_irq, (void *) aconnector))
4625 				return -ENOMEM;
4626 		}
4627 
4628 		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
4629 
4630 			/* Also register for DP short pulse (hpd_rx). */
4631 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4632 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
4633 
4634 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4635 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1RX ||
4636 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6RX) {
4637 				drm_err(adev_to_drm(adev), "Failed to register hpd rx irq!\n");
4638 				return -EINVAL;
4639 			}
4640 
4641 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4642 				handle_hpd_rx_irq, (void *) aconnector))
4643 				return -ENOMEM;
4644 		}
4645 	}
4646 	return 0;
4647 }
4648 
4649 /* Register IRQ sources and initialize IRQ callbacks */
4650 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
4651 {
4652 	struct dc *dc = adev->dm.dc;
4653 	struct common_irq_params *c_irq_params;
4654 	struct dc_interrupt_params int_params = {0};
4655 	int r;
4656 	int i;
4657 	unsigned int src_id;
4658 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4659 	/* Use different interrupts for VBLANK on DCE 6 vs. newer. */
4660 	const unsigned int vblank_d1 =
4661 		adev->dm.dc->ctx->dce_version >= DCE_VERSION_8_0
4662 		? VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0 : 1;
4663 
4664 	if (adev->family >= AMDGPU_FAMILY_AI)
4665 		client_id = SOC15_IH_CLIENTID_DCE;
4666 
4667 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4668 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4669 
4670 	/*
4671 	 * Actions of amdgpu_irq_add_id():
4672 	 * 1. Register a set() function with base driver.
4673 	 *    Base driver will call set() function to enable/disable an
4674 	 *    interrupt in DC hardware.
4675 	 * 2. Register amdgpu_dm_irq_handler().
4676 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4677 	 *    coming from DC hardware.
4678 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4679 	 *    for acknowledging and handling.
4680 	 */
4681 
4682 	/* Use VBLANK interrupt */
4683 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
4684 		src_id = vblank_d1 + i;
4685 		r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->crtc_irq);
4686 		if (r) {
4687 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4688 			return r;
4689 		}
4690 
4691 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4692 		int_params.irq_source =
4693 			dc_interrupt_to_irq_source(dc, src_id, 0);
4694 
4695 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4696 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4697 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4698 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4699 			return -EINVAL;
4700 		}
4701 
4702 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4703 
4704 		c_irq_params->adev = adev;
4705 		c_irq_params->irq_src = int_params.irq_source;
4706 
4707 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4708 			dm_crtc_high_irq, c_irq_params))
4709 			return -ENOMEM;
4710 	}
4711 
4712 	if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
4713 		/* Use VUPDATE interrupt */
4714 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
4715 			src_id = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT + i * 2;
4716 			r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->vupdate_irq);
4717 			if (r) {
4718 				drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4719 				return r;
4720 			}
4721 
4722 			int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4723 			int_params.irq_source =
4724 				dc_interrupt_to_irq_source(dc, src_id, 0);
4725 
4726 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4727 				int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4728 				int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4729 				drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4730 				return -EINVAL;
4731 			}
4732 
4733 			c_irq_params = &adev->dm.vupdate_params[
4734 				int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4735 			c_irq_params->adev = adev;
4736 			c_irq_params->irq_src = int_params.irq_source;
4737 
4738 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4739 				dm_vupdate_high_irq, c_irq_params))
4740 				return -ENOMEM;
4741 		}
4742 	}
4743 
4744 	/* Use GRPH_PFLIP interrupt */
4745 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4746 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4747 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4748 		if (r) {
4749 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4750 			return r;
4751 		}
4752 
4753 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4754 		int_params.irq_source =
4755 			dc_interrupt_to_irq_source(dc, i, 0);
4756 
4757 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4758 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4759 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4760 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4761 			return -EINVAL;
4762 		}
4763 
4764 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4765 
4766 		c_irq_params->adev = adev;
4767 		c_irq_params->irq_src = int_params.irq_source;
4768 
4769 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4770 			dm_pflip_high_irq, c_irq_params))
4771 			return -ENOMEM;
4772 	}
4773 
4774 	/* HPD */
4775 	r = amdgpu_irq_add_id(adev, client_id,
4776 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4777 	if (r) {
4778 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4779 		return r;
4780 	}
4781 
4782 	r = register_hpd_handlers(adev);
4783 
4784 	return r;
4785 }
4786 
4787 /* Register IRQ sources and initialize IRQ callbacks */
4788 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
4789 {
4790 	struct dc *dc = adev->dm.dc;
4791 	struct common_irq_params *c_irq_params;
4792 	struct dc_interrupt_params int_params = {0};
4793 	int r;
4794 	int i;
4795 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4796 	static const unsigned int vrtl_int_srcid[] = {
4797 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
4798 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
4799 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
4800 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
4801 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
4802 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
4803 	};
4804 #endif
4805 
4806 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4807 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4808 
4809 	/*
4810 	 * Actions of amdgpu_irq_add_id():
4811 	 * 1. Register a set() function with base driver.
4812 	 *    Base driver will call set() function to enable/disable an
4813 	 *    interrupt in DC hardware.
4814 	 * 2. Register amdgpu_dm_irq_handler().
4815 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4816 	 *    coming from DC hardware.
4817 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4818 	 *    for acknowledging and handling.
4819 	 */
4820 
4821 	/* Use VSTARTUP interrupt */
4822 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
4823 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
4824 			i++) {
4825 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
4826 
4827 		if (r) {
4828 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4829 			return r;
4830 		}
4831 
4832 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4833 		int_params.irq_source =
4834 			dc_interrupt_to_irq_source(dc, i, 0);
4835 
4836 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4837 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4838 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4839 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4840 			return -EINVAL;
4841 		}
4842 
4843 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4844 
4845 		c_irq_params->adev = adev;
4846 		c_irq_params->irq_src = int_params.irq_source;
4847 
4848 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4849 			dm_crtc_high_irq, c_irq_params))
4850 			return -ENOMEM;
4851 	}
4852 
4853 	/* Use otg vertical line interrupt */
4854 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4855 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
4856 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
4857 				vrtl_int_srcid[i], &adev->vline0_irq);
4858 
4859 		if (r) {
4860 			drm_err(adev_to_drm(adev), "Failed to add vline0 irq id!\n");
4861 			return r;
4862 		}
4863 
4864 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4865 		int_params.irq_source =
4866 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
4867 
4868 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4869 			int_params.irq_source < DC_IRQ_SOURCE_DC1_VLINE0 ||
4870 			int_params.irq_source > DC_IRQ_SOURCE_DC6_VLINE0) {
4871 			drm_err(adev_to_drm(adev), "Failed to register vline0 irq!\n");
4872 			return -EINVAL;
4873 		}
4874 
4875 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
4876 					- DC_IRQ_SOURCE_DC1_VLINE0];
4877 
4878 		c_irq_params->adev = adev;
4879 		c_irq_params->irq_src = int_params.irq_source;
4880 
4881 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4882 			dm_dcn_vertical_interrupt0_high_irq,
4883 			c_irq_params))
4884 			return -ENOMEM;
4885 	}
4886 #endif
4887 
4888 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
4889 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
4890 	 * to trigger at end of each vblank, regardless of state of the lock,
4891 	 * matching DCE behaviour.
4892 	 */
4893 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
4894 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
4895 	     i++) {
4896 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
4897 
4898 		if (r) {
4899 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4900 			return r;
4901 		}
4902 
4903 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4904 		int_params.irq_source =
4905 			dc_interrupt_to_irq_source(dc, i, 0);
4906 
4907 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4908 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4909 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4910 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4911 			return -EINVAL;
4912 		}
4913 
4914 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4915 
4916 		c_irq_params->adev = adev;
4917 		c_irq_params->irq_src = int_params.irq_source;
4918 
4919 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4920 			dm_vupdate_high_irq, c_irq_params))
4921 			return -ENOMEM;
4922 	}
4923 
4924 	/* Use GRPH_PFLIP interrupt */
4925 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
4926 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
4927 			i++) {
4928 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
4929 		if (r) {
4930 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4931 			return r;
4932 		}
4933 
4934 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4935 		int_params.irq_source =
4936 			dc_interrupt_to_irq_source(dc, i, 0);
4937 
4938 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4939 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4940 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4941 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4942 			return -EINVAL;
4943 		}
4944 
4945 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4946 
4947 		c_irq_params->adev = adev;
4948 		c_irq_params->irq_src = int_params.irq_source;
4949 
4950 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4951 			dm_pflip_high_irq, c_irq_params))
4952 			return -ENOMEM;
4953 	}
4954 
4955 	/* HPD */
4956 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
4957 			&adev->hpd_irq);
4958 	if (r) {
4959 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4960 		return r;
4961 	}
4962 
4963 	r = register_hpd_handlers(adev);
4964 
4965 	return r;
4966 }
4967 /* Register Outbox IRQ sources and initialize IRQ callbacks */
4968 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
4969 {
4970 	struct dc *dc = adev->dm.dc;
4971 	struct common_irq_params *c_irq_params;
4972 	struct dc_interrupt_params int_params = {0};
4973 	int r, i;
4974 
4975 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4976 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4977 
4978 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
4979 			&adev->dmub_outbox_irq);
4980 	if (r) {
4981 		drm_err(adev_to_drm(adev), "Failed to add outbox irq id!\n");
4982 		return r;
4983 	}
4984 
4985 	if (dc->ctx->dmub_srv) {
4986 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
4987 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4988 		int_params.irq_source =
4989 		dc_interrupt_to_irq_source(dc, i, 0);
4990 
4991 		c_irq_params = &adev->dm.dmub_outbox_params[0];
4992 
4993 		c_irq_params->adev = adev;
4994 		c_irq_params->irq_src = int_params.irq_source;
4995 
4996 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4997 			dm_dmub_outbox1_low_irq, c_irq_params))
4998 			return -ENOMEM;
4999 	}
5000 
5001 	return 0;
5002 }
5003 
5004 /*
5005  * Acquires the lock for the atomic state object and returns
5006  * the new atomic state.
5007  *
5008  * This should only be called during atomic check.
5009  */
5010 int dm_atomic_get_state(struct drm_atomic_commit *state,
5011 			struct dm_atomic_state **dm_state)
5012 {
5013 	struct drm_device *dev = state->dev;
5014 	struct amdgpu_device *adev = drm_to_adev(dev);
5015 	struct amdgpu_display_manager *dm = &adev->dm;
5016 	struct drm_private_state *priv_state;
5017 
5018 	if (*dm_state)
5019 		return 0;
5020 
5021 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
5022 	if (IS_ERR(priv_state))
5023 		return PTR_ERR(priv_state);
5024 
5025 	*dm_state = to_dm_atomic_state(priv_state);
5026 
5027 	return 0;
5028 }
5029 
5030 static struct dm_atomic_state *
5031 dm_atomic_get_new_state(struct drm_atomic_commit *state)
5032 {
5033 	struct drm_device *dev = state->dev;
5034 	struct amdgpu_device *adev = drm_to_adev(dev);
5035 	struct amdgpu_display_manager *dm = &adev->dm;
5036 	struct drm_private_obj *obj;
5037 	struct drm_private_state *new_obj_state;
5038 	int i;
5039 
5040 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
5041 		if (obj->funcs == dm->atomic_obj.funcs)
5042 			return to_dm_atomic_state(new_obj_state);
5043 	}
5044 
5045 	return NULL;
5046 }
5047 
5048 static struct drm_private_state *
5049 dm_atomic_duplicate_state(struct drm_private_obj *obj)
5050 {
5051 	struct dm_atomic_state *old_state, *new_state;
5052 
5053 	new_state = kzalloc_obj(*new_state);
5054 	if (!new_state)
5055 		return NULL;
5056 
5057 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
5058 
5059 	old_state = to_dm_atomic_state(obj->state);
5060 
5061 	if (old_state && old_state->context)
5062 		new_state->context = dc_state_create_copy(old_state->context);
5063 
5064 	if (!new_state->context) {
5065 		kfree(new_state);
5066 		return NULL;
5067 	}
5068 
5069 	return &new_state->base;
5070 }
5071 
5072 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
5073 				    struct drm_private_state *state)
5074 {
5075 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
5076 
5077 	if (dm_state && dm_state->context)
5078 		dc_state_release(dm_state->context);
5079 
5080 	kfree(dm_state);
5081 }
5082 
5083 static struct drm_private_state *
5084 dm_atomic_create_state(struct drm_private_obj *obj)
5085 {
5086 	struct amdgpu_device *adev = drm_to_adev(obj->dev);
5087 	struct dm_atomic_state *dm_state;
5088 	struct dc_state *context;
5089 
5090 	dm_state = kzalloc_obj(*dm_state);
5091 	if (!dm_state)
5092 		return ERR_PTR(-ENOMEM);
5093 
5094 	context = dc_state_create_current_copy(adev->dm.dc);
5095 	if (!context) {
5096 		kfree(dm_state);
5097 		return ERR_PTR(-ENOMEM);
5098 	}
5099 
5100 	__drm_atomic_helper_private_obj_create_state(obj, &dm_state->base);
5101 	dm_state->context = context;
5102 
5103 	return &dm_state->base;
5104 }
5105 
5106 static struct drm_private_state_funcs dm_atomic_state_funcs = {
5107 	.atomic_create_state = dm_atomic_create_state,
5108 	.atomic_duplicate_state = dm_atomic_duplicate_state,
5109 	.atomic_destroy_state = dm_atomic_destroy_state,
5110 };
5111 
5112 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
5113 {
5114 	int r;
5115 
5116 	adev->mode_info.mode_config_initialized = true;
5117 
5118 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
5119 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
5120 
5121 	adev_to_drm(adev)->mode_config.max_width = 16384;
5122 	adev_to_drm(adev)->mode_config.max_height = 16384;
5123 
5124 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
5125 	if (adev->asic_type == CHIP_HAWAII)
5126 		/* disable prefer shadow for now due to hibernation issues */
5127 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
5128 	else
5129 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
5130 	/* indicates support for immediate flip */
5131 	adev_to_drm(adev)->mode_config.async_page_flip = true;
5132 
5133 	drm_atomic_private_obj_init(adev_to_drm(adev),
5134 				    &adev->dm.atomic_obj,
5135 				    &dm_atomic_state_funcs);
5136 
5137 	r = amdgpu_display_modeset_create_props(adev);
5138 	if (r)
5139 		return r;
5140 
5141 #ifdef AMD_PRIVATE_COLOR
5142 	if (amdgpu_dm_create_color_properties(adev))
5143 		return -ENOMEM;
5144 #endif
5145 
5146 	r = amdgpu_dm_audio_init(adev);
5147 	if (r)
5148 		return r;
5149 
5150 	return 0;
5151 }
5152 
5153 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
5154 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
5155 #define AMDGPU_DM_MIN_SPREAD ((AMDGPU_DM_DEFAULT_MAX_BACKLIGHT - AMDGPU_DM_DEFAULT_MIN_BACKLIGHT) / 2)
5156 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
5157 
5158 void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
5159 				     int bl_idx)
5160 {
5161 	struct amdgpu_dm_backlight_caps *caps = &dm->backlight_caps[bl_idx];
5162 
5163 	if (caps->caps_valid)
5164 		return;
5165 
5166 #if defined(CONFIG_ACPI)
5167 	amdgpu_acpi_get_backlight_caps(caps);
5168 
5169 	/* validate the firmware value is sane */
5170 	if (caps->caps_valid) {
5171 		int spread = caps->max_input_signal - caps->min_input_signal;
5172 
5173 		if (caps->max_input_signal > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5174 		    caps->min_input_signal < 0 ||
5175 		    spread > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5176 		    spread < AMDGPU_DM_MIN_SPREAD) {
5177 			drm_dbg_kms(adev_to_drm(dm->adev), "DM: Invalid backlight caps: min=%d, max=%d\n",
5178 				      caps->min_input_signal, caps->max_input_signal);
5179 			caps->caps_valid = false;
5180 		}
5181 	}
5182 
5183 	if (!caps->caps_valid) {
5184 		caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5185 		caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5186 		caps->caps_valid = true;
5187 	}
5188 #else
5189 	if (caps->aux_support)
5190 		return;
5191 
5192 	caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5193 	caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5194 	caps->caps_valid = true;
5195 #endif
5196 }
5197 
5198 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
5199 				unsigned int *min, unsigned int *max)
5200 {
5201 	if (!caps)
5202 		return 0;
5203 
5204 	if (caps->aux_support) {
5205 		// Firmware limits are in nits, DC API wants millinits.
5206 		*max = 1000 * caps->aux_max_input_signal;
5207 		*min = 1000 * caps->aux_min_input_signal;
5208 	} else {
5209 		// Firmware limits are 8-bit, PWM control is 16-bit.
5210 		*max = 0x101 * caps->max_input_signal;
5211 		*min = 0x101 * caps->min_input_signal;
5212 	}
5213 	return 1;
5214 }
5215 
5216 /* Rescale from [min..max] to [0..AMDGPU_MAX_BL_LEVEL] */
5217 static inline u32 scale_input_to_fw(int min, int max, u64 input)
5218 {
5219 	return DIV_ROUND_CLOSEST_ULL(input * AMDGPU_MAX_BL_LEVEL, max - min);
5220 }
5221 
5222 /* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [min..max] */
5223 static inline u32 scale_fw_to_input(int min, int max, u64 input)
5224 {
5225 	return min + DIV_ROUND_CLOSEST_ULL(input * (max - min), AMDGPU_MAX_BL_LEVEL);
5226 }
5227 
5228 static void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps,
5229 				      unsigned int min, unsigned int max,
5230 				      uint32_t *user_brightness)
5231 {
5232 	u32 brightness = scale_input_to_fw(min, max, *user_brightness);
5233 	u8 lower_signal, upper_signal, upper_lum, lower_lum, lum;
5234 	int left, right;
5235 
5236 	if (amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)
5237 		return;
5238 
5239 	if (!caps->data_points)
5240 		return;
5241 
5242 	/*
5243 	 * Handle the case where brightness is below the first data point
5244 	 * Interpolate between (0,0) and (first_signal, first_lum)
5245 	 */
5246 	if (brightness < caps->luminance_data[0].input_signal) {
5247 		lum = DIV_ROUND_CLOSEST(caps->luminance_data[0].luminance * brightness,
5248 					caps->luminance_data[0].input_signal);
5249 		goto scale;
5250 	}
5251 
5252 	left = 0;
5253 	right = caps->data_points - 1;
5254 	while (left <= right) {
5255 		int mid = left + (right - left) / 2;
5256 		u8 signal = caps->luminance_data[mid].input_signal;
5257 
5258 		/* Exact match found */
5259 		if (signal == brightness) {
5260 			lum = caps->luminance_data[mid].luminance;
5261 			goto scale;
5262 		}
5263 
5264 		if (signal < brightness)
5265 			left = mid + 1;
5266 		else
5267 			right = mid - 1;
5268 	}
5269 
5270 	/* verify bound */
5271 	if (left >= caps->data_points)
5272 		left = caps->data_points - 1;
5273 
5274 	/* At this point, left > right */
5275 	lower_signal = caps->luminance_data[right].input_signal;
5276 	upper_signal = caps->luminance_data[left].input_signal;
5277 	lower_lum = caps->luminance_data[right].luminance;
5278 	upper_lum = caps->luminance_data[left].luminance;
5279 
5280 	/* interpolate */
5281 	if (right == left || !lower_lum)
5282 		lum = upper_lum;
5283 	else
5284 		lum = lower_lum + DIV_ROUND_CLOSEST((upper_lum - lower_lum) *
5285 						    (brightness - lower_signal),
5286 						    upper_signal - lower_signal);
5287 scale:
5288 	*user_brightness = scale_fw_to_input(min, max,
5289 					     DIV_ROUND_CLOSEST(lum * brightness, 101));
5290 }
5291 
5292 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
5293 					uint32_t brightness)
5294 {
5295 	unsigned int min, max;
5296 
5297 	if (!get_brightness_range(caps, &min, &max))
5298 		return brightness;
5299 
5300 	convert_custom_brightness(caps, min, max, &brightness);
5301 
5302 	// Rescale 0..max to min..max
5303 	return min + DIV_ROUND_CLOSEST_ULL((u64)(max - min) * brightness, max);
5304 }
5305 
5306 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
5307 				      uint32_t brightness)
5308 {
5309 	unsigned int min, max;
5310 
5311 	if (!get_brightness_range(caps, &min, &max))
5312 		return brightness;
5313 
5314 	if (brightness < min)
5315 		return 0;
5316 	// Rescale min..max to 0..max
5317 	return DIV_ROUND_CLOSEST_ULL((u64)max * (brightness - min),
5318 				 max - min);
5319 }
5320 
5321 static struct dc_stream_state *dm_find_stream_with_link(
5322 	struct amdgpu_display_manager *dm,
5323 	struct dc_link *link)
5324 {
5325 	struct dc_state *cur_dc_state = dm->dc->current_state;
5326 	struct dc_stream_state *stream = NULL;
5327 	int i;
5328 
5329 	for (i = 0; i < cur_dc_state->stream_count; i++) {
5330 		stream = cur_dc_state->streams[i];
5331 		if (stream->link == link)
5332 			return stream;
5333 	}
5334 
5335 	return NULL;
5336 }
5337 
5338 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
5339 					 int bl_idx,
5340 					 u32 user_brightness)
5341 {
5342 	struct amdgpu_dm_backlight_caps *caps;
5343 	struct dc_link *link;
5344 	u32 brightness = 0;
5345 	bool rc = false, reallow_idle = false;
5346 	struct drm_connector *connector;
5347 	struct dc_stream_state *stream;
5348 	unsigned int min, max;
5349 
5350 	list_for_each_entry(connector, &dm->ddev->mode_config.connector_list, head) {
5351 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5352 
5353 		if (aconnector->bl_idx != bl_idx)
5354 			continue;
5355 
5356 		/* if connector is off, save the brightness for next time it's on */
5357 		if (!aconnector->base.encoder) {
5358 			dm->brightness[bl_idx] = user_brightness;
5359 			dm->actual_brightness[bl_idx] = 0;
5360 			return;
5361 		}
5362 	}
5363 
5364 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5365 	caps = &dm->backlight_caps[bl_idx];
5366 
5367 	dm->brightness[bl_idx] = user_brightness;
5368 	/* update scratch register */
5369 	if (bl_idx == 0)
5370 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
5371 	brightness = convert_brightness_from_user(caps, dm->brightness[bl_idx]);
5372 	link = (struct dc_link *)dm->backlight_link[bl_idx];
5373 
5374 	/* Apply brightness quirk */
5375 	if (caps->brightness_mask)
5376 		brightness |= caps->brightness_mask;
5377 
5378 	if (trace_amdgpu_dm_brightness_enabled()) {
5379 		trace_amdgpu_dm_brightness(__builtin_return_address(0),
5380 					   user_brightness,
5381 					   brightness,
5382 					   caps->aux_support,
5383 					   power_supply_is_system_supplied() > 0);
5384 	}
5385 
5386 	stream = dm_find_stream_with_link(dm, link);
5387 	if (!stream)
5388 		return;
5389 
5390 	mutex_lock(&dm->dc_lock);
5391 	if (dm->dc->caps.ips_support && dm->dc->ctx->dmub_srv->idle_allowed) {
5392 		dc_allow_idle_optimizations(dm->dc, false);
5393 		reallow_idle = true;
5394 	}
5395 
5396 	if (caps->aux_support) {
5397 		rc = mod_power_set_backlight_nits(dm->power_module, stream, brightness,
5398 			AUX_BL_DEFAULT_TRANSITION_TIME_MS, false, true);
5399 	} else {
5400 		/* power module uses millipercent */
5401 		get_brightness_range(caps, &min, &max);
5402 		brightness = DIV_ROUND_CLOSEST(brightness * 100, (max - min)) * 1000;
5403 		rc = mod_power_set_backlight_percent(dm->power_module, stream,
5404 						     brightness, 0, false);
5405 	}
5406 
5407 	/*
5408 	 * Some kms clients create a ramped backlight transition effect
5409 	 * by rapidly changing the backlight. Yet we must wait on dmcub
5410 	 * fw to exit psr/replay before programming backlight. To
5411 	 * prevent lag, keep disable psr/replay and let the next atomic
5412 	 * flip clear the event.
5413 	 *
5414 	 * ToDo: use ISM to handle rapidly backlight change
5415 	 *
5416 	 * Rapidly backlight change is similar to rapidly cursor events,
5417 	 * which is now handled by ISM. ISM can delay the event until system
5418 	 * is really idle, so we may use ISM to handle backlight change as well.
5419 	 */
5420 	amdgpu_dm_psr_set_event(dm, stream, true,
5421 		psr_event_hw_programming, true);
5422 	amdgpu_dm_replay_set_event(dm, stream, true,
5423 		replay_event_hw_programming, true);
5424 
5425 	if (dm->dc->caps.ips_support && reallow_idle)
5426 		dc_allow_idle_optimizations(dm->dc, true);
5427 
5428 	mutex_unlock(&dm->dc_lock);
5429 
5430 	if (rc)
5431 		dm->actual_brightness[bl_idx] = user_brightness;
5432 }
5433 
5434 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
5435 {
5436 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5437 	int i;
5438 
5439 	for (i = 0; i < dm->num_of_edps; i++) {
5440 		if (bd == dm->backlight_dev[i])
5441 			break;
5442 	}
5443 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5444 		i = 0;
5445 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
5446 
5447 	return 0;
5448 }
5449 
5450 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
5451 					 int bl_idx)
5452 {
5453 	int ret;
5454 	struct amdgpu_dm_backlight_caps caps;
5455 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
5456 
5457 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5458 	caps = dm->backlight_caps[bl_idx];
5459 
5460 	if (caps.aux_support) {
5461 		u32 avg, peak;
5462 
5463 		if (!dc_link_get_backlight_level_nits(link, &avg, &peak))
5464 			return dm->brightness[bl_idx];
5465 		return convert_brightness_to_user(&caps, avg);
5466 	}
5467 
5468 	ret = dc_link_get_backlight_level(link);
5469 
5470 	if (ret == DC_ERROR_UNEXPECTED)
5471 		return dm->brightness[bl_idx];
5472 
5473 	return convert_brightness_to_user(&caps, ret);
5474 }
5475 
5476 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
5477 {
5478 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5479 	int i;
5480 
5481 	for (i = 0; i < dm->num_of_edps; i++) {
5482 		if (bd == dm->backlight_dev[i])
5483 			break;
5484 	}
5485 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5486 		i = 0;
5487 	return amdgpu_dm_backlight_get_level(dm, i);
5488 }
5489 
5490 static const struct backlight_ops amdgpu_dm_backlight_ops = {
5491 	.options = BL_CORE_SUSPENDRESUME,
5492 	.get_brightness = amdgpu_dm_backlight_get_brightness,
5493 	.update_status	= amdgpu_dm_backlight_update_status,
5494 };
5495 
5496 static void
5497 amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector *aconnector)
5498 {
5499 	struct drm_device *drm = aconnector->base.dev;
5500 	struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
5501 	struct backlight_properties props = { 0 };
5502 	struct amdgpu_dm_backlight_caps *caps;
5503 	char bl_name[16];
5504 	int min, max;
5505 	int real_brightness;
5506 	int init_brightness;
5507 
5508 	if (aconnector->bl_idx == -1)
5509 		return;
5510 
5511 	if (!acpi_video_backlight_use_native()) {
5512 		drm_info(drm, "Skipping amdgpu DM backlight registration\n");
5513 		/* Try registering an ACPI video backlight device instead. */
5514 		acpi_video_register_backlight();
5515 		return;
5516 	}
5517 
5518 	caps = &dm->backlight_caps[aconnector->bl_idx];
5519 	if (get_brightness_range(caps, &min, &max)) {
5520 		if (power_supply_is_system_supplied() > 0)
5521 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->ac_level, 100);
5522 		else
5523 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->dc_level, 100);
5524 		/* min is zero, so max needs to be adjusted */
5525 		props.max_brightness = max - min;
5526 		drm_dbg(drm, "Backlight caps: min: %d, max: %d, ac %d, dc %d\n", min, max,
5527 			caps->ac_level, caps->dc_level);
5528 	} else
5529 		props.brightness = props.max_brightness = MAX_BACKLIGHT_LEVEL;
5530 
5531 	init_brightness = props.brightness;
5532 
5533 	if (caps->data_points && !(amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)) {
5534 		drm_info(drm, "Using custom brightness curve\n");
5535 		props.scale = BACKLIGHT_SCALE_NON_LINEAR;
5536 	} else
5537 		props.scale = BACKLIGHT_SCALE_LINEAR;
5538 	props.type = BACKLIGHT_RAW;
5539 
5540 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
5541 		 drm->primary->index + aconnector->bl_idx);
5542 
5543 	dm->backlight_dev[aconnector->bl_idx] =
5544 		backlight_device_register(bl_name, aconnector->base.kdev, dm,
5545 					  &amdgpu_dm_backlight_ops, &props);
5546 	dm->brightness[aconnector->bl_idx] = props.brightness;
5547 
5548 	if (IS_ERR(dm->backlight_dev[aconnector->bl_idx])) {
5549 		drm_err(drm, "DM: Backlight registration failed!\n");
5550 		dm->backlight_dev[aconnector->bl_idx] = NULL;
5551 	} else {
5552 		/*
5553 		 * dm->brightness[x] can be inconsistent just after startup until
5554 		 * ops.get_brightness is called.
5555 		 */
5556 		real_brightness =
5557 			amdgpu_dm_backlight_ops.get_brightness(dm->backlight_dev[aconnector->bl_idx]);
5558 
5559 		if (real_brightness != init_brightness) {
5560 			dm->actual_brightness[aconnector->bl_idx] = real_brightness;
5561 			dm->brightness[aconnector->bl_idx] = real_brightness;
5562 		}
5563 		drm_dbg_driver(drm, "DM: Registered Backlight device: %s\n", bl_name);
5564 	}
5565 }
5566 
5567 static int initialize_plane(struct amdgpu_display_manager *dm,
5568 			    struct amdgpu_mode_info *mode_info, int plane_id,
5569 			    enum drm_plane_type plane_type,
5570 			    const struct dc_plane_cap *plane_cap)
5571 {
5572 	struct drm_plane *plane;
5573 	unsigned long possible_crtcs;
5574 	int ret = 0;
5575 
5576 	plane = kzalloc_obj(struct drm_plane);
5577 	if (!plane) {
5578 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
5579 		return -ENOMEM;
5580 	}
5581 	plane->type = plane_type;
5582 
5583 	/*
5584 	 * HACK: IGT tests expect that the primary plane for a CRTC
5585 	 * can only have one possible CRTC. Only expose support for
5586 	 * any CRTC if they're not going to be used as a primary plane
5587 	 * for a CRTC - like overlay or underlay planes.
5588 	 */
5589 	possible_crtcs = 1 << plane_id;
5590 	if (plane_id >= dm->dc->caps.max_streams)
5591 		possible_crtcs = 0xff;
5592 
5593 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
5594 
5595 	if (ret) {
5596 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
5597 		kfree(plane);
5598 		return ret;
5599 	}
5600 
5601 	if (mode_info)
5602 		mode_info->planes[plane_id] = plane;
5603 
5604 	return ret;
5605 }
5606 
5607 
5608 static void setup_backlight_device(struct amdgpu_display_manager *dm,
5609 				   struct amdgpu_dm_connector *aconnector)
5610 {
5611 	struct amdgpu_dm_backlight_caps *caps;
5612 	struct dc_link *link = aconnector->dc_link;
5613 	int bl_idx = dm->num_of_edps;
5614 
5615 	if (!(link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) ||
5616 	    link->type == dc_connection_none)
5617 		return;
5618 
5619 	if (dm->num_of_edps >= AMDGPU_DM_MAX_NUM_EDP) {
5620 		drm_warn(adev_to_drm(dm->adev), "Too much eDP connections, skipping backlight setup for additional eDPs\n");
5621 		return;
5622 	}
5623 
5624 	aconnector->bl_idx = bl_idx;
5625 
5626 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5627 	dm->backlight_link[bl_idx] = link;
5628 	dm->num_of_edps++;
5629 
5630 	update_connector_ext_caps(aconnector);
5631 	caps = &dm->backlight_caps[aconnector->bl_idx];
5632 
5633 	/* Only offer ABM property when non-OLED and user didn't turn off by module parameter */
5634 	if (caps->ext_caps && !caps->ext_caps->bits.oled && amdgpu_dm_abm_level < 0)
5635 		drm_object_attach_property(&aconnector->base.base,
5636 					   dm->adev->mode_info.abm_level_property,
5637 					   ABM_SYSFS_CONTROL);
5638 }
5639 
5640 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
5641 
5642 
5643 
5644 /*
5645  * In this architecture, the association
5646  * connector -> encoder -> crtc
5647  * id not really requried. The crtc and connector will hold the
5648  * display_index as an abstraction to use with DAL component
5649  *
5650  * Returns 0 on success
5651  */
5652 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
5653 {
5654 	struct amdgpu_display_manager *dm = &adev->dm;
5655 	s32 i;
5656 	struct amdgpu_dm_connector *aconnector = NULL;
5657 	struct amdgpu_encoder *aencoder = NULL;
5658 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5659 	u32 link_cnt;
5660 	s32 primary_planes;
5661 	enum dc_connection_type new_connection_type = dc_connection_none;
5662 	const struct dc_plane_cap *plane;
5663 	bool psr_feature_enabled = false;
5664 	bool replay_feature_enabled = false;
5665 	int max_overlay = dm->dc->caps.max_slave_planes;
5666 
5667 	dm->display_indexes_num = dm->dc->caps.max_streams;
5668 	/* Update the actual used number of crtc */
5669 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
5670 
5671 	amdgpu_dm_set_irq_funcs(adev);
5672 
5673 	link_cnt = dm->dc->caps.max_links;
5674 	if (amdgpu_dm_mode_config_init(dm->adev)) {
5675 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
5676 		return -EINVAL;
5677 	}
5678 
5679 	/* There is one primary plane per CRTC */
5680 	primary_planes = dm->dc->caps.max_streams;
5681 	if (primary_planes > AMDGPU_MAX_PLANES) {
5682 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
5683 		return -EINVAL;
5684 	}
5685 
5686 	/*
5687 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
5688 	 * Order is reversed to match iteration order in atomic check.
5689 	 */
5690 	for (i = (primary_planes - 1); i >= 0; i--) {
5691 		plane = &dm->dc->caps.planes[i];
5692 
5693 		if (initialize_plane(dm, mode_info, i,
5694 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
5695 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
5696 			goto fail;
5697 		}
5698 	}
5699 
5700 	/*
5701 	 * Initialize overlay planes, index starting after primary planes.
5702 	 * These planes have a higher DRM index than the primary planes since
5703 	 * they should be considered as having a higher z-order.
5704 	 * Order is reversed to match iteration order in atomic check.
5705 	 *
5706 	 * Only support DCN for now, and only expose one so we don't encourage
5707 	 * userspace to use up all the pipes.
5708 	 */
5709 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
5710 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
5711 
5712 		/* Do not create overlay if MPO disabled */
5713 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
5714 			break;
5715 
5716 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
5717 			continue;
5718 
5719 		if (!plane->pixel_format_support.argb8888)
5720 			continue;
5721 
5722 		if (max_overlay-- == 0)
5723 			break;
5724 
5725 		if (initialize_plane(dm, NULL, primary_planes + i,
5726 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
5727 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
5728 			goto fail;
5729 		}
5730 	}
5731 
5732 	for (i = 0; i < dm->dc->caps.max_streams; i++)
5733 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
5734 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
5735 			goto fail;
5736 		}
5737 
5738 	/* Use Outbox interrupt */
5739 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5740 	case IP_VERSION(3, 0, 0):
5741 	case IP_VERSION(3, 1, 2):
5742 	case IP_VERSION(3, 1, 3):
5743 	case IP_VERSION(3, 1, 4):
5744 	case IP_VERSION(3, 1, 5):
5745 	case IP_VERSION(3, 1, 6):
5746 	case IP_VERSION(3, 2, 0):
5747 	case IP_VERSION(3, 2, 1):
5748 	case IP_VERSION(2, 1, 0):
5749 	case IP_VERSION(3, 5, 0):
5750 	case IP_VERSION(3, 5, 1):
5751 	case IP_VERSION(3, 6, 0):
5752 	case IP_VERSION(4, 0, 1):
5753 	case IP_VERSION(4, 2, 0):
5754 	case IP_VERSION(4, 2, 1):
5755 		if (register_outbox_irq_handlers(dm->adev)) {
5756 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5757 			goto fail;
5758 		}
5759 		break;
5760 	default:
5761 		drm_dbg_kms(adev_to_drm(adev), "Unsupported DCN IP version for outbox: 0x%X\n",
5762 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
5763 	}
5764 
5765 	/* Determine whether to enable PSR support by default. */
5766 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
5767 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5768 		case IP_VERSION(3, 1, 2):
5769 		case IP_VERSION(3, 1, 3):
5770 		case IP_VERSION(3, 1, 4):
5771 		case IP_VERSION(3, 1, 5):
5772 		case IP_VERSION(3, 1, 6):
5773 		case IP_VERSION(3, 2, 0):
5774 		case IP_VERSION(3, 2, 1):
5775 		case IP_VERSION(3, 5, 0):
5776 		case IP_VERSION(3, 5, 1):
5777 		case IP_VERSION(3, 6, 0):
5778 		case IP_VERSION(4, 0, 1):
5779 		case IP_VERSION(4, 2, 0):
5780 		case IP_VERSION(4, 2, 1):
5781 			psr_feature_enabled = true;
5782 			break;
5783 		default:
5784 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
5785 			break;
5786 		}
5787 	}
5788 
5789 	/* Determine whether to enable Replay support by default. */
5790 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
5791 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5792 		case IP_VERSION(3, 1, 4):
5793 		case IP_VERSION(3, 2, 0):
5794 		case IP_VERSION(3, 2, 1):
5795 		case IP_VERSION(3, 5, 0):
5796 		case IP_VERSION(3, 5, 1):
5797 		case IP_VERSION(3, 6, 0):
5798 		case IP_VERSION(4, 2, 0):
5799 		case IP_VERSION(4, 2, 1):
5800 			replay_feature_enabled = true;
5801 			break;
5802 
5803 		default:
5804 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
5805 			break;
5806 		}
5807 	}
5808 
5809 	if (link_cnt > MAX_LINKS) {
5810 		drm_err(adev_to_drm(adev),
5811 			"KMS: Cannot support more than %d display indexes\n",
5812 				MAX_LINKS);
5813 		goto fail;
5814 	}
5815 
5816 	/* loops over all connectors on the board */
5817 	for (i = 0; i < link_cnt; i++) {
5818 		struct dc_link *link = NULL;
5819 
5820 		link = dc_get_link_at_index(dm->dc, i);
5821 
5822 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
5823 			struct amdgpu_dm_wb_connector *wbcon = kzalloc_obj(*wbcon);
5824 
5825 			if (!wbcon) {
5826 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
5827 				continue;
5828 			}
5829 
5830 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
5831 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
5832 				kfree(wbcon);
5833 				continue;
5834 			}
5835 
5836 			link->psr_settings.psr_feature_enabled = false;
5837 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
5838 
5839 			continue;
5840 		}
5841 
5842 		aconnector = kzalloc_obj(*aconnector);
5843 		if (!aconnector)
5844 			goto fail;
5845 
5846 		aencoder = kzalloc_obj(*aencoder);
5847 		if (!aencoder)
5848 			goto fail;
5849 
5850 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
5851 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
5852 			goto fail;
5853 		}
5854 
5855 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
5856 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
5857 			goto fail;
5858 		}
5859 
5860 		if (dm->hpd_rx_offload_wq)
5861 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
5862 				aconnector;
5863 
5864 		if (!dc_link_detect_connection_type(link, &new_connection_type))
5865 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
5866 
5867 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
5868 			emulated_link_detect(link);
5869 			amdgpu_dm_update_connector_after_detect(aconnector);
5870 		} else {
5871 			bool ret = false;
5872 
5873 			mutex_lock(&dm->dc_lock);
5874 			dc_exit_ips_for_hw_access(dm->dc);
5875 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
5876 			mutex_unlock(&dm->dc_lock);
5877 
5878 			if (ret) {
5879 				amdgpu_dm_update_connector_after_detect(aconnector);
5880 				setup_backlight_device(dm, aconnector);
5881 
5882 				/* Disable PSR if Replay can be enabled */
5883 				if (replay_feature_enabled)
5884 					if (amdgpu_dm_set_replay_caps(link, aconnector))
5885 						psr_feature_enabled = false;
5886 
5887 				if (psr_feature_enabled) {
5888 					amdgpu_dm_set_psr_caps(link, aconnector);
5889 					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",
5890 						 aconnector->base.name,
5891 						 link->psr_settings.psr_feature_enabled,
5892 						 link->psr_settings.psr_version,
5893 						 link->dpcd_caps.psr_info.psr_version,
5894 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
5895 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
5896 				}
5897 			}
5898 		}
5899 		amdgpu_set_panel_orientation(&aconnector->base);
5900 	}
5901 
5902 	/* Debug dump: list all DC links and their associated sinks after detection
5903 	 * is complete for all connectors. This provides a comprehensive view of the
5904 	 * final state without repeating the dump for each connector.
5905 	 */
5906 	amdgpu_dm_dump_links_and_sinks(adev);
5907 
5908 	/* Software is initialized. Now we can register interrupt handlers. */
5909 	switch (adev->asic_type) {
5910 #if defined(CONFIG_DRM_AMD_DC_SI)
5911 	case CHIP_TAHITI:
5912 	case CHIP_PITCAIRN:
5913 	case CHIP_VERDE:
5914 	case CHIP_OLAND:
5915 #endif
5916 	case CHIP_BONAIRE:
5917 	case CHIP_HAWAII:
5918 	case CHIP_KAVERI:
5919 	case CHIP_KABINI:
5920 	case CHIP_MULLINS:
5921 	case CHIP_TONGA:
5922 	case CHIP_FIJI:
5923 	case CHIP_CARRIZO:
5924 	case CHIP_STONEY:
5925 	case CHIP_POLARIS11:
5926 	case CHIP_POLARIS10:
5927 	case CHIP_POLARIS12:
5928 	case CHIP_VEGAM:
5929 	case CHIP_VEGA10:
5930 	case CHIP_VEGA12:
5931 	case CHIP_VEGA20:
5932 		if (dce110_register_irq_handlers(dm->adev)) {
5933 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5934 			goto fail;
5935 		}
5936 		break;
5937 	default:
5938 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5939 		case IP_VERSION(1, 0, 0):
5940 		case IP_VERSION(1, 0, 1):
5941 		case IP_VERSION(2, 0, 2):
5942 		case IP_VERSION(2, 0, 3):
5943 		case IP_VERSION(2, 0, 0):
5944 		case IP_VERSION(2, 1, 0):
5945 		case IP_VERSION(3, 0, 0):
5946 		case IP_VERSION(3, 0, 2):
5947 		case IP_VERSION(3, 0, 3):
5948 		case IP_VERSION(3, 0, 1):
5949 		case IP_VERSION(3, 1, 2):
5950 		case IP_VERSION(3, 1, 3):
5951 		case IP_VERSION(3, 1, 4):
5952 		case IP_VERSION(3, 1, 5):
5953 		case IP_VERSION(3, 1, 6):
5954 		case IP_VERSION(3, 2, 0):
5955 		case IP_VERSION(3, 2, 1):
5956 		case IP_VERSION(3, 5, 0):
5957 		case IP_VERSION(3, 5, 1):
5958 		case IP_VERSION(3, 6, 0):
5959 		case IP_VERSION(4, 0, 1):
5960 		case IP_VERSION(4, 2, 0):
5961 		case IP_VERSION(4, 2, 1):
5962 			if (dcn10_register_irq_handlers(dm->adev)) {
5963 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5964 				goto fail;
5965 			}
5966 			break;
5967 		default:
5968 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
5969 					amdgpu_ip_version(adev, DCE_HWIP, 0));
5970 			goto fail;
5971 		}
5972 		break;
5973 	}
5974 
5975 	return 0;
5976 fail:
5977 	kfree(aencoder);
5978 	kfree(aconnector);
5979 
5980 	return -EINVAL;
5981 }
5982 
5983 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
5984 {
5985 	if (dm->atomic_obj.state)
5986 		drm_atomic_private_obj_fini(&dm->atomic_obj);
5987 }
5988 
5989 /******************************************************************************
5990  * amdgpu_display_funcs functions
5991  *****************************************************************************/
5992 
5993 /*
5994  * dm_bandwidth_update - program display watermarks
5995  *
5996  * @adev: amdgpu_device pointer
5997  *
5998  * Calculate and program the display watermarks and line buffer allocation.
5999  */
6000 static void dm_bandwidth_update(struct amdgpu_device *adev)
6001 {
6002 	/* TODO: implement later */
6003 }
6004 
6005 static const struct amdgpu_display_funcs dm_display_funcs = {
6006 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
6007 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
6008 	.backlight_set_level = NULL, /* never called for DC */
6009 	.backlight_get_level = NULL, /* never called for DC */
6010 	.hpd_sense = NULL,/* called unconditionally */
6011 	.hpd_set_polarity = NULL, /* called unconditionally */
6012 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
6013 	.page_flip_get_scanoutpos =
6014 		dm_crtc_get_scanoutpos,/* called unconditionally */
6015 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
6016 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
6017 };
6018 
6019 #if defined(CONFIG_DEBUG_KERNEL_DC)
6020 
6021 static ssize_t s3_debug_store(struct device *device,
6022 			      struct device_attribute *attr,
6023 			      const char *buf,
6024 			      size_t count)
6025 {
6026 	int ret;
6027 	int s3_state;
6028 	struct drm_device *drm_dev = dev_get_drvdata(device);
6029 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
6030 	struct amdgpu_ip_block *ip_block;
6031 
6032 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
6033 	if (!ip_block)
6034 		return -EINVAL;
6035 
6036 	ret = kstrtoint(buf, 0, &s3_state);
6037 
6038 	if (ret == 0) {
6039 		if (s3_state) {
6040 			dm_resume(ip_block);
6041 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
6042 		} else
6043 			dm_suspend(ip_block);
6044 	}
6045 
6046 	return ret == 0 ? count : 0;
6047 }
6048 
6049 DEVICE_ATTR_WO(s3_debug);
6050 
6051 #endif
6052 
6053 static int dm_init_microcode(struct amdgpu_device *adev)
6054 {
6055 	char *fw_name_dmub;
6056 	int r;
6057 
6058 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6059 	case IP_VERSION(2, 1, 0):
6060 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
6061 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
6062 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
6063 		break;
6064 	case IP_VERSION(3, 0, 0):
6065 		if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(10, 3, 0))
6066 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
6067 		else
6068 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
6069 		break;
6070 	case IP_VERSION(3, 0, 1):
6071 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
6072 		break;
6073 	case IP_VERSION(3, 0, 2):
6074 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
6075 		break;
6076 	case IP_VERSION(3, 0, 3):
6077 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
6078 		break;
6079 	case IP_VERSION(3, 1, 2):
6080 	case IP_VERSION(3, 1, 3):
6081 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
6082 		break;
6083 	case IP_VERSION(3, 1, 4):
6084 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
6085 		break;
6086 	case IP_VERSION(3, 1, 5):
6087 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
6088 		break;
6089 	case IP_VERSION(3, 1, 6):
6090 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
6091 		break;
6092 	case IP_VERSION(3, 2, 0):
6093 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
6094 		break;
6095 	case IP_VERSION(3, 2, 1):
6096 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
6097 		break;
6098 	case IP_VERSION(3, 5, 0):
6099 		fw_name_dmub = FIRMWARE_DCN_35_DMUB;
6100 		break;
6101 	case IP_VERSION(3, 5, 1):
6102 		fw_name_dmub = FIRMWARE_DCN_351_DMUB;
6103 		break;
6104 	case IP_VERSION(3, 6, 0):
6105 		fw_name_dmub = FIRMWARE_DCN_36_DMUB;
6106 		break;
6107 	case IP_VERSION(4, 0, 1):
6108 		fw_name_dmub = FIRMWARE_DCN_401_DMUB;
6109 		break;
6110 	case IP_VERSION(4, 2, 0):
6111 		fw_name_dmub = FIRMWARE_DCN_42_DMUB;
6112 		break;
6113 	case IP_VERSION(4, 2, 1):
6114 		fw_name_dmub = FIRMWARE_DCN_42B_DMUB;
6115 		break;
6116 	default:
6117 		/* ASIC doesn't support DMUB. */
6118 		return 0;
6119 	}
6120 	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, AMDGPU_UCODE_REQUIRED,
6121 				 "%s", fw_name_dmub);
6122 	return r;
6123 }
6124 
6125 static int dm_early_init(struct amdgpu_ip_block *ip_block)
6126 {
6127 	struct amdgpu_device *adev = ip_block->adev;
6128 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
6129 	struct atom_context *ctx = mode_info->atom_context;
6130 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
6131 	u16 data_offset;
6132 
6133 	/* if there is no object header, skip DM */
6134 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
6135 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
6136 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
6137 		return -ENOENT;
6138 	}
6139 
6140 	switch (adev->asic_type) {
6141 #if defined(CONFIG_DRM_AMD_DC_SI)
6142 	case CHIP_TAHITI:
6143 	case CHIP_PITCAIRN:
6144 	case CHIP_VERDE:
6145 		adev->mode_info.num_crtc = 6;
6146 		adev->mode_info.num_hpd = 6;
6147 		adev->mode_info.num_dig = 6;
6148 		break;
6149 	case CHIP_OLAND:
6150 		adev->mode_info.num_crtc = 2;
6151 		adev->mode_info.num_hpd = 2;
6152 		adev->mode_info.num_dig = 2;
6153 		break;
6154 #endif
6155 	case CHIP_BONAIRE:
6156 	case CHIP_HAWAII:
6157 		adev->mode_info.num_crtc = 6;
6158 		adev->mode_info.num_hpd = 6;
6159 		adev->mode_info.num_dig = 6;
6160 		break;
6161 	case CHIP_KAVERI:
6162 		adev->mode_info.num_crtc = 4;
6163 		adev->mode_info.num_hpd = 6;
6164 		adev->mode_info.num_dig = 7;
6165 		break;
6166 	case CHIP_KABINI:
6167 	case CHIP_MULLINS:
6168 		adev->mode_info.num_crtc = 2;
6169 		adev->mode_info.num_hpd = 6;
6170 		adev->mode_info.num_dig = 6;
6171 		break;
6172 	case CHIP_FIJI:
6173 	case CHIP_TONGA:
6174 		adev->mode_info.num_crtc = 6;
6175 		adev->mode_info.num_hpd = 6;
6176 		adev->mode_info.num_dig = 7;
6177 		break;
6178 	case CHIP_CARRIZO:
6179 		adev->mode_info.num_crtc = 3;
6180 		adev->mode_info.num_hpd = 6;
6181 		adev->mode_info.num_dig = 9;
6182 		break;
6183 	case CHIP_STONEY:
6184 		adev->mode_info.num_crtc = 2;
6185 		adev->mode_info.num_hpd = 6;
6186 		adev->mode_info.num_dig = 9;
6187 		break;
6188 	case CHIP_POLARIS11:
6189 	case CHIP_POLARIS12:
6190 		adev->mode_info.num_crtc = 5;
6191 		adev->mode_info.num_hpd = 5;
6192 		adev->mode_info.num_dig = 5;
6193 		break;
6194 	case CHIP_POLARIS10:
6195 	case CHIP_VEGAM:
6196 		adev->mode_info.num_crtc = 6;
6197 		adev->mode_info.num_hpd = 6;
6198 		adev->mode_info.num_dig = 6;
6199 		break;
6200 	case CHIP_VEGA10:
6201 	case CHIP_VEGA12:
6202 	case CHIP_VEGA20:
6203 		adev->mode_info.num_crtc = 6;
6204 		adev->mode_info.num_hpd = 6;
6205 		adev->mode_info.num_dig = 6;
6206 		break;
6207 	default:
6208 
6209 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6210 		case IP_VERSION(2, 0, 2):
6211 		case IP_VERSION(3, 0, 0):
6212 			adev->mode_info.num_crtc = 6;
6213 			adev->mode_info.num_hpd = 6;
6214 			adev->mode_info.num_dig = 6;
6215 			break;
6216 		case IP_VERSION(2, 0, 0):
6217 		case IP_VERSION(3, 0, 2):
6218 			adev->mode_info.num_crtc = 5;
6219 			adev->mode_info.num_hpd = 5;
6220 			adev->mode_info.num_dig = 5;
6221 			break;
6222 		case IP_VERSION(2, 0, 3):
6223 		case IP_VERSION(3, 0, 3):
6224 			adev->mode_info.num_crtc = 2;
6225 			adev->mode_info.num_hpd = 2;
6226 			adev->mode_info.num_dig = 2;
6227 			break;
6228 		case IP_VERSION(1, 0, 0):
6229 		case IP_VERSION(1, 0, 1):
6230 		case IP_VERSION(3, 0, 1):
6231 		case IP_VERSION(2, 1, 0):
6232 		case IP_VERSION(3, 1, 2):
6233 		case IP_VERSION(3, 1, 3):
6234 		case IP_VERSION(3, 1, 4):
6235 		case IP_VERSION(3, 1, 5):
6236 		case IP_VERSION(3, 1, 6):
6237 		case IP_VERSION(3, 2, 0):
6238 		case IP_VERSION(3, 2, 1):
6239 		case IP_VERSION(3, 5, 0):
6240 		case IP_VERSION(3, 5, 1):
6241 		case IP_VERSION(3, 6, 0):
6242 		case IP_VERSION(4, 0, 1):
6243 		case IP_VERSION(4, 2, 0):
6244 		case IP_VERSION(4, 2, 1):
6245 			adev->mode_info.num_crtc = 4;
6246 			adev->mode_info.num_hpd = 4;
6247 			adev->mode_info.num_dig = 4;
6248 			break;
6249 		default:
6250 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
6251 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6252 			return -EINVAL;
6253 		}
6254 		break;
6255 	}
6256 
6257 	if (adev->mode_info.funcs == NULL)
6258 		adev->mode_info.funcs = &dm_display_funcs;
6259 
6260 	/*
6261 	 * Note: Do NOT change adev->reg.audio_endpt.rreg and
6262 	 * adev->reg.audio_endpt.wreg because they are initialised in
6263 	 * amdgpu_device_init()
6264 	 */
6265 #if defined(CONFIG_DEBUG_KERNEL_DC)
6266 	device_create_file(
6267 		adev_to_drm(adev)->dev,
6268 		&dev_attr_s3_debug);
6269 #endif
6270 	adev->dc_enabled = true;
6271 
6272 	return dm_init_microcode(adev);
6273 }
6274 
6275 static bool modereset_required(struct drm_crtc_state *crtc_state)
6276 {
6277 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
6278 }
6279 
6280 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
6281 {
6282 	drm_encoder_cleanup(encoder);
6283 	kfree(encoder);
6284 }
6285 
6286 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
6287 	.destroy = amdgpu_dm_encoder_destroy,
6288 };
6289 
6290 static int
6291 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
6292 			    const enum surface_pixel_format format,
6293 			    enum dc_color_space *color_space)
6294 {
6295 	bool full_range;
6296 
6297 	*color_space = COLOR_SPACE_SRGB;
6298 
6299 	/* Ignore properties when DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE is set */
6300 	if (plane_state->state && plane_state->state->plane_color_pipeline)
6301 		return 0;
6302 
6303 	/* DRM color properties only affect non-RGB formats. */
6304 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
6305 		return 0;
6306 
6307 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
6308 
6309 	switch (plane_state->color_encoding) {
6310 	case DRM_COLOR_YCBCR_BT601:
6311 		if (full_range)
6312 			*color_space = COLOR_SPACE_YCBCR601;
6313 		else
6314 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
6315 		break;
6316 
6317 	case DRM_COLOR_YCBCR_BT709:
6318 		if (full_range)
6319 			*color_space = COLOR_SPACE_YCBCR709;
6320 		else
6321 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
6322 		break;
6323 
6324 	case DRM_COLOR_YCBCR_BT2020:
6325 		if (full_range)
6326 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
6327 		else
6328 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6329 		break;
6330 
6331 	default:
6332 		return -EINVAL;
6333 	}
6334 
6335 	return 0;
6336 }
6337 
6338 static int
6339 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
6340 			    const struct drm_plane_state *plane_state,
6341 			    const u64 tiling_flags,
6342 			    struct dc_plane_info *plane_info,
6343 			    struct dc_plane_address *address,
6344 			    bool tmz_surface)
6345 {
6346 	const struct drm_framebuffer *fb = plane_state->fb;
6347 	const struct amdgpu_framebuffer *afb =
6348 		to_amdgpu_framebuffer(plane_state->fb);
6349 	int ret;
6350 
6351 	memset(plane_info, 0, sizeof(*plane_info));
6352 
6353 	switch (fb->format->format) {
6354 	case DRM_FORMAT_C8:
6355 		plane_info->format =
6356 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
6357 		break;
6358 	case DRM_FORMAT_RGB565:
6359 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
6360 		break;
6361 	case DRM_FORMAT_XRGB8888:
6362 	case DRM_FORMAT_ARGB8888:
6363 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6364 		break;
6365 	case DRM_FORMAT_XRGB2101010:
6366 	case DRM_FORMAT_ARGB2101010:
6367 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
6368 		break;
6369 	case DRM_FORMAT_XBGR2101010:
6370 	case DRM_FORMAT_ABGR2101010:
6371 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
6372 		break;
6373 	case DRM_FORMAT_XBGR8888:
6374 	case DRM_FORMAT_ABGR8888:
6375 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
6376 		break;
6377 	case DRM_FORMAT_NV21:
6378 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
6379 		break;
6380 	case DRM_FORMAT_NV12:
6381 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
6382 		break;
6383 	case DRM_FORMAT_P010:
6384 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
6385 		break;
6386 	case DRM_FORMAT_XRGB16161616F:
6387 	case DRM_FORMAT_ARGB16161616F:
6388 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
6389 		break;
6390 	case DRM_FORMAT_XBGR16161616F:
6391 	case DRM_FORMAT_ABGR16161616F:
6392 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
6393 		break;
6394 	case DRM_FORMAT_XRGB16161616:
6395 	case DRM_FORMAT_ARGB16161616:
6396 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
6397 		break;
6398 	case DRM_FORMAT_XBGR16161616:
6399 	case DRM_FORMAT_ABGR16161616:
6400 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
6401 		break;
6402 	default:
6403 		drm_err(adev_to_drm(adev),
6404 			"Unsupported screen format %p4cc\n",
6405 			&fb->format->format);
6406 		return -EINVAL;
6407 	}
6408 
6409 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
6410 	case DRM_MODE_ROTATE_0:
6411 		plane_info->rotation = ROTATION_ANGLE_0;
6412 		break;
6413 	case DRM_MODE_ROTATE_90:
6414 		plane_info->rotation = ROTATION_ANGLE_90;
6415 		break;
6416 	case DRM_MODE_ROTATE_180:
6417 		plane_info->rotation = ROTATION_ANGLE_180;
6418 		break;
6419 	case DRM_MODE_ROTATE_270:
6420 		plane_info->rotation = ROTATION_ANGLE_270;
6421 		break;
6422 	default:
6423 		plane_info->rotation = ROTATION_ANGLE_0;
6424 		break;
6425 	}
6426 
6427 
6428 	plane_info->visible = true;
6429 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
6430 
6431 	plane_info->layer_index = plane_state->normalized_zpos;
6432 
6433 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
6434 					  &plane_info->color_space);
6435 	if (ret)
6436 		return ret;
6437 
6438 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
6439 					   plane_info->rotation, tiling_flags,
6440 					   &plane_info->tiling_info,
6441 					   &plane_info->plane_size,
6442 					   &plane_info->dcc, address,
6443 					   tmz_surface);
6444 	if (ret)
6445 		return ret;
6446 
6447 	amdgpu_dm_plane_fill_blending_from_plane_state(
6448 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
6449 		&plane_info->global_alpha, &plane_info->global_alpha_value);
6450 
6451 	return 0;
6452 }
6453 
6454 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
6455 				    struct dc_plane_state *dc_plane_state,
6456 				    struct drm_plane_state *plane_state,
6457 				    struct drm_crtc_state *crtc_state)
6458 {
6459 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6460 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
6461 	struct dc_scaling_info scaling_info;
6462 	struct dc_plane_info plane_info;
6463 	int ret;
6464 
6465 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
6466 	if (ret)
6467 		return ret;
6468 
6469 	dc_plane_state->src_rect = scaling_info.src_rect;
6470 	dc_plane_state->dst_rect = scaling_info.dst_rect;
6471 	dc_plane_state->clip_rect = scaling_info.clip_rect;
6472 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
6473 
6474 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
6475 					  afb->tiling_flags,
6476 					  &plane_info,
6477 					  &dc_plane_state->address,
6478 					  afb->tmz_surface);
6479 	if (ret)
6480 		return ret;
6481 
6482 	dc_plane_state->format = plane_info.format;
6483 	dc_plane_state->color_space = plane_info.color_space;
6484 	dc_plane_state->format = plane_info.format;
6485 	dc_plane_state->plane_size = plane_info.plane_size;
6486 	dc_plane_state->rotation = plane_info.rotation;
6487 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
6488 	dc_plane_state->stereo_format = plane_info.stereo_format;
6489 	dc_plane_state->tiling_info = plane_info.tiling_info;
6490 	dc_plane_state->visible = plane_info.visible;
6491 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
6492 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
6493 	dc_plane_state->global_alpha = plane_info.global_alpha;
6494 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
6495 	dc_plane_state->dcc = plane_info.dcc;
6496 	dc_plane_state->layer_index = plane_info.layer_index;
6497 	dc_plane_state->flip_int_enabled = true;
6498 
6499 	/*
6500 	 * Always set input transfer function, since plane state is refreshed
6501 	 * every time.
6502 	 */
6503 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
6504 						plane_state,
6505 						dc_plane_state);
6506 	if (ret)
6507 		return ret;
6508 
6509 	return 0;
6510 }
6511 
6512 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
6513 				      struct rect *dirty_rect, int32_t x,
6514 				      s32 y, s32 width, s32 height,
6515 				      int *i, bool ffu)
6516 {
6517 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
6518 
6519 	dirty_rect->x = x;
6520 	dirty_rect->y = y;
6521 	dirty_rect->width = width;
6522 	dirty_rect->height = height;
6523 
6524 	if (ffu)
6525 		drm_dbg(plane->dev,
6526 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
6527 			plane->base.id, width, height);
6528 	else
6529 		drm_dbg(plane->dev,
6530 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
6531 			plane->base.id, x, y, width, height);
6532 
6533 	(*i)++;
6534 }
6535 
6536 /**
6537  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
6538  *
6539  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
6540  *         remote fb
6541  * @old_plane_state: Old state of @plane
6542  * @new_plane_state: New state of @plane
6543  * @crtc_state: New state of CRTC connected to the @plane
6544  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
6545  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
6546  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
6547  *             that have changed will be updated. If PSR SU is not enabled,
6548  *             or if damage clips are not available, the entire screen will be updated.
6549  * @dirty_regions_changed: dirty regions changed
6550  *
6551  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
6552  * (referred to as "damage clips" in DRM nomenclature) that require updating on
6553  * the eDP remote buffer. The responsibility of specifying the dirty regions is
6554  * amdgpu_dm's.
6555  *
6556  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
6557  * plane with regions that require flushing to the eDP remote buffer. In
6558  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
6559  * implicitly provide damage clips without any client support via the plane
6560  * bounds.
6561  */
6562 static void fill_dc_dirty_rects(struct drm_plane *plane,
6563 				struct drm_plane_state *old_plane_state,
6564 				struct drm_plane_state *new_plane_state,
6565 				struct drm_crtc_state *crtc_state,
6566 				struct dc_flip_addrs *flip_addrs,
6567 				bool is_psr_su,
6568 				bool *dirty_regions_changed)
6569 {
6570 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6571 	struct rect *dirty_rects = flip_addrs->dirty_rects;
6572 	u32 num_clips;
6573 	struct drm_mode_rect *clips;
6574 	bool bb_changed;
6575 	bool fb_changed;
6576 	u32 i = 0;
6577 	*dirty_regions_changed = false;
6578 
6579 	/*
6580 	 * Cursor plane has it's own dirty rect update interface. See
6581 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
6582 	 */
6583 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
6584 		return;
6585 
6586 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
6587 		goto ffu;
6588 
6589 	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
6590 	clips = drm_plane_get_damage_clips(new_plane_state);
6591 
6592 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
6593 						   is_psr_su)))
6594 		goto ffu;
6595 
6596 	if (!dm_crtc_state->mpo_requested) {
6597 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
6598 			goto ffu;
6599 
6600 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
6601 			fill_dc_dirty_rect(new_plane_state->plane,
6602 					   &dirty_rects[flip_addrs->dirty_rect_count],
6603 					   clips->x1, clips->y1,
6604 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
6605 					   &flip_addrs->dirty_rect_count,
6606 					   false);
6607 		return;
6608 	}
6609 
6610 	/*
6611 	 * MPO is requested. Add entire plane bounding box to dirty rects if
6612 	 * flipped to or damaged.
6613 	 *
6614 	 * If plane is moved or resized, also add old bounding box to dirty
6615 	 * rects.
6616 	 */
6617 	fb_changed = old_plane_state->fb->base.id !=
6618 		     new_plane_state->fb->base.id;
6619 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
6620 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
6621 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
6622 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
6623 
6624 	drm_dbg(plane->dev,
6625 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
6626 		new_plane_state->plane->base.id,
6627 		bb_changed, fb_changed, num_clips);
6628 
6629 	*dirty_regions_changed = bb_changed;
6630 
6631 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
6632 		goto ffu;
6633 
6634 	if (bb_changed) {
6635 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6636 				   new_plane_state->crtc_x,
6637 				   new_plane_state->crtc_y,
6638 				   new_plane_state->crtc_w,
6639 				   new_plane_state->crtc_h, &i, false);
6640 
6641 		/* Add old plane bounding-box if plane is moved or resized */
6642 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6643 				   old_plane_state->crtc_x,
6644 				   old_plane_state->crtc_y,
6645 				   old_plane_state->crtc_w,
6646 				   old_plane_state->crtc_h, &i, false);
6647 	}
6648 
6649 	if (num_clips) {
6650 		for (; i < num_clips; clips++)
6651 			fill_dc_dirty_rect(new_plane_state->plane,
6652 					   &dirty_rects[i], clips->x1,
6653 					   clips->y1, clips->x2 - clips->x1,
6654 					   clips->y2 - clips->y1, &i, false);
6655 	} else if (fb_changed && !bb_changed) {
6656 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6657 				   new_plane_state->crtc_x,
6658 				   new_plane_state->crtc_y,
6659 				   new_plane_state->crtc_w,
6660 				   new_plane_state->crtc_h, &i, false);
6661 	}
6662 
6663 	flip_addrs->dirty_rect_count = i;
6664 	return;
6665 
6666 ffu:
6667 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
6668 			   dm_crtc_state->base.mode.crtc_hdisplay,
6669 			   dm_crtc_state->base.mode.crtc_vdisplay,
6670 			   &flip_addrs->dirty_rect_count, true);
6671 }
6672 
6673 static void update_stream_scaling_settings(struct drm_device *dev,
6674 					   const struct drm_display_mode *mode,
6675 					   const struct dm_connector_state *dm_state,
6676 					   struct dc_stream_state *stream)
6677 {
6678 	enum amdgpu_rmx_type rmx_type;
6679 
6680 	struct rect src = { 0 }; /* viewport in composition space*/
6681 	struct rect dst = { 0 }; /* stream addressable area */
6682 
6683 	/* no mode. nothing to be done */
6684 	if (!mode)
6685 		return;
6686 
6687 	/* Full screen scaling by default */
6688 	src.width = mode->hdisplay;
6689 	src.height = mode->vdisplay;
6690 	dst.width = stream->timing.h_addressable;
6691 	dst.height = stream->timing.v_addressable;
6692 
6693 	if (dm_state) {
6694 		rmx_type = dm_state->scaling;
6695 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
6696 			if (src.width * dst.height <
6697 					src.height * dst.width) {
6698 				/* height needs less upscaling/more downscaling */
6699 				dst.width = src.width *
6700 						dst.height / src.height;
6701 			} else {
6702 				/* width needs less upscaling/more downscaling */
6703 				dst.height = src.height *
6704 						dst.width / src.width;
6705 			}
6706 		} else if (rmx_type == RMX_CENTER) {
6707 			dst = src;
6708 		}
6709 
6710 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
6711 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
6712 
6713 		if (dm_state->underscan_enable) {
6714 			dst.x += dm_state->underscan_hborder / 2;
6715 			dst.y += dm_state->underscan_vborder / 2;
6716 			dst.width -= dm_state->underscan_hborder;
6717 			dst.height -= dm_state->underscan_vborder;
6718 		}
6719 	}
6720 
6721 	stream->src = src;
6722 	stream->dst = dst;
6723 
6724 	drm_dbg_kms(dev, "Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
6725 		    dst.x, dst.y, dst.width, dst.height);
6726 
6727 }
6728 
6729 static enum dc_color_depth
6730 convert_color_depth_from_display_info(const struct drm_connector *connector,
6731 				      bool is_y420, int requested_bpc)
6732 {
6733 	u8 bpc;
6734 
6735 	if (is_y420) {
6736 		bpc = 8;
6737 
6738 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
6739 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
6740 			bpc = 16;
6741 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
6742 			bpc = 12;
6743 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
6744 			bpc = 10;
6745 	} else {
6746 		bpc = (uint8_t)connector->display_info.bpc;
6747 		/* Assume 8 bpc by default if no bpc is specified. */
6748 		bpc = bpc ? bpc : 8;
6749 	}
6750 
6751 	if (requested_bpc > 0) {
6752 		/*
6753 		 * Cap display bpc based on the user requested value.
6754 		 *
6755 		 * The value for state->max_bpc may not correctly updated
6756 		 * depending on when the connector gets added to the state
6757 		 * or if this was called outside of atomic check, so it
6758 		 * can't be used directly.
6759 		 */
6760 		bpc = min_t(u8, bpc, requested_bpc);
6761 
6762 		/* Round down to the nearest even number. */
6763 		bpc = bpc - (bpc & 1);
6764 	}
6765 
6766 	switch (bpc) {
6767 	case 0:
6768 		/*
6769 		 * Temporary Work around, DRM doesn't parse color depth for
6770 		 * EDID revision before 1.4
6771 		 * TODO: Fix edid parsing
6772 		 */
6773 		return COLOR_DEPTH_888;
6774 	case 6:
6775 		return COLOR_DEPTH_666;
6776 	case 8:
6777 		return COLOR_DEPTH_888;
6778 	case 10:
6779 		return COLOR_DEPTH_101010;
6780 	case 12:
6781 		return COLOR_DEPTH_121212;
6782 	case 14:
6783 		return COLOR_DEPTH_141414;
6784 	case 16:
6785 		return COLOR_DEPTH_161616;
6786 	default:
6787 		return COLOR_DEPTH_UNDEFINED;
6788 	}
6789 }
6790 
6791 static enum dc_aspect_ratio
6792 get_aspect_ratio(const struct drm_display_mode *mode_in)
6793 {
6794 	/* 1-1 mapping, since both enums follow the HDMI spec. */
6795 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
6796 }
6797 
6798 static enum dc_color_space
6799 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
6800 		       const struct drm_connector_state *connector_state)
6801 {
6802 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
6803 
6804 	switch (connector_state->colorspace) {
6805 	case DRM_MODE_COLORIMETRY_BT601_YCC:
6806 		if (dc_crtc_timing->flags.Y_ONLY)
6807 			color_space = COLOR_SPACE_YCBCR601_LIMITED;
6808 		else
6809 			color_space = COLOR_SPACE_YCBCR601;
6810 		break;
6811 	case DRM_MODE_COLORIMETRY_BT709_YCC:
6812 		if (dc_crtc_timing->flags.Y_ONLY)
6813 			color_space = COLOR_SPACE_YCBCR709_LIMITED;
6814 		else
6815 			color_space = COLOR_SPACE_YCBCR709;
6816 		break;
6817 	case DRM_MODE_COLORIMETRY_OPRGB:
6818 		color_space = COLOR_SPACE_ADOBERGB;
6819 		break;
6820 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
6821 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
6822 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
6823 			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
6824 		else
6825 			color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6826 		break;
6827 	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
6828 	default:
6829 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
6830 			color_space = COLOR_SPACE_SRGB;
6831 			if (connector_state->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_LIMITED)
6832 				color_space = COLOR_SPACE_SRGB_LIMITED;
6833 		/*
6834 		 * 27030khz is the separation point between HDTV and SDTV
6835 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
6836 		 * respectively
6837 		 */
6838 		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
6839 			if (dc_crtc_timing->flags.Y_ONLY)
6840 				color_space =
6841 					COLOR_SPACE_YCBCR709_LIMITED;
6842 			else
6843 				color_space = COLOR_SPACE_YCBCR709;
6844 		} else {
6845 			if (dc_crtc_timing->flags.Y_ONLY)
6846 				color_space =
6847 					COLOR_SPACE_YCBCR601_LIMITED;
6848 			else
6849 				color_space = COLOR_SPACE_YCBCR601;
6850 		}
6851 		break;
6852 	}
6853 
6854 	return color_space;
6855 }
6856 
6857 static enum display_content_type
6858 get_output_content_type(const struct drm_connector_state *connector_state)
6859 {
6860 	switch (connector_state->content_type) {
6861 	default:
6862 	case DRM_MODE_CONTENT_TYPE_NO_DATA:
6863 		return DISPLAY_CONTENT_TYPE_NO_DATA;
6864 	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
6865 		return DISPLAY_CONTENT_TYPE_GRAPHICS;
6866 	case DRM_MODE_CONTENT_TYPE_PHOTO:
6867 		return DISPLAY_CONTENT_TYPE_PHOTO;
6868 	case DRM_MODE_CONTENT_TYPE_CINEMA:
6869 		return DISPLAY_CONTENT_TYPE_CINEMA;
6870 	case DRM_MODE_CONTENT_TYPE_GAME:
6871 		return DISPLAY_CONTENT_TYPE_GAME;
6872 	}
6873 }
6874 
6875 static bool adjust_colour_depth_from_display_info(
6876 	struct dc_crtc_timing *timing_out,
6877 	const struct drm_display_info *info)
6878 {
6879 	enum dc_color_depth depth = timing_out->display_color_depth;
6880 	int normalized_clk;
6881 
6882 	do {
6883 		normalized_clk = timing_out->pix_clk_100hz / 10;
6884 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
6885 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
6886 			normalized_clk /= 2;
6887 		/* Adjusting pix clock following on HDMI spec based on colour depth */
6888 		switch (depth) {
6889 		case COLOR_DEPTH_888:
6890 			break;
6891 		case COLOR_DEPTH_101010:
6892 			normalized_clk = (normalized_clk * 30) / 24;
6893 			break;
6894 		case COLOR_DEPTH_121212:
6895 			normalized_clk = (normalized_clk * 36) / 24;
6896 			break;
6897 		case COLOR_DEPTH_161616:
6898 			normalized_clk = (normalized_clk * 48) / 24;
6899 			break;
6900 		default:
6901 			/* The above depths are the only ones valid for HDMI. */
6902 			return false;
6903 		}
6904 		if (normalized_clk <= info->max_tmds_clock) {
6905 			timing_out->display_color_depth = depth;
6906 			return true;
6907 		}
6908 	} while (--depth > COLOR_DEPTH_666);
6909 	return false;
6910 }
6911 
6912 static void fill_stream_properties_from_drm_display_mode(
6913 	struct dc_stream_state *stream,
6914 	const struct drm_display_mode *mode_in,
6915 	const struct drm_connector *connector,
6916 	const struct drm_connector_state *connector_state,
6917 	const struct dc_stream_state *old_stream,
6918 	int requested_bpc)
6919 {
6920 	struct dc_crtc_timing *timing_out = &stream->timing;
6921 	const struct drm_display_info *info = &connector->display_info;
6922 	struct amdgpu_dm_connector *aconnector = NULL;
6923 	struct hdmi_vendor_infoframe hv_frame;
6924 	struct hdmi_avi_infoframe avi_frame;
6925 	ssize_t err;
6926 
6927 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
6928 		aconnector = to_amdgpu_dm_connector(connector);
6929 
6930 	memset(&hv_frame, 0, sizeof(hv_frame));
6931 	memset(&avi_frame, 0, sizeof(avi_frame));
6932 
6933 	timing_out->h_border_left = 0;
6934 	timing_out->h_border_right = 0;
6935 	timing_out->v_border_top = 0;
6936 	timing_out->v_border_bottom = 0;
6937 	/* TODO: un-hardcode */
6938 	if (drm_mode_is_420_only(info, mode_in)
6939 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6940 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6941 	else if (drm_mode_is_420_also(info, mode_in)
6942 			&& aconnector
6943 			&& aconnector->force_yuv420_output)
6944 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6945 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR422))
6946 			&& aconnector
6947 			&& aconnector->force_yuv422_output)
6948 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR422;
6949 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR444))
6950 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6951 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
6952 	else
6953 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
6954 
6955 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
6956 	timing_out->display_color_depth = convert_color_depth_from_display_info(
6957 		connector,
6958 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
6959 		requested_bpc);
6960 	timing_out->scan_type = SCANNING_TYPE_NODATA;
6961 	timing_out->hdmi_vic = 0;
6962 
6963 	if (old_stream) {
6964 		timing_out->vic = old_stream->timing.vic;
6965 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
6966 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
6967 	} else {
6968 		timing_out->vic = drm_match_cea_mode(mode_in);
6969 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
6970 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
6971 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
6972 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
6973 	}
6974 
6975 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
6976 		err = drm_hdmi_avi_infoframe_from_display_mode(&avi_frame,
6977 							       (struct drm_connector *)connector,
6978 							       mode_in);
6979 		if (err < 0)
6980 			drm_warn_once(connector->dev, "Failed to setup avi infoframe on connector %s: %zd\n",
6981 				      connector->name, err);
6982 		timing_out->vic = avi_frame.video_code;
6983 		err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame,
6984 								  (struct drm_connector *)connector,
6985 								  mode_in);
6986 		if (err < 0)
6987 			drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n",
6988 				      connector->name, err);
6989 		timing_out->hdmi_vic = hv_frame.vic;
6990 	}
6991 
6992 	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
6993 		timing_out->h_addressable = mode_in->hdisplay;
6994 		timing_out->h_total = mode_in->htotal;
6995 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
6996 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
6997 		timing_out->v_total = mode_in->vtotal;
6998 		timing_out->v_addressable = mode_in->vdisplay;
6999 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
7000 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
7001 		timing_out->pix_clk_100hz = mode_in->clock * 10;
7002 	} else {
7003 		timing_out->h_addressable = mode_in->crtc_hdisplay;
7004 		timing_out->h_total = mode_in->crtc_htotal;
7005 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
7006 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
7007 		timing_out->v_total = mode_in->crtc_vtotal;
7008 		timing_out->v_addressable = mode_in->crtc_vdisplay;
7009 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
7010 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
7011 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
7012 	}
7013 
7014 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
7015 
7016 	stream->out_transfer_func.type = TF_TYPE_PREDEFINED;
7017 	stream->out_transfer_func.tf = TRANSFER_FUNCTION_SRGB;
7018 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
7019 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
7020 		    drm_mode_is_420_also(info, mode_in) &&
7021 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
7022 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
7023 			adjust_colour_depth_from_display_info(timing_out, info);
7024 		}
7025 	}
7026 
7027 	stream->output_color_space = get_output_color_space(timing_out, connector_state);
7028 	stream->content_type = get_output_content_type(connector_state);
7029 }
7030 
7031 static void fill_audio_info(struct audio_info *audio_info,
7032 			    const struct drm_connector *drm_connector,
7033 			    const struct dc_sink *dc_sink)
7034 {
7035 	int i = 0;
7036 	int cea_revision = 0;
7037 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
7038 
7039 	audio_info->manufacture_id = edid_caps->manufacturer_id;
7040 	audio_info->product_id = edid_caps->product_id;
7041 
7042 	cea_revision = drm_connector->display_info.cea_rev;
7043 
7044 	strscpy(audio_info->display_name,
7045 		edid_caps->display_name,
7046 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
7047 
7048 	if (cea_revision >= 3) {
7049 		audio_info->mode_count = edid_caps->audio_mode_count;
7050 
7051 		for (i = 0; i < audio_info->mode_count; ++i) {
7052 			audio_info->modes[i].format_code =
7053 					(enum audio_format_code)
7054 					(edid_caps->audio_modes[i].format_code);
7055 			audio_info->modes[i].channel_count =
7056 					edid_caps->audio_modes[i].channel_count;
7057 			audio_info->modes[i].sample_rates.all =
7058 					edid_caps->audio_modes[i].sample_rate;
7059 			audio_info->modes[i].sample_size =
7060 					edid_caps->audio_modes[i].sample_size;
7061 		}
7062 	}
7063 
7064 	audio_info->flags.all = edid_caps->speaker_flags;
7065 
7066 	/* TODO: We only check for the progressive mode, check for interlace mode too */
7067 	if (drm_connector->latency_present[0]) {
7068 		audio_info->video_latency = drm_connector->video_latency[0];
7069 		audio_info->audio_latency = drm_connector->audio_latency[0];
7070 	}
7071 
7072 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
7073 
7074 }
7075 
7076 static void
7077 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
7078 				      struct drm_display_mode *dst_mode)
7079 {
7080 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
7081 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
7082 	dst_mode->crtc_clock = src_mode->crtc_clock;
7083 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
7084 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
7085 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
7086 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
7087 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
7088 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
7089 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
7090 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
7091 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
7092 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
7093 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
7094 }
7095 
7096 static void
7097 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
7098 					const struct drm_display_mode *native_mode,
7099 					bool scale_enabled)
7100 {
7101 	if (scale_enabled || (
7102 	    native_mode->clock == drm_mode->clock &&
7103 	    native_mode->htotal == drm_mode->htotal &&
7104 	    native_mode->vtotal == drm_mode->vtotal)) {
7105 		if (native_mode->crtc_clock)
7106 			copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
7107 	} else {
7108 		/* no scaling nor amdgpu inserted, no need to patch */
7109 	}
7110 }
7111 
7112 static struct dc_sink *
7113 create_fake_sink(struct drm_device *dev, struct dc_link *link)
7114 {
7115 	struct dc_sink_init_data sink_init_data = { 0 };
7116 	struct dc_sink *sink = NULL;
7117 
7118 	sink_init_data.link = link;
7119 	sink_init_data.sink_signal = link->connector_signal;
7120 
7121 	sink = dc_sink_create(&sink_init_data);
7122 	if (!sink) {
7123 		drm_err(dev, "Failed to create sink!\n");
7124 		return NULL;
7125 	}
7126 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
7127 
7128 	return sink;
7129 }
7130 
7131 static void set_multisync_trigger_params(
7132 		struct dc_stream_state *stream)
7133 {
7134 	struct dc_stream_state *master = NULL;
7135 
7136 	if (stream->triggered_crtc_reset.enabled) {
7137 		master = stream->triggered_crtc_reset.event_source;
7138 		stream->triggered_crtc_reset.event =
7139 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
7140 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
7141 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
7142 	}
7143 }
7144 
7145 static void set_master_stream(struct dc_stream_state *stream_set[],
7146 			      int stream_count)
7147 {
7148 	int j, highest_rfr = 0, master_stream = 0;
7149 
7150 	for (j = 0;  j < stream_count; j++) {
7151 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
7152 			int refresh_rate = 0;
7153 
7154 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
7155 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
7156 			if (refresh_rate > highest_rfr) {
7157 				highest_rfr = refresh_rate;
7158 				master_stream = j;
7159 			}
7160 		}
7161 	}
7162 	for (j = 0;  j < stream_count; j++) {
7163 		if (stream_set[j])
7164 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
7165 	}
7166 }
7167 
7168 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
7169 {
7170 	int i = 0;
7171 	struct dc_stream_state *stream;
7172 
7173 	if (context->stream_count < 2)
7174 		return;
7175 	for (i = 0; i < context->stream_count ; i++) {
7176 		if (!context->streams[i])
7177 			continue;
7178 		/*
7179 		 * TODO: add a function to read AMD VSDB bits and set
7180 		 * crtc_sync_master.multi_sync_enabled flag
7181 		 * For now it's set to false
7182 		 */
7183 	}
7184 
7185 	set_master_stream(context->streams, context->stream_count);
7186 
7187 	for (i = 0; i < context->stream_count ; i++) {
7188 		stream = context->streams[i];
7189 
7190 		if (!stream)
7191 			continue;
7192 
7193 		set_multisync_trigger_params(stream);
7194 	}
7195 }
7196 
7197 /**
7198  * DOC: FreeSync Video
7199  *
7200  * When a userspace application wants to play a video, the content follows a
7201  * standard format definition that usually specifies the FPS for that format.
7202  * The below list illustrates some video format and the expected FPS,
7203  * respectively:
7204  *
7205  * - TV/NTSC (23.976 FPS)
7206  * - Cinema (24 FPS)
7207  * - TV/PAL (25 FPS)
7208  * - TV/NTSC (29.97 FPS)
7209  * - TV/NTSC (30 FPS)
7210  * - Cinema HFR (48 FPS)
7211  * - TV/PAL (50 FPS)
7212  * - Commonly used (60 FPS)
7213  * - Multiples of 24 (48,72,96 FPS)
7214  *
7215  * The list of standards video format is not huge and can be added to the
7216  * connector modeset list beforehand. With that, userspace can leverage
7217  * FreeSync to extends the front porch in order to attain the target refresh
7218  * rate. Such a switch will happen seamlessly, without screen blanking or
7219  * reprogramming of the output in any other way. If the userspace requests a
7220  * modesetting change compatible with FreeSync modes that only differ in the
7221  * refresh rate, DC will skip the full update and avoid blink during the
7222  * transition. For example, the video player can change the modesetting from
7223  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
7224  * causing any display blink. This same concept can be applied to a mode
7225  * setting change.
7226  */
7227 static struct drm_display_mode *
7228 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
7229 		bool use_probed_modes)
7230 {
7231 	struct drm_display_mode *m, *m_pref = NULL;
7232 	u16 current_refresh, highest_refresh;
7233 	struct list_head *list_head = use_probed_modes ?
7234 		&aconnector->base.probed_modes :
7235 		&aconnector->base.modes;
7236 
7237 	if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
7238 		return NULL;
7239 
7240 	if (aconnector->freesync_vid_base.clock != 0)
7241 		return &aconnector->freesync_vid_base;
7242 
7243 	/* Find the preferred mode */
7244 	list_for_each_entry(m, list_head, head) {
7245 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
7246 			m_pref = m;
7247 			break;
7248 		}
7249 	}
7250 
7251 	if (!m_pref) {
7252 		/* Probably an EDID with no preferred mode. Fallback to first entry */
7253 		m_pref = list_first_entry_or_null(
7254 				&aconnector->base.modes, struct drm_display_mode, head);
7255 		if (!m_pref) {
7256 			drm_dbg_driver(aconnector->base.dev, "No preferred mode found in EDID\n");
7257 			return NULL;
7258 		}
7259 	}
7260 
7261 	highest_refresh = drm_mode_vrefresh(m_pref);
7262 
7263 	/*
7264 	 * Find the mode with highest refresh rate with same resolution.
7265 	 * For some monitors, preferred mode is not the mode with highest
7266 	 * supported refresh rate.
7267 	 */
7268 	list_for_each_entry(m, list_head, head) {
7269 		current_refresh  = drm_mode_vrefresh(m);
7270 
7271 		if (m->hdisplay == m_pref->hdisplay &&
7272 		    m->vdisplay == m_pref->vdisplay &&
7273 		    highest_refresh < current_refresh) {
7274 			highest_refresh = current_refresh;
7275 			m_pref = m;
7276 		}
7277 	}
7278 
7279 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
7280 	return m_pref;
7281 }
7282 
7283 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
7284 		struct amdgpu_dm_connector *aconnector)
7285 {
7286 	struct drm_display_mode *high_mode;
7287 	int timing_diff;
7288 
7289 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
7290 	if (!high_mode || !mode)
7291 		return false;
7292 
7293 	timing_diff = high_mode->vtotal - mode->vtotal;
7294 
7295 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
7296 	    high_mode->hdisplay != mode->hdisplay ||
7297 	    high_mode->vdisplay != mode->vdisplay ||
7298 	    high_mode->hsync_start != mode->hsync_start ||
7299 	    high_mode->hsync_end != mode->hsync_end ||
7300 	    high_mode->htotal != mode->htotal ||
7301 	    high_mode->hskew != mode->hskew ||
7302 	    high_mode->vscan != mode->vscan ||
7303 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
7304 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
7305 		return false;
7306 	else
7307 		return true;
7308 }
7309 
7310 #if defined(CONFIG_DRM_AMD_DC_FP)
7311 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
7312 			    struct dc_sink *sink, struct dc_stream_state *stream,
7313 			    struct dsc_dec_dpcd_caps *dsc_caps)
7314 {
7315 	stream->timing.flags.DSC = 0;
7316 	dsc_caps->is_dsc_supported = false;
7317 
7318 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
7319 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
7320 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
7321 			sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
7322 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7323 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7324 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7325 				dsc_caps);
7326 	}
7327 }
7328 
7329 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
7330 				    struct dc_sink *sink, struct dc_stream_state *stream,
7331 				    struct dsc_dec_dpcd_caps *dsc_caps,
7332 				    uint32_t max_dsc_target_bpp_limit_override)
7333 {
7334 	const struct dc_link_settings *verified_link_cap = NULL;
7335 	u32 link_bw_in_kbps;
7336 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
7337 	struct dc *dc = sink->ctx->dc;
7338 	struct dc_dsc_bw_range bw_range = {0};
7339 	struct dc_dsc_config dsc_cfg = {0};
7340 	struct dc_dsc_config_options dsc_options = {0};
7341 
7342 	dc_dsc_get_default_config_option(dc, &dsc_options);
7343 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7344 
7345 	verified_link_cap = dc_link_get_link_cap(stream->link);
7346 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
7347 	edp_min_bpp_x16 = 8 * 16;
7348 	edp_max_bpp_x16 = 8 * 16;
7349 
7350 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
7351 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
7352 
7353 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
7354 		edp_min_bpp_x16 = edp_max_bpp_x16;
7355 
7356 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
7357 				dc->debug.dsc_min_slice_height_override,
7358 				edp_min_bpp_x16, edp_max_bpp_x16,
7359 				dsc_caps,
7360 				&stream->timing,
7361 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7362 				&bw_range)) {
7363 
7364 		if (bw_range.max_kbps < link_bw_in_kbps) {
7365 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7366 					dsc_caps,
7367 					&dsc_options,
7368 					0,
7369 					&stream->timing,
7370 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7371 					&dsc_cfg)) {
7372 				stream->timing.dsc_cfg = dsc_cfg;
7373 				stream->timing.flags.DSC = 1;
7374 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
7375 			}
7376 			return;
7377 		}
7378 	}
7379 
7380 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7381 				dsc_caps,
7382 				&dsc_options,
7383 				link_bw_in_kbps,
7384 				&stream->timing,
7385 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7386 				&dsc_cfg)) {
7387 		stream->timing.dsc_cfg = dsc_cfg;
7388 		stream->timing.flags.DSC = 1;
7389 	}
7390 }
7391 
7392 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
7393 					struct dc_sink *sink, struct dc_stream_state *stream,
7394 					struct dsc_dec_dpcd_caps *dsc_caps)
7395 {
7396 	struct drm_connector *drm_connector = &aconnector->base;
7397 	u32 link_bandwidth_kbps;
7398 	struct dc *dc = sink->ctx->dc;
7399 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
7400 	u32 dsc_max_supported_bw_in_kbps;
7401 	u32 max_dsc_target_bpp_limit_override =
7402 		drm_connector->display_info.max_dsc_bpp;
7403 	struct dc_dsc_config_options dsc_options = {0};
7404 
7405 	dc_dsc_get_default_config_option(dc, &dsc_options);
7406 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7407 
7408 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
7409 							dc_link_get_link_cap(aconnector->dc_link));
7410 
7411 	/* Set DSC policy according to dsc_clock_en */
7412 	dc_dsc_policy_set_enable_dsc_when_not_needed(
7413 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
7414 
7415 	if (sink->sink_signal == SIGNAL_TYPE_EDP &&
7416 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
7417 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
7418 
7419 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
7420 
7421 	} else if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
7422 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
7423 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7424 						dsc_caps,
7425 						&dsc_options,
7426 						link_bandwidth_kbps,
7427 						&stream->timing,
7428 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7429 						&stream->timing.dsc_cfg)) {
7430 				stream->timing.flags.DSC = 1;
7431 				drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from SST RX\n",
7432 							__func__, drm_connector->name);
7433 			}
7434 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7435 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
7436 					dc_link_get_highest_encoding_format(aconnector->dc_link));
7437 			max_supported_bw_in_kbps = link_bandwidth_kbps;
7438 			dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
7439 
7440 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
7441 					max_supported_bw_in_kbps > 0 &&
7442 					dsc_max_supported_bw_in_kbps > 0)
7443 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7444 						dsc_caps,
7445 						&dsc_options,
7446 						dsc_max_supported_bw_in_kbps,
7447 						&stream->timing,
7448 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7449 						&stream->timing.dsc_cfg)) {
7450 					stream->timing.flags.DSC = 1;
7451 					drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from DP-HDMI PCON\n",
7452 									 __func__, drm_connector->name);
7453 				}
7454 		}
7455 	}
7456 
7457 	/* Overwrite the stream flag if DSC is enabled through debugfs */
7458 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
7459 		stream->timing.flags.DSC = 1;
7460 
7461 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
7462 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
7463 
7464 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
7465 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
7466 
7467 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
7468 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
7469 }
7470 #endif
7471 
7472 static struct dc_stream_state *
7473 create_stream_for_sink(struct drm_connector *connector,
7474 		       const struct drm_display_mode *drm_mode,
7475 		       const struct dm_connector_state *dm_state,
7476 		       const struct dc_stream_state *old_stream,
7477 		       int requested_bpc)
7478 {
7479 	struct drm_device *dev = connector->dev;
7480 	struct amdgpu_dm_connector *aconnector = NULL;
7481 	struct drm_display_mode *preferred_mode = NULL;
7482 	const struct drm_connector_state *con_state = &dm_state->base;
7483 	struct dc_stream_state *stream = NULL;
7484 	struct drm_display_mode mode;
7485 	struct drm_display_mode saved_mode;
7486 	struct drm_display_mode *freesync_mode = NULL;
7487 	bool native_mode_found = false;
7488 	bool recalculate_timing = false;
7489 	bool scale = dm_state->scaling != RMX_OFF;
7490 	int mode_refresh;
7491 	int preferred_refresh = 0;
7492 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
7493 #if defined(CONFIG_DRM_AMD_DC_FP)
7494 	struct dsc_dec_dpcd_caps dsc_caps = {0};
7495 #endif
7496 	struct dc_link *link = NULL;
7497 	struct dc_sink *sink = NULL;
7498 
7499 	drm_mode_init(&mode, drm_mode);
7500 	memset(&saved_mode, 0, sizeof(saved_mode));
7501 
7502 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK) {
7503 		aconnector = NULL;
7504 		aconnector = to_amdgpu_dm_connector(connector);
7505 		link = aconnector->dc_link;
7506 	} else {
7507 		struct drm_writeback_connector *wbcon = NULL;
7508 		struct amdgpu_dm_wb_connector *dm_wbcon = NULL;
7509 
7510 		wbcon = drm_connector_to_writeback(connector);
7511 		dm_wbcon = to_amdgpu_dm_wb_connector(wbcon);
7512 		link = dm_wbcon->link;
7513 	}
7514 
7515 	if (!aconnector || !aconnector->dc_sink) {
7516 		sink = create_fake_sink(dev, link);
7517 		if (!sink)
7518 			return stream;
7519 
7520 	} else {
7521 		sink = aconnector->dc_sink;
7522 		dc_sink_retain(sink);
7523 	}
7524 
7525 	stream = dc_create_stream_for_sink(sink);
7526 
7527 	if (stream == NULL) {
7528 		drm_err(dev, "Failed to create stream for sink!\n");
7529 		goto finish;
7530 	}
7531 
7532 	/* We leave this NULL for writeback connectors */
7533 	stream->dm_stream_context = aconnector;
7534 
7535 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
7536 		connector->display_info.hdmi.scdc.scrambling.low_rates;
7537 
7538 	list_for_each_entry(preferred_mode, &connector->modes, head) {
7539 		/* Search for preferred mode */
7540 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
7541 			native_mode_found = true;
7542 			break;
7543 		}
7544 	}
7545 	if (!native_mode_found)
7546 		preferred_mode = list_first_entry_or_null(
7547 				&connector->modes,
7548 				struct drm_display_mode,
7549 				head);
7550 
7551 	mode_refresh = drm_mode_vrefresh(&mode);
7552 
7553 	if (preferred_mode == NULL) {
7554 		/*
7555 		 * This may not be an error, the use case is when we have no
7556 		 * usermode calls to reset and set mode upon hotplug. In this
7557 		 * case, we call set mode ourselves to restore the previous mode
7558 		 * and the modelist may not be filled in time.
7559 		 */
7560 		drm_dbg_driver(dev, "No preferred mode found\n");
7561 	} else if (aconnector) {
7562 		recalculate_timing = amdgpu_freesync_vid_mode &&
7563 				 is_freesync_video_mode(&mode, aconnector);
7564 		if (recalculate_timing) {
7565 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
7566 			drm_mode_copy(&saved_mode, &mode);
7567 			saved_mode.picture_aspect_ratio = mode.picture_aspect_ratio;
7568 			drm_mode_copy(&mode, freesync_mode);
7569 			mode.picture_aspect_ratio = saved_mode.picture_aspect_ratio;
7570 		} else {
7571 			decide_crtc_timing_for_drm_display_mode(
7572 					&mode, preferred_mode, scale);
7573 
7574 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
7575 		}
7576 	}
7577 
7578 	if (recalculate_timing)
7579 		drm_mode_set_crtcinfo(&saved_mode, 0);
7580 
7581 	/*
7582 	 * If scaling is enabled and refresh rate didn't change
7583 	 * we copy the vic and polarities of the old timings
7584 	 */
7585 	if (!scale || mode_refresh != preferred_refresh)
7586 		fill_stream_properties_from_drm_display_mode(
7587 			stream, &mode, connector, con_state, NULL,
7588 			requested_bpc);
7589 	else
7590 		fill_stream_properties_from_drm_display_mode(
7591 			stream, &mode, connector, con_state, old_stream,
7592 			requested_bpc);
7593 
7594 	/* The rest isn't needed for writeback connectors */
7595 	if (!aconnector)
7596 		goto finish;
7597 
7598 	if (aconnector->timing_changed) {
7599 		drm_dbg(aconnector->base.dev,
7600 			"overriding timing for automated test, bpc %d, changing to %d\n",
7601 			stream->timing.display_color_depth,
7602 			aconnector->timing_requested->display_color_depth);
7603 		stream->timing = *aconnector->timing_requested;
7604 	}
7605 
7606 #if defined(CONFIG_DRM_AMD_DC_FP)
7607 	/* SST DSC determination policy */
7608 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
7609 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
7610 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
7611 #endif
7612 
7613 	update_stream_scaling_settings(dev, &mode, dm_state, stream);
7614 
7615 	fill_audio_info(
7616 		&stream->audio_info,
7617 		connector,
7618 		sink);
7619 
7620 	update_stream_signal(stream, sink);
7621 
7622 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
7623 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket);
7624 
7625 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT ||
7626 	    stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
7627 	    stream->signal == SIGNAL_TYPE_EDP) {
7628 		const struct dc_edid_caps *edid_caps;
7629 		unsigned int disable_colorimetry = 0;
7630 
7631 		if (aconnector->dc_sink) {
7632 			edid_caps = &aconnector->dc_sink->edid_caps;
7633 			disable_colorimetry = edid_caps->panel_patch.disable_colorimetry;
7634 		}
7635 
7636 		//
7637 		// should decide stream support vsc sdp colorimetry capability
7638 		// before building vsc info packet
7639 		//
7640 		stream->use_vsc_sdp_for_colorimetry = stream->link->dpcd_caps.dpcd_rev.raw >= 0x14 &&
7641 						      stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED &&
7642 						      !disable_colorimetry;
7643 
7644 		if (stream->out_transfer_func.tf == TRANSFER_FUNCTION_GAMMA22)
7645 			tf = TRANSFER_FUNC_GAMMA_22;
7646 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
7647 		aconnector->sr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
7648 
7649 	}
7650 finish:
7651 	dc_sink_release(sink);
7652 
7653 	return stream;
7654 }
7655 
7656 /**
7657  * amdgpu_dm_connector_poll - Poll a connector to see if it's connected to a display
7658  * @aconnector: DM connector to poll (owns @base drm_connector and @dc_link)
7659  * @force: if true, force polling even when DAC load detection was used
7660  *
7661  * Used for connectors that don't support HPD (hotplug detection) to
7662  * periodically check whether the connector is connected to a display.
7663  *
7664  * When connection was determined via DAC load detection, we avoid
7665  * re-running it on normal polls to prevent visible glitches, unless
7666  * @force is set.
7667  *
7668  * Return: The probed connector status (connected/disconnected/unknown).
7669  */
7670 static enum drm_connector_status
7671 amdgpu_dm_connector_poll(struct amdgpu_dm_connector *aconnector, bool force)
7672 {
7673 	struct drm_connector *connector = &aconnector->base;
7674 	struct drm_device *dev = connector->dev;
7675 	struct amdgpu_device *adev = drm_to_adev(dev);
7676 	struct dc_link *link = aconnector->dc_link;
7677 	enum dc_connection_type conn_type = dc_connection_none;
7678 	enum drm_connector_status status = connector_status_disconnected;
7679 
7680 	/* When we determined the connection using DAC load detection,
7681 	 * do NOT poll the connector do detect disconnect because
7682 	 * that would run DAC load detection again which can cause
7683 	 * visible visual glitches.
7684 	 *
7685 	 * Only allow to poll such a connector again when forcing.
7686 	 */
7687 	if (!force && link->local_sink && link->type == dc_connection_analog_load)
7688 		return connector->status;
7689 
7690 	mutex_lock(&aconnector->hpd_lock);
7691 
7692 	if (dc_link_detect_connection_type(aconnector->dc_link, &conn_type) &&
7693 	    conn_type != dc_connection_none) {
7694 		mutex_lock(&adev->dm.dc_lock);
7695 
7696 		/* Only call full link detection when a sink isn't created yet,
7697 		 * ie. just when the display is plugged in, otherwise we risk flickering.
7698 		 */
7699 		if (link->local_sink ||
7700 			dc_link_detect(link, DETECT_REASON_HPD))
7701 			status = connector_status_connected;
7702 
7703 		mutex_unlock(&adev->dm.dc_lock);
7704 	}
7705 
7706 	if (connector->status != status) {
7707 		if (status == connector_status_disconnected) {
7708 			if (link->local_sink)
7709 				dc_sink_release(link->local_sink);
7710 
7711 			link->local_sink = NULL;
7712 			link->dpcd_sink_count = 0;
7713 			link->type = dc_connection_none;
7714 		}
7715 
7716 		amdgpu_dm_update_connector_after_detect(aconnector);
7717 	}
7718 
7719 	mutex_unlock(&aconnector->hpd_lock);
7720 	return status;
7721 }
7722 
7723 /**
7724  * amdgpu_dm_connector_detect() - Detect whether a DRM connector is connected to a display
7725  *
7726  * A connector is considered connected when it has a sink that is not NULL.
7727  * For connectors that support HPD (hotplug detection), the connection is
7728  * handled in the HPD interrupt.
7729  * For connectors that may not support HPD, such as analog connectors,
7730  * DRM will call this function repeatedly to poll them.
7731  *
7732  * Notes:
7733  * 1. This interface is NOT called in context of HPD irq.
7734  * 2. This interface *is called* in context of user-mode ioctl. Which
7735  *    makes it a bad place for *any* MST-related activity.
7736  *
7737  * @connector: The DRM connector we are checking. We convert it to
7738  *             amdgpu_dm_connector so we can read the DC link and state.
7739  * @force:     If true, do a full detect again. This is used even when
7740  *             a lighter check would normally be used to avoid flicker.
7741  *
7742  * Return: The connector status (connected, disconnected, or unknown).
7743  *
7744  */
7745 static enum drm_connector_status
7746 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
7747 {
7748 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7749 
7750 	update_subconnector_property(aconnector);
7751 
7752 	if (aconnector->base.force == DRM_FORCE_ON ||
7753 		aconnector->base.force == DRM_FORCE_ON_DIGITAL)
7754 		return connector_status_connected;
7755 	else if (aconnector->base.force == DRM_FORCE_OFF)
7756 		return connector_status_disconnected;
7757 
7758 	/* Poll analog connectors and only when either
7759 	 * disconnected or connected to an analog display.
7760 	 */
7761 	if (drm_kms_helper_is_poll_worker() &&
7762 		dc_connector_supports_analog(aconnector->dc_link->link_id.id) &&
7763 		(!aconnector->dc_sink || aconnector->dc_sink->edid_caps.analog))
7764 		return amdgpu_dm_connector_poll(aconnector, force);
7765 
7766 	return (aconnector->dc_sink ? connector_status_connected :
7767 			connector_status_disconnected);
7768 }
7769 
7770 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
7771 					    struct drm_connector_state *connector_state,
7772 					    struct drm_property *property,
7773 					    uint64_t val)
7774 {
7775 	struct drm_device *dev = connector->dev;
7776 	struct amdgpu_device *adev = drm_to_adev(dev);
7777 	struct dm_connector_state *dm_old_state =
7778 		to_dm_connector_state(connector->state);
7779 	struct dm_connector_state *dm_new_state =
7780 		to_dm_connector_state(connector_state);
7781 
7782 	int ret = -EINVAL;
7783 
7784 	if (property == dev->mode_config.scaling_mode_property) {
7785 		enum amdgpu_rmx_type rmx_type;
7786 
7787 		switch (val) {
7788 		case DRM_MODE_SCALE_CENTER:
7789 			rmx_type = RMX_CENTER;
7790 			break;
7791 		case DRM_MODE_SCALE_ASPECT:
7792 			rmx_type = RMX_ASPECT;
7793 			break;
7794 		case DRM_MODE_SCALE_FULLSCREEN:
7795 			rmx_type = RMX_FULL;
7796 			break;
7797 		case DRM_MODE_SCALE_NONE:
7798 		default:
7799 			rmx_type = RMX_OFF;
7800 			break;
7801 		}
7802 
7803 		if (dm_old_state->scaling == rmx_type)
7804 			return 0;
7805 
7806 		dm_new_state->scaling = rmx_type;
7807 		ret = 0;
7808 	} else if (property == adev->mode_info.underscan_hborder_property) {
7809 		dm_new_state->underscan_hborder = val;
7810 		ret = 0;
7811 	} else if (property == adev->mode_info.underscan_vborder_property) {
7812 		dm_new_state->underscan_vborder = val;
7813 		ret = 0;
7814 	} else if (property == adev->mode_info.underscan_property) {
7815 		dm_new_state->underscan_enable = val;
7816 		ret = 0;
7817 	} else if (property == adev->mode_info.abm_level_property) {
7818 		switch (val) {
7819 		case ABM_SYSFS_CONTROL:
7820 			dm_new_state->abm_sysfs_forbidden = false;
7821 			break;
7822 		case ABM_LEVEL_OFF:
7823 			dm_new_state->abm_sysfs_forbidden = true;
7824 			dm_new_state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7825 			break;
7826 		default:
7827 			dm_new_state->abm_sysfs_forbidden = true;
7828 			dm_new_state->abm_level = val;
7829 		}
7830 		ret = 0;
7831 	}
7832 
7833 	return ret;
7834 }
7835 
7836 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
7837 					    const struct drm_connector_state *state,
7838 					    struct drm_property *property,
7839 					    uint64_t *val)
7840 {
7841 	struct drm_device *dev = connector->dev;
7842 	struct amdgpu_device *adev = drm_to_adev(dev);
7843 	struct dm_connector_state *dm_state =
7844 		to_dm_connector_state(state);
7845 	int ret = -EINVAL;
7846 
7847 	if (property == dev->mode_config.scaling_mode_property) {
7848 		switch (dm_state->scaling) {
7849 		case RMX_CENTER:
7850 			*val = DRM_MODE_SCALE_CENTER;
7851 			break;
7852 		case RMX_ASPECT:
7853 			*val = DRM_MODE_SCALE_ASPECT;
7854 			break;
7855 		case RMX_FULL:
7856 			*val = DRM_MODE_SCALE_FULLSCREEN;
7857 			break;
7858 		case RMX_OFF:
7859 		default:
7860 			*val = DRM_MODE_SCALE_NONE;
7861 			break;
7862 		}
7863 		ret = 0;
7864 	} else if (property == adev->mode_info.underscan_hborder_property) {
7865 		*val = dm_state->underscan_hborder;
7866 		ret = 0;
7867 	} else if (property == adev->mode_info.underscan_vborder_property) {
7868 		*val = dm_state->underscan_vborder;
7869 		ret = 0;
7870 	} else if (property == adev->mode_info.underscan_property) {
7871 		*val = dm_state->underscan_enable;
7872 		ret = 0;
7873 	} else if (property == adev->mode_info.abm_level_property) {
7874 		if (!dm_state->abm_sysfs_forbidden)
7875 			*val = ABM_SYSFS_CONTROL;
7876 		else
7877 			*val = (dm_state->abm_level != ABM_LEVEL_IMMEDIATE_DISABLE) ?
7878 				dm_state->abm_level : 0;
7879 		ret = 0;
7880 	}
7881 
7882 	return ret;
7883 }
7884 
7885 /**
7886  * DOC: panel power savings
7887  *
7888  * The display manager allows you to set your desired **panel power savings**
7889  * level (between 0-4, with 0 representing off), e.g. using the following::
7890  *
7891  *   # echo 3 > /sys/class/drm/card0-eDP-1/amdgpu/panel_power_savings
7892  *
7893  * Modifying this value can have implications on color accuracy, so tread
7894  * carefully.
7895  */
7896 
7897 static ssize_t panel_power_savings_show(struct device *device,
7898 					struct device_attribute *attr,
7899 					char *buf)
7900 {
7901 	struct drm_connector *connector = dev_get_drvdata(device);
7902 	struct drm_device *dev = connector->dev;
7903 	u8 val;
7904 
7905 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
7906 	val = to_dm_connector_state(connector->state)->abm_level ==
7907 		ABM_LEVEL_IMMEDIATE_DISABLE ? 0 :
7908 		to_dm_connector_state(connector->state)->abm_level;
7909 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
7910 
7911 	return sysfs_emit(buf, "%u\n", val);
7912 }
7913 
7914 static ssize_t panel_power_savings_store(struct device *device,
7915 					 struct device_attribute *attr,
7916 					 const char *buf, size_t count)
7917 {
7918 	struct drm_connector *connector = dev_get_drvdata(device);
7919 	struct drm_device *dev = connector->dev;
7920 	long val;
7921 	int ret;
7922 
7923 	ret = kstrtol(buf, 0, &val);
7924 
7925 	if (ret)
7926 		return ret;
7927 
7928 	if (val < 0 || val > 4)
7929 		return -EINVAL;
7930 
7931 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
7932 	if (to_dm_connector_state(connector->state)->abm_sysfs_forbidden)
7933 		ret = -EBUSY;
7934 	else
7935 		to_dm_connector_state(connector->state)->abm_level = val ?:
7936 			ABM_LEVEL_IMMEDIATE_DISABLE;
7937 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
7938 
7939 	if (ret)
7940 		return ret;
7941 
7942 	drm_kms_helper_hotplug_event(dev);
7943 
7944 	return count;
7945 }
7946 
7947 static DEVICE_ATTR_RW(panel_power_savings);
7948 
7949 static struct attribute *amdgpu_attrs[] = {
7950 	&dev_attr_panel_power_savings.attr,
7951 	NULL
7952 };
7953 
7954 static const struct attribute_group amdgpu_group = {
7955 	.name = "amdgpu",
7956 	.attrs = amdgpu_attrs
7957 };
7958 
7959 static bool
7960 amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector *amdgpu_dm_connector)
7961 {
7962 	if (amdgpu_dm_abm_level >= 0)
7963 		return false;
7964 
7965 	if (amdgpu_dm_connector->base.connector_type != DRM_MODE_CONNECTOR_eDP)
7966 		return false;
7967 
7968 	/* check for OLED panels */
7969 	if (amdgpu_dm_connector->bl_idx >= 0) {
7970 		struct drm_device *drm = amdgpu_dm_connector->base.dev;
7971 		struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
7972 		struct amdgpu_dm_backlight_caps *caps;
7973 
7974 		caps = &dm->backlight_caps[amdgpu_dm_connector->bl_idx];
7975 		if (caps->aux_support)
7976 			return false;
7977 	}
7978 
7979 	return true;
7980 }
7981 
7982 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
7983 {
7984 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
7985 
7986 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector))
7987 		sysfs_remove_group(&connector->kdev->kobj, &amdgpu_group);
7988 
7989 	cec_notifier_conn_unregister(amdgpu_dm_connector->notifier);
7990 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
7991 }
7992 
7993 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
7994 {
7995 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7996 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
7997 	struct amdgpu_display_manager *dm = &adev->dm;
7998 
7999 	/*
8000 	 * Call only if mst_mgr was initialized before since it's not done
8001 	 * for all connector types.
8002 	 */
8003 	if (aconnector->mst_mgr.dev)
8004 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
8005 
8006 	/* Cancel and flush any pending HDMI HPD debounce work */
8007 	if (aconnector->hdmi_hpd_debounce_delay_ms) {
8008 		cancel_delayed_work_sync(&aconnector->hdmi_hpd_debounce_work);
8009 		if (aconnector->hdmi_prev_sink) {
8010 			dc_sink_release(aconnector->hdmi_prev_sink);
8011 			aconnector->hdmi_prev_sink = NULL;
8012 		}
8013 	}
8014 
8015 	if (aconnector->bl_idx != -1) {
8016 		backlight_device_unregister(dm->backlight_dev[aconnector->bl_idx]);
8017 		dm->backlight_dev[aconnector->bl_idx] = NULL;
8018 	}
8019 
8020 	if (aconnector->dc_em_sink)
8021 		dc_sink_release(aconnector->dc_em_sink);
8022 	aconnector->dc_em_sink = NULL;
8023 	if (aconnector->dc_sink)
8024 		dc_sink_release(aconnector->dc_sink);
8025 	aconnector->dc_sink = NULL;
8026 
8027 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
8028 	drm_connector_unregister(connector);
8029 	drm_connector_cleanup(connector);
8030 	kfree(aconnector->dm_dp_aux.aux.name);
8031 
8032 	kfree(connector);
8033 }
8034 
8035 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
8036 {
8037 	struct dm_connector_state *state =
8038 		to_dm_connector_state(connector->state);
8039 
8040 	if (connector->state)
8041 		__drm_atomic_helper_connector_destroy_state(connector->state);
8042 
8043 	kfree(state);
8044 
8045 	state = kzalloc_obj(*state);
8046 
8047 	if (state) {
8048 		state->scaling = RMX_OFF;
8049 		state->underscan_enable = false;
8050 		state->underscan_hborder = 0;
8051 		state->underscan_vborder = 0;
8052 		state->base.max_requested_bpc = 8;
8053 		state->vcpi_slots = 0;
8054 		state->pbn = 0;
8055 
8056 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) {
8057 			if (amdgpu_dm_abm_level <= 0)
8058 				state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
8059 			else
8060 				state->abm_level = amdgpu_dm_abm_level;
8061 		}
8062 
8063 		__drm_atomic_helper_connector_reset(connector, &state->base);
8064 	}
8065 }
8066 
8067 struct drm_connector_state *
8068 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
8069 {
8070 	struct dm_connector_state *state =
8071 		to_dm_connector_state(connector->state);
8072 
8073 	struct dm_connector_state *new_state =
8074 			kmemdup(state, sizeof(*state), GFP_KERNEL);
8075 
8076 	if (!new_state)
8077 		return NULL;
8078 
8079 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
8080 
8081 	new_state->freesync_capable = state->freesync_capable;
8082 	new_state->abm_level = state->abm_level;
8083 	new_state->scaling = state->scaling;
8084 	new_state->underscan_enable = state->underscan_enable;
8085 	new_state->underscan_hborder = state->underscan_hborder;
8086 	new_state->underscan_vborder = state->underscan_vborder;
8087 	new_state->vcpi_slots = state->vcpi_slots;
8088 	new_state->pbn = state->pbn;
8089 	return &new_state->base;
8090 }
8091 
8092 static int
8093 amdgpu_dm_connector_late_register(struct drm_connector *connector)
8094 {
8095 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8096 		to_amdgpu_dm_connector(connector);
8097 	int r;
8098 
8099 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector)) {
8100 		r = sysfs_create_group(&connector->kdev->kobj,
8101 				       &amdgpu_group);
8102 		if (r)
8103 			return r;
8104 	}
8105 
8106 	amdgpu_dm_register_backlight_device(amdgpu_dm_connector);
8107 
8108 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
8109 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
8110 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
8111 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
8112 		if (r)
8113 			return r;
8114 	}
8115 
8116 #if defined(CONFIG_DEBUG_FS)
8117 	connector_debugfs_init(amdgpu_dm_connector);
8118 #endif
8119 
8120 	return 0;
8121 }
8122 
8123 static void amdgpu_dm_connector_funcs_force(struct drm_connector *connector)
8124 {
8125 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8126 	struct dc_link *dc_link = aconnector->dc_link;
8127 	struct dc_sink *dc_em_sink = aconnector->dc_em_sink;
8128 	const struct drm_edid *drm_edid;
8129 	struct i2c_adapter *ddc;
8130 	struct drm_device *dev = connector->dev;
8131 
8132 	if (dc_link && dc_link->aux_mode)
8133 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8134 	else
8135 		ddc = &aconnector->i2c->base;
8136 
8137 	drm_edid = drm_edid_read_ddc(connector, ddc);
8138 	drm_edid_connector_update(connector, drm_edid);
8139 	if (!drm_edid) {
8140 		drm_err(dev, "No EDID found on connector: %s.\n", connector->name);
8141 		return;
8142 	}
8143 
8144 	aconnector->drm_edid = drm_edid;
8145 	/* Update emulated (virtual) sink's EDID */
8146 	if (dc_em_sink && dc_link) {
8147 		// FIXME: Get rid of drm_edid_raw()
8148 		const struct edid *edid = drm_edid_raw(drm_edid);
8149 
8150 		memset(&dc_em_sink->edid_caps, 0, sizeof(struct dc_edid_caps));
8151 		memmove(dc_em_sink->dc_edid.raw_edid, edid,
8152 			(edid->extensions + 1) * EDID_LENGTH);
8153 		dm_helpers_parse_edid_caps(
8154 			dc_link,
8155 			&dc_em_sink->dc_edid,
8156 			&dc_em_sink->edid_caps);
8157 	}
8158 }
8159 
8160 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
8161 	.reset = amdgpu_dm_connector_funcs_reset,
8162 	.detect = amdgpu_dm_connector_detect,
8163 	.fill_modes = drm_helper_probe_single_connector_modes,
8164 	.destroy = amdgpu_dm_connector_destroy,
8165 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
8166 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
8167 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
8168 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
8169 	.late_register = amdgpu_dm_connector_late_register,
8170 	.early_unregister = amdgpu_dm_connector_unregister,
8171 	.force = amdgpu_dm_connector_funcs_force
8172 };
8173 
8174 static int get_modes(struct drm_connector *connector)
8175 {
8176 	return amdgpu_dm_connector_get_modes(connector);
8177 }
8178 
8179 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
8180 {
8181 	struct drm_connector *connector = &aconnector->base;
8182 	struct dc_link *dc_link = aconnector->dc_link;
8183 	struct dc_sink_init_data init_params = {
8184 			.link = aconnector->dc_link,
8185 			.sink_signal = SIGNAL_TYPE_VIRTUAL
8186 	};
8187 	const struct drm_edid *drm_edid;
8188 	const struct edid *edid;
8189 	struct i2c_adapter *ddc;
8190 
8191 	if (dc_link && dc_link->aux_mode)
8192 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8193 	else
8194 		ddc = &aconnector->i2c->base;
8195 
8196 	drm_edid = drm_edid_read_ddc(connector, ddc);
8197 	drm_edid_connector_update(connector, drm_edid);
8198 	if (!drm_edid) {
8199 		drm_err(connector->dev, "No EDID found on connector: %s.\n", connector->name);
8200 		return;
8201 	}
8202 
8203 	if (connector->display_info.is_hdmi)
8204 		init_params.sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
8205 
8206 	aconnector->drm_edid = drm_edid;
8207 
8208 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
8209 	aconnector->dc_em_sink = dc_link_add_remote_sink(
8210 		aconnector->dc_link,
8211 		(uint8_t *)edid,
8212 		(edid->extensions + 1) * EDID_LENGTH,
8213 		&init_params);
8214 
8215 	if (aconnector->base.force == DRM_FORCE_ON) {
8216 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
8217 		aconnector->dc_link->local_sink :
8218 		aconnector->dc_em_sink;
8219 		if (aconnector->dc_sink)
8220 			dc_sink_retain(aconnector->dc_sink);
8221 	}
8222 }
8223 
8224 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
8225 {
8226 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
8227 
8228 	/*
8229 	 * In case of headless boot with force on for DP managed connector
8230 	 * Those settings have to be != 0 to get initial modeset
8231 	 */
8232 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
8233 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
8234 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
8235 	}
8236 
8237 	create_eml_sink(aconnector);
8238 }
8239 
8240 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
8241 						struct dc_stream_state *stream)
8242 {
8243 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
8244 	struct dc_plane_state *dc_plane_state = NULL;
8245 	struct dc_state *dc_state = NULL;
8246 
8247 	if (!stream)
8248 		goto cleanup;
8249 
8250 	dc_plane_state = dc_create_plane_state(dc);
8251 	if (!dc_plane_state)
8252 		goto cleanup;
8253 
8254 	dc_state = dc_state_create(dc, NULL);
8255 	if (!dc_state)
8256 		goto cleanup;
8257 
8258 	/* populate stream to plane */
8259 	dc_plane_state->src_rect.height  = stream->src.height;
8260 	dc_plane_state->src_rect.width   = stream->src.width;
8261 	dc_plane_state->dst_rect.height  = stream->src.height;
8262 	dc_plane_state->dst_rect.width   = stream->src.width;
8263 	dc_plane_state->clip_rect.height = stream->src.height;
8264 	dc_plane_state->clip_rect.width  = stream->src.width;
8265 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
8266 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
8267 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
8268 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
8269 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
8270 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
8271 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
8272 	dc_plane_state->rotation = ROTATION_ANGLE_0;
8273 	dc_plane_state->is_tiling_rotated = false;
8274 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
8275 
8276 	dc_result = dc_validate_stream(dc, stream);
8277 	if (dc_result == DC_OK)
8278 		dc_result = dc_validate_plane(dc, dc_plane_state);
8279 
8280 	if (dc_result == DC_OK)
8281 		dc_result = dc_state_add_stream(dc, dc_state, stream);
8282 
8283 	if (dc_result == DC_OK && !dc_state_add_plane(
8284 						dc,
8285 						stream,
8286 						dc_plane_state,
8287 						dc_state))
8288 		dc_result = DC_FAIL_ATTACH_SURFACES;
8289 
8290 	if (dc_result == DC_OK)
8291 		dc_result = dc_validate_global_state(dc, dc_state, DC_VALIDATE_MODE_ONLY);
8292 
8293 cleanup:
8294 	if (dc_state)
8295 		dc_state_release(dc_state);
8296 
8297 	if (dc_plane_state)
8298 		dc_plane_state_release(dc_plane_state);
8299 
8300 	return dc_result;
8301 }
8302 
8303 struct dc_stream_state *
8304 create_validate_stream_for_sink(struct drm_connector *connector,
8305 				const struct drm_display_mode *drm_mode,
8306 				const struct dm_connector_state *dm_state,
8307 				const struct dc_stream_state *old_stream)
8308 {
8309 	struct amdgpu_dm_connector *aconnector = NULL;
8310 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8311 	struct dc_stream_state *stream;
8312 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
8313 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
8314 	enum dc_status dc_result = DC_OK;
8315 	uint8_t bpc_limit = 6;
8316 
8317 	if (!dm_state)
8318 		return NULL;
8319 
8320 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
8321 		aconnector = to_amdgpu_dm_connector(connector);
8322 
8323 	if (aconnector &&
8324 	    (aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
8325 	     aconnector->dc_link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER))
8326 		bpc_limit = 8;
8327 
8328 	do {
8329 		drm_dbg_kms(connector->dev, "Trying with %d bpc\n", requested_bpc);
8330 		stream = create_stream_for_sink(connector, drm_mode,
8331 						dm_state, old_stream,
8332 						requested_bpc);
8333 		if (stream == NULL) {
8334 			drm_err(adev_to_drm(adev), "Failed to create stream for sink!\n");
8335 			break;
8336 		}
8337 
8338 		dc_result = dc_validate_stream(adev->dm.dc, stream);
8339 
8340 		if (!aconnector) /* writeback connector */
8341 			return stream;
8342 
8343 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
8344 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
8345 
8346 		if (dc_result == DC_OK)
8347 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
8348 
8349 		if (dc_result != DC_OK) {
8350 			drm_dbg_kms(connector->dev, "Pruned mode %d x %d (clk %d) %s %s -- %s\n",
8351 				      drm_mode->hdisplay,
8352 				      drm_mode->vdisplay,
8353 				      drm_mode->clock,
8354 				      dc_pixel_encoding_to_str(stream->timing.pixel_encoding),
8355 				      dc_color_depth_to_str(stream->timing.display_color_depth),
8356 				      dc_status_to_str(dc_result));
8357 
8358 			dc_stream_release(stream);
8359 			stream = NULL;
8360 			requested_bpc -= 2; /* lower bpc to retry validation */
8361 		}
8362 
8363 	} while (stream == NULL && requested_bpc >= bpc_limit);
8364 
8365 	switch (dc_result) {
8366 	/*
8367 	 * If we failed to validate DP bandwidth stream with the requested RGB color depth,
8368 	 * we try to fallback and configure in order:
8369 	 * YUV422 (8bpc, 6bpc)
8370 	 * YUV420 (8bpc, 6bpc)
8371 	 */
8372 	case DC_FAIL_ENC_VALIDATE:
8373 	case DC_EXCEED_DONGLE_CAP:
8374 	case DC_NO_DP_LINK_BANDWIDTH:
8375 		/* recursively entered twice and already tried both YUV422 and YUV420 */
8376 		if (aconnector->force_yuv422_output && aconnector->force_yuv420_output)
8377 			break;
8378 		/* first failure; try YUV422 */
8379 		if (!aconnector->force_yuv422_output) {
8380 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV422\n",
8381 				    __func__, __LINE__, dc_result);
8382 			aconnector->force_yuv422_output = true;
8383 		/* recursively entered and YUV422 failed, try YUV420 */
8384 		} else if (!aconnector->force_yuv420_output) {
8385 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV420\n",
8386 				    __func__, __LINE__, dc_result);
8387 			aconnector->force_yuv420_output = true;
8388 		}
8389 		stream = create_validate_stream_for_sink(connector, drm_mode,
8390 							 dm_state, old_stream);
8391 		aconnector->force_yuv422_output = false;
8392 		aconnector->force_yuv420_output = false;
8393 		break;
8394 	case DC_OK:
8395 		break;
8396 	default:
8397 		drm_dbg_kms(connector->dev, "%s:%d Unhandled validation failure %d\n",
8398 			    __func__, __LINE__, dc_result);
8399 		break;
8400 	}
8401 
8402 	return stream;
8403 }
8404 
8405 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
8406 				   const struct drm_display_mode *mode)
8407 {
8408 	int result = MODE_ERROR;
8409 	struct dc_sink *dc_sink;
8410 	struct drm_display_mode *test_mode;
8411 	/* TODO: Unhardcode stream count */
8412 	struct dc_stream_state *stream;
8413 	/* we always have an amdgpu_dm_connector here since we got
8414 	 * here via the amdgpu_dm_connector_helper_funcs
8415 	 */
8416 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8417 
8418 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
8419 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
8420 		return result;
8421 
8422 	/*
8423 	 * Only run this the first time mode_valid is called to initilialize
8424 	 * EDID mgmt
8425 	 */
8426 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
8427 		!aconnector->dc_em_sink)
8428 		handle_edid_mgmt(aconnector);
8429 
8430 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
8431 
8432 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
8433 				aconnector->base.force != DRM_FORCE_ON) {
8434 		drm_err(connector->dev, "dc_sink is NULL!\n");
8435 		goto fail;
8436 	}
8437 
8438 	test_mode = drm_mode_duplicate(connector->dev, mode);
8439 	if (!test_mode)
8440 		goto fail;
8441 
8442 	drm_mode_set_crtcinfo(test_mode, 0);
8443 
8444 	stream = create_validate_stream_for_sink(connector, test_mode,
8445 						 to_dm_connector_state(connector->state),
8446 						 NULL);
8447 	drm_mode_destroy(connector->dev, test_mode);
8448 	if (stream) {
8449 		dc_stream_release(stream);
8450 		result = MODE_OK;
8451 	}
8452 
8453 fail:
8454 	/* TODO: error handling*/
8455 	return result;
8456 }
8457 
8458 static int fill_hdr_info_packet(const struct drm_connector_state *state,
8459 				struct dc_info_packet *out)
8460 {
8461 	struct hdmi_drm_infoframe frame;
8462 	unsigned char buf[30]; /* 26 + 4 */
8463 	ssize_t len;
8464 	int ret, i;
8465 
8466 	memset(out, 0, sizeof(*out));
8467 
8468 	if (!state->hdr_output_metadata)
8469 		return 0;
8470 
8471 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
8472 	if (ret)
8473 		return ret;
8474 
8475 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
8476 	if (len < 0)
8477 		return (int)len;
8478 
8479 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
8480 	if (len != 30)
8481 		return -EINVAL;
8482 
8483 	/* Prepare the infopacket for DC. */
8484 	switch (state->connector->connector_type) {
8485 	case DRM_MODE_CONNECTOR_HDMIA:
8486 		out->hb0 = 0x87; /* type */
8487 		out->hb1 = 0x01; /* version */
8488 		out->hb2 = 0x1A; /* length */
8489 		out->sb[0] = buf[3]; /* checksum */
8490 		i = 1;
8491 		break;
8492 
8493 	case DRM_MODE_CONNECTOR_DisplayPort:
8494 	case DRM_MODE_CONNECTOR_eDP:
8495 		out->hb0 = 0x00; /* sdp id, zero */
8496 		out->hb1 = 0x87; /* type */
8497 		out->hb2 = 0x1D; /* payload len - 1 */
8498 		out->hb3 = (0x13 << 2); /* sdp version */
8499 		out->sb[0] = 0x01; /* version */
8500 		out->sb[1] = 0x1A; /* length */
8501 		i = 2;
8502 		break;
8503 
8504 	default:
8505 		return -EINVAL;
8506 	}
8507 
8508 	memcpy(&out->sb[i], &buf[4], 26);
8509 	out->valid = true;
8510 
8511 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
8512 		       sizeof(out->sb), false);
8513 
8514 	return 0;
8515 }
8516 
8517 static int
8518 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
8519 				 struct drm_atomic_commit *state)
8520 {
8521 	struct drm_connector_state *new_con_state =
8522 		drm_atomic_get_new_connector_state(state, conn);
8523 	struct drm_connector_state *old_con_state =
8524 		drm_atomic_get_old_connector_state(state, conn);
8525 	struct drm_crtc *crtc = new_con_state->crtc;
8526 	struct drm_crtc_state *new_crtc_state;
8527 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
8528 	int ret;
8529 
8530 	if (WARN_ON(unlikely(!old_con_state || !new_con_state)))
8531 		return -EINVAL;
8532 
8533 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
8534 
8535 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
8536 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
8537 		if (ret < 0)
8538 			return ret;
8539 	}
8540 
8541 	if (!crtc)
8542 		return 0;
8543 
8544 	if (new_con_state->privacy_screen_sw_state != old_con_state->privacy_screen_sw_state) {
8545 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8546 		if (IS_ERR(new_crtc_state))
8547 			return PTR_ERR(new_crtc_state);
8548 
8549 		new_crtc_state->mode_changed = true;
8550 	}
8551 
8552 	if (new_con_state->colorspace != old_con_state->colorspace) {
8553 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8554 		if (IS_ERR(new_crtc_state))
8555 			return PTR_ERR(new_crtc_state);
8556 
8557 		new_crtc_state->mode_changed = true;
8558 	}
8559 
8560 	if (new_con_state->content_type != old_con_state->content_type) {
8561 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8562 		if (IS_ERR(new_crtc_state))
8563 			return PTR_ERR(new_crtc_state);
8564 
8565 		new_crtc_state->mode_changed = true;
8566 	}
8567 
8568 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
8569 		struct dc_info_packet hdr_infopacket;
8570 
8571 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
8572 		if (ret)
8573 			return ret;
8574 
8575 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8576 		if (IS_ERR(new_crtc_state))
8577 			return PTR_ERR(new_crtc_state);
8578 
8579 		/*
8580 		 * DC considers the stream backends changed if the
8581 		 * static metadata changes. Forcing the modeset also
8582 		 * gives a simple way for userspace to switch from
8583 		 * 8bpc to 10bpc when setting the metadata to enter
8584 		 * or exit HDR.
8585 		 *
8586 		 * Changing the static metadata after it's been
8587 		 * set is permissible, however. So only force a
8588 		 * modeset if we're entering or exiting HDR.
8589 		 */
8590 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
8591 			!old_con_state->hdr_output_metadata ||
8592 			!new_con_state->hdr_output_metadata;
8593 	}
8594 
8595 	return 0;
8596 }
8597 
8598 static const struct drm_connector_helper_funcs
8599 amdgpu_dm_connector_helper_funcs = {
8600 	/*
8601 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
8602 	 * modes will be filtered by drm_mode_validate_size(), and those modes
8603 	 * are missing after user start lightdm. So we need to renew modes list.
8604 	 * in get_modes call back, not just return the modes count
8605 	 */
8606 	.get_modes = get_modes,
8607 	.mode_valid = amdgpu_dm_connector_mode_valid,
8608 	.atomic_check = amdgpu_dm_connector_atomic_check,
8609 };
8610 
8611 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
8612 {
8613 
8614 }
8615 
8616 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
8617 {
8618 	switch (display_color_depth) {
8619 	case COLOR_DEPTH_666:
8620 		return 6;
8621 	case COLOR_DEPTH_888:
8622 		return 8;
8623 	case COLOR_DEPTH_101010:
8624 		return 10;
8625 	case COLOR_DEPTH_121212:
8626 		return 12;
8627 	case COLOR_DEPTH_141414:
8628 		return 14;
8629 	case COLOR_DEPTH_161616:
8630 		return 16;
8631 	default:
8632 		break;
8633 	}
8634 	return 0;
8635 }
8636 
8637 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
8638 					  struct drm_crtc_state *crtc_state,
8639 					  struct drm_connector_state *conn_state)
8640 {
8641 	struct drm_atomic_commit *state = crtc_state->state;
8642 	struct drm_connector *connector = conn_state->connector;
8643 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8644 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
8645 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
8646 	struct drm_dp_mst_topology_mgr *mst_mgr;
8647 	struct drm_dp_mst_port *mst_port;
8648 	struct drm_dp_mst_topology_state *mst_state;
8649 	enum dc_color_depth color_depth;
8650 	int clock, bpp = 0;
8651 	bool is_y420 = false;
8652 
8653 	if ((connector->connector_type == DRM_MODE_CONNECTOR_eDP) ||
8654 	    (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)) {
8655 		struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8656 		struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8657 		enum drm_mode_status result;
8658 
8659 		result = drm_crtc_helper_mode_valid_fixed(encoder->crtc, adjusted_mode, native_mode);
8660 		if (result != MODE_OK && dm_new_connector_state->scaling == RMX_OFF) {
8661 			drm_dbg_driver(encoder->dev,
8662 				       "mode %dx%d@%dHz is not native, enabling scaling\n",
8663 				       adjusted_mode->hdisplay, adjusted_mode->vdisplay,
8664 				       drm_mode_vrefresh(adjusted_mode));
8665 			dm_new_connector_state->scaling = RMX_ASPECT;
8666 		}
8667 		return 0;
8668 	}
8669 
8670 	if (!aconnector->mst_output_port)
8671 		return 0;
8672 
8673 	mst_port = aconnector->mst_output_port;
8674 	mst_mgr = &aconnector->mst_root->mst_mgr;
8675 
8676 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
8677 		return 0;
8678 
8679 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
8680 	if (IS_ERR(mst_state))
8681 		return PTR_ERR(mst_state);
8682 
8683 	mst_state->pbn_div.full = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
8684 
8685 	if (!state->duplicated) {
8686 		int max_bpc = conn_state->max_requested_bpc;
8687 
8688 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
8689 			  aconnector->force_yuv420_output;
8690 		color_depth = convert_color_depth_from_display_info(connector,
8691 								    is_y420,
8692 								    max_bpc);
8693 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
8694 		clock = adjusted_mode->clock;
8695 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
8696 	}
8697 
8698 	dm_new_connector_state->vcpi_slots =
8699 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
8700 					      dm_new_connector_state->pbn);
8701 	if (dm_new_connector_state->vcpi_slots < 0) {
8702 		drm_dbg_atomic(connector->dev, "failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
8703 		return dm_new_connector_state->vcpi_slots;
8704 	}
8705 	return 0;
8706 }
8707 
8708 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
8709 	.disable = dm_encoder_helper_disable,
8710 	.atomic_check = dm_encoder_helper_atomic_check
8711 };
8712 
8713 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_commit *state,
8714 					    struct dc_state *dc_state,
8715 					    struct dsc_mst_fairness_vars *vars)
8716 {
8717 	struct dc_stream_state *stream = NULL;
8718 	struct drm_connector *connector;
8719 	struct drm_connector_state *new_con_state;
8720 	struct amdgpu_dm_connector *aconnector;
8721 	struct dm_connector_state *dm_conn_state;
8722 	int i, j, ret;
8723 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
8724 
8725 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8726 
8727 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
8728 			continue;
8729 
8730 		aconnector = to_amdgpu_dm_connector(connector);
8731 
8732 		if (!aconnector->mst_output_port)
8733 			continue;
8734 
8735 		if (!new_con_state || !new_con_state->crtc)
8736 			continue;
8737 
8738 		dm_conn_state = to_dm_connector_state(new_con_state);
8739 
8740 		for (j = 0; j < dc_state->stream_count; j++) {
8741 			stream = dc_state->streams[j];
8742 			if (!stream)
8743 				continue;
8744 
8745 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
8746 				break;
8747 
8748 			stream = NULL;
8749 		}
8750 
8751 		if (!stream)
8752 			continue;
8753 
8754 		pbn_div = dm_mst_get_pbn_divider(stream->link);
8755 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
8756 		for (j = 0; j < dc_state->stream_count; j++) {
8757 			if (vars[j].aconnector == aconnector) {
8758 				pbn = vars[j].pbn;
8759 				break;
8760 			}
8761 		}
8762 
8763 		if (j == dc_state->stream_count || pbn_div == 0)
8764 			continue;
8765 
8766 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
8767 
8768 		if (stream->timing.flags.DSC != 1) {
8769 			dm_conn_state->pbn = pbn;
8770 			dm_conn_state->vcpi_slots = slot_num;
8771 
8772 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
8773 							   dm_conn_state->pbn, false);
8774 			if (ret < 0)
8775 				return ret;
8776 
8777 			continue;
8778 		}
8779 
8780 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
8781 		if (vcpi < 0)
8782 			return vcpi;
8783 
8784 		dm_conn_state->pbn = pbn;
8785 		dm_conn_state->vcpi_slots = vcpi;
8786 	}
8787 	return 0;
8788 }
8789 
8790 static int to_drm_connector_type(enum signal_type st, uint32_t connector_id)
8791 {
8792 	switch (st) {
8793 	case SIGNAL_TYPE_HDMI_TYPE_A:
8794 		return DRM_MODE_CONNECTOR_HDMIA;
8795 	case SIGNAL_TYPE_EDP:
8796 		return DRM_MODE_CONNECTOR_eDP;
8797 	case SIGNAL_TYPE_LVDS:
8798 		return DRM_MODE_CONNECTOR_LVDS;
8799 	case SIGNAL_TYPE_RGB:
8800 		return DRM_MODE_CONNECTOR_VGA;
8801 	case SIGNAL_TYPE_DISPLAY_PORT:
8802 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
8803 		/* External DP bridges have a different connector type. */
8804 		if (connector_id == CONNECTOR_ID_VGA)
8805 			return DRM_MODE_CONNECTOR_VGA;
8806 		else if (connector_id == CONNECTOR_ID_LVDS)
8807 			return DRM_MODE_CONNECTOR_LVDS;
8808 
8809 		return DRM_MODE_CONNECTOR_DisplayPort;
8810 	case SIGNAL_TYPE_DVI_DUAL_LINK:
8811 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
8812 		if (connector_id == CONNECTOR_ID_SINGLE_LINK_DVII ||
8813 			connector_id == CONNECTOR_ID_DUAL_LINK_DVII)
8814 			return DRM_MODE_CONNECTOR_DVII;
8815 
8816 		return DRM_MODE_CONNECTOR_DVID;
8817 	case SIGNAL_TYPE_VIRTUAL:
8818 		return DRM_MODE_CONNECTOR_VIRTUAL;
8819 
8820 	default:
8821 		return DRM_MODE_CONNECTOR_Unknown;
8822 	}
8823 }
8824 
8825 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
8826 {
8827 	struct drm_encoder *encoder;
8828 
8829 	/* There is only one encoder per connector */
8830 	drm_connector_for_each_possible_encoder(connector, encoder)
8831 		return encoder;
8832 
8833 	return NULL;
8834 }
8835 
8836 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
8837 {
8838 	struct drm_encoder *encoder;
8839 	struct amdgpu_encoder *amdgpu_encoder;
8840 
8841 	encoder = amdgpu_dm_connector_to_encoder(connector);
8842 
8843 	if (encoder == NULL)
8844 		return;
8845 
8846 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8847 
8848 	amdgpu_encoder->native_mode.clock = 0;
8849 
8850 	if (!list_empty(&connector->probed_modes)) {
8851 		struct drm_display_mode *preferred_mode = NULL;
8852 
8853 		list_for_each_entry(preferred_mode,
8854 				    &connector->probed_modes,
8855 				    head) {
8856 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
8857 				amdgpu_encoder->native_mode = *preferred_mode;
8858 
8859 			break;
8860 		}
8861 
8862 	}
8863 }
8864 
8865 static struct drm_display_mode *
8866 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
8867 			     const char *name,
8868 			     int hdisplay, int vdisplay)
8869 {
8870 	struct drm_device *dev = encoder->dev;
8871 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8872 	struct drm_display_mode *mode = NULL;
8873 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8874 
8875 	mode = drm_mode_duplicate(dev, native_mode);
8876 
8877 	if (mode == NULL)
8878 		return NULL;
8879 
8880 	mode->hdisplay = hdisplay;
8881 	mode->vdisplay = vdisplay;
8882 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8883 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
8884 
8885 	return mode;
8886 
8887 }
8888 
8889 static const struct amdgpu_dm_mode_size {
8890 	char name[DRM_DISPLAY_MODE_LEN];
8891 	int w;
8892 	int h;
8893 } common_modes[] = {
8894 	{  "640x480",  640,  480},
8895 	{  "800x600",  800,  600},
8896 	{ "1024x768", 1024,  768},
8897 	{ "1280x720", 1280,  720},
8898 	{ "1280x800", 1280,  800},
8899 	{"1280x1024", 1280, 1024},
8900 	{ "1440x900", 1440,  900},
8901 	{"1680x1050", 1680, 1050},
8902 	{"1600x1200", 1600, 1200},
8903 	{"1920x1080", 1920, 1080},
8904 	{"1920x1200", 1920, 1200}
8905 };
8906 
8907 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
8908 						 struct drm_connector *connector)
8909 {
8910 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8911 	struct drm_display_mode *mode = NULL;
8912 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8913 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8914 				to_amdgpu_dm_connector(connector);
8915 	int i;
8916 	int n;
8917 
8918 	if ((connector->connector_type != DRM_MODE_CONNECTOR_eDP) &&
8919 	    (connector->connector_type != DRM_MODE_CONNECTOR_LVDS))
8920 		return;
8921 
8922 	n = ARRAY_SIZE(common_modes);
8923 
8924 	for (i = 0; i < n; i++) {
8925 		struct drm_display_mode *curmode = NULL;
8926 		bool mode_existed = false;
8927 
8928 		if (common_modes[i].w > native_mode->hdisplay ||
8929 		    common_modes[i].h > native_mode->vdisplay ||
8930 		   (common_modes[i].w == native_mode->hdisplay &&
8931 		    common_modes[i].h == native_mode->vdisplay))
8932 			continue;
8933 
8934 		list_for_each_entry(curmode, &connector->probed_modes, head) {
8935 			if (common_modes[i].w == curmode->hdisplay &&
8936 			    common_modes[i].h == curmode->vdisplay) {
8937 				mode_existed = true;
8938 				break;
8939 			}
8940 		}
8941 
8942 		if (mode_existed)
8943 			continue;
8944 
8945 		mode = amdgpu_dm_create_common_mode(encoder,
8946 				common_modes[i].name, common_modes[i].w,
8947 				common_modes[i].h);
8948 		if (!mode)
8949 			continue;
8950 
8951 		drm_mode_probed_add(connector, mode);
8952 		amdgpu_dm_connector->num_modes++;
8953 	}
8954 }
8955 
8956 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
8957 {
8958 	struct drm_encoder *encoder;
8959 	struct amdgpu_encoder *amdgpu_encoder;
8960 	const struct drm_display_mode *native_mode;
8961 
8962 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
8963 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
8964 		return;
8965 
8966 	mutex_lock(&connector->dev->mode_config.mutex);
8967 	amdgpu_dm_connector_get_modes(connector);
8968 	mutex_unlock(&connector->dev->mode_config.mutex);
8969 
8970 	encoder = amdgpu_dm_connector_to_encoder(connector);
8971 	if (!encoder)
8972 		return;
8973 
8974 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8975 
8976 	native_mode = &amdgpu_encoder->native_mode;
8977 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
8978 		return;
8979 
8980 	drm_connector_set_panel_orientation_with_quirk(connector,
8981 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
8982 						       native_mode->hdisplay,
8983 						       native_mode->vdisplay);
8984 }
8985 
8986 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
8987 					      const struct drm_edid *drm_edid)
8988 {
8989 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8990 			to_amdgpu_dm_connector(connector);
8991 
8992 	if (drm_edid) {
8993 		/* empty probed_modes */
8994 		INIT_LIST_HEAD(&connector->probed_modes);
8995 		amdgpu_dm_connector->num_modes =
8996 				drm_edid_connector_add_modes(connector);
8997 
8998 		/* sorting the probed modes before calling function
8999 		 * amdgpu_dm_get_native_mode() since EDID can have
9000 		 * more than one preferred mode. The modes that are
9001 		 * later in the probed mode list could be of higher
9002 		 * and preferred resolution. For example, 3840x2160
9003 		 * resolution in base EDID preferred timing and 4096x2160
9004 		 * preferred resolution in DID extension block later.
9005 		 */
9006 		drm_mode_sort(&connector->probed_modes);
9007 		amdgpu_dm_get_native_mode(connector);
9008 
9009 		/* Freesync capabilities are reset by calling
9010 		 * drm_edid_connector_add_modes() and need to be
9011 		 * restored here.
9012 		 */
9013 		amdgpu_dm_update_freesync_caps(connector, drm_edid, false);
9014 	} else {
9015 		amdgpu_dm_connector->num_modes = 0;
9016 	}
9017 }
9018 
9019 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
9020 			      struct drm_display_mode *mode)
9021 {
9022 	struct drm_display_mode *m;
9023 
9024 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
9025 		if (drm_mode_equal(m, mode))
9026 			return true;
9027 	}
9028 
9029 	return false;
9030 }
9031 
9032 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
9033 {
9034 	const struct drm_display_mode *m;
9035 	struct drm_display_mode *new_mode;
9036 	uint i;
9037 	u32 new_modes_count = 0;
9038 
9039 	/* Standard FPS values
9040 	 *
9041 	 * 23.976       - TV/NTSC
9042 	 * 24           - Cinema
9043 	 * 25           - TV/PAL
9044 	 * 29.97        - TV/NTSC
9045 	 * 30           - TV/NTSC
9046 	 * 48           - Cinema HFR
9047 	 * 50           - TV/PAL
9048 	 * 60           - Commonly used
9049 	 * 48,72,96,120 - Multiples of 24
9050 	 */
9051 	static const u32 common_rates[] = {
9052 		23976, 24000, 25000, 29970, 30000,
9053 		48000, 50000, 60000, 72000, 96000, 120000
9054 	};
9055 
9056 	/*
9057 	 * Find mode with highest refresh rate with the same resolution
9058 	 * as the preferred mode. Some monitors report a preferred mode
9059 	 * with lower resolution than the highest refresh rate supported.
9060 	 */
9061 
9062 	m = get_highest_refresh_rate_mode(aconnector, true);
9063 	if (!m)
9064 		return 0;
9065 
9066 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
9067 		u64 target_vtotal, target_vtotal_diff;
9068 		u64 num, den;
9069 
9070 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
9071 			continue;
9072 
9073 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
9074 		    common_rates[i] > aconnector->max_vfreq * 1000)
9075 			continue;
9076 
9077 		num = (unsigned long long)m->clock * 1000 * 1000;
9078 		den = common_rates[i] * (unsigned long long)m->htotal;
9079 		target_vtotal = div_u64(num, den);
9080 		target_vtotal_diff = target_vtotal - m->vtotal;
9081 
9082 		/* Check for illegal modes */
9083 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
9084 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
9085 		    m->vtotal + target_vtotal_diff < m->vsync_end)
9086 			continue;
9087 
9088 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
9089 		if (!new_mode)
9090 			goto out;
9091 
9092 		new_mode->vtotal += (u16)target_vtotal_diff;
9093 		new_mode->vsync_start += (u16)target_vtotal_diff;
9094 		new_mode->vsync_end += (u16)target_vtotal_diff;
9095 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
9096 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
9097 
9098 		if (!is_duplicate_mode(aconnector, new_mode)) {
9099 			drm_mode_probed_add(&aconnector->base, new_mode);
9100 			new_modes_count += 1;
9101 		} else
9102 			drm_mode_destroy(aconnector->base.dev, new_mode);
9103 	}
9104  out:
9105 	return new_modes_count;
9106 }
9107 
9108 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
9109 						   const struct drm_edid *drm_edid)
9110 {
9111 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9112 		to_amdgpu_dm_connector(connector);
9113 
9114 	if (!(amdgpu_freesync_vid_mode && drm_edid))
9115 		return;
9116 
9117 	if (!amdgpu_dm_connector->dc_sink || !amdgpu_dm_connector->dc_link)
9118 		return;
9119 
9120 	if (!dc_supports_vrr(amdgpu_dm_connector->dc_sink->ctx->dce_version))
9121 		return;
9122 
9123 	if (dc_connector_supports_analog(amdgpu_dm_connector->dc_link->link_id.id) &&
9124 	    amdgpu_dm_connector->dc_sink->edid_caps.analog)
9125 		return;
9126 
9127 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
9128 		amdgpu_dm_connector->num_modes +=
9129 			add_fs_modes(amdgpu_dm_connector);
9130 }
9131 
9132 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
9133 {
9134 	struct amdgpu_dm_connector *amdgpu_dm_connector =
9135 			to_amdgpu_dm_connector(connector);
9136 	struct dc_link *dc_link = amdgpu_dm_connector->dc_link;
9137 	struct drm_encoder *encoder;
9138 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
9139 	struct dc_link_settings *verified_link_cap = &dc_link->verified_link_cap;
9140 	const struct dc *dc = dc_link->dc;
9141 
9142 	encoder = amdgpu_dm_connector_to_encoder(connector);
9143 
9144 	if (!drm_edid) {
9145 		amdgpu_dm_connector->num_modes =
9146 				drm_add_modes_noedid(connector, 640, 480);
9147 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
9148 			amdgpu_dm_connector->num_modes +=
9149 				drm_add_modes_noedid(connector, 1920, 1080);
9150 
9151 		if (amdgpu_dm_connector->dc_sink &&
9152 		    amdgpu_dm_connector->dc_sink->edid_caps.analog &&
9153 		    dc_connector_supports_analog(dc_link->link_id.id)) {
9154 			/* Analog monitor connected by DAC load detection.
9155 			 * Add common modes. It will be up to the user to select one that works.
9156 			 */
9157 			for (int i = 0; i < ARRAY_SIZE(common_modes); i++)
9158 				amdgpu_dm_connector->num_modes += drm_add_modes_noedid(
9159 					connector, common_modes[i].w, common_modes[i].h);
9160 		}
9161 	} else {
9162 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
9163 		if (encoder)
9164 			amdgpu_dm_connector_add_common_modes(encoder, connector);
9165 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
9166 	}
9167 	amdgpu_dm_fbc_init(connector);
9168 
9169 	return amdgpu_dm_connector->num_modes;
9170 }
9171 
9172 static const u32 supported_colorspaces =
9173 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
9174 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
9175 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
9176 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
9177 
9178 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
9179 				     struct amdgpu_dm_connector *aconnector,
9180 				     int connector_type,
9181 				     struct dc_link *link,
9182 				     int link_index)
9183 {
9184 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
9185 
9186 	/*
9187 	 * Some of the properties below require access to state, like bpc.
9188 	 * Allocate some default initial connector state with our reset helper.
9189 	 */
9190 	if (aconnector->base.funcs->reset)
9191 		aconnector->base.funcs->reset(&aconnector->base);
9192 
9193 	aconnector->connector_id = link_index;
9194 	aconnector->bl_idx = -1;
9195 	aconnector->dc_link = link;
9196 	aconnector->base.interlace_allowed = false;
9197 	aconnector->base.doublescan_allowed = false;
9198 	aconnector->base.stereo_allowed = false;
9199 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
9200 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
9201 	aconnector->audio_inst = -1;
9202 	aconnector->pack_sdp_v1_3 = false;
9203 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
9204 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
9205 	mutex_init(&aconnector->hpd_lock);
9206 	mutex_init(&aconnector->handle_mst_msg_ready);
9207 
9208 	/*
9209 	 * If HDMI HPD debounce delay is set, use the minimum between selected
9210 	 * value and AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS
9211 	 */
9212 	if (amdgpu_hdmi_hpd_debounce_delay_ms) {
9213 		aconnector->hdmi_hpd_debounce_delay_ms = min(amdgpu_hdmi_hpd_debounce_delay_ms,
9214 							     AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS);
9215 		INIT_DELAYED_WORK(&aconnector->hdmi_hpd_debounce_work, hdmi_hpd_debounce_work);
9216 		aconnector->hdmi_prev_sink = NULL;
9217 	} else {
9218 		aconnector->hdmi_hpd_debounce_delay_ms = 0;
9219 	}
9220 
9221 	/*
9222 	 * configure support HPD hot plug connector_>polled default value is 0
9223 	 * which means HPD hot plug not supported
9224 	 */
9225 	switch (connector_type) {
9226 	case DRM_MODE_CONNECTOR_HDMIA:
9227 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9228 		aconnector->base.ycbcr_420_allowed =
9229 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
9230 		break;
9231 	case DRM_MODE_CONNECTOR_DisplayPort:
9232 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9233 		link->link_enc = link_enc_cfg_get_link_enc(link);
9234 		ASSERT(link->link_enc);
9235 		if (link->link_enc)
9236 			aconnector->base.ycbcr_420_allowed =
9237 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
9238 		break;
9239 	case DRM_MODE_CONNECTOR_DVID:
9240 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9241 		break;
9242 	case DRM_MODE_CONNECTOR_DVII:
9243 	case DRM_MODE_CONNECTOR_VGA:
9244 		aconnector->base.polled =
9245 			DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT;
9246 		break;
9247 	default:
9248 		break;
9249 	}
9250 
9251 	drm_object_attach_property(&aconnector->base.base,
9252 				dm->ddev->mode_config.scaling_mode_property,
9253 				DRM_MODE_SCALE_NONE);
9254 
9255 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA
9256 		|| (connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root))
9257 		drm_connector_attach_broadcast_rgb_property(&aconnector->base);
9258 
9259 	drm_object_attach_property(&aconnector->base.base,
9260 				adev->mode_info.underscan_property,
9261 				UNDERSCAN_OFF);
9262 	drm_object_attach_property(&aconnector->base.base,
9263 				adev->mode_info.underscan_hborder_property,
9264 				0);
9265 	drm_object_attach_property(&aconnector->base.base,
9266 				adev->mode_info.underscan_vborder_property,
9267 				0);
9268 
9269 	if (!aconnector->mst_root)
9270 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
9271 
9272 	aconnector->base.state->max_bpc = 16;
9273 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
9274 
9275 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9276 		/* Content Type is currently only implemented for HDMI. */
9277 		drm_connector_attach_content_type_property(&aconnector->base);
9278 	}
9279 
9280 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9281 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
9282 			drm_connector_attach_colorspace_property(&aconnector->base);
9283 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
9284 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
9285 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
9286 			drm_connector_attach_colorspace_property(&aconnector->base);
9287 	}
9288 
9289 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9290 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
9291 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
9292 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
9293 
9294 		if (!aconnector->mst_root)
9295 			drm_connector_attach_vrr_capable_property(&aconnector->base);
9296 
9297 		if (adev->dm.hdcp_workqueue)
9298 			drm_connector_attach_content_protection_property(&aconnector->base, true);
9299 	}
9300 
9301 	if (connector_type == DRM_MODE_CONNECTOR_eDP) {
9302 		struct drm_privacy_screen *privacy_screen;
9303 
9304 		drm_connector_attach_panel_type_property(&aconnector->base);
9305 
9306 		privacy_screen = drm_privacy_screen_get(adev_to_drm(adev)->dev, NULL);
9307 		if (!IS_ERR(privacy_screen)) {
9308 			drm_connector_attach_privacy_screen_provider(&aconnector->base,
9309 								     privacy_screen);
9310 		} else if (PTR_ERR(privacy_screen) != -ENODEV) {
9311 			drm_warn(adev_to_drm(adev), "Error getting privacy-screen\n");
9312 		}
9313 	}
9314 }
9315 
9316 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
9317 			      struct i2c_msg *msgs, int num)
9318 {
9319 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
9320 	struct ddc_service *ddc_service = i2c->ddc_service;
9321 	struct i2c_command cmd;
9322 	int i;
9323 	int result = -EIO;
9324 
9325 	if (!ddc_service->ddc_pin)
9326 		return result;
9327 
9328 	cmd.payloads = kzalloc_objs(struct i2c_payload, num);
9329 
9330 	if (!cmd.payloads)
9331 		return result;
9332 
9333 	cmd.number_of_payloads = num;
9334 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
9335 	cmd.speed = 100;
9336 
9337 	for (i = 0; i < num; i++) {
9338 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
9339 		cmd.payloads[i].address = msgs[i].addr;
9340 		cmd.payloads[i].length = msgs[i].len;
9341 		cmd.payloads[i].data = msgs[i].buf;
9342 	}
9343 
9344 	if (i2c->oem) {
9345 		if (dc_submit_i2c_oem(
9346 			    ddc_service->ctx->dc,
9347 			    &cmd))
9348 			result = num;
9349 	} else {
9350 		if (dc_submit_i2c(
9351 			    ddc_service->ctx->dc,
9352 			    ddc_service->link->link_index,
9353 			    &cmd))
9354 			result = num;
9355 	}
9356 
9357 	kfree(cmd.payloads);
9358 	return result;
9359 }
9360 
9361 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
9362 {
9363 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
9364 }
9365 
9366 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
9367 	.master_xfer = amdgpu_dm_i2c_xfer,
9368 	.functionality = amdgpu_dm_i2c_func,
9369 };
9370 
9371 static struct amdgpu_i2c_adapter *
9372 create_i2c(struct ddc_service *ddc_service, bool oem)
9373 {
9374 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
9375 	struct amdgpu_i2c_adapter *i2c;
9376 
9377 	i2c = kzalloc_obj(struct amdgpu_i2c_adapter);
9378 	if (!i2c)
9379 		return NULL;
9380 	i2c->base.owner = THIS_MODULE;
9381 	i2c->base.dev.parent = &adev->pdev->dev;
9382 	i2c->base.algo = &amdgpu_dm_i2c_algo;
9383 	if (oem)
9384 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c OEM bus");
9385 	else
9386 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d",
9387 			 ddc_service->link->link_index);
9388 	i2c_set_adapdata(&i2c->base, i2c);
9389 	i2c->ddc_service = ddc_service;
9390 	i2c->oem = oem;
9391 
9392 	return i2c;
9393 }
9394 
9395 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
9396 {
9397 	struct cec_connector_info conn_info;
9398 	struct drm_device *ddev = aconnector->base.dev;
9399 	struct device *hdmi_dev = ddev->dev;
9400 
9401 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
9402 		drm_info(ddev, "HDMI-CEC feature masked\n");
9403 		return -EINVAL;
9404 	}
9405 
9406 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
9407 	aconnector->notifier =
9408 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
9409 	if (!aconnector->notifier) {
9410 		drm_err(ddev, "Failed to create cec notifier\n");
9411 		return -ENOMEM;
9412 	}
9413 
9414 	return 0;
9415 }
9416 
9417 /*
9418  * Note: this function assumes that dc_link_detect() was called for the
9419  * dc_link which will be represented by this aconnector.
9420  */
9421 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
9422 				    struct amdgpu_dm_connector *aconnector,
9423 				    u32 link_index,
9424 				    struct amdgpu_encoder *aencoder)
9425 {
9426 	int res = 0;
9427 	int connector_type;
9428 	struct dc *dc = dm->dc;
9429 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
9430 	struct amdgpu_i2c_adapter *i2c;
9431 
9432 	/* Not needed for writeback connector */
9433 	link->priv = aconnector;
9434 
9435 
9436 	i2c = create_i2c(link->ddc, false);
9437 	if (!i2c) {
9438 		drm_err(adev_to_drm(dm->adev), "Failed to create i2c adapter data\n");
9439 		return -ENOMEM;
9440 	}
9441 
9442 	aconnector->i2c = i2c;
9443 	res = devm_i2c_add_adapter(dm->adev->dev, &i2c->base);
9444 
9445 	if (res) {
9446 		drm_err(adev_to_drm(dm->adev), "Failed to register hw i2c %d\n", link->link_index);
9447 		goto out_free;
9448 	}
9449 
9450 	connector_type = to_drm_connector_type(link->connector_signal, link->link_id.id);
9451 
9452 	res = drm_connector_init_with_ddc(
9453 			dm->ddev,
9454 			&aconnector->base,
9455 			&amdgpu_dm_connector_funcs,
9456 			connector_type,
9457 			&i2c->base);
9458 
9459 	if (res) {
9460 		drm_err(adev_to_drm(dm->adev), "connector_init failed\n");
9461 		aconnector->connector_id = -1;
9462 		goto out_free;
9463 	}
9464 
9465 	drm_connector_helper_add(
9466 			&aconnector->base,
9467 			&amdgpu_dm_connector_helper_funcs);
9468 
9469 	amdgpu_dm_connector_init_helper(
9470 		dm,
9471 		aconnector,
9472 		connector_type,
9473 		link,
9474 		link_index);
9475 
9476 	drm_connector_attach_encoder(
9477 		&aconnector->base, &aencoder->base);
9478 
9479 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9480 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
9481 		amdgpu_dm_initialize_hdmi_connector(aconnector);
9482 
9483 	if (dc_is_dp_signal(link->connector_signal))
9484 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
9485 
9486 out_free:
9487 	if (res) {
9488 		kfree(i2c);
9489 		aconnector->i2c = NULL;
9490 	}
9491 	return res;
9492 }
9493 
9494 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
9495 {
9496 	switch (adev->mode_info.num_crtc) {
9497 	case 1:
9498 		return 0x1;
9499 	case 2:
9500 		return 0x3;
9501 	case 3:
9502 		return 0x7;
9503 	case 4:
9504 		return 0xf;
9505 	case 5:
9506 		return 0x1f;
9507 	case 6:
9508 	default:
9509 		return 0x3f;
9510 	}
9511 }
9512 
9513 static int amdgpu_dm_encoder_init(struct drm_device *dev,
9514 				  struct amdgpu_encoder *aencoder,
9515 				  uint32_t link_index)
9516 {
9517 	struct amdgpu_device *adev = drm_to_adev(dev);
9518 
9519 	int res = drm_encoder_init(dev,
9520 				   &aencoder->base,
9521 				   &amdgpu_dm_encoder_funcs,
9522 				   DRM_MODE_ENCODER_TMDS,
9523 				   NULL);
9524 
9525 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
9526 
9527 	if (!res)
9528 		aencoder->encoder_id = link_index;
9529 	else
9530 		aencoder->encoder_id = -1;
9531 
9532 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
9533 
9534 	return res;
9535 }
9536 
9537 static void manage_dm_interrupts(struct amdgpu_device *adev,
9538 				 struct amdgpu_crtc *acrtc,
9539 				 struct dm_crtc_state *acrtc_state)
9540 {	/*
9541 	 * We cannot be sure that the frontend index maps to the same
9542 	 * backend index - some even map to more than one.
9543 	 * So we have to go through the CRTC to find the right IRQ.
9544 	 */
9545 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
9546 			adev,
9547 			acrtc->crtc_id);
9548 	struct drm_device *dev = adev_to_drm(adev);
9549 
9550 	struct drm_vblank_crtc_config config = {0};
9551 	struct dc_crtc_timing *timing;
9552 	int offdelay;
9553 
9554 	if (acrtc_state) {
9555 		timing = &acrtc_state->stream->timing;
9556 
9557 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) >=
9558 		      IP_VERSION(3, 2, 0) &&
9559 		      !(adev->flags & AMD_IS_APU)) {
9560 			/*
9561 			 * DGPUs NV3x and newer that support idle optimizations
9562 			 * experience intermittent flip-done timeouts on cursor
9563 			 * updates. Restore 5s offdelay behavior for now.
9564 			 *
9565 			 * Discussion on the issue:
9566 			 * https://lore.kernel.org/amd-gfx/20260217191632.1243826-1-sysdadmin@m1k.cloud/
9567 			 */
9568 			config.offdelay_ms = 5000;
9569 			config.disable_immediate = false;
9570 		} else if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
9571 			     IP_VERSION(3, 5, 0)) {
9572 			/*
9573 			 * Older HW and DGPU have issues with instant off;
9574 			 * use a 2 frame offdelay.
9575 			 */
9576 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
9577 						      timing->v_total *
9578 						      timing->h_total,
9579 						      timing->pix_clk_100hz);
9580 
9581 			config.offdelay_ms = offdelay ?: 30;
9582 		} else {
9583 			/* offdelay_ms = 0 will never disable vblank */
9584 			config.offdelay_ms = 1;
9585 			config.disable_immediate = true;
9586 		}
9587 
9588 		drm_crtc_vblank_on_config(&acrtc->base,
9589 					  &config);
9590 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_get.*/
9591 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9592 		case IP_VERSION(3, 0, 0):
9593 		case IP_VERSION(3, 0, 2):
9594 		case IP_VERSION(3, 0, 3):
9595 		case IP_VERSION(3, 2, 0):
9596 			if (amdgpu_irq_get(adev, &adev->pageflip_irq, irq_type))
9597 				drm_err(dev, "DM_IRQ: Cannot get pageflip irq!\n");
9598 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9599 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
9600 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
9601 #endif
9602 		}
9603 
9604 	} else {
9605 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
9606 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9607 		case IP_VERSION(3, 0, 0):
9608 		case IP_VERSION(3, 0, 2):
9609 		case IP_VERSION(3, 0, 3):
9610 		case IP_VERSION(3, 2, 0):
9611 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9612 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
9613 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
9614 #endif
9615 			if (amdgpu_irq_put(adev, &adev->pageflip_irq, irq_type))
9616 				drm_err(dev, "DM_IRQ: Cannot put pageflip irq!\n");
9617 		}
9618 
9619 		drm_crtc_vblank_off(&acrtc->base);
9620 	}
9621 }
9622 
9623 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
9624 				      struct amdgpu_crtc *acrtc)
9625 {
9626 	int irq_type =
9627 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
9628 
9629 	/**
9630 	 * This reads the current state for the IRQ and force reapplies
9631 	 * the setting to hardware.
9632 	 */
9633 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
9634 }
9635 
9636 static bool
9637 is_scaling_state_different(const struct dm_connector_state *dm_state,
9638 			   const struct dm_connector_state *old_dm_state)
9639 {
9640 	if (dm_state->scaling != old_dm_state->scaling)
9641 		return true;
9642 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
9643 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
9644 			return true;
9645 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
9646 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
9647 			return true;
9648 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
9649 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
9650 		return true;
9651 	return false;
9652 }
9653 
9654 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
9655 					    struct drm_crtc_state *old_crtc_state,
9656 					    struct drm_connector_state *new_conn_state,
9657 					    struct drm_connector_state *old_conn_state,
9658 					    const struct drm_connector *connector,
9659 					    struct hdcp_workqueue *hdcp_w)
9660 {
9661 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
9662 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
9663 
9664 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
9665 		connector->index, connector->status, connector->dpms);
9666 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
9667 		old_conn_state->content_protection, new_conn_state->content_protection);
9668 
9669 	if (old_crtc_state)
9670 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9671 		old_crtc_state->enable,
9672 		old_crtc_state->active,
9673 		old_crtc_state->mode_changed,
9674 		old_crtc_state->active_changed,
9675 		old_crtc_state->connectors_changed);
9676 
9677 	if (new_crtc_state)
9678 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9679 		new_crtc_state->enable,
9680 		new_crtc_state->active,
9681 		new_crtc_state->mode_changed,
9682 		new_crtc_state->active_changed,
9683 		new_crtc_state->connectors_changed);
9684 
9685 	/* hdcp content type change */
9686 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
9687 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
9688 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9689 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
9690 		return true;
9691 	}
9692 
9693 	/* CP is being re enabled, ignore this */
9694 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
9695 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9696 		if (new_crtc_state && new_crtc_state->mode_changed) {
9697 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9698 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
9699 			return true;
9700 		}
9701 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
9702 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
9703 		return false;
9704 	}
9705 
9706 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
9707 	 *
9708 	 * Handles:	UNDESIRED -> ENABLED
9709 	 */
9710 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
9711 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
9712 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9713 
9714 	/* Stream removed and re-enabled
9715 	 *
9716 	 * Can sometimes overlap with the HPD case,
9717 	 * thus set update_hdcp to false to avoid
9718 	 * setting HDCP multiple times.
9719 	 *
9720 	 * Handles:	DESIRED -> DESIRED (Special case)
9721 	 */
9722 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
9723 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
9724 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9725 		dm_con_state->update_hdcp = false;
9726 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
9727 			__func__);
9728 		return true;
9729 	}
9730 
9731 	/* Hot-plug, headless s3, dpms
9732 	 *
9733 	 * Only start HDCP if the display is connected/enabled.
9734 	 * update_hdcp flag will be set to false until the next
9735 	 * HPD comes in.
9736 	 *
9737 	 * Handles:	DESIRED -> DESIRED (Special case)
9738 	 */
9739 	if (dm_con_state->update_hdcp &&
9740 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
9741 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
9742 		dm_con_state->update_hdcp = false;
9743 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
9744 			__func__);
9745 		return true;
9746 	}
9747 
9748 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
9749 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9750 			if (new_crtc_state && new_crtc_state->mode_changed) {
9751 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
9752 					__func__);
9753 				return true;
9754 			}
9755 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
9756 				__func__);
9757 			return false;
9758 		}
9759 
9760 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
9761 		return false;
9762 	}
9763 
9764 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9765 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
9766 			__func__);
9767 		return true;
9768 	}
9769 
9770 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
9771 	return false;
9772 }
9773 
9774 static void remove_stream(struct amdgpu_device *adev,
9775 			  struct amdgpu_crtc *acrtc,
9776 			  struct dc_stream_state *stream)
9777 {
9778 	/* this is the update mode case */
9779 
9780 	acrtc->otg_inst = -1;
9781 	acrtc->enabled = false;
9782 }
9783 
9784 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
9785 {
9786 
9787 	assert_spin_locked(&acrtc->base.dev->event_lock);
9788 	WARN_ON(acrtc->event);
9789 
9790 	acrtc->event = acrtc->base.state->event;
9791 
9792 	/* Set the flip status */
9793 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
9794 
9795 	/* Mark this event as consumed */
9796 	acrtc->base.state->event = NULL;
9797 
9798 	drm_dbg_state(acrtc->base.dev,
9799 		      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
9800 		      acrtc->crtc_id);
9801 }
9802 
9803 static void update_freesync_state_on_stream(
9804 	struct amdgpu_display_manager *dm,
9805 	struct dm_crtc_state *new_crtc_state,
9806 	struct dc_stream_state *new_stream,
9807 	struct dc_plane_state *surface,
9808 	u32 flip_timestamp_in_us)
9809 {
9810 	struct mod_vrr_params vrr_params;
9811 	struct dc_info_packet vrr_infopacket = {0};
9812 	struct amdgpu_device *adev = dm->adev;
9813 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9814 	unsigned long flags;
9815 	bool pack_sdp_v1_3 = false;
9816 	struct amdgpu_dm_connector *aconn;
9817 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
9818 
9819 	if (!new_stream)
9820 		return;
9821 
9822 	/*
9823 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9824 	 * For now it's sufficient to just guard against these conditions.
9825 	 */
9826 
9827 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9828 		return;
9829 
9830 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9831 	vrr_params = acrtc->dm_irq_params.vrr_params;
9832 
9833 	if (surface) {
9834 		mod_freesync_handle_preflip(
9835 			dm->freesync_module,
9836 			surface,
9837 			new_stream,
9838 			flip_timestamp_in_us,
9839 			&vrr_params);
9840 
9841 		if (adev->family < AMDGPU_FAMILY_AI &&
9842 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
9843 			mod_freesync_handle_v_update(dm->freesync_module,
9844 						     new_stream, &vrr_params);
9845 
9846 			/* Need to call this before the frame ends. */
9847 			dc_stream_adjust_vmin_vmax(dm->dc,
9848 						   new_crtc_state->stream,
9849 						   &vrr_params.adjust);
9850 		}
9851 	}
9852 
9853 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
9854 
9855 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
9856 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
9857 
9858 		if (aconn->vsdb_info.amd_vsdb_version == 1)
9859 			packet_type = PACKET_TYPE_FS_V1;
9860 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
9861 			packet_type = PACKET_TYPE_FS_V2;
9862 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
9863 			packet_type = PACKET_TYPE_FS_V3;
9864 
9865 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
9866 					&new_stream->adaptive_sync_infopacket);
9867 	}
9868 
9869 	mod_freesync_build_vrr_infopacket(
9870 		dm->freesync_module,
9871 		new_stream,
9872 		&vrr_params,
9873 		packet_type,
9874 		TRANSFER_FUNC_UNKNOWN,
9875 		&vrr_infopacket,
9876 		pack_sdp_v1_3);
9877 
9878 	new_crtc_state->freesync_vrr_info_changed |=
9879 		(memcmp(&new_crtc_state->vrr_infopacket,
9880 			&vrr_infopacket,
9881 			sizeof(vrr_infopacket)) != 0);
9882 
9883 	acrtc->dm_irq_params.vrr_params = vrr_params;
9884 	new_crtc_state->vrr_infopacket = vrr_infopacket;
9885 
9886 	new_stream->vrr_infopacket = vrr_infopacket;
9887 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
9888 
9889 	if (new_crtc_state->freesync_vrr_info_changed)
9890 		drm_dbg_kms(adev_to_drm(adev), "VRR packet update: crtc=%u enabled=%d state=%d",
9891 			      new_crtc_state->base.crtc->base.id,
9892 			      (int)new_crtc_state->base.vrr_enabled,
9893 			      (int)vrr_params.state);
9894 
9895 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9896 }
9897 
9898 static void update_stream_irq_parameters(
9899 	struct amdgpu_display_manager *dm,
9900 	struct dm_crtc_state *new_crtc_state)
9901 {
9902 	struct dc_stream_state *new_stream = new_crtc_state->stream;
9903 	struct mod_vrr_params vrr_params;
9904 	struct mod_freesync_config config = new_crtc_state->freesync_config;
9905 	struct amdgpu_device *adev = dm->adev;
9906 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9907 	unsigned long flags;
9908 
9909 	if (!new_stream)
9910 		return;
9911 
9912 	/*
9913 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9914 	 * For now it's sufficient to just guard against these conditions.
9915 	 */
9916 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9917 		return;
9918 
9919 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9920 	vrr_params = acrtc->dm_irq_params.vrr_params;
9921 
9922 	if (new_crtc_state->vrr_supported &&
9923 	    config.min_refresh_in_uhz &&
9924 	    config.max_refresh_in_uhz) {
9925 		/*
9926 		 * if freesync compatible mode was set, config.state will be set
9927 		 * in atomic check
9928 		 */
9929 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
9930 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
9931 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
9932 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
9933 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
9934 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
9935 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
9936 		} else {
9937 			config.state = new_crtc_state->base.vrr_enabled ?
9938 						     VRR_STATE_ACTIVE_VARIABLE :
9939 						     VRR_STATE_INACTIVE;
9940 		}
9941 	} else {
9942 		config.state = VRR_STATE_UNSUPPORTED;
9943 	}
9944 
9945 	mod_freesync_build_vrr_params(dm->freesync_module,
9946 				      new_stream,
9947 				      &config, &vrr_params);
9948 
9949 	new_crtc_state->freesync_config = config;
9950 	/* Copy state for access from DM IRQ handler */
9951 	acrtc->dm_irq_params.freesync_config = config;
9952 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
9953 	acrtc->dm_irq_params.vrr_params = vrr_params;
9954 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9955 }
9956 
9957 static void amdgpu_dm_handle_vrr_transition(struct amdgpu_display_manager *dm,
9958 					    struct dm_crtc_state *old_state,
9959 					    struct dm_crtc_state *new_state)
9960 {
9961 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
9962 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
9963 
9964 	if (!old_vrr_active && new_vrr_active) {
9965 		/* Transition VRR inactive -> active:
9966 		 * While VRR is active, we must not disable vblank irq, as a
9967 		 * reenable after disable would compute bogus vblank/pflip
9968 		 * timestamps if it likely happened inside display front-porch.
9969 		 *
9970 		 * We also need vupdate irq for the actual core vblank handling
9971 		 * at end of vblank.
9972 		 */
9973 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
9974 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
9975 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR off->on: Get vblank ref\n",
9976 				 __func__, new_state->base.crtc->base.id);
9977 
9978 		scoped_guard(mutex, &dm->dc_lock) {
9979 			dc_exit_ips_for_hw_access(dm->dc);
9980 			amdgpu_dm_psr_set_event(dm, new_state->stream, true,
9981 				psr_event_vrr_transition, true);
9982 			amdgpu_dm_replay_set_event(dm, new_state->stream, true,
9983 				replay_event_vrr, true);
9984 		}
9985 	} else if (old_vrr_active && !new_vrr_active) {
9986 		/* Transition VRR active -> inactive:
9987 		 * Allow vblank irq disable again for fixed refresh rate.
9988 		 */
9989 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
9990 		drm_crtc_vblank_put(new_state->base.crtc);
9991 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR on->off: Drop vblank ref\n",
9992 				 __func__, new_state->base.crtc->base.id);
9993 
9994 		scoped_guard(mutex, &dm->dc_lock) {
9995 			dc_exit_ips_for_hw_access(dm->dc);
9996 			amdgpu_dm_psr_set_event(dm, new_state->stream, false,
9997 				psr_event_vrr_transition, false);
9998 			amdgpu_dm_replay_set_event(dm, new_state->stream, false,
9999 				replay_event_vrr, false);
10000 		}
10001 	}
10002 }
10003 
10004 static void amdgpu_dm_commit_cursors(struct drm_atomic_commit *state)
10005 {
10006 	struct drm_plane *plane;
10007 	struct drm_plane_state *old_plane_state;
10008 	int i;
10009 
10010 	/*
10011 	 * TODO: Make this per-stream so we don't issue redundant updates for
10012 	 * commits with multiple streams.
10013 	 */
10014 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
10015 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
10016 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
10017 }
10018 
10019 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
10020 {
10021 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
10022 
10023 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
10024 }
10025 
10026 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
10027 				    struct drm_plane_state *old_plane_state,
10028 				    struct dc_stream_update *update)
10029 {
10030 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
10031 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
10032 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
10033 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
10034 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
10035 	uint64_t address = afb ? afb->address : 0;
10036 	struct dc_cursor_position position = {0};
10037 	struct dc_cursor_attributes attributes;
10038 	int ret;
10039 
10040 	if (!plane->state->fb && !old_plane_state->fb)
10041 		return;
10042 
10043 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
10044 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
10045 		       plane->state->crtc_h);
10046 
10047 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
10048 	if (ret)
10049 		return;
10050 
10051 	if (!position.enable) {
10052 		/* turn off cursor */
10053 		if (crtc_state && crtc_state->stream) {
10054 			dc_stream_set_cursor_position(crtc_state->stream,
10055 						      &position);
10056 			update->cursor_position = &crtc_state->stream->cursor_position;
10057 		}
10058 		return;
10059 	}
10060 
10061 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
10062 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
10063 
10064 	memset(&attributes, 0, sizeof(attributes));
10065 	attributes.address.high_part = upper_32_bits(address);
10066 	attributes.address.low_part  = lower_32_bits(address);
10067 	attributes.width             = plane->state->crtc_w;
10068 	attributes.height            = plane->state->crtc_h;
10069 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
10070 	attributes.rotation_angle    = 0;
10071 	attributes.attribute_flags.value = 0;
10072 
10073 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
10074 	 * legacy gamma setup.
10075 	 */
10076 	if (crtc_state->cm_is_degamma_srgb &&
10077 	    adev->dm.dc->caps.color.dpp.gamma_corr)
10078 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
10079 
10080 	if (afb)
10081 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
10082 
10083 	if (crtc_state->stream) {
10084 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
10085 						     &attributes))
10086 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
10087 
10088 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
10089 
10090 		if (!dc_stream_set_cursor_position(crtc_state->stream,
10091 						   &position))
10092 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
10093 
10094 		update->cursor_position = &crtc_state->stream->cursor_position;
10095 	}
10096 }
10097 
10098 static void amdgpu_dm_enable_self_refresh(struct amdgpu_display_manager *dm,
10099 					  struct amdgpu_crtc *acrtc_attach,
10100 					  const struct dm_crtc_state *acrtc_state,
10101 					  const u64 current_ts)
10102 {
10103 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
10104 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
10105 	struct amdgpu_dm_connector *aconn =
10106 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
10107 
10108 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
10109 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
10110 	    (psr->psr_feature_enabled || pr->replay_feature_enabled)) {
10111 		if (aconn->sr_skip_count > 0)
10112 			aconn->sr_skip_count--;
10113 
10114 		/* Allow SR when skip count is 0. */
10115 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
10116 
10117 		/*
10118 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
10119 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
10120 		 * can be enabled immediately once OS demonstrates an
10121 		 * adequate number of fast atomic commits to notify KMD
10122 		 * of update events.
10123 		 * See `amdgpu_dm_crtc_vblank_control_worker()`.
10124 		 */
10125 		if (acrtc_attach->dm_irq_params.allow_sr_entry &&
10126 			(current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
10127 			amdgpu_dm_psr_set_event(dm, acrtc_state->stream, false,
10128 				psr_event_hw_programming, false);
10129 
10130 			amdgpu_dm_replay_set_event(dm, acrtc_state->stream, false,
10131 				replay_event_hw_programming, false);
10132 		}
10133 	} else {
10134 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
10135 	}
10136 }
10137 
10138 static void amdgpu_dm_commit_planes(struct drm_atomic_commit *state,
10139 				    struct drm_device *dev,
10140 				    struct amdgpu_display_manager *dm,
10141 				    struct drm_crtc *pcrtc,
10142 				    bool wait_for_vblank)
10143 {
10144 	u32 i;
10145 	u64 timestamp_ns = ktime_get_ns();
10146 	struct drm_plane *plane;
10147 	struct drm_plane_state *old_plane_state, *new_plane_state;
10148 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
10149 	struct drm_crtc_state *new_pcrtc_state =
10150 			drm_atomic_get_new_crtc_state(state, pcrtc);
10151 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
10152 	struct dm_crtc_state *dm_old_crtc_state =
10153 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
10154 	int planes_count = 0, vpos, hpos;
10155 	unsigned long flags;
10156 	u32 target_vblank, last_flip_vblank;
10157 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
10158 	bool cursor_update = false;
10159 	bool pflip_present = false;
10160 	bool dirty_rects_changed = false;
10161 	bool updated_planes_and_streams = false;
10162 	struct {
10163 		struct dc_surface_update surface_updates[MAX_SURFACES];
10164 		struct dc_plane_info plane_infos[MAX_SURFACES];
10165 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
10166 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
10167 		struct dc_stream_update stream_update;
10168 	} *bundle;
10169 
10170 	bundle = kzalloc_obj(*bundle);
10171 
10172 	if (!bundle) {
10173 		drm_err(dev, "Failed to allocate update bundle\n");
10174 		goto cleanup;
10175 	}
10176 
10177 	/*
10178 	 * Disable the cursor first if we're disabling all the planes.
10179 	 * It'll remain on the screen after the planes are re-enabled
10180 	 * if we don't.
10181 	 *
10182 	 * If the cursor is transitioning from native to overlay mode, the
10183 	 * native cursor needs to be disabled first.
10184 	 */
10185 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
10186 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10187 		struct dc_cursor_position cursor_position = {0};
10188 
10189 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
10190 						   &cursor_position))
10191 			drm_err(dev, "DC failed to disable native cursor\n");
10192 
10193 		bundle->stream_update.cursor_position =
10194 				&acrtc_state->stream->cursor_position;
10195 	}
10196 
10197 	if (acrtc_state->active_planes == 0 &&
10198 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10199 		amdgpu_dm_commit_cursors(state);
10200 
10201 	/* update planes when needed */
10202 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
10203 		struct drm_crtc *crtc = new_plane_state->crtc;
10204 		struct drm_crtc_state *new_crtc_state;
10205 		struct drm_framebuffer *fb = new_plane_state->fb;
10206 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
10207 		bool plane_needs_flip;
10208 		struct dc_plane_state *dc_plane;
10209 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
10210 
10211 		/* Cursor plane is handled after stream updates */
10212 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
10213 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10214 			if ((fb && crtc == pcrtc) ||
10215 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
10216 				cursor_update = true;
10217 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
10218 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
10219 			}
10220 
10221 			continue;
10222 		}
10223 
10224 		if (!fb || !crtc || pcrtc != crtc)
10225 			continue;
10226 
10227 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
10228 		if (!new_crtc_state->active)
10229 			continue;
10230 
10231 		dc_plane = dm_new_plane_state->dc_state;
10232 		if (!dc_plane)
10233 			continue;
10234 
10235 		bundle->surface_updates[planes_count].surface = dc_plane;
10236 		if (new_pcrtc_state->color_mgmt_changed) {
10237 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
10238 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
10239 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
10240 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
10241 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
10242 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
10243 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
10244 		}
10245 
10246 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
10247 				     &bundle->scaling_infos[planes_count]);
10248 
10249 		bundle->surface_updates[planes_count].scaling_info =
10250 			&bundle->scaling_infos[planes_count];
10251 
10252 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
10253 
10254 		pflip_present = pflip_present || plane_needs_flip;
10255 
10256 		if (!plane_needs_flip) {
10257 			planes_count += 1;
10258 			continue;
10259 		}
10260 
10261 		fill_dc_plane_info_and_addr(
10262 			dm->adev, new_plane_state,
10263 			afb->tiling_flags,
10264 			&bundle->plane_infos[planes_count],
10265 			&bundle->flip_addrs[planes_count].address,
10266 			afb->tmz_surface);
10267 
10268 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
10269 				 new_plane_state->plane->index,
10270 				 bundle->plane_infos[planes_count].dcc.enable);
10271 
10272 		bundle->surface_updates[planes_count].plane_info =
10273 			&bundle->plane_infos[planes_count];
10274 
10275 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
10276 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
10277 			fill_dc_dirty_rects(plane, old_plane_state,
10278 					    new_plane_state, new_crtc_state,
10279 					    &bundle->flip_addrs[planes_count],
10280 					    acrtc_state->stream->link->psr_settings.psr_version ==
10281 					    DC_PSR_VERSION_SU_1,
10282 					    &dirty_rects_changed);
10283 
10284 			/*
10285 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
10286 			 * and enabled it again after dirty regions are stable to avoid video glitch.
10287 			 * PSR-SU will be enabled in
10288 			 * amdgpu_dm_crtc_vblank_control_worker() if user
10289 			 * pause the video during the PSR-SU was disabled.
10290 			 */
10291 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
10292 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
10293 			    dirty_rects_changed) {
10294 				mutex_lock(&dm->dc_lock);
10295 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
10296 				timestamp_ns;
10297 				dc_exit_ips_for_hw_access(dm->dc);
10298 				amdgpu_dm_psr_set_event(dm, acrtc_state->stream, true,
10299 					psr_event_hw_programming, true);
10300 				mutex_unlock(&dm->dc_lock);
10301 			}
10302 		}
10303 
10304 		/*
10305 		 * Only allow immediate flips for fast updates that don't
10306 		 * change memory domain, FB pitch, DCC state, rotation or
10307 		 * mirroring.
10308 		 *
10309 		 * dm_crtc_helper_atomic_check() only accepts async flips with
10310 		 * fast updates.
10311 		 */
10312 		if (crtc->state->async_flip &&
10313 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
10314 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
10315 			drm_warn_once(state->dev,
10316 				      "[PLANE:%d:%s] async flip with non-fast update\n",
10317 				      plane->base.id, plane->name);
10318 
10319 		bundle->flip_addrs[planes_count].flip_immediate =
10320 			crtc->state->async_flip &&
10321 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
10322 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
10323 
10324 		timestamp_ns = ktime_get_ns();
10325 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
10326 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
10327 		bundle->surface_updates[planes_count].surface = dc_plane;
10328 
10329 		if (!bundle->surface_updates[planes_count].surface) {
10330 			drm_err(dev, "No surface for CRTC: id=%d\n",
10331 					acrtc_attach->crtc_id);
10332 			continue;
10333 		}
10334 
10335 		if (plane == pcrtc->primary)
10336 			update_freesync_state_on_stream(
10337 				dm,
10338 				acrtc_state,
10339 				acrtc_state->stream,
10340 				dc_plane,
10341 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
10342 
10343 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
10344 				 __func__,
10345 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
10346 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
10347 
10348 		planes_count += 1;
10349 
10350 	}
10351 
10352 	if (pflip_present) {
10353 		if (!vrr_active) {
10354 			/* Use old throttling in non-vrr fixed refresh rate mode
10355 			 * to keep flip scheduling based on target vblank counts
10356 			 * working in a backwards compatible way, e.g., for
10357 			 * clients using the GLX_OML_sync_control extension or
10358 			 * DRI3/Present extension with defined target_msc.
10359 			 */
10360 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
10361 		} else {
10362 			/* For variable refresh rate mode only:
10363 			 * Get vblank of last completed flip to avoid > 1 vrr
10364 			 * flips per video frame by use of throttling, but allow
10365 			 * flip programming anywhere in the possibly large
10366 			 * variable vrr vblank interval for fine-grained flip
10367 			 * timing control and more opportunity to avoid stutter
10368 			 * on late submission of flips.
10369 			 */
10370 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10371 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
10372 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10373 		}
10374 
10375 		target_vblank = last_flip_vblank + wait_for_vblank;
10376 
10377 		/*
10378 		 * Wait until we're out of the vertical blank period before the one
10379 		 * targeted by the flip
10380 		 */
10381 		while ((acrtc_attach->enabled &&
10382 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
10383 							    0, &vpos, &hpos, NULL,
10384 							    NULL, &pcrtc->hwmode)
10385 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
10386 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
10387 			(int)(target_vblank -
10388 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
10389 			usleep_range(1000, 1100);
10390 		}
10391 
10392 		/**
10393 		 * Prepare the flip event for the pageflip interrupt to handle.
10394 		 *
10395 		 * This only works in the case where we've already turned on the
10396 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
10397 		 * from 0 -> n planes we have to skip a hardware generated event
10398 		 * and rely on sending it from software.
10399 		 */
10400 		if (acrtc_attach->base.state->event &&
10401 		    acrtc_state->active_planes > 0) {
10402 			drm_crtc_vblank_get(pcrtc);
10403 
10404 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10405 
10406 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
10407 			prepare_flip_isr(acrtc_attach);
10408 
10409 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10410 		}
10411 
10412 		if (acrtc_state->stream) {
10413 			if (acrtc_state->freesync_vrr_info_changed)
10414 				bundle->stream_update.vrr_infopacket =
10415 					&acrtc_state->stream->vrr_infopacket;
10416 		}
10417 	} else if (cursor_update && acrtc_state->active_planes > 0) {
10418 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10419 		if (acrtc_attach->base.state->event) {
10420 			drm_crtc_vblank_get(pcrtc);
10421 			acrtc_attach->event = acrtc_attach->base.state->event;
10422 			acrtc_attach->base.state->event = NULL;
10423 		}
10424 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10425 	}
10426 
10427 	/* Update the planes if changed or disable if we don't have any. */
10428 	if ((planes_count || acrtc_state->active_planes == 0) &&
10429 		acrtc_state->stream) {
10430 		/*
10431 		 * If PSR or idle optimizations are enabled then flush out
10432 		 * any pending work before hardware programming.
10433 		 */
10434 		if (dm->vblank_control_workqueue)
10435 			flush_workqueue(dm->vblank_control_workqueue);
10436 
10437 		bundle->stream_update.stream = acrtc_state->stream;
10438 		if (new_pcrtc_state->mode_changed) {
10439 			bundle->stream_update.src = acrtc_state->stream->src;
10440 			bundle->stream_update.dst = acrtc_state->stream->dst;
10441 		}
10442 
10443 		if (new_pcrtc_state->color_mgmt_changed) {
10444 			/*
10445 			 * TODO: This isn't fully correct since we've actually
10446 			 * already modified the stream in place.
10447 			 */
10448 			bundle->stream_update.gamut_remap =
10449 				&acrtc_state->stream->gamut_remap_matrix;
10450 			bundle->stream_update.output_csc_transform =
10451 				&acrtc_state->stream->csc_color_matrix;
10452 			bundle->stream_update.out_transfer_func =
10453 				&acrtc_state->stream->out_transfer_func;
10454 			bundle->stream_update.lut3d_func =
10455 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
10456 			bundle->stream_update.func_shaper =
10457 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
10458 		}
10459 
10460 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
10461 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
10462 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
10463 
10464 		/*
10465 		 * If FreeSync state on the stream has changed then we need to
10466 		 * re-adjust the min/max bounds now that DC doesn't handle this
10467 		 * as part of commit.
10468 		 */
10469 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
10470 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10471 			dc_stream_adjust_vmin_vmax(
10472 				dm->dc, acrtc_state->stream,
10473 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
10474 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10475 		}
10476 		mutex_lock(&dm->dc_lock);
10477 		update_planes_and_stream_adapter(dm->dc,
10478 					 acrtc_state->update_type,
10479 					 planes_count,
10480 					 acrtc_state->stream,
10481 					 &bundle->stream_update,
10482 					 bundle->surface_updates);
10483 		updated_planes_and_streams = true;
10484 
10485 		/**
10486 		 * Enable or disable the interrupts on the backend.
10487 		 *
10488 		 * Most pipes are put into power gating when unused.
10489 		 *
10490 		 * When power gating is enabled on a pipe we lose the
10491 		 * interrupt enablement state when power gating is disabled.
10492 		 *
10493 		 * So we need to update the IRQ control state in hardware
10494 		 * whenever the pipe turns on (since it could be previously
10495 		 * power gated) or off (since some pipes can't be power gated
10496 		 * on some ASICs).
10497 		 */
10498 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
10499 			dm_update_pflip_irq_state(drm_to_adev(dev),
10500 						  acrtc_attach);
10501 		amdgpu_dm_enable_self_refresh(dm, acrtc_attach, acrtc_state,
10502 					      timestamp_ns);
10503 		mutex_unlock(&dm->dc_lock);
10504 	}
10505 
10506 	/*
10507 	 * Update cursor state *after* programming all the planes.
10508 	 * This avoids redundant programming in the case where we're going
10509 	 * to be disabling a single plane - those pipes are being disabled.
10510 	 */
10511 	if (acrtc_state->active_planes &&
10512 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
10513 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10514 		amdgpu_dm_commit_cursors(state);
10515 
10516 cleanup:
10517 	kfree(bundle);
10518 }
10519 
10520 static void amdgpu_dm_commit_audio(struct drm_device *dev,
10521 				   struct drm_atomic_commit *state)
10522 {
10523 	struct amdgpu_device *adev = drm_to_adev(dev);
10524 	struct amdgpu_dm_connector *aconnector;
10525 	struct drm_connector *connector;
10526 	struct drm_connector_state *old_con_state, *new_con_state;
10527 	struct drm_crtc_state *new_crtc_state;
10528 	struct dm_crtc_state *new_dm_crtc_state;
10529 	const struct dc_stream_status *status;
10530 	int i, inst;
10531 
10532 	/* Notify device removals. */
10533 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10534 		if (old_con_state->crtc != new_con_state->crtc) {
10535 			/* CRTC changes require notification. */
10536 			goto notify;
10537 		}
10538 
10539 		if (!new_con_state->crtc)
10540 			continue;
10541 
10542 		new_crtc_state = drm_atomic_get_new_crtc_state(
10543 			state, new_con_state->crtc);
10544 
10545 		if (!new_crtc_state)
10546 			continue;
10547 
10548 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10549 			continue;
10550 
10551 notify:
10552 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10553 			continue;
10554 
10555 		aconnector = to_amdgpu_dm_connector(connector);
10556 
10557 		mutex_lock(&adev->dm.audio_lock);
10558 		inst = aconnector->audio_inst;
10559 		aconnector->audio_inst = -1;
10560 		mutex_unlock(&adev->dm.audio_lock);
10561 
10562 		amdgpu_dm_audio_eld_notify(adev, inst);
10563 	}
10564 
10565 	/* Notify audio device additions. */
10566 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10567 		if (!new_con_state->crtc)
10568 			continue;
10569 
10570 		new_crtc_state = drm_atomic_get_new_crtc_state(
10571 			state, new_con_state->crtc);
10572 
10573 		if (!new_crtc_state)
10574 			continue;
10575 
10576 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10577 			continue;
10578 
10579 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
10580 		if (!new_dm_crtc_state->stream)
10581 			continue;
10582 
10583 		status = dc_stream_get_status(new_dm_crtc_state->stream);
10584 		if (!status)
10585 			continue;
10586 
10587 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10588 			continue;
10589 
10590 		aconnector = to_amdgpu_dm_connector(connector);
10591 
10592 		mutex_lock(&adev->dm.audio_lock);
10593 		inst = status->audio_inst;
10594 		aconnector->audio_inst = inst;
10595 		mutex_unlock(&adev->dm.audio_lock);
10596 
10597 		amdgpu_dm_audio_eld_notify(adev, inst);
10598 	}
10599 }
10600 
10601 /*
10602  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
10603  * @crtc_state: the DRM CRTC state
10604  * @stream_state: the DC stream state.
10605  *
10606  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
10607  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
10608  */
10609 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
10610 						struct dc_stream_state *stream_state)
10611 {
10612 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
10613 }
10614 
10615 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
10616 			      struct dm_crtc_state *crtc_state)
10617 {
10618 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
10619 }
10620 
10621 /**
10622  * amdgpu_dm_mod_power_update_streams - update mod_power stream state on modeset
10623  * @state: the drm atomic state
10624  * @dm: the display manager to update mod_power on
10625  *
10626  * Notify mod_power of stream changes on modeset events, and disable PSR/Replay
10627  * in preparation for hardware programming. See also
10628  * amdgpu_dm_mod_power_setup_streams() for post-modeset mod_power setup.
10629  */
10630 static void amdgpu_dm_mod_power_update_streams(struct drm_atomic_commit *state,
10631 					       struct amdgpu_display_manager *dm)
10632 {
10633 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10634 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10635 	struct amdgpu_dm_connector *aconnector;
10636 	struct drm_crtc *crtc;
10637 	int i = 0;
10638 
10639 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10640 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10641 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10642 
10643 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10644 			continue;
10645 
10646 		/*
10647 		 * Update mod_power on modeset event in preparation for hw
10648 		 * programming. Always use the old stream, since it would have
10649 		 * been previously added to mod_power. If old stream is null (on
10650 		 * crtc enable, for example), mod_power will no-op, which is the
10651 		 * desried behavior.
10652 		 */
10653 		if (old_crtc_state->active) {
10654 			scoped_guard(mutex, &dm->dc_lock) {
10655 				dc_exit_ips_for_hw_access(dm->dc);
10656 				amdgpu_dm_psr_set_event(dm, dm_old_crtc_state->stream, true,
10657 					psr_event_hw_programming, true);
10658 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, true,
10659 					replay_event_hw_programming, true);
10660 				amdgpu_dm_replay_set_event(dm, dm_old_crtc_state->stream, false,
10661 					replay_event_general_ui, false);
10662 			}
10663 		}
10664 
10665 		if (new_crtc_state->active) {
10666 			aconnector = (struct amdgpu_dm_connector *)
10667 				dm_new_crtc_state->stream->dm_stream_context;
10668 			if (old_crtc_state->active) {
10669 				mod_power_replace_stream(dm->power_module,
10670 					dm_old_crtc_state->stream,
10671 					dm_new_crtc_state->stream,
10672 					&aconnector->psr_caps);
10673 			} else {
10674 				mod_power_add_stream(dm->power_module,
10675 					dm_new_crtc_state->stream,
10676 					&aconnector->psr_caps);
10677 			}
10678 		} else if (old_crtc_state->active) {
10679 			mod_power_remove_stream(dm->power_module,
10680 				dm_old_crtc_state->stream);
10681 		}
10682 	}
10683 }
10684 
10685 /**
10686  * amdgpu_dm_mod_power_setup_streams - setup mod_power stream state post modeset
10687  * @state: the drm atomic state
10688  * @dm: the display manager to update mod_power on
10689  *
10690  * Notify mod_power of mode_change. This needs to be done after dc_stream
10691  * updates have been committed, and VRR parameters have been updated.
10692  */
10693 static void amdgpu_dm_mod_power_setup_streams(struct drm_atomic_commit *state,
10694 					      struct amdgpu_display_manager *dm)
10695 {
10696 	struct dm_crtc_state *dm_new_crtc_state;
10697 	struct drm_crtc_state *new_crtc_state;
10698 	struct amdgpu_crtc *acrtc;
10699 	struct drm_crtc *crtc;
10700 	int i = 0;
10701 
10702 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10703 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10704 		acrtc = to_amdgpu_crtc(crtc);
10705 
10706 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10707 			continue;
10708 
10709 		if (new_crtc_state->active) {
10710 			amdgpu_dm_link_setup_replay(dm_new_crtc_state->stream,
10711 					&acrtc->dm_irq_params.vrr_params);
10712 			mod_power_notify_mode_change(dm->power_module,
10713 						dm_new_crtc_state->stream,
10714 						false);
10715 
10716 			/*
10717 			 * Block PSR / Replay on the new stream until display settles post-modeset.
10718 			 * These events will be cleared by amdgpu_dm_enable_self_refresh() once
10719 			 * allow_sr_entry becomes true.
10720 			 */
10721 			amdgpu_dm_psr_set_event(dm, dm_new_crtc_state->stream, true,
10722 				psr_event_hw_programming, true);
10723 
10724 			amdgpu_dm_replay_set_event(dm, dm_new_crtc_state->stream, true,
10725 				replay_event_hw_programming | replay_event_general_ui,
10726 				true);
10727 		}
10728 	}
10729 
10730 }
10731 
10732 static void amdgpu_dm_commit_streams(struct drm_atomic_commit *state,
10733 					struct dc_state *dc_state)
10734 {
10735 	struct drm_device *dev = state->dev;
10736 	struct amdgpu_device *adev = drm_to_adev(dev);
10737 	struct amdgpu_display_manager *dm = &adev->dm;
10738 	struct drm_crtc *crtc;
10739 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10740 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10741 	struct drm_connector_state *old_con_state;
10742 	struct drm_connector *connector;
10743 	bool mode_set_reset_required = false;
10744 	u32 i;
10745 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
10746 	bool set_backlight_level = false;
10747 
10748 	/* Disable writeback */
10749 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
10750 		struct dm_connector_state *dm_old_con_state;
10751 		struct amdgpu_crtc *acrtc;
10752 
10753 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
10754 			continue;
10755 
10756 		old_crtc_state = NULL;
10757 
10758 		dm_old_con_state = to_dm_connector_state(old_con_state);
10759 		if (!dm_old_con_state->base.crtc)
10760 			continue;
10761 
10762 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
10763 		if (acrtc)
10764 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10765 
10766 		if (!acrtc || !acrtc->wb_enabled)
10767 			continue;
10768 
10769 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10770 
10771 		dm_clear_writeback(dm, dm_old_crtc_state);
10772 		acrtc->wb_enabled = false;
10773 	}
10774 
10775 	amdgpu_dm_mod_power_update_streams(state, dm);
10776 
10777 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
10778 				      new_crtc_state, i) {
10779 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10780 
10781 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10782 
10783 		if (old_crtc_state->active &&
10784 		    (!new_crtc_state->active ||
10785 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10786 			manage_dm_interrupts(adev, acrtc, NULL);
10787 			dc_stream_release(dm_old_crtc_state->stream);
10788 		}
10789 	}
10790 
10791 	drm_atomic_helper_calc_timestamping_constants(state);
10792 
10793 	/* update changed items */
10794 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10795 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10796 
10797 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10798 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10799 
10800 		drm_dbg_state(state->dev,
10801 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
10802 			acrtc->crtc_id,
10803 			new_crtc_state->enable,
10804 			new_crtc_state->active,
10805 			new_crtc_state->planes_changed,
10806 			new_crtc_state->mode_changed,
10807 			new_crtc_state->active_changed,
10808 			new_crtc_state->connectors_changed);
10809 
10810 		/* Disable cursor if disabling crtc */
10811 		if (old_crtc_state->active && !new_crtc_state->active) {
10812 			struct dc_cursor_position position;
10813 
10814 			memset(&position, 0, sizeof(position));
10815 			mutex_lock(&dm->dc_lock);
10816 			dc_exit_ips_for_hw_access(dm->dc);
10817 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
10818 			mutex_unlock(&dm->dc_lock);
10819 		}
10820 
10821 		/* Copy all transient state flags into dc state */
10822 		if (dm_new_crtc_state->stream) {
10823 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
10824 							    dm_new_crtc_state->stream);
10825 		}
10826 
10827 		/* handles headless hotplug case, updating new_state and
10828 		 * aconnector as needed
10829 		 */
10830 
10831 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
10832 
10833 			drm_dbg_atomic(dev,
10834 				       "Atomic commit: SET crtc id %d: [%p]\n",
10835 				       acrtc->crtc_id, acrtc);
10836 
10837 			if (!dm_new_crtc_state->stream) {
10838 				/*
10839 				 * this could happen because of issues with
10840 				 * userspace notifications delivery.
10841 				 * In this case userspace tries to set mode on
10842 				 * display which is disconnected in fact.
10843 				 * dc_sink is NULL in this case on aconnector.
10844 				 * We expect reset mode will come soon.
10845 				 *
10846 				 * This can also happen when unplug is done
10847 				 * during resume sequence ended
10848 				 *
10849 				 * In this case, we want to pretend we still
10850 				 * have a sink to keep the pipe running so that
10851 				 * hw state is consistent with the sw state
10852 				 */
10853 				drm_dbg_atomic(dev,
10854 					       "Failed to create new stream for crtc %d\n",
10855 						acrtc->base.base.id);
10856 				continue;
10857 			}
10858 
10859 			if (dm_old_crtc_state->stream)
10860 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10861 
10862 			pm_runtime_get_noresume(dev->dev);
10863 
10864 			acrtc->enabled = true;
10865 			acrtc->hw_mode = new_crtc_state->mode;
10866 			crtc->hwmode = new_crtc_state->mode;
10867 			mode_set_reset_required = true;
10868 			set_backlight_level = true;
10869 		} else if (modereset_required(new_crtc_state)) {
10870 			drm_dbg_atomic(dev,
10871 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
10872 				       acrtc->crtc_id, acrtc);
10873 			/* i.e. reset mode */
10874 			if (dm_old_crtc_state->stream)
10875 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10876 
10877 			mode_set_reset_required = true;
10878 		}
10879 	} /* for_each_crtc_in_state() */
10880 
10881 	/* if there mode set or reset, flush vblank work queue */
10882 	if (mode_set_reset_required) {
10883 		if (dm->vblank_control_workqueue)
10884 			flush_workqueue(dm->vblank_control_workqueue);
10885 	}
10886 
10887 	dm_enable_per_frame_crtc_master_sync(dc_state);
10888 	mutex_lock(&dm->dc_lock);
10889 	dc_exit_ips_for_hw_access(dm->dc);
10890 	WARN_ON(!dc_commit_streams(dm->dc, &params));
10891 
10892 	/* Allow idle optimization when vblank count is 0 for display off */
10893 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
10894 		dc_allow_idle_optimizations(dm->dc, true);
10895 	mutex_unlock(&dm->dc_lock);
10896 
10897 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10898 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10899 
10900 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10901 
10902 		if (dm_new_crtc_state->stream != NULL) {
10903 			const struct dc_stream_status *status =
10904 					dc_stream_get_status(dm_new_crtc_state->stream);
10905 
10906 			if (!status)
10907 				status = dc_state_get_stream_status(dc_state,
10908 									 dm_new_crtc_state->stream);
10909 			if (!status)
10910 				drm_err(dev,
10911 					"got no status for stream %p on acrtc%p\n",
10912 					dm_new_crtc_state->stream, acrtc);
10913 			else
10914 				acrtc->otg_inst = status->primary_otg_inst;
10915 		}
10916 	}
10917 
10918 	/* During boot up and resume the DC layer will reset the panel brightness
10919 	 * to fix a flicker issue.
10920 	 * It will cause the dm->actual_brightness is not the current panel brightness
10921 	 * level. (the dm->brightness is the correct panel level)
10922 	 * So we set the backlight level with dm->brightness value after set mode
10923 	 */
10924 	if (set_backlight_level) {
10925 		for (i = 0; i < dm->num_of_edps; i++) {
10926 			if (dm->backlight_dev[i])
10927 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
10928 		}
10929 	}
10930 }
10931 
10932 static void dm_set_writeback(struct amdgpu_display_manager *dm,
10933 			      struct dm_crtc_state *crtc_state,
10934 			      struct drm_connector *connector,
10935 			      struct drm_connector_state *new_con_state)
10936 {
10937 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
10938 	struct amdgpu_device *adev = dm->adev;
10939 	struct amdgpu_crtc *acrtc;
10940 	struct dc_writeback_info *wb_info;
10941 	struct pipe_ctx *pipe = NULL;
10942 	struct amdgpu_framebuffer *afb;
10943 	int i = 0;
10944 
10945 	wb_info = kzalloc_obj(*wb_info);
10946 	if (!wb_info) {
10947 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
10948 		return;
10949 	}
10950 
10951 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
10952 	if (!acrtc) {
10953 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
10954 		kfree(wb_info);
10955 		return;
10956 	}
10957 
10958 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
10959 	if (!afb) {
10960 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
10961 		kfree(wb_info);
10962 		return;
10963 	}
10964 
10965 	for (i = 0; i < MAX_PIPES; i++) {
10966 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
10967 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
10968 			break;
10969 		}
10970 	}
10971 
10972 	/* fill in wb_info */
10973 	wb_info->wb_enabled = true;
10974 
10975 	wb_info->dwb_pipe_inst = 0;
10976 	wb_info->dwb_params.dwbscl_black_color = 0;
10977 	wb_info->dwb_params.hdr_mult = 0x1F000;
10978 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
10979 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
10980 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
10981 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
10982 
10983 	/* width & height from crtc */
10984 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
10985 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
10986 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
10987 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
10988 
10989 	wb_info->dwb_params.cnv_params.crop_en = false;
10990 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
10991 
10992 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
10993 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
10994 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
10995 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
10996 
10997 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
10998 
10999 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
11000 
11001 	wb_info->dwb_params.scaler_taps.h_taps = 1;
11002 	wb_info->dwb_params.scaler_taps.v_taps = 1;
11003 	wb_info->dwb_params.scaler_taps.h_taps_c = 1;
11004 	wb_info->dwb_params.scaler_taps.v_taps_c = 1;
11005 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
11006 
11007 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
11008 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
11009 
11010 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
11011 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
11012 		wb_info->mcif_buf_params.chroma_address[i] = 0;
11013 	}
11014 
11015 	wb_info->mcif_buf_params.p_vmid = 1;
11016 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
11017 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
11018 		wb_info->mcif_warmup_params.region_size =
11019 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
11020 	}
11021 	wb_info->mcif_warmup_params.p_vmid = 1;
11022 	wb_info->writeback_source_plane = pipe->plane_state;
11023 
11024 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
11025 
11026 	acrtc->wb_pending = true;
11027 	acrtc->wb_conn = wb_conn;
11028 	drm_writeback_queue_job(wb_conn, new_con_state);
11029 }
11030 
11031 static void amdgpu_dm_update_hdcp(struct drm_atomic_commit *state)
11032 {
11033 	struct drm_connector_state *old_con_state, *new_con_state;
11034 	struct drm_device *dev = state->dev;
11035 	struct drm_connector *connector;
11036 	struct amdgpu_device *adev = drm_to_adev(dev);
11037 	int i;
11038 
11039 	if (!adev->dm.hdcp_workqueue)
11040 		return;
11041 
11042 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11043 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11044 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11045 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11046 		struct dm_crtc_state *dm_new_crtc_state;
11047 		struct amdgpu_dm_connector *aconnector;
11048 
11049 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11050 			continue;
11051 
11052 		aconnector = to_amdgpu_dm_connector(connector);
11053 
11054 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
11055 
11056 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
11057 			connector->index, connector->status, connector->dpms);
11058 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
11059 			old_con_state->content_protection, new_con_state->content_protection);
11060 
11061 		if (aconnector->dc_sink) {
11062 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
11063 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
11064 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
11065 				aconnector->dc_sink->edid_caps.display_name);
11066 			}
11067 		}
11068 
11069 		new_crtc_state = NULL;
11070 		old_crtc_state = NULL;
11071 
11072 		if (acrtc) {
11073 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11074 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11075 		}
11076 
11077 		if (old_crtc_state)
11078 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11079 			old_crtc_state->enable,
11080 			old_crtc_state->active,
11081 			old_crtc_state->mode_changed,
11082 			old_crtc_state->active_changed,
11083 			old_crtc_state->connectors_changed);
11084 
11085 		if (new_crtc_state)
11086 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
11087 			new_crtc_state->enable,
11088 			new_crtc_state->active,
11089 			new_crtc_state->mode_changed,
11090 			new_crtc_state->active_changed,
11091 			new_crtc_state->connectors_changed);
11092 
11093 
11094 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11095 
11096 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
11097 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
11098 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
11099 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
11100 			dm_new_con_state->update_hdcp = true;
11101 			continue;
11102 		}
11103 
11104 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
11105 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
11106 			/* when display is unplugged from mst hub, connctor will
11107 			 * be destroyed within dm_dp_mst_connector_destroy. connector
11108 			 * hdcp perperties, like type, undesired, desired, enabled,
11109 			 * will be lost. So, save hdcp properties into hdcp_work within
11110 			 * amdgpu_dm_atomic_commit_tail. if the same display is
11111 			 * plugged back with same display index, its hdcp properties
11112 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
11113 			 */
11114 
11115 			bool enable_encryption = false;
11116 
11117 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
11118 				enable_encryption = true;
11119 
11120 			if (aconnector->dc_link && aconnector->dc_sink &&
11121 				aconnector->dc_link->type == dc_connection_mst_branch) {
11122 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
11123 				struct hdcp_workqueue *hdcp_w =
11124 					&hdcp_work[aconnector->dc_link->link_index];
11125 
11126 				hdcp_w->hdcp_content_type[connector->index] =
11127 					new_con_state->hdcp_content_type;
11128 				hdcp_w->content_protection[connector->index] =
11129 					new_con_state->content_protection;
11130 			}
11131 
11132 			if (new_crtc_state && new_crtc_state->mode_changed &&
11133 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
11134 				enable_encryption = true;
11135 
11136 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
11137 
11138 			if (aconnector->dc_link)
11139 				hdcp_update_display(
11140 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
11141 					new_con_state->hdcp_content_type, enable_encryption);
11142 		}
11143 	}
11144 }
11145 
11146 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_commit *state)
11147 {
11148 	struct drm_crtc *crtc;
11149 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11150 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11151 	int i, ret;
11152 
11153 	ret = drm_dp_mst_atomic_setup_commit(state);
11154 	if (ret)
11155 		return ret;
11156 
11157 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11158 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11159 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11160 		/*
11161 		 * Color management settings. We also update color properties
11162 		 * when a modeset is needed, to ensure it gets reprogrammed.
11163 		 */
11164 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
11165 		    (dm_new_crtc_state->base.color_mgmt_changed ||
11166 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11167 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11168 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
11169 			if (ret) {
11170 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
11171 				return ret;
11172 			}
11173 		}
11174 	}
11175 
11176 	return 0;
11177 }
11178 
11179 /**
11180  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
11181  * @state: The atomic state to commit
11182  *
11183  * This will tell DC to commit the constructed DC state from atomic_check,
11184  * programming the hardware. Any failures here implies a hardware failure, since
11185  * atomic check should have filtered anything non-kosher.
11186  */
11187 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_commit *state)
11188 {
11189 	struct drm_device *dev = state->dev;
11190 	struct amdgpu_device *adev = drm_to_adev(dev);
11191 	struct amdgpu_display_manager *dm = &adev->dm;
11192 	struct dm_atomic_state *dm_state;
11193 	struct dc_state *dc_state = NULL;
11194 	u32 i, j;
11195 	struct drm_crtc *crtc;
11196 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11197 	unsigned long flags;
11198 	bool wait_for_vblank = true;
11199 	struct drm_connector *connector;
11200 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
11201 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11202 	int crtc_disable_count = 0;
11203 
11204 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
11205 
11206 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
11207 	drm_dp_mst_atomic_wait_for_dependencies(state);
11208 
11209 	dm_state = dm_atomic_get_new_state(state);
11210 	if (dm_state && dm_state->context) {
11211 		dc_state = dm_state->context;
11212 		amdgpu_dm_commit_streams(state, dc_state);
11213 	}
11214 
11215 	amdgpu_dm_update_hdcp(state);
11216 
11217 	/* Handle connector state changes */
11218 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
11219 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11220 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
11221 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11222 		struct dc_surface_update *dummy_updates;
11223 		struct dc_stream_update stream_update;
11224 		struct dc_info_packet hdr_packet;
11225 		struct dc_stream_status *status = NULL;
11226 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
11227 
11228 		memset(&stream_update, 0, sizeof(stream_update));
11229 
11230 		if (acrtc) {
11231 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11232 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
11233 		}
11234 
11235 		/* Skip any modesets/resets */
11236 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
11237 			continue;
11238 
11239 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11240 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11241 
11242 		scaling_changed = is_scaling_state_different(dm_new_con_state,
11243 							     dm_old_con_state);
11244 
11245 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
11246 			(dm_old_crtc_state->stream->output_color_space !=
11247 				get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
11248 			output_color_space_changed = true;
11249 
11250 		abm_changed = dm_new_crtc_state->abm_level !=
11251 			      dm_old_crtc_state->abm_level;
11252 
11253 		hdr_changed =
11254 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
11255 
11256 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
11257 			continue;
11258 
11259 		stream_update.stream = dm_new_crtc_state->stream;
11260 		if (scaling_changed) {
11261 			update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
11262 					dm_new_con_state, dm_new_crtc_state->stream);
11263 
11264 			stream_update.src = dm_new_crtc_state->stream->src;
11265 			stream_update.dst = dm_new_crtc_state->stream->dst;
11266 		}
11267 
11268 		if (output_color_space_changed) {
11269 			dm_new_crtc_state->stream->output_color_space
11270 				= get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
11271 
11272 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
11273 		}
11274 
11275 		if (abm_changed) {
11276 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
11277 
11278 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
11279 		}
11280 
11281 		if (hdr_changed) {
11282 			fill_hdr_info_packet(new_con_state, &hdr_packet);
11283 			stream_update.hdr_static_metadata = &hdr_packet;
11284 		}
11285 
11286 		status = dc_stream_get_status(dm_new_crtc_state->stream);
11287 
11288 		if (WARN_ON(!status))
11289 			continue;
11290 
11291 		WARN_ON(!status->plane_count);
11292 
11293 		/*
11294 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
11295 		 * Here we create an empty update on each plane.
11296 		 * To fix this, DC should permit updating only stream properties.
11297 		 */
11298 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
11299 		if (!dummy_updates) {
11300 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
11301 			continue;
11302 		}
11303 		for (j = 0; j < status->plane_count; j++)
11304 			dummy_updates[j].surface = status->plane_states[j];
11305 
11306 		sort(dummy_updates, status->plane_count,
11307 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
11308 
11309 		mutex_lock(&dm->dc_lock);
11310 		dc_exit_ips_for_hw_access(dm->dc);
11311 		dc_update_planes_and_stream(dm->dc,
11312 					    dummy_updates,
11313 					    status->plane_count,
11314 					    dm_new_crtc_state->stream,
11315 					    &stream_update);
11316 		mutex_unlock(&dm->dc_lock);
11317 		kfree(dummy_updates);
11318 
11319 		drm_connector_update_privacy_screen(new_con_state);
11320 	}
11321 
11322 	/**
11323 	 * Enable interrupts for CRTCs that are newly enabled or went through
11324 	 * a modeset. It was intentionally deferred until after the front end
11325 	 * state was modified to wait until the OTG was on and so the IRQ
11326 	 * handlers didn't access stale or invalid state.
11327 	 */
11328 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11329 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11330 #ifdef CONFIG_DEBUG_FS
11331 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
11332 #endif
11333 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
11334 		if (old_crtc_state->active && !new_crtc_state->active)
11335 			crtc_disable_count++;
11336 
11337 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11338 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11339 
11340 		/* For freesync config update on crtc state and params for irq */
11341 		update_stream_irq_parameters(dm, dm_new_crtc_state);
11342 
11343 #ifdef CONFIG_DEBUG_FS
11344 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11345 		cur_crc_src = acrtc->dm_irq_params.crc_src;
11346 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11347 #endif
11348 
11349 		if (new_crtc_state->active &&
11350 		    (!old_crtc_state->active ||
11351 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11352 			dc_stream_retain(dm_new_crtc_state->stream);
11353 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
11354 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
11355 		}
11356 		/* Handle vrr on->off / off->on transitions */
11357 		amdgpu_dm_handle_vrr_transition(dm, dm_old_crtc_state, dm_new_crtc_state);
11358 
11359 #ifdef CONFIG_DEBUG_FS
11360 		if (new_crtc_state->active &&
11361 		    (!old_crtc_state->active ||
11362 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11363 			/**
11364 			 * Frontend may have changed so reapply the CRC capture
11365 			 * settings for the stream.
11366 			 */
11367 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
11368 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
11369 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
11370 					uint8_t cnt;
11371 
11372 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11373 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
11374 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
11375 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
11376 
11377 							/**
11378 							 * It takes 2 frames for HW to stably generate CRC when
11379 							 * resuming from suspend, so we set skip_frame_cnt 2.
11380 							 */
11381 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
11382 						}
11383 					}
11384 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11385 				}
11386 #endif
11387 				if (amdgpu_dm_crtc_configure_crc_source(
11388 					crtc, dm_new_crtc_state, cur_crc_src))
11389 					drm_dbg_atomic(dev, "Failed to configure crc source");
11390 			}
11391 		}
11392 #endif
11393 	}
11394 
11395 	amdgpu_dm_mod_power_setup_streams(state, dm);
11396 
11397 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
11398 		if (new_crtc_state->async_flip)
11399 			wait_for_vblank = false;
11400 
11401 	/* update planes when needed per crtc*/
11402 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
11403 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11404 
11405 		if (dm_new_crtc_state->stream)
11406 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
11407 	}
11408 
11409 	/* Enable writeback */
11410 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11411 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11412 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11413 
11414 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11415 			continue;
11416 
11417 		if (!new_con_state->writeback_job)
11418 			continue;
11419 
11420 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11421 
11422 		if (!new_crtc_state)
11423 			continue;
11424 
11425 		if (acrtc->wb_enabled)
11426 			continue;
11427 
11428 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11429 
11430 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
11431 		acrtc->wb_enabled = true;
11432 	}
11433 
11434 	/* Update audio instances for each connector. */
11435 	amdgpu_dm_commit_audio(dev, state);
11436 
11437 	/* restore the backlight level */
11438 	for (i = 0; i < dm->num_of_edps; i++) {
11439 		if (dm->backlight_dev[i] &&
11440 		    (dm->actual_brightness[i] != dm->brightness[i]))
11441 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11442 	}
11443 
11444 	/*
11445 	 * send vblank event on all events not handled in flip and
11446 	 * mark consumed event for drm_atomic_helper_commit_hw_done
11447 	 */
11448 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11449 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11450 
11451 		if (new_crtc_state->event)
11452 			drm_send_event_locked(dev, &new_crtc_state->event->base);
11453 
11454 		new_crtc_state->event = NULL;
11455 	}
11456 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11457 
11458 	/* Signal HW programming completion */
11459 	drm_atomic_helper_commit_hw_done(state);
11460 
11461 	if (wait_for_vblank)
11462 		drm_atomic_helper_wait_for_flip_done(dev, state);
11463 
11464 	drm_atomic_helper_cleanup_planes(dev, state);
11465 
11466 	/* Don't free the memory if we are hitting this as part of suspend.
11467 	 * This way we don't free any memory during suspend; see
11468 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
11469 	 * non-suspend modeset or when the driver is torn down.
11470 	 */
11471 	if (!adev->in_suspend) {
11472 		/* return the stolen vga memory back to VRAM */
11473 		if (!adev->mman.keep_stolen_vga_memory)
11474 			amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_VGA);
11475 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_EXTENDED);
11476 	}
11477 
11478 	/*
11479 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
11480 	 * so we can put the GPU into runtime suspend if we're not driving any
11481 	 * displays anymore
11482 	 */
11483 	for (i = 0; i < crtc_disable_count; i++)
11484 		pm_runtime_put_autosuspend(dev->dev);
11485 	pm_runtime_mark_last_busy(dev->dev);
11486 
11487 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
11488 }
11489 
11490 static int dm_force_atomic_commit(struct drm_connector *connector)
11491 {
11492 	int ret = 0;
11493 	struct drm_device *ddev = connector->dev;
11494 	struct drm_atomic_commit *state = drm_atomic_commit_alloc(ddev);
11495 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11496 	struct drm_plane *plane = disconnected_acrtc->base.primary;
11497 	struct drm_connector_state *conn_state;
11498 	struct drm_crtc_state *crtc_state;
11499 	struct drm_plane_state *plane_state;
11500 
11501 	if (!state)
11502 		return -ENOMEM;
11503 
11504 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
11505 
11506 	/* Construct an atomic state to restore previous display setting */
11507 
11508 	/*
11509 	 * Attach connectors to drm_atomic_commit
11510 	 */
11511 	conn_state = drm_atomic_get_connector_state(state, connector);
11512 
11513 	/* Check for error in getting connector state */
11514 	if (IS_ERR(conn_state)) {
11515 		ret = PTR_ERR(conn_state);
11516 		goto out;
11517 	}
11518 
11519 	/* Attach crtc to drm_atomic_commit*/
11520 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
11521 
11522 	/* Check for error in getting crtc state */
11523 	if (IS_ERR(crtc_state)) {
11524 		ret = PTR_ERR(crtc_state);
11525 		goto out;
11526 	}
11527 
11528 	/* force a restore */
11529 	crtc_state->mode_changed = true;
11530 
11531 	/* Attach plane to drm_atomic_commit */
11532 	plane_state = drm_atomic_get_plane_state(state, plane);
11533 
11534 	/* Check for error in getting plane state */
11535 	if (IS_ERR(plane_state)) {
11536 		ret = PTR_ERR(plane_state);
11537 		goto out;
11538 	}
11539 
11540 	/* Call commit internally with the state we just constructed */
11541 	ret = drm_atomic_commit(state);
11542 
11543 out:
11544 	drm_atomic_commit_put(state);
11545 	if (ret)
11546 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
11547 
11548 	return ret;
11549 }
11550 
11551 /*
11552  * This function handles all cases when set mode does not come upon hotplug.
11553  * This includes when a display is unplugged then plugged back into the
11554  * same port and when running without usermode desktop manager supprot
11555  */
11556 void dm_restore_drm_connector_state(struct drm_device *dev,
11557 				    struct drm_connector *connector)
11558 {
11559 	struct amdgpu_dm_connector *aconnector;
11560 	struct amdgpu_crtc *disconnected_acrtc;
11561 	struct dm_crtc_state *acrtc_state;
11562 
11563 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11564 		return;
11565 
11566 	aconnector = to_amdgpu_dm_connector(connector);
11567 
11568 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
11569 		return;
11570 
11571 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11572 	if (!disconnected_acrtc)
11573 		return;
11574 
11575 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
11576 	if (!acrtc_state->stream)
11577 		return;
11578 
11579 	/*
11580 	 * If the previous sink is not released and different from the current,
11581 	 * we deduce we are in a state where we can not rely on usermode call
11582 	 * to turn on the display, so we do it here
11583 	 */
11584 	if (acrtc_state->stream->sink != aconnector->dc_sink)
11585 		dm_force_atomic_commit(&aconnector->base);
11586 }
11587 
11588 /*
11589  * Grabs all modesetting locks to serialize against any blocking commits,
11590  * Waits for completion of all non blocking commits.
11591  */
11592 static int do_aquire_global_lock(struct drm_device *dev,
11593 				 struct drm_atomic_commit *state)
11594 {
11595 	struct drm_crtc *crtc;
11596 	struct drm_crtc_commit *commit;
11597 	long ret;
11598 
11599 	/*
11600 	 * Adding all modeset locks to aquire_ctx will
11601 	 * ensure that when the framework release it the
11602 	 * extra locks we are locking here will get released to
11603 	 */
11604 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
11605 	if (ret)
11606 		return ret;
11607 
11608 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
11609 		spin_lock(&crtc->commit_lock);
11610 		commit = list_first_entry_or_null(&crtc->commit_list,
11611 				struct drm_crtc_commit, commit_entry);
11612 		if (commit)
11613 			drm_crtc_commit_get(commit);
11614 		spin_unlock(&crtc->commit_lock);
11615 
11616 		if (!commit)
11617 			continue;
11618 
11619 		/*
11620 		 * Make sure all pending HW programming completed and
11621 		 * page flips done
11622 		 */
11623 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
11624 
11625 		if (ret > 0)
11626 			ret = wait_for_completion_interruptible_timeout(
11627 					&commit->flip_done, 10*HZ);
11628 
11629 		if (ret == 0)
11630 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
11631 				  crtc->base.id, crtc->name);
11632 
11633 		drm_crtc_commit_put(commit);
11634 	}
11635 
11636 	return ret < 0 ? ret : 0;
11637 }
11638 
11639 static void get_freesync_config_for_crtc(
11640 	struct dm_crtc_state *new_crtc_state,
11641 	struct dm_connector_state *new_con_state)
11642 {
11643 	struct mod_freesync_config config = {0};
11644 	struct amdgpu_dm_connector *aconnector;
11645 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
11646 	int vrefresh = drm_mode_vrefresh(mode);
11647 	bool fs_vid_mode = false;
11648 
11649 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11650 		return;
11651 
11652 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
11653 
11654 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
11655 					vrefresh >= aconnector->min_vfreq &&
11656 					vrefresh <= aconnector->max_vfreq;
11657 
11658 	if (new_crtc_state->vrr_supported) {
11659 		new_crtc_state->stream->ignore_msa_timing_param = true;
11660 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
11661 
11662 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
11663 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
11664 		config.vsif_supported = true;
11665 		config.btr = true;
11666 
11667 		if (fs_vid_mode) {
11668 			config.state = VRR_STATE_ACTIVE_FIXED;
11669 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
11670 			goto out;
11671 		} else if (new_crtc_state->base.vrr_enabled) {
11672 			config.state = VRR_STATE_ACTIVE_VARIABLE;
11673 		} else {
11674 			config.state = VRR_STATE_INACTIVE;
11675 		}
11676 	} else {
11677 		config.state = VRR_STATE_UNSUPPORTED;
11678 	}
11679 out:
11680 	new_crtc_state->freesync_config = config;
11681 }
11682 
11683 static void reset_freesync_config_for_crtc(
11684 	struct dm_crtc_state *new_crtc_state)
11685 {
11686 	new_crtc_state->vrr_supported = false;
11687 
11688 	memset(&new_crtc_state->vrr_infopacket, 0,
11689 	       sizeof(new_crtc_state->vrr_infopacket));
11690 }
11691 
11692 static bool
11693 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
11694 				 struct drm_crtc_state *new_crtc_state)
11695 {
11696 	const struct drm_display_mode *old_mode, *new_mode;
11697 
11698 	if (!old_crtc_state || !new_crtc_state)
11699 		return false;
11700 
11701 	old_mode = &old_crtc_state->mode;
11702 	new_mode = &new_crtc_state->mode;
11703 
11704 	if (old_mode->clock       == new_mode->clock &&
11705 	    old_mode->hdisplay    == new_mode->hdisplay &&
11706 	    old_mode->vdisplay    == new_mode->vdisplay &&
11707 	    old_mode->htotal      == new_mode->htotal &&
11708 	    old_mode->vtotal      != new_mode->vtotal &&
11709 	    old_mode->hsync_start == new_mode->hsync_start &&
11710 	    old_mode->vsync_start != new_mode->vsync_start &&
11711 	    old_mode->hsync_end   == new_mode->hsync_end &&
11712 	    old_mode->vsync_end   != new_mode->vsync_end &&
11713 	    old_mode->hskew       == new_mode->hskew &&
11714 	    old_mode->vscan       == new_mode->vscan &&
11715 	    (old_mode->vsync_end - old_mode->vsync_start) ==
11716 	    (new_mode->vsync_end - new_mode->vsync_start))
11717 		return true;
11718 
11719 	return false;
11720 }
11721 
11722 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
11723 {
11724 	u64 num, den, res;
11725 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
11726 
11727 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
11728 
11729 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
11730 	den = (unsigned long long)new_crtc_state->mode.htotal *
11731 	      (unsigned long long)new_crtc_state->mode.vtotal;
11732 
11733 	res = div_u64(num, den);
11734 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
11735 }
11736 
11737 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
11738 			 struct drm_atomic_commit *state,
11739 			 struct drm_crtc *crtc,
11740 			 struct drm_crtc_state *old_crtc_state,
11741 			 struct drm_crtc_state *new_crtc_state,
11742 			 bool enable,
11743 			 bool *lock_and_validation_needed)
11744 {
11745 	struct dm_atomic_state *dm_state = NULL;
11746 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11747 	struct dc_stream_state *new_stream;
11748 	struct amdgpu_device *adev = dm->adev;
11749 	int ret = 0;
11750 
11751 	/*
11752 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
11753 	 * update changed items
11754 	 */
11755 	struct amdgpu_crtc *acrtc = NULL;
11756 	struct drm_connector *connector = NULL;
11757 	struct amdgpu_dm_connector *aconnector = NULL;
11758 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
11759 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
11760 
11761 	new_stream = NULL;
11762 
11763 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11764 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11765 	acrtc = to_amdgpu_crtc(crtc);
11766 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
11767 	if (connector)
11768 		aconnector = to_amdgpu_dm_connector(connector);
11769 
11770 	/* TODO This hack should go away */
11771 	if (connector && enable) {
11772 		/* Make sure fake sink is created in plug-in scenario */
11773 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
11774 									connector);
11775 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
11776 									connector);
11777 
11778 		if (WARN_ON(!drm_new_conn_state)) {
11779 			ret = -EINVAL;
11780 			goto fail;
11781 		}
11782 
11783 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
11784 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
11785 
11786 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11787 			goto skip_modeset;
11788 
11789 		new_stream = create_validate_stream_for_sink(connector,
11790 							     &new_crtc_state->mode,
11791 							     dm_new_conn_state,
11792 							     dm_old_crtc_state->stream);
11793 
11794 		/*
11795 		 * we can have no stream on ACTION_SET if a display
11796 		 * was disconnected during S3, in this case it is not an
11797 		 * error, the OS will be updated after detection, and
11798 		 * will do the right thing on next atomic commit
11799 		 */
11800 
11801 		if (!new_stream) {
11802 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
11803 					__func__, acrtc->base.base.id);
11804 			ret = -ENOMEM;
11805 			goto fail;
11806 		}
11807 
11808 		/*
11809 		 * TODO: Check VSDB bits to decide whether this should
11810 		 * be enabled or not.
11811 		 */
11812 		new_stream->triggered_crtc_reset.enabled =
11813 			dm->force_timing_sync;
11814 
11815 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11816 
11817 		ret = fill_hdr_info_packet(drm_new_conn_state,
11818 					   &new_stream->hdr_static_metadata);
11819 		if (ret)
11820 			goto fail;
11821 
11822 		/*
11823 		 * If we already removed the old stream from the context
11824 		 * (and set the new stream to NULL) then we can't reuse
11825 		 * the old stream even if the stream and scaling are unchanged.
11826 		 * We'll hit the BUG_ON and black screen.
11827 		 *
11828 		 * TODO: Refactor this function to allow this check to work
11829 		 * in all conditions.
11830 		 */
11831 		if (amdgpu_freesync_vid_mode &&
11832 		    dm_new_crtc_state->stream &&
11833 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
11834 			goto skip_modeset;
11835 
11836 		if (dm_new_crtc_state->stream &&
11837 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11838 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
11839 			new_crtc_state->mode_changed = false;
11840 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
11841 					 new_crtc_state->mode_changed);
11842 		}
11843 	}
11844 
11845 	/* mode_changed flag may get updated above, need to check again */
11846 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11847 		goto skip_modeset;
11848 
11849 	drm_dbg_state(state->dev,
11850 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
11851 		acrtc->crtc_id,
11852 		new_crtc_state->enable,
11853 		new_crtc_state->active,
11854 		new_crtc_state->planes_changed,
11855 		new_crtc_state->mode_changed,
11856 		new_crtc_state->active_changed,
11857 		new_crtc_state->connectors_changed);
11858 
11859 	/* Remove stream for any changed/disabled CRTC */
11860 	if (!enable) {
11861 
11862 		if (!dm_old_crtc_state->stream)
11863 			goto skip_modeset;
11864 
11865 		/* Unset freesync video if it was active before */
11866 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
11867 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
11868 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
11869 		}
11870 
11871 		/* Now check if we should set freesync video mode */
11872 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
11873 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11874 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
11875 		    is_timing_unchanged_for_freesync(new_crtc_state,
11876 						     old_crtc_state)) {
11877 			new_crtc_state->mode_changed = false;
11878 			drm_dbg_driver(adev_to_drm(adev),
11879 				"Mode change not required for front porch change, setting mode_changed to %d",
11880 				new_crtc_state->mode_changed);
11881 
11882 			set_freesync_fixed_config(dm_new_crtc_state);
11883 
11884 			goto skip_modeset;
11885 		} else if (amdgpu_freesync_vid_mode && aconnector &&
11886 			   is_freesync_video_mode(&new_crtc_state->mode,
11887 						  aconnector)) {
11888 			struct drm_display_mode *high_mode;
11889 
11890 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
11891 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
11892 				set_freesync_fixed_config(dm_new_crtc_state);
11893 		}
11894 
11895 		ret = dm_atomic_get_state(state, &dm_state);
11896 		if (ret)
11897 			goto fail;
11898 
11899 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
11900 				crtc->base.id);
11901 
11902 		/* i.e. reset mode */
11903 		if (dc_state_remove_stream(
11904 				dm->dc,
11905 				dm_state->context,
11906 				dm_old_crtc_state->stream) != DC_OK) {
11907 			ret = -EINVAL;
11908 			goto fail;
11909 		}
11910 
11911 		dc_stream_release(dm_old_crtc_state->stream);
11912 		dm_new_crtc_state->stream = NULL;
11913 
11914 		reset_freesync_config_for_crtc(dm_new_crtc_state);
11915 
11916 		*lock_and_validation_needed = true;
11917 
11918 	} else {/* Add stream for any updated/enabled CRTC */
11919 		/*
11920 		 * Quick fix to prevent NULL pointer on new_stream when
11921 		 * added MST connectors not found in existing crtc_state in the chained mode
11922 		 * TODO: need to dig out the root cause of that
11923 		 */
11924 		if (!connector)
11925 			goto skip_modeset;
11926 
11927 		if (modereset_required(new_crtc_state))
11928 			goto skip_modeset;
11929 
11930 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
11931 				     dm_old_crtc_state->stream)) {
11932 
11933 			WARN_ON(dm_new_crtc_state->stream);
11934 
11935 			ret = dm_atomic_get_state(state, &dm_state);
11936 			if (ret)
11937 				goto fail;
11938 
11939 			dm_new_crtc_state->stream = new_stream;
11940 
11941 			dc_stream_retain(new_stream);
11942 
11943 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
11944 					 crtc->base.id);
11945 
11946 			if (dc_state_add_stream(
11947 					dm->dc,
11948 					dm_state->context,
11949 					dm_new_crtc_state->stream) != DC_OK) {
11950 				ret = -EINVAL;
11951 				goto fail;
11952 			}
11953 
11954 			*lock_and_validation_needed = true;
11955 		}
11956 	}
11957 
11958 skip_modeset:
11959 	/* Release extra reference */
11960 	if (new_stream)
11961 		dc_stream_release(new_stream);
11962 
11963 	/*
11964 	 * We want to do dc stream updates that do not require a
11965 	 * full modeset below.
11966 	 */
11967 	if (!(enable && connector && new_crtc_state->active))
11968 		return 0;
11969 	/*
11970 	 * Given above conditions, the dc state cannot be NULL because:
11971 	 * 1. We're in the process of enabling CRTCs (just been added
11972 	 *    to the dc context, or already is on the context)
11973 	 * 2. Has a valid connector attached, and
11974 	 * 3. Is currently active and enabled.
11975 	 * => The dc stream state currently exists.
11976 	 */
11977 	BUG_ON(dm_new_crtc_state->stream == NULL);
11978 
11979 	/* Scaling or underscan settings */
11980 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
11981 				drm_atomic_crtc_needs_modeset(new_crtc_state))
11982 		update_stream_scaling_settings(adev_to_drm(adev),
11983 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
11984 
11985 	/* ABM settings */
11986 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11987 
11988 	/*
11989 	 * Color management settings. We also update color properties
11990 	 * when a modeset is needed, to ensure it gets reprogrammed.
11991 	 */
11992 	if (dm_new_crtc_state->base.color_mgmt_changed ||
11993 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11994 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
11995 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
11996 		if (ret)
11997 			goto fail;
11998 	}
11999 
12000 	/* Update Freesync settings. */
12001 	get_freesync_config_for_crtc(dm_new_crtc_state,
12002 				     dm_new_conn_state);
12003 
12004 	return ret;
12005 
12006 fail:
12007 	if (new_stream)
12008 		dc_stream_release(new_stream);
12009 	return ret;
12010 }
12011 
12012 static bool should_reset_plane(struct drm_atomic_commit *state,
12013 			       struct drm_plane *plane,
12014 			       struct drm_plane_state *old_plane_state,
12015 			       struct drm_plane_state *new_plane_state)
12016 {
12017 	struct drm_plane *other;
12018 	struct drm_plane_state *old_other_state, *new_other_state;
12019 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12020 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
12021 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
12022 	struct drm_connector_state *new_con_state;
12023 	struct drm_connector *connector;
12024 	int i;
12025 
12026 	/*
12027 	 * TODO: Remove this hack for all asics once it proves that the
12028 	 * fast updates works fine on DCN3.2+.
12029 	 */
12030 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
12031 	    state->allow_modeset)
12032 		return true;
12033 
12034 	/* Check for writeback commit */
12035 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
12036 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
12037 			continue;
12038 
12039 		if (new_con_state->writeback_job)
12040 			return true;
12041 	}
12042 
12043 	if (amdgpu_in_reset(adev) && state->allow_modeset)
12044 		return true;
12045 
12046 	/* Exit early if we know that we're adding or removing the plane. */
12047 	if (old_plane_state->crtc != new_plane_state->crtc)
12048 		return true;
12049 
12050 	/* old crtc == new_crtc == NULL, plane not in context. */
12051 	if (!new_plane_state->crtc)
12052 		return false;
12053 
12054 	new_crtc_state =
12055 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
12056 	old_crtc_state =
12057 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
12058 
12059 	if (!new_crtc_state)
12060 		return true;
12061 
12062 	/*
12063 	 * A change in cursor mode means a new dc pipe needs to be acquired or
12064 	 * released from the state
12065 	 */
12066 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
12067 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
12068 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
12069 	    old_dm_crtc_state != NULL &&
12070 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
12071 		return true;
12072 	}
12073 
12074 	/* CRTC Degamma changes currently require us to recreate planes. */
12075 	if (new_crtc_state->color_mgmt_changed)
12076 		return true;
12077 
12078 	/*
12079 	 * On zpos change, planes need to be reordered by removing and re-adding
12080 	 * them one by one to the dc state, in order of descending zpos.
12081 	 *
12082 	 * TODO: We can likely skip bandwidth validation if the only thing that
12083 	 * changed about the plane was it'z z-ordering.
12084 	 */
12085 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
12086 		return true;
12087 
12088 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
12089 		return true;
12090 
12091 	/*
12092 	 * If there are any new primary or overlay planes being added or
12093 	 * removed then the z-order can potentially change. To ensure
12094 	 * correct z-order and pipe acquisition the current DC architecture
12095 	 * requires us to remove and recreate all existing planes.
12096 	 *
12097 	 * TODO: Come up with a more elegant solution for this.
12098 	 */
12099 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
12100 		struct amdgpu_framebuffer *old_afb, *new_afb;
12101 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
12102 
12103 		dm_new_other_state = to_dm_plane_state(new_other_state);
12104 		dm_old_other_state = to_dm_plane_state(old_other_state);
12105 
12106 		if (other->type == DRM_PLANE_TYPE_CURSOR)
12107 			continue;
12108 
12109 		if (old_other_state->crtc != new_plane_state->crtc &&
12110 		    new_other_state->crtc != new_plane_state->crtc)
12111 			continue;
12112 
12113 		if (old_other_state->crtc != new_other_state->crtc)
12114 			return true;
12115 
12116 		/* Src/dst size and scaling updates. */
12117 		if (old_other_state->src_w != new_other_state->src_w ||
12118 		    old_other_state->src_h != new_other_state->src_h ||
12119 		    old_other_state->crtc_w != new_other_state->crtc_w ||
12120 		    old_other_state->crtc_h != new_other_state->crtc_h)
12121 			return true;
12122 
12123 		/* Rotation / mirroring updates. */
12124 		if (old_other_state->rotation != new_other_state->rotation)
12125 			return true;
12126 
12127 		/* Blending updates. */
12128 		if (old_other_state->pixel_blend_mode !=
12129 		    new_other_state->pixel_blend_mode)
12130 			return true;
12131 
12132 		/* Alpha updates. */
12133 		if (old_other_state->alpha != new_other_state->alpha)
12134 			return true;
12135 
12136 		/* Colorspace changes. */
12137 		if (old_other_state->color_range != new_other_state->color_range ||
12138 		    old_other_state->color_encoding != new_other_state->color_encoding)
12139 			return true;
12140 
12141 		/* HDR/Transfer Function changes. */
12142 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
12143 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
12144 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
12145 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
12146 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
12147 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
12148 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
12149 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
12150 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
12151 			return true;
12152 
12153 		/* Framebuffer checks fall at the end. */
12154 		if (!old_other_state->fb || !new_other_state->fb)
12155 			continue;
12156 
12157 		/* Pixel format changes can require bandwidth updates. */
12158 		if (old_other_state->fb->format != new_other_state->fb->format)
12159 			return true;
12160 
12161 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
12162 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
12163 
12164 		/* Tiling and DCC changes also require bandwidth updates. */
12165 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
12166 		    old_afb->base.modifier != new_afb->base.modifier)
12167 			return true;
12168 	}
12169 
12170 	return false;
12171 }
12172 
12173 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
12174 			      struct drm_plane_state *new_plane_state,
12175 			      struct drm_framebuffer *fb)
12176 {
12177 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
12178 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
12179 	unsigned int pitch;
12180 	bool linear;
12181 
12182 	if (fb->width > new_acrtc->max_cursor_width ||
12183 	    fb->height > new_acrtc->max_cursor_height) {
12184 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB size %dx%d\n",
12185 				 new_plane_state->fb->width,
12186 				 new_plane_state->fb->height);
12187 		return -EINVAL;
12188 	}
12189 	if (new_plane_state->src_w != fb->width << 16 ||
12190 	    new_plane_state->src_h != fb->height << 16) {
12191 		drm_dbg_atomic(adev_to_drm(adev), "Cropping not supported for cursor plane\n");
12192 		return -EINVAL;
12193 	}
12194 
12195 	/* Pitch in pixels */
12196 	pitch = fb->pitches[0] / fb->format->cpp[0];
12197 
12198 	if (fb->width != pitch) {
12199 		drm_dbg_atomic(adev_to_drm(adev), "Cursor FB width %d doesn't match pitch %d",
12200 				 fb->width, pitch);
12201 		return -EINVAL;
12202 	}
12203 
12204 	switch (pitch) {
12205 	case 64:
12206 	case 128:
12207 	case 256:
12208 		/* FB pitch is supported by cursor plane */
12209 		break;
12210 	default:
12211 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB pitch %d px\n", pitch);
12212 		return -EINVAL;
12213 	}
12214 
12215 	/* Core DRM takes care of checking FB modifiers, so we only need to
12216 	 * check tiling flags when the FB doesn't have a modifier.
12217 	 */
12218 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
12219 		if (adev->family == AMDGPU_FAMILY_GC_12_0_0) {
12220 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
12221 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
12222 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
12223 		} else {
12224 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
12225 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
12226 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
12227 		}
12228 		if (!linear) {
12229 			drm_dbg_atomic(adev_to_drm(adev), "Cursor FB not linear");
12230 			return -EINVAL;
12231 		}
12232 	}
12233 
12234 	return 0;
12235 }
12236 
12237 /*
12238  * Helper function for checking the cursor in native mode
12239  */
12240 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
12241 					struct drm_plane *plane,
12242 					struct drm_plane_state *new_plane_state,
12243 					bool enable)
12244 {
12245 
12246 	struct amdgpu_crtc *new_acrtc;
12247 	int ret;
12248 
12249 	if (!enable || !new_plane_crtc ||
12250 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
12251 		return 0;
12252 
12253 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
12254 
12255 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
12256 		drm_dbg_atomic(new_plane_crtc->dev, "Cropping not supported for cursor plane\n");
12257 		return -EINVAL;
12258 	}
12259 
12260 	if (new_plane_state->fb) {
12261 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
12262 						new_plane_state->fb);
12263 		if (ret)
12264 			return ret;
12265 	}
12266 
12267 	return 0;
12268 }
12269 
12270 static bool dm_should_update_native_cursor(struct drm_atomic_commit *state,
12271 					   struct drm_crtc *old_plane_crtc,
12272 					   struct drm_crtc *new_plane_crtc,
12273 					   bool enable)
12274 {
12275 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12276 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12277 
12278 	if (!enable) {
12279 		if (old_plane_crtc == NULL)
12280 			return true;
12281 
12282 		old_crtc_state = drm_atomic_get_old_crtc_state(
12283 			state, old_plane_crtc);
12284 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12285 
12286 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12287 	} else {
12288 		if (new_plane_crtc == NULL)
12289 			return true;
12290 
12291 		new_crtc_state = drm_atomic_get_new_crtc_state(
12292 			state, new_plane_crtc);
12293 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12294 
12295 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12296 	}
12297 }
12298 
12299 static int dm_update_plane_state(struct dc *dc,
12300 				 struct drm_atomic_commit *state,
12301 				 struct drm_plane *plane,
12302 				 struct drm_plane_state *old_plane_state,
12303 				 struct drm_plane_state *new_plane_state,
12304 				 bool enable,
12305 				 bool *lock_and_validation_needed,
12306 				 bool *is_top_most_overlay)
12307 {
12308 
12309 	struct dm_atomic_state *dm_state = NULL;
12310 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
12311 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12312 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
12313 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
12314 	bool needs_reset, update_native_cursor;
12315 	int ret = 0;
12316 
12317 
12318 	new_plane_crtc = new_plane_state->crtc;
12319 	old_plane_crtc = old_plane_state->crtc;
12320 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
12321 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
12322 
12323 	update_native_cursor = dm_should_update_native_cursor(state,
12324 							      old_plane_crtc,
12325 							      new_plane_crtc,
12326 							      enable);
12327 
12328 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
12329 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12330 						    new_plane_state, enable);
12331 		if (ret)
12332 			return ret;
12333 
12334 		return 0;
12335 	}
12336 
12337 	needs_reset = should_reset_plane(state, plane, old_plane_state,
12338 					 new_plane_state);
12339 
12340 	/* Remove any changed/removed planes */
12341 	if (!enable) {
12342 		if (!needs_reset)
12343 			return 0;
12344 
12345 		if (!old_plane_crtc)
12346 			return 0;
12347 
12348 		old_crtc_state = drm_atomic_get_old_crtc_state(
12349 				state, old_plane_crtc);
12350 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12351 
12352 		if (!dm_old_crtc_state->stream)
12353 			return 0;
12354 
12355 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
12356 				plane->base.id, old_plane_crtc->base.id);
12357 
12358 		ret = dm_atomic_get_state(state, &dm_state);
12359 		if (ret)
12360 			return ret;
12361 
12362 		if (!dc_state_remove_plane(
12363 				dc,
12364 				dm_old_crtc_state->stream,
12365 				dm_old_plane_state->dc_state,
12366 				dm_state->context)) {
12367 
12368 			return -EINVAL;
12369 		}
12370 
12371 		if (dm_old_plane_state->dc_state)
12372 			dc_plane_state_release(dm_old_plane_state->dc_state);
12373 
12374 		dm_new_plane_state->dc_state = NULL;
12375 
12376 		*lock_and_validation_needed = true;
12377 
12378 	} else { /* Add new planes */
12379 		struct dc_plane_state *dc_new_plane_state;
12380 
12381 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
12382 			return 0;
12383 
12384 		if (!new_plane_crtc)
12385 			return 0;
12386 
12387 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
12388 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12389 
12390 		if (!dm_new_crtc_state->stream)
12391 			return 0;
12392 
12393 		if (!needs_reset)
12394 			return 0;
12395 
12396 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
12397 		if (ret)
12398 			goto out;
12399 
12400 		WARN_ON(dm_new_plane_state->dc_state);
12401 
12402 		dc_new_plane_state = dc_create_plane_state(dc);
12403 		if (!dc_new_plane_state) {
12404 			ret = -ENOMEM;
12405 			goto out;
12406 		}
12407 
12408 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
12409 				 plane->base.id, new_plane_crtc->base.id);
12410 
12411 		ret = fill_dc_plane_attributes(
12412 			drm_to_adev(new_plane_crtc->dev),
12413 			dc_new_plane_state,
12414 			new_plane_state,
12415 			new_crtc_state);
12416 		if (ret) {
12417 			dc_plane_state_release(dc_new_plane_state);
12418 			goto out;
12419 		}
12420 
12421 		ret = dm_atomic_get_state(state, &dm_state);
12422 		if (ret) {
12423 			dc_plane_state_release(dc_new_plane_state);
12424 			goto out;
12425 		}
12426 
12427 		/*
12428 		 * Any atomic check errors that occur after this will
12429 		 * not need a release. The plane state will be attached
12430 		 * to the stream, and therefore part of the atomic
12431 		 * state. It'll be released when the atomic state is
12432 		 * cleaned.
12433 		 */
12434 		if (!dc_state_add_plane(
12435 				dc,
12436 				dm_new_crtc_state->stream,
12437 				dc_new_plane_state,
12438 				dm_state->context)) {
12439 
12440 			dc_plane_state_release(dc_new_plane_state);
12441 			ret = -EINVAL;
12442 			goto out;
12443 		}
12444 
12445 		dm_new_plane_state->dc_state = dc_new_plane_state;
12446 
12447 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
12448 
12449 		/* Tell DC to do a full surface update every time there
12450 		 * is a plane change. Inefficient, but works for now.
12451 		 */
12452 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
12453 
12454 		*lock_and_validation_needed = true;
12455 	}
12456 
12457 out:
12458 	/* If enabling cursor overlay failed, attempt fallback to native mode */
12459 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
12460 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12461 						    new_plane_state, enable);
12462 		if (ret)
12463 			return ret;
12464 
12465 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
12466 	}
12467 
12468 	return ret;
12469 }
12470 
12471 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
12472 				       int *src_w, int *src_h)
12473 {
12474 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
12475 	case DRM_MODE_ROTATE_90:
12476 	case DRM_MODE_ROTATE_270:
12477 		*src_w = plane_state->src_h >> 16;
12478 		*src_h = plane_state->src_w >> 16;
12479 		break;
12480 	case DRM_MODE_ROTATE_0:
12481 	case DRM_MODE_ROTATE_180:
12482 	default:
12483 		*src_w = plane_state->src_w >> 16;
12484 		*src_h = plane_state->src_h >> 16;
12485 		break;
12486 	}
12487 }
12488 
12489 static void
12490 dm_get_plane_scale(struct drm_plane_state *plane_state,
12491 		   int *out_plane_scale_w, int *out_plane_scale_h)
12492 {
12493 	int plane_src_w, plane_src_h;
12494 
12495 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
12496 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
12497 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
12498 }
12499 
12500 /*
12501  * The normalized_zpos value cannot be used by this iterator directly. It's only
12502  * calculated for enabled planes, potentially causing normalized_zpos collisions
12503  * between enabled/disabled planes in the atomic state. We need a unique value
12504  * so that the iterator will not generate the same object twice, or loop
12505  * indefinitely.
12506  */
12507 static inline struct __drm_planes_state *__get_next_zpos(
12508 	struct drm_atomic_commit *state,
12509 	struct __drm_planes_state *prev)
12510 {
12511 	unsigned int highest_zpos = 0, prev_zpos = 256;
12512 	uint32_t highest_id = 0, prev_id = UINT_MAX;
12513 	struct drm_plane_state *new_plane_state;
12514 	struct drm_plane *plane;
12515 	int i, highest_i = -1;
12516 
12517 	if (prev != NULL) {
12518 		prev_zpos = prev->new_state->zpos;
12519 		prev_id = prev->ptr->base.id;
12520 	}
12521 
12522 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
12523 		/* Skip planes with higher zpos than the previously returned */
12524 		if (new_plane_state->zpos > prev_zpos ||
12525 		    (new_plane_state->zpos == prev_zpos &&
12526 		     plane->base.id >= prev_id))
12527 			continue;
12528 
12529 		/* Save the index of the plane with highest zpos */
12530 		if (new_plane_state->zpos > highest_zpos ||
12531 		    (new_plane_state->zpos == highest_zpos &&
12532 		     plane->base.id > highest_id)) {
12533 			highest_zpos = new_plane_state->zpos;
12534 			highest_id = plane->base.id;
12535 			highest_i = i;
12536 		}
12537 	}
12538 
12539 	if (highest_i < 0)
12540 		return NULL;
12541 
12542 	return &state->planes[highest_i];
12543 }
12544 
12545 /*
12546  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
12547  * by descending zpos, as read from the new plane state. This is the same
12548  * ordering as defined by drm_atomic_normalize_zpos().
12549  */
12550 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
12551 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
12552 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
12553 		for_each_if(((plane) = __i->ptr,				\
12554 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
12555 			     (old_plane_state) = __i->old_state,		\
12556 			     (new_plane_state) = __i->new_state, 1))
12557 
12558 static int add_affected_mst_dsc_crtcs(struct drm_atomic_commit *state, struct drm_crtc *crtc)
12559 {
12560 	struct drm_connector *connector;
12561 	struct drm_connector_state *conn_state, *old_conn_state;
12562 	struct amdgpu_dm_connector *aconnector = NULL;
12563 	int i;
12564 
12565 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
12566 		if (!conn_state->crtc)
12567 			conn_state = old_conn_state;
12568 
12569 		if (conn_state->crtc != crtc)
12570 			continue;
12571 
12572 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
12573 			continue;
12574 
12575 		aconnector = to_amdgpu_dm_connector(connector);
12576 		if (!aconnector->mst_output_port || !aconnector->mst_root)
12577 			aconnector = NULL;
12578 		else
12579 			break;
12580 	}
12581 
12582 	if (!aconnector)
12583 		return 0;
12584 
12585 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
12586 }
12587 
12588 /**
12589  * DOC: Cursor Modes - Native vs Overlay
12590  *
12591  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
12592  * plane. It does not require a dedicated hw plane to enable, but it is
12593  * subjected to the same z-order and scaling as the hw plane. It also has format
12594  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
12595  * hw plane.
12596  *
12597  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
12598  * own scaling and z-pos. It also has no blending restrictions. It lends to a
12599  * cursor behavior more akin to a DRM client's expectations. However, it does
12600  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
12601  * available.
12602  */
12603 
12604 /**
12605  * dm_plane_color_pipeline_active() - Check if a plane's color pipeline active.
12606  * @state: DRM atomic state
12607  * @plane: DRM plane to check
12608  * @use_old: if true, inspect the old colorop states; otherwise the new ones
12609  *
12610  * A color pipeline may be selected (color_pipeline != NULL) but still is
12611  * inactive if every colorop in the chain is bypassed.  Only return
12612  * true when at least one colorop has bypass == false, meaning the cursor
12613  * would be subjected to the transformation in native mode.
12614  *
12615  * Return: true if the pipeline modifies pixels, false otherwise.
12616  */
12617 static bool dm_plane_color_pipeline_active(struct drm_atomic_commit *state,
12618 					   struct drm_plane *plane,
12619 					   bool use_old)
12620 {
12621 	struct drm_colorop *colorop;
12622 	struct drm_colorop_state *old_colorop_state, *new_colorop_state;
12623 	int i;
12624 
12625 	for_each_oldnew_colorop_in_state(state, colorop, old_colorop_state, new_colorop_state, i) {
12626 		struct drm_colorop_state *cstate = use_old ? old_colorop_state : new_colorop_state;
12627 
12628 		if (cstate->colorop->plane != plane)
12629 			continue;
12630 		if (!cstate->bypass)
12631 			return true;
12632 	}
12633 	return false;
12634 }
12635 
12636 /**
12637  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
12638  * @adev: amdgpu device
12639  * @state: DRM atomic state
12640  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
12641  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
12642  *
12643  * Get whether the cursor should be enabled in native mode, or overlay mode, on
12644  * the dm_crtc_state.
12645  *
12646  * The cursor should be enabled in overlay mode if there exists an underlying
12647  * plane - on which the cursor may be blended - that is either YUV formatted,
12648  * scaled differently from the cursor, or has a color pipeline active.
12649  *
12650  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
12651  * calling this function.
12652  *
12653  * Return: 0 on success, or an error code if getting the cursor plane state
12654  * failed.
12655  */
12656 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
12657 				   struct drm_atomic_commit *state,
12658 				   struct dm_crtc_state *dm_crtc_state,
12659 				   enum amdgpu_dm_cursor_mode *cursor_mode)
12660 {
12661 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
12662 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
12663 	struct drm_plane *plane;
12664 	bool consider_mode_change = false;
12665 	bool entire_crtc_covered = false;
12666 	bool cursor_changed = false;
12667 	int underlying_scale_w, underlying_scale_h;
12668 	int cursor_scale_w, cursor_scale_h;
12669 	int i;
12670 
12671 	/* Overlay cursor not supported on HW before DCN
12672 	 * DCN401/420 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
12673 	 * as previous DCN generations, so enable native mode on DCN401/420
12674 	 */
12675 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1) ||
12676 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
12677 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 1)) {
12678 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12679 		return 0;
12680 	}
12681 
12682 	/* Init cursor_mode to be the same as current */
12683 	*cursor_mode = dm_crtc_state->cursor_mode;
12684 
12685 	/*
12686 	 * Cursor mode can change if a plane's format changes, scale changes, is
12687 	 * enabled/disabled, z-order changes, or color management properties change.
12688 	 */
12689 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
12690 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
12691 
12692 		/* Only care about planes on this CRTC */
12693 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
12694 			continue;
12695 
12696 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
12697 			cursor_changed = true;
12698 
12699 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
12700 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
12701 		    old_plane_state->fb->format != plane_state->fb->format) {
12702 			consider_mode_change = true;
12703 			break;
12704 		}
12705 
12706 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
12707 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
12708 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
12709 			consider_mode_change = true;
12710 			break;
12711 		}
12712 
12713 		if (dm_plane_color_pipeline_active(state, plane, true) !=
12714 		    dm_plane_color_pipeline_active(state, plane, false)) {
12715 			consider_mode_change = true;
12716 			break;
12717 		}
12718 	}
12719 
12720 	if (!consider_mode_change && !crtc_state->zpos_changed)
12721 		return 0;
12722 
12723 	/*
12724 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
12725 	 * no need to set cursor mode. This avoids needlessly locking the cursor
12726 	 * state.
12727 	 */
12728 	if (!cursor_changed &&
12729 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
12730 		return 0;
12731 	}
12732 
12733 	cursor_state = drm_atomic_get_plane_state(state,
12734 						  crtc_state->crtc->cursor);
12735 	if (IS_ERR(cursor_state))
12736 		return PTR_ERR(cursor_state);
12737 
12738 	/* Cursor is disabled */
12739 	if (!cursor_state->fb)
12740 		return 0;
12741 
12742 	/* For all planes in descending z-order (all of which are below cursor
12743 	 * as per zpos definitions), check their scaling and format
12744 	 */
12745 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
12746 
12747 		/* Only care about non-cursor planes on this CRTC */
12748 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
12749 		    plane->type == DRM_PLANE_TYPE_CURSOR)
12750 			continue;
12751 
12752 		/* Underlying plane is YUV format - use overlay cursor */
12753 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
12754 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12755 			return 0;
12756 		}
12757 
12758 		/* Underlying plane has an active color pipeline - cursor would be transformed */
12759 		if (dm_plane_color_pipeline_active(state, plane, false)) {
12760 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12761 			return 0;
12762 		}
12763 
12764 		dm_get_plane_scale(plane_state,
12765 				   &underlying_scale_w, &underlying_scale_h);
12766 		dm_get_plane_scale(cursor_state,
12767 				   &cursor_scale_w, &cursor_scale_h);
12768 
12769 		/* Underlying plane has different scale - use overlay cursor */
12770 		if (cursor_scale_w != underlying_scale_w &&
12771 		    cursor_scale_h != underlying_scale_h) {
12772 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12773 			return 0;
12774 		}
12775 
12776 		/* If this plane covers the whole CRTC, no need to check planes underneath */
12777 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
12778 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
12779 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
12780 			entire_crtc_covered = true;
12781 			break;
12782 		}
12783 	}
12784 
12785 	/* If planes do not cover the entire CRTC, use overlay mode to enable
12786 	 * cursor over holes
12787 	 */
12788 	if (entire_crtc_covered)
12789 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12790 	else
12791 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12792 
12793 	return 0;
12794 }
12795 
12796 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
12797 					    struct drm_atomic_commit *state,
12798 					    struct drm_crtc_state *crtc_state)
12799 {
12800 	struct drm_plane *plane;
12801 	struct drm_plane_state *new_plane_state, *old_plane_state;
12802 
12803 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
12804 		new_plane_state = drm_atomic_get_plane_state(state, plane);
12805 		old_plane_state = drm_atomic_get_plane_state(state, plane);
12806 
12807 		if (IS_ERR(new_plane_state) || IS_ERR(old_plane_state)) {
12808 			drm_err(dev, "Failed to get plane state for plane %s\n", plane->name);
12809 			return false;
12810 		}
12811 
12812 		if (old_plane_state->fb && new_plane_state->fb &&
12813 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
12814 			return true;
12815 	}
12816 
12817 	return false;
12818 }
12819 
12820 /**
12821  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
12822  *
12823  * @dev: The DRM device
12824  * @state: The atomic state to commit
12825  *
12826  * Validate that the given atomic state is programmable by DC into hardware.
12827  * This involves constructing a &struct dc_state reflecting the new hardware
12828  * state we wish to commit, then querying DC to see if it is programmable. It's
12829  * important not to modify the existing DC state. Otherwise, atomic_check
12830  * may unexpectedly commit hardware changes.
12831  *
12832  * When validating the DC state, it's important that the right locks are
12833  * acquired. For full updates case which removes/adds/updates streams on one
12834  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
12835  * that any such full update commit will wait for completion of any outstanding
12836  * flip using DRMs synchronization events.
12837  *
12838  * Note that DM adds the affected connectors for all CRTCs in state, when that
12839  * might not seem necessary. This is because DC stream creation requires the
12840  * DC sink, which is tied to the DRM connector state. Cleaning this up should
12841  * be possible but non-trivial - a possible TODO item.
12842  *
12843  * Return: -Error code if validation failed.
12844  */
12845 static int amdgpu_dm_atomic_check(struct drm_device *dev,
12846 				  struct drm_atomic_commit *state)
12847 {
12848 	struct amdgpu_device *adev = drm_to_adev(dev);
12849 	struct dm_atomic_state *dm_state = NULL;
12850 	struct dc *dc = adev->dm.dc;
12851 	struct drm_connector *connector;
12852 	struct drm_connector_state *old_con_state, *new_con_state;
12853 	struct drm_crtc *crtc;
12854 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12855 	struct drm_plane *plane;
12856 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
12857 	enum dc_status status;
12858 	int ret, i;
12859 	bool lock_and_validation_needed = false;
12860 	bool is_top_most_overlay = true;
12861 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12862 	struct drm_dp_mst_topology_mgr *mgr;
12863 	struct drm_dp_mst_topology_state *mst_state;
12864 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
12865 
12866 	trace_amdgpu_dm_atomic_check_begin(state);
12867 
12868 	ret = drm_atomic_helper_check_modeset(dev, state);
12869 	if (ret) {
12870 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
12871 		goto fail;
12872 	}
12873 
12874 	/* Check connector changes */
12875 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
12876 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
12877 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
12878 
12879 		/* Skip connectors that are disabled or part of modeset already. */
12880 		if (!new_con_state->crtc)
12881 			continue;
12882 
12883 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
12884 		if (IS_ERR(new_crtc_state)) {
12885 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
12886 			ret = PTR_ERR(new_crtc_state);
12887 			goto fail;
12888 		}
12889 
12890 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
12891 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
12892 			new_crtc_state->connectors_changed = true;
12893 	}
12894 
12895 	if (dc_resource_is_dsc_encoding_supported(dc)) {
12896 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12897 			dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12898 			dm_new_crtc_state->mode_changed_independent_from_dsc = new_crtc_state->mode_changed;
12899 		}
12900 
12901 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12902 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
12903 				ret = add_affected_mst_dsc_crtcs(state, crtc);
12904 				if (ret) {
12905 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
12906 					goto fail;
12907 				}
12908 			}
12909 		}
12910 	}
12911 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12912 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12913 
12914 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
12915 		    !new_crtc_state->color_mgmt_changed &&
12916 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
12917 			dm_old_crtc_state->dsc_force_changed == false)
12918 			continue;
12919 
12920 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
12921 		if (ret) {
12922 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
12923 			goto fail;
12924 		}
12925 
12926 		if (!new_crtc_state->enable)
12927 			continue;
12928 
12929 		ret = drm_atomic_add_affected_connectors(state, crtc);
12930 		if (ret) {
12931 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
12932 			goto fail;
12933 		}
12934 
12935 		ret = drm_atomic_add_affected_planes(state, crtc);
12936 		if (ret) {
12937 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
12938 			goto fail;
12939 		}
12940 
12941 		if (dm_old_crtc_state->dsc_force_changed)
12942 			new_crtc_state->mode_changed = true;
12943 	}
12944 
12945 	/*
12946 	 * Add all primary and overlay planes on the CRTC to the state
12947 	 * whenever a plane is enabled to maintain correct z-ordering
12948 	 * and to enable fast surface updates.
12949 	 */
12950 	drm_for_each_crtc(crtc, dev) {
12951 		bool modified = false;
12952 
12953 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
12954 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12955 				continue;
12956 
12957 			if (new_plane_state->crtc == crtc ||
12958 			    old_plane_state->crtc == crtc) {
12959 				modified = true;
12960 				break;
12961 			}
12962 		}
12963 
12964 		if (!modified)
12965 			continue;
12966 
12967 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
12968 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12969 				continue;
12970 
12971 			new_plane_state =
12972 				drm_atomic_get_plane_state(state, plane);
12973 
12974 			if (IS_ERR(new_plane_state)) {
12975 				ret = PTR_ERR(new_plane_state);
12976 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
12977 				goto fail;
12978 			}
12979 		}
12980 	}
12981 
12982 	/*
12983 	 * DC consults the zpos (layer_index in DC terminology) to determine the
12984 	 * hw plane on which to enable the hw cursor (see
12985 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
12986 	 * atomic state, so call drm helper to normalize zpos.
12987 	 */
12988 	ret = drm_atomic_normalize_zpos(dev, state);
12989 	if (ret) {
12990 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
12991 		goto fail;
12992 	}
12993 
12994 	/*
12995 	 * Determine whether cursors on each CRTC should be enabled in native or
12996 	 * overlay mode.
12997 	 */
12998 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12999 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13000 
13001 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
13002 					      &dm_new_crtc_state->cursor_mode);
13003 		if (ret) {
13004 			drm_dbg(dev, "Failed to determine cursor mode\n");
13005 			goto fail;
13006 		}
13007 
13008 		/*
13009 		 * If overlay cursor is needed, DC cannot go through the
13010 		 * native cursor update path. All enabled planes on the CRTC
13011 		 * need to be added for DC to not disable a plane by mistake
13012 		 */
13013 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
13014 			if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
13015 				drm_dbg(dev, "Overlay cursor not supported on DCE\n");
13016 				ret = -EINVAL;
13017 				goto fail;
13018 			}
13019 
13020 			ret = drm_atomic_add_affected_planes(state, crtc);
13021 			if (ret)
13022 				goto fail;
13023 		}
13024 	}
13025 
13026 	/* Remove exiting planes if they are modified */
13027 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13028 
13029 		ret = dm_update_plane_state(dc, state, plane,
13030 					    old_plane_state,
13031 					    new_plane_state,
13032 					    false,
13033 					    &lock_and_validation_needed,
13034 					    &is_top_most_overlay);
13035 		if (ret) {
13036 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13037 			goto fail;
13038 		}
13039 	}
13040 
13041 	/* Disable all crtcs which require disable */
13042 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13043 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
13044 					   old_crtc_state,
13045 					   new_crtc_state,
13046 					   false,
13047 					   &lock_and_validation_needed);
13048 		if (ret) {
13049 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
13050 			goto fail;
13051 		}
13052 	}
13053 
13054 	/* Enable all crtcs which require enable */
13055 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
13056 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
13057 					   old_crtc_state,
13058 					   new_crtc_state,
13059 					   true,
13060 					   &lock_and_validation_needed);
13061 		if (ret) {
13062 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
13063 			goto fail;
13064 		}
13065 	}
13066 
13067 	/* Add new/modified planes */
13068 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
13069 		ret = dm_update_plane_state(dc, state, plane,
13070 					    old_plane_state,
13071 					    new_plane_state,
13072 					    true,
13073 					    &lock_and_validation_needed,
13074 					    &is_top_most_overlay);
13075 		if (ret) {
13076 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
13077 			goto fail;
13078 		}
13079 	}
13080 
13081 #if defined(CONFIG_DRM_AMD_DC_FP)
13082 	if (dc_resource_is_dsc_encoding_supported(dc)) {
13083 		ret = pre_validate_dsc(state, &dm_state, vars);
13084 		if (ret != 0)
13085 			goto fail;
13086 	}
13087 #endif
13088 
13089 	/* Run this here since we want to validate the streams we created */
13090 	ret = drm_atomic_helper_check_planes(dev, state);
13091 	if (ret) {
13092 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
13093 		goto fail;
13094 	}
13095 
13096 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13097 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13098 		if (dm_new_crtc_state->mpo_requested)
13099 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
13100 	}
13101 
13102 	/* Check cursor restrictions */
13103 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13104 		enum amdgpu_dm_cursor_mode required_cursor_mode;
13105 		int is_rotated, is_scaled;
13106 
13107 		/* Overlay cusor not subject to native cursor restrictions */
13108 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
13109 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
13110 			continue;
13111 
13112 		/* Check if rotation or scaling is enabled on DCN401 */
13113 		if ((drm_plane_mask(crtc->cursor) &
13114 		     new_crtc_state->plane_mask) &&
13115 		    (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 1) ||
13116 		     amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
13117 		     amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1))) {
13118 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
13119 
13120 			is_rotated = new_cursor_state &&
13121 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
13122 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
13123 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
13124 
13125 			if (is_rotated || is_scaled) {
13126 				drm_dbg_driver(
13127 					crtc->dev,
13128 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
13129 					crtc->base.id, crtc->name);
13130 				ret = -EINVAL;
13131 				goto fail;
13132 			}
13133 		}
13134 
13135 		/* If HW can only do native cursor, check restrictions again */
13136 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
13137 					      &required_cursor_mode);
13138 		if (ret) {
13139 			drm_dbg_driver(crtc->dev,
13140 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
13141 				       crtc->base.id, crtc->name);
13142 			goto fail;
13143 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
13144 			drm_dbg_driver(crtc->dev,
13145 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling, YUV, or color pipeline restrictions\n",
13146 				       crtc->base.id, crtc->name);
13147 			ret = -EINVAL;
13148 			goto fail;
13149 		}
13150 	}
13151 
13152 	if (state->legacy_cursor_update) {
13153 		/*
13154 		 * This is a fast cursor update coming from the plane update
13155 		 * helper, check if it can be done asynchronously for better
13156 		 * performance.
13157 		 */
13158 		state->async_update =
13159 			!drm_atomic_helper_async_check(dev, state);
13160 
13161 		/*
13162 		 * Skip the remaining global validation if this is an async
13163 		 * update. Cursor updates can be done without affecting
13164 		 * state or bandwidth calcs and this avoids the performance
13165 		 * penalty of locking the private state object and
13166 		 * allocating a new dc_state.
13167 		 */
13168 		if (state->async_update)
13169 			return 0;
13170 	}
13171 
13172 	/* Check scaling and underscan changes*/
13173 	/* TODO Removed scaling changes validation due to inability to commit
13174 	 * new stream into context w\o causing full reset. Need to
13175 	 * decide how to handle.
13176 	 */
13177 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
13178 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
13179 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
13180 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
13181 
13182 		/* Skip any modesets/resets */
13183 		if (!acrtc || drm_atomic_crtc_needs_modeset(
13184 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
13185 			continue;
13186 
13187 		/* Skip any thing not scale or underscan changes */
13188 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
13189 			continue;
13190 
13191 		lock_and_validation_needed = true;
13192 	}
13193 
13194 	/* set the slot info for each mst_state based on the link encoding format */
13195 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
13196 		struct amdgpu_dm_connector *aconnector;
13197 		struct drm_connector *connector;
13198 		struct drm_connector_list_iter iter;
13199 		u8 link_coding_cap;
13200 
13201 		drm_connector_list_iter_begin(dev, &iter);
13202 		drm_for_each_connector_iter(connector, &iter) {
13203 			if (connector->index == mst_state->mgr->conn_base_id) {
13204 				aconnector = to_amdgpu_dm_connector(connector);
13205 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
13206 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
13207 
13208 				break;
13209 			}
13210 		}
13211 		drm_connector_list_iter_end(&iter);
13212 	}
13213 
13214 	/**
13215 	 * Streams and planes are reset when there are changes that affect
13216 	 * bandwidth. Anything that affects bandwidth needs to go through
13217 	 * DC global validation to ensure that the configuration can be applied
13218 	 * to hardware.
13219 	 *
13220 	 * We have to currently stall out here in atomic_check for outstanding
13221 	 * commits to finish in this case because our IRQ handlers reference
13222 	 * DRM state directly - we can end up disabling interrupts too early
13223 	 * if we don't.
13224 	 *
13225 	 * TODO: Remove this stall and drop DM state private objects.
13226 	 */
13227 	if (lock_and_validation_needed) {
13228 		ret = dm_atomic_get_state(state, &dm_state);
13229 		if (ret) {
13230 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
13231 			goto fail;
13232 		}
13233 
13234 		ret = do_aquire_global_lock(dev, state);
13235 		if (ret) {
13236 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
13237 			goto fail;
13238 		}
13239 
13240 #if defined(CONFIG_DRM_AMD_DC_FP)
13241 		if (dc_resource_is_dsc_encoding_supported(dc)) {
13242 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
13243 			if (ret) {
13244 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
13245 				ret = -EINVAL;
13246 				goto fail;
13247 			}
13248 		}
13249 #endif
13250 
13251 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
13252 		if (ret) {
13253 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
13254 			goto fail;
13255 		}
13256 
13257 		/*
13258 		 * Perform validation of MST topology in the state:
13259 		 * We need to perform MST atomic check before calling
13260 		 * dc_validate_global_state(), or there is a chance
13261 		 * to get stuck in an infinite loop and hang eventually.
13262 		 */
13263 		ret = drm_dp_mst_atomic_check(state);
13264 		if (ret) {
13265 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
13266 			goto fail;
13267 		}
13268 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
13269 		if (status != DC_OK) {
13270 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
13271 				       dc_status_to_str(status), status);
13272 			ret = -EINVAL;
13273 			goto fail;
13274 		}
13275 	} else {
13276 		/*
13277 		 * The commit is a fast update. Fast updates shouldn't change
13278 		 * the DC context, affect global validation, and can have their
13279 		 * commit work done in parallel with other commits not touching
13280 		 * the same resource. If we have a new DC context as part of
13281 		 * the DM atomic state from validation we need to free it and
13282 		 * retain the existing one instead.
13283 		 *
13284 		 * Furthermore, since the DM atomic state only contains the DC
13285 		 * context and can safely be annulled, we can free the state
13286 		 * and clear the associated private object now to free
13287 		 * some memory and avoid a possible use-after-free later.
13288 		 */
13289 
13290 		for (i = 0; i < state->num_private_objs; i++) {
13291 			struct drm_private_obj *obj = state->private_objs[i].ptr;
13292 
13293 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
13294 				int j = state->num_private_objs-1;
13295 
13296 				dm_atomic_destroy_state(obj,
13297 						state->private_objs[i].state_to_destroy);
13298 
13299 				/* If i is not at the end of the array then the
13300 				 * last element needs to be moved to where i was
13301 				 * before the array can safely be truncated.
13302 				 */
13303 				if (i != j)
13304 					state->private_objs[i] =
13305 						state->private_objs[j];
13306 
13307 				state->private_objs[j].ptr = NULL;
13308 				state->private_objs[j].state_to_destroy = NULL;
13309 				state->private_objs[j].old_state = NULL;
13310 				state->private_objs[j].new_state = NULL;
13311 
13312 				state->num_private_objs = j;
13313 				break;
13314 			}
13315 		}
13316 	}
13317 
13318 	/* Store the overall update type for use later in atomic check. */
13319 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13320 		struct dm_crtc_state *dm_new_crtc_state =
13321 			to_dm_crtc_state(new_crtc_state);
13322 
13323 		/*
13324 		 * Only allow async flips for fast updates that don't change
13325 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
13326 		 */
13327 		if (new_crtc_state->async_flip &&
13328 		    (lock_and_validation_needed ||
13329 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
13330 			drm_dbg_atomic(crtc->dev,
13331 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
13332 				       crtc->base.id, crtc->name);
13333 			ret = -EINVAL;
13334 			goto fail;
13335 		}
13336 
13337 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
13338 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
13339 	}
13340 
13341 	/* Must be success */
13342 	WARN_ON(ret);
13343 
13344 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13345 
13346 	return ret;
13347 
13348 fail:
13349 	if (ret == -EDEADLK)
13350 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
13351 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
13352 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
13353 	else
13354 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
13355 
13356 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13357 
13358 	return ret;
13359 }
13360 
13361 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
13362 		unsigned int offset,
13363 		unsigned int total_length,
13364 		u8 *data,
13365 		unsigned int length,
13366 		struct amdgpu_hdmi_vsdb_info *vsdb)
13367 {
13368 	bool res;
13369 	union dmub_rb_cmd cmd;
13370 	struct dmub_cmd_send_edid_cea *input;
13371 	struct dmub_cmd_edid_cea_output *output;
13372 
13373 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
13374 		return false;
13375 
13376 	memset(&cmd, 0, sizeof(cmd));
13377 
13378 	input = &cmd.edid_cea.data.input;
13379 
13380 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
13381 	cmd.edid_cea.header.sub_type = 0;
13382 	cmd.edid_cea.header.payload_bytes =
13383 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
13384 	input->offset = offset;
13385 	input->length = length;
13386 	input->cea_total_length = total_length;
13387 	memcpy(input->payload, data, length);
13388 
13389 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
13390 	if (!res) {
13391 		drm_err(adev_to_drm(dm->adev), "EDID CEA parser failed\n");
13392 		return false;
13393 	}
13394 
13395 	output = &cmd.edid_cea.data.output;
13396 
13397 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
13398 		if (!output->ack.success) {
13399 			drm_err(adev_to_drm(dm->adev), "EDID CEA ack failed at offset %d\n",
13400 					output->ack.offset);
13401 		}
13402 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
13403 		if (!output->amd_vsdb.vsdb_found)
13404 			return false;
13405 
13406 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
13407 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
13408 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
13409 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
13410 		vsdb->freesync_mccs_vcp_code = output->amd_vsdb.freesync_mccs_vcp_code;
13411 	} else {
13412 		drm_warn(adev_to_drm(dm->adev), "Unknown EDID CEA parser results\n");
13413 		return false;
13414 	}
13415 
13416 	return true;
13417 }
13418 
13419 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
13420 		u8 *edid_ext, int len,
13421 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13422 {
13423 	int i;
13424 
13425 	/* send extension block to DMCU for parsing */
13426 	for (i = 0; i < len; i += 8) {
13427 		bool res;
13428 		int offset;
13429 
13430 		/* send 8 bytes a time */
13431 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
13432 			return false;
13433 
13434 		if (i+8 == len) {
13435 			/* EDID block sent completed, expect result */
13436 			int version, min_rate, max_rate;
13437 
13438 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
13439 			if (res) {
13440 				/* amd vsdb found */
13441 				vsdb_info->freesync_supported = 1;
13442 				vsdb_info->amd_vsdb_version = version;
13443 				vsdb_info->min_refresh_rate_hz = min_rate;
13444 				vsdb_info->max_refresh_rate_hz = max_rate;
13445 				/* Not enabled on DMCU*/
13446 				vsdb_info->freesync_mccs_vcp_code = 0;
13447 				return true;
13448 			}
13449 			/* not amd vsdb */
13450 			return false;
13451 		}
13452 
13453 		/* check for ack*/
13454 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
13455 		if (!res)
13456 			return false;
13457 	}
13458 
13459 	return false;
13460 }
13461 
13462 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
13463 		u8 *edid_ext, int len,
13464 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13465 {
13466 	int i;
13467 
13468 	/* send extension block to DMCU for parsing */
13469 	for (i = 0; i < len; i += 8) {
13470 		/* send 8 bytes a time */
13471 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
13472 			return false;
13473 	}
13474 
13475 	return vsdb_info->freesync_supported;
13476 }
13477 
13478 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
13479 		u8 *edid_ext, int len,
13480 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13481 {
13482 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
13483 	bool ret;
13484 
13485 	mutex_lock(&adev->dm.dc_lock);
13486 	if (adev->dm.dmub_srv)
13487 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
13488 	else
13489 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
13490 	mutex_unlock(&adev->dm.dc_lock);
13491 	return ret;
13492 }
13493 
13494 static void parse_edid_displayid_vrr(struct drm_connector *connector,
13495 				     const struct edid *edid)
13496 {
13497 	u8 *edid_ext = NULL;
13498 	int i;
13499 	int j = 0;
13500 	u16 min_vfreq;
13501 	u16 max_vfreq;
13502 
13503 	if (!edid || !edid->extensions)
13504 		return;
13505 
13506 	/* Find DisplayID extension */
13507 	for (i = 0; i < edid->extensions; i++) {
13508 		edid_ext = (void *)(edid + (i + 1));
13509 		if (edid_ext[0] == DISPLAYID_EXT)
13510 			break;
13511 	}
13512 
13513 	if (i == edid->extensions)
13514 		return;
13515 
13516 	while (j < EDID_LENGTH) {
13517 		/* Get dynamic video timing range from DisplayID if available */
13518 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
13519 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
13520 			min_vfreq = edid_ext[j+9];
13521 			if (edid_ext[j+1] & 7)
13522 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
13523 			else
13524 				max_vfreq = edid_ext[j+10];
13525 
13526 			if (max_vfreq && min_vfreq) {
13527 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
13528 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
13529 
13530 				return;
13531 			}
13532 		}
13533 		j++;
13534 	}
13535 }
13536 
13537 static int get_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13538 			struct amdgpu_hdmi_vsdb_info *vsdb_info)
13539 {
13540 	struct drm_connector *connector = &aconnector->base;
13541 
13542 	vsdb_info->replay_mode = connector->display_info.amd_vsdb.replay_mode;
13543 	vsdb_info->amd_vsdb_version = connector->display_info.amd_vsdb.version;
13544 
13545 	return connector->display_info.amd_vsdb.version != 0;
13546 }
13547 
13548 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13549 			       const struct edid *edid,
13550 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
13551 {
13552 	u8 *edid_ext = NULL;
13553 	int i;
13554 	bool valid_vsdb_found = false;
13555 
13556 	/*----- drm_find_cea_extension() -----*/
13557 	/* No EDID or EDID extensions */
13558 	if (edid == NULL || edid->extensions == 0)
13559 		return -ENODEV;
13560 
13561 	/* Find CEA extension */
13562 	for (i = 0; i < edid->extensions; i++) {
13563 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
13564 		if (edid_ext[0] == CEA_EXT)
13565 			break;
13566 	}
13567 
13568 	if (i == edid->extensions)
13569 		return -ENODEV;
13570 
13571 	/*----- cea_db_offsets() -----*/
13572 	if (edid_ext[0] != CEA_EXT)
13573 		return -ENODEV;
13574 
13575 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
13576 
13577 	return valid_vsdb_found ? i : -ENODEV;
13578 }
13579 
13580 /**
13581  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
13582  *
13583  * @connector: Connector to query.
13584  * @drm_edid: DRM EDID from monitor
13585  * @do_mccs: Controls whether MCCS (Monitor Control Command Set) over
13586  *	      DDC (Display Data Channel) transactions are performed. When true,
13587  *	      the driver queries the monitor to get or update additional FreeSync
13588  *	      capability information. When false, these transactions are skipped.
13589  *
13590  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
13591  * track of some of the display information in the internal data struct used by
13592  * amdgpu_dm. This function checks which type of connector we need to set the
13593  * FreeSync parameters.
13594  */
13595 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
13596 				    const struct drm_edid *drm_edid, bool do_mccs)
13597 {
13598 	int i = 0;
13599 	struct amdgpu_dm_connector *amdgpu_dm_connector =
13600 			to_amdgpu_dm_connector(connector);
13601 	struct dm_connector_state *dm_con_state = NULL;
13602 	struct dc_sink *sink;
13603 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
13604 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
13605 	const struct edid *edid;
13606 	bool freesync_capable = false;
13607 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
13608 
13609 	if (!connector->state) {
13610 		drm_err(adev_to_drm(adev), "%s - Connector has no state", __func__);
13611 		goto update;
13612 	}
13613 
13614 	sink = amdgpu_dm_connector->dc_sink ?
13615 		amdgpu_dm_connector->dc_sink :
13616 		amdgpu_dm_connector->dc_em_sink;
13617 
13618 	drm_edid_connector_update(connector, drm_edid);
13619 
13620 	if (!drm_edid || !sink) {
13621 		dm_con_state = to_dm_connector_state(connector->state);
13622 
13623 		amdgpu_dm_connector->min_vfreq = 0;
13624 		amdgpu_dm_connector->max_vfreq = 0;
13625 		freesync_capable = false;
13626 
13627 		goto update;
13628 	}
13629 
13630 	dm_con_state = to_dm_connector_state(connector->state);
13631 
13632 	if (!adev->dm.freesync_module || !dc_supports_vrr(sink->ctx->dce_version))
13633 		goto update;
13634 
13635 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
13636 
13637 	/* Some eDP panels only have the refresh rate range info in DisplayID */
13638 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
13639 	     connector->display_info.monitor_range.max_vfreq == 0))
13640 		parse_edid_displayid_vrr(connector, edid);
13641 
13642 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
13643 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
13644 		if (amdgpu_dm_connector->dc_link &&
13645 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
13646 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
13647 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
13648 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13649 				freesync_capable = true;
13650 		}
13651 
13652 		get_amd_vsdb(amdgpu_dm_connector, &vsdb_info);
13653 
13654 		if (vsdb_info.replay_mode) {
13655 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
13656 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
13657 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
13658 		}
13659 
13660 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
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) {
13667 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13668 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13669 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13670 					freesync_capable = true;
13671 
13672 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13673 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13674 			}
13675 		}
13676 	}
13677 
13678 	if (amdgpu_dm_connector->dc_link)
13679 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
13680 
13681 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
13682 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13683 		if (i >= 0) {
13684 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13685 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13686 
13687 			if (vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
13688 				amdgpu_dm_connector->pack_sdp_v1_3 = true;
13689 				amdgpu_dm_connector->as_type = as_type;
13690 
13691 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13692 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13693 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13694 					freesync_capable = true;
13695 
13696 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13697 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13698 			}
13699 		}
13700 	}
13701 
13702 	/* Handle MCCS */
13703 	if (do_mccs)
13704 		dm_helpers_read_mccs_caps(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13705 
13706 	if ((sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
13707 		as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) &&
13708 		(!sink->edid_caps.freesync_vcp_code ||
13709 		(sink->edid_caps.freesync_vcp_code && !sink->mccs_caps.freesync_supported)))
13710 		freesync_capable = false;
13711 
13712 	if (do_mccs && sink->mccs_caps.freesync_supported && freesync_capable)
13713 		dm_helpers_mccs_vcp_set(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13714 
13715 update:
13716 	if (dm_con_state)
13717 		dm_con_state->freesync_capable = freesync_capable;
13718 
13719 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
13720 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
13721 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
13722 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
13723 	}
13724 
13725 	if (connector->vrr_capable_property)
13726 		drm_connector_set_vrr_capable_property(connector,
13727 						       freesync_capable);
13728 }
13729 
13730 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
13731 {
13732 	struct amdgpu_device *adev = drm_to_adev(dev);
13733 	struct dc *dc = adev->dm.dc;
13734 	int i;
13735 
13736 	mutex_lock(&adev->dm.dc_lock);
13737 	if (dc->current_state) {
13738 		for (i = 0; i < dc->current_state->stream_count; ++i)
13739 			dc->current_state->streams[i]
13740 				->triggered_crtc_reset.enabled =
13741 				adev->dm.force_timing_sync;
13742 
13743 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
13744 		dc_trigger_sync(dc, dc->current_state);
13745 	}
13746 	mutex_unlock(&adev->dm.dc_lock);
13747 }
13748 
13749 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
13750 {
13751 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
13752 		dc_exit_ips_for_hw_access(dc);
13753 }
13754 
13755 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
13756 		       u32 value, const char *func_name)
13757 {
13758 #ifdef DM_CHECK_ADDR_0
13759 	if (address == 0) {
13760 		drm_err(adev_to_drm(ctx->driver_context),
13761 			"invalid register write. address = 0");
13762 		return;
13763 	}
13764 #endif
13765 
13766 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13767 	cgs_write_register(ctx->cgs_device, address, value);
13768 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
13769 }
13770 
13771 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
13772 			  const char *func_name)
13773 {
13774 	u32 value;
13775 #ifdef DM_CHECK_ADDR_0
13776 	if (address == 0) {
13777 		drm_err(adev_to_drm(ctx->driver_context),
13778 			"invalid register read; address = 0\n");
13779 		return 0;
13780 	}
13781 #endif
13782 
13783 	if (ctx->dmub_srv &&
13784 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
13785 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
13786 		ASSERT(false);
13787 		return 0;
13788 	}
13789 
13790 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13791 
13792 	value = cgs_read_register(ctx->cgs_device, address);
13793 
13794 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
13795 
13796 	return value;
13797 }
13798 
13799 int amdgpu_dm_process_dmub_aux_transfer_sync(
13800 		struct dc_context *ctx,
13801 		unsigned int link_index,
13802 		struct aux_payload *payload,
13803 		enum aux_return_code_type *operation_result)
13804 {
13805 	struct amdgpu_device *adev = ctx->driver_context;
13806 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
13807 	int ret = -1;
13808 
13809 	mutex_lock(&adev->dm.dpia_aux_lock);
13810 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
13811 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
13812 		goto out;
13813 	}
13814 
13815 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13816 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13817 		*operation_result = AUX_RET_ERROR_TIMEOUT;
13818 		goto out;
13819 	}
13820 
13821 	if (p_notify->result != AUX_RET_SUCCESS) {
13822 		/*
13823 		 * Transient states before tunneling is enabled could
13824 		 * lead to this error. We can ignore this for now.
13825 		 */
13826 		if (p_notify->result == AUX_RET_ERROR_PROTOCOL_ERROR) {
13827 			drm_warn(adev_to_drm(adev), "DPIA AUX failed on 0x%x(%d), error %d\n",
13828 					payload->address, payload->length,
13829 					p_notify->result);
13830 		}
13831 		*operation_result = p_notify->result;
13832 		goto out;
13833 	}
13834 
13835 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command & 0xF;
13836 	if (adev->dm.dmub_notify->aux_reply.command & 0xF0)
13837 		/* The reply is stored in the top nibble of the command. */
13838 		payload->reply[0] = (adev->dm.dmub_notify->aux_reply.command >> 4) & 0xF;
13839 
13840 	/*write req may receive a byte indicating partially written number as well*/
13841 	if (p_notify->aux_reply.length)
13842 		memcpy(payload->data, p_notify->aux_reply.data,
13843 				p_notify->aux_reply.length);
13844 
13845 	/* success */
13846 	ret = p_notify->aux_reply.length;
13847 	*operation_result = p_notify->result;
13848 out:
13849 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
13850 	mutex_unlock(&adev->dm.dpia_aux_lock);
13851 	return ret;
13852 }
13853 
13854 static void abort_fused_io(
13855 		struct dc_context *ctx,
13856 		const struct dmub_cmd_fused_request *request
13857 )
13858 {
13859 	union dmub_rb_cmd command = { 0 };
13860 	struct dmub_rb_cmd_fused_io *io = &command.fused_io;
13861 
13862 	io->header.type = DMUB_CMD__FUSED_IO;
13863 	io->header.sub_type = DMUB_CMD__FUSED_IO_ABORT;
13864 	io->header.payload_bytes = sizeof(*io) - sizeof(io->header);
13865 	io->request = *request;
13866 	dm_execute_dmub_cmd(ctx, &command, DM_DMUB_WAIT_TYPE_NO_WAIT);
13867 }
13868 
13869 static bool execute_fused_io(
13870 		struct amdgpu_device *dev,
13871 		struct dc_context *ctx,
13872 		union dmub_rb_cmd *commands,
13873 		uint8_t count,
13874 		uint32_t timeout_us
13875 )
13876 {
13877 	const uint8_t ddc_line = commands[0].fused_io.request.u.aux.ddc_line;
13878 
13879 	if (ddc_line >= ARRAY_SIZE(dev->dm.fused_io))
13880 		return false;
13881 
13882 	struct fused_io_sync *sync = &dev->dm.fused_io[ddc_line];
13883 	struct dmub_rb_cmd_fused_io *first = &commands[0].fused_io;
13884 	const bool result = dm_execute_dmub_cmd_list(ctx, count, commands, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY)
13885 			&& first->header.ret_status
13886 			&& first->request.status == FUSED_REQUEST_STATUS_SUCCESS;
13887 
13888 	if (!result)
13889 		return false;
13890 
13891 	while (wait_for_completion_timeout(&sync->replied, usecs_to_jiffies(timeout_us))) {
13892 		reinit_completion(&sync->replied);
13893 
13894 		struct dmub_cmd_fused_request *reply = (struct dmub_cmd_fused_request *) sync->reply_data;
13895 
13896 		static_assert(sizeof(*reply) <= sizeof(sync->reply_data), "Size mismatch");
13897 
13898 		if (reply->identifier == first->request.identifier) {
13899 			first->request = *reply;
13900 			return true;
13901 		}
13902 	}
13903 
13904 	reinit_completion(&sync->replied);
13905 	first->request.status = FUSED_REQUEST_STATUS_TIMEOUT;
13906 	abort_fused_io(ctx, &first->request);
13907 	return false;
13908 }
13909 
13910 bool amdgpu_dm_execute_fused_io(
13911 		struct amdgpu_device *dev,
13912 		struct dc_link *link,
13913 		union dmub_rb_cmd *commands,
13914 		uint8_t count,
13915 		uint32_t timeout_us)
13916 {
13917 	struct amdgpu_display_manager *dm = &dev->dm;
13918 
13919 	mutex_lock(&dm->dpia_aux_lock);
13920 
13921 	const bool result = execute_fused_io(dev, link->ctx, commands, count, timeout_us);
13922 
13923 	mutex_unlock(&dm->dpia_aux_lock);
13924 	return result;
13925 }
13926 
13927 int amdgpu_dm_process_dmub_set_config_sync(
13928 		struct dc_context *ctx,
13929 		unsigned int link_index,
13930 		struct set_config_cmd_payload *payload,
13931 		enum set_config_status *operation_result)
13932 {
13933 	struct amdgpu_device *adev = ctx->driver_context;
13934 	bool is_cmd_complete;
13935 	int ret;
13936 
13937 	mutex_lock(&adev->dm.dpia_aux_lock);
13938 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
13939 			link_index, payload, adev->dm.dmub_notify);
13940 
13941 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13942 		ret = 0;
13943 		*operation_result = adev->dm.dmub_notify->sc_status;
13944 	} else {
13945 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13946 		ret = -1;
13947 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
13948 	}
13949 
13950 	if (!is_cmd_complete)
13951 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
13952 	mutex_unlock(&adev->dm.dpia_aux_lock);
13953 	return ret;
13954 }
13955 
13956 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
13957 {
13958 	struct amdgpu_device *adev = ctx->driver_context;
13959 
13960 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
13961 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
13962 }
13963 
13964 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)
13965 {
13966 	struct amdgpu_device *adev = ctx->driver_context;
13967 
13968 	guard(spinlock_irqsave)(&adev->dm.dmub_lock);
13969 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
13970 }
13971 
13972 void dm_acpi_process_phy_transition_interlock(
13973 	const struct dc_context *ctx,
13974 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
13975 {
13976 	// Not yet implemented
13977 }
13978