xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision 4a9671a03f2be13acde0cb15c5208767a9cc56e4)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright 2015 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_gem_atomic_helper.h>
99 
100 #include <media/cec-notifier.h>
101 #include <acpi/video.h>
102 
103 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
104 
105 #include "modules/inc/mod_freesync.h"
106 #include "modules/power/power_helpers.h"
107 
108 static_assert(AMDGPU_DMUB_NOTIFICATION_MAX == DMUB_NOTIFICATION_MAX, "AMDGPU_DMUB_NOTIFICATION_MAX mismatch");
109 
110 #define FIRMWARE_RENOIR_DMUB "amdgpu/renoir_dmcub.bin"
111 MODULE_FIRMWARE(FIRMWARE_RENOIR_DMUB);
112 #define FIRMWARE_SIENNA_CICHLID_DMUB "amdgpu/sienna_cichlid_dmcub.bin"
113 MODULE_FIRMWARE(FIRMWARE_SIENNA_CICHLID_DMUB);
114 #define FIRMWARE_NAVY_FLOUNDER_DMUB "amdgpu/navy_flounder_dmcub.bin"
115 MODULE_FIRMWARE(FIRMWARE_NAVY_FLOUNDER_DMUB);
116 #define FIRMWARE_GREEN_SARDINE_DMUB "amdgpu/green_sardine_dmcub.bin"
117 MODULE_FIRMWARE(FIRMWARE_GREEN_SARDINE_DMUB);
118 #define FIRMWARE_VANGOGH_DMUB "amdgpu/vangogh_dmcub.bin"
119 MODULE_FIRMWARE(FIRMWARE_VANGOGH_DMUB);
120 #define FIRMWARE_DIMGREY_CAVEFISH_DMUB "amdgpu/dimgrey_cavefish_dmcub.bin"
121 MODULE_FIRMWARE(FIRMWARE_DIMGREY_CAVEFISH_DMUB);
122 #define FIRMWARE_BEIGE_GOBY_DMUB "amdgpu/beige_goby_dmcub.bin"
123 MODULE_FIRMWARE(FIRMWARE_BEIGE_GOBY_DMUB);
124 #define FIRMWARE_YELLOW_CARP_DMUB "amdgpu/yellow_carp_dmcub.bin"
125 MODULE_FIRMWARE(FIRMWARE_YELLOW_CARP_DMUB);
126 #define FIRMWARE_DCN_314_DMUB "amdgpu/dcn_3_1_4_dmcub.bin"
127 MODULE_FIRMWARE(FIRMWARE_DCN_314_DMUB);
128 #define FIRMWARE_DCN_315_DMUB "amdgpu/dcn_3_1_5_dmcub.bin"
129 MODULE_FIRMWARE(FIRMWARE_DCN_315_DMUB);
130 #define FIRMWARE_DCN316_DMUB "amdgpu/dcn_3_1_6_dmcub.bin"
131 MODULE_FIRMWARE(FIRMWARE_DCN316_DMUB);
132 
133 #define FIRMWARE_DCN_V3_2_0_DMCUB "amdgpu/dcn_3_2_0_dmcub.bin"
134 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_0_DMCUB);
135 #define FIRMWARE_DCN_V3_2_1_DMCUB "amdgpu/dcn_3_2_1_dmcub.bin"
136 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_1_DMCUB);
137 
138 #define FIRMWARE_RAVEN_DMCU		"amdgpu/raven_dmcu.bin"
139 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
140 
141 #define FIRMWARE_NAVI12_DMCU            "amdgpu/navi12_dmcu.bin"
142 MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
143 
144 #define FIRMWARE_DCN_35_DMUB "amdgpu/dcn_3_5_dmcub.bin"
145 MODULE_FIRMWARE(FIRMWARE_DCN_35_DMUB);
146 
147 #define FIRMWARE_DCN_351_DMUB "amdgpu/dcn_3_5_1_dmcub.bin"
148 MODULE_FIRMWARE(FIRMWARE_DCN_351_DMUB);
149 
150 #define FIRMWARE_DCN_36_DMUB "amdgpu/dcn_3_6_dmcub.bin"
151 MODULE_FIRMWARE(FIRMWARE_DCN_36_DMUB);
152 
153 #define FIRMWARE_DCN_401_DMUB "amdgpu/dcn_4_0_1_dmcub.bin"
154 MODULE_FIRMWARE(FIRMWARE_DCN_401_DMUB);
155 
156 /**
157  * DOC: overview
158  *
159  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
160  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
161  * requests into DC requests, and DC responses into DRM responses.
162  *
163  * The root control structure is &struct amdgpu_display_manager.
164  */
165 
166 /* basic init/fini API */
167 static int amdgpu_dm_init(struct amdgpu_device *adev);
168 static void amdgpu_dm_fini(struct amdgpu_device *adev);
169 static bool is_freesync_video_mode(const struct drm_display_mode *mode, struct amdgpu_dm_connector *aconnector);
170 static void reset_freesync_config_for_crtc(struct dm_crtc_state *new_crtc_state);
171 static struct amdgpu_i2c_adapter *
172 create_i2c(struct ddc_service *ddc_service, bool oem);
173 
174 static enum drm_mode_subconnector get_subconnector_type(struct dc_link *link)
175 {
176 	switch (link->dpcd_caps.dongle_type) {
177 	case DISPLAY_DONGLE_NONE:
178 		return DRM_MODE_SUBCONNECTOR_Native;
179 	case DISPLAY_DONGLE_DP_VGA_CONVERTER:
180 		return DRM_MODE_SUBCONNECTOR_VGA;
181 	case DISPLAY_DONGLE_DP_DVI_CONVERTER:
182 	case DISPLAY_DONGLE_DP_DVI_DONGLE:
183 		return DRM_MODE_SUBCONNECTOR_DVID;
184 	case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
185 	case DISPLAY_DONGLE_DP_HDMI_DONGLE:
186 		return DRM_MODE_SUBCONNECTOR_HDMIA;
187 	case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
188 	default:
189 		return DRM_MODE_SUBCONNECTOR_Unknown;
190 	}
191 }
192 
193 static void update_subconnector_property(struct amdgpu_dm_connector *aconnector)
194 {
195 	struct dc_link *link = aconnector->dc_link;
196 	struct drm_connector *connector = &aconnector->base;
197 	enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
198 
199 	if (connector->connector_type != DRM_MODE_CONNECTOR_DisplayPort)
200 		return;
201 
202 	if (aconnector->dc_sink)
203 		subconnector = get_subconnector_type(link);
204 
205 	drm_object_property_set_value(&connector->base,
206 			connector->dev->mode_config.dp_subconnector_property,
207 			subconnector);
208 }
209 
210 /*
211  * initializes drm_device display related structures, based on the information
212  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
213  * drm_encoder, drm_mode_config
214  *
215  * Returns 0 on success
216  */
217 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
218 /* removes and deallocates the drm structures, created by the above function */
219 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
220 
221 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
222 				    struct amdgpu_dm_connector *amdgpu_dm_connector,
223 				    u32 link_index,
224 				    struct amdgpu_encoder *amdgpu_encoder);
225 static int amdgpu_dm_encoder_init(struct drm_device *dev,
226 				  struct amdgpu_encoder *aencoder,
227 				  uint32_t link_index);
228 
229 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
230 
231 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_state *state);
232 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
233 
234 static int amdgpu_dm_atomic_check(struct drm_device *dev,
235 				  struct drm_atomic_state *state);
236 
237 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector);
238 static void handle_hpd_rx_irq(void *param);
239 
240 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
241 					 int bl_idx,
242 					 u32 user_brightness);
243 
244 static bool
245 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
246 				 struct drm_crtc_state *new_crtc_state);
247 /*
248  * dm_vblank_get_counter
249  *
250  * @brief
251  * Get counter for number of vertical blanks
252  *
253  * @param
254  * struct amdgpu_device *adev - [in] desired amdgpu device
255  * int disp_idx - [in] which CRTC to get the counter from
256  *
257  * @return
258  * Counter for vertical blanks
259  */
260 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
261 {
262 	struct amdgpu_crtc *acrtc = NULL;
263 
264 	if (crtc >= adev->mode_info.num_crtc)
265 		return 0;
266 
267 	acrtc = adev->mode_info.crtcs[crtc];
268 
269 	if (!acrtc->dm_irq_params.stream) {
270 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
271 			  crtc);
272 		return 0;
273 	}
274 
275 	return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
276 }
277 
278 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
279 				  u32 *vbl, u32 *position)
280 {
281 	u32 v_blank_start = 0, v_blank_end = 0, h_position = 0, v_position = 0;
282 	struct amdgpu_crtc *acrtc = NULL;
283 	struct dc *dc = adev->dm.dc;
284 
285 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
286 		return -EINVAL;
287 
288 	acrtc = adev->mode_info.crtcs[crtc];
289 
290 	if (!acrtc->dm_irq_params.stream) {
291 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
292 			  crtc);
293 		return 0;
294 	}
295 
296 	if (dc && dc->caps.ips_support && dc->idle_optimizations_allowed)
297 		dc_allow_idle_optimizations(dc, false);
298 
299 	/*
300 	 * TODO rework base driver to use values directly.
301 	 * for now parse it back into reg-format
302 	 */
303 	dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
304 				 &v_blank_start,
305 				 &v_blank_end,
306 				 &h_position,
307 				 &v_position);
308 
309 	*position = v_position | (h_position << 16);
310 	*vbl = v_blank_start | (v_blank_end << 16);
311 
312 	return 0;
313 }
314 
315 static bool dm_is_idle(struct amdgpu_ip_block *ip_block)
316 {
317 	/* XXX todo */
318 	return true;
319 }
320 
321 static int dm_wait_for_idle(struct amdgpu_ip_block *ip_block)
322 {
323 	/* XXX todo */
324 	return 0;
325 }
326 
327 static bool dm_check_soft_reset(struct amdgpu_ip_block *ip_block)
328 {
329 	return false;
330 }
331 
332 static int dm_soft_reset(struct amdgpu_ip_block *ip_block)
333 {
334 	/* XXX todo */
335 	return 0;
336 }
337 
338 static struct amdgpu_crtc *
339 get_crtc_by_otg_inst(struct amdgpu_device *adev,
340 		     int otg_inst)
341 {
342 	struct drm_device *dev = adev_to_drm(adev);
343 	struct drm_crtc *crtc;
344 	struct amdgpu_crtc *amdgpu_crtc;
345 
346 	if (WARN_ON(otg_inst == -1))
347 		return adev->mode_info.crtcs[0];
348 
349 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
350 		amdgpu_crtc = to_amdgpu_crtc(crtc);
351 
352 		if (amdgpu_crtc->otg_inst == otg_inst)
353 			return amdgpu_crtc;
354 	}
355 
356 	return NULL;
357 }
358 
359 static inline bool is_dc_timing_adjust_needed(struct dm_crtc_state *old_state,
360 					      struct dm_crtc_state *new_state)
361 {
362 	if (new_state->stream->adjust.timing_adjust_pending)
363 		return true;
364 	if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
365 		return true;
366 	else if (amdgpu_dm_crtc_vrr_active(old_state) != amdgpu_dm_crtc_vrr_active(new_state))
367 		return true;
368 	else
369 		return false;
370 }
371 
372 /*
373  * DC will program planes with their z-order determined by their ordering
374  * in the dc_surface_updates array. This comparator is used to sort them
375  * by descending zpos.
376  */
377 static int dm_plane_layer_index_cmp(const void *a, const void *b)
378 {
379 	const struct dc_surface_update *sa = (struct dc_surface_update *)a;
380 	const struct dc_surface_update *sb = (struct dc_surface_update *)b;
381 
382 	/* Sort by descending dc_plane layer_index (i.e. normalized_zpos) */
383 	return sb->surface->layer_index - sa->surface->layer_index;
384 }
385 
386 /**
387  * update_planes_and_stream_adapter() - Send planes to be updated in DC
388  *
389  * DC has a generic way to update planes and stream via
390  * dc_update_planes_and_stream function; however, DM might need some
391  * adjustments and preparation before calling it. This function is a wrapper
392  * for the dc_update_planes_and_stream that does any required configuration
393  * before passing control to DC.
394  *
395  * @dc: Display Core control structure
396  * @update_type: specify whether it is FULL/MEDIUM/FAST update
397  * @planes_count: planes count to update
398  * @stream: stream state
399  * @stream_update: stream update
400  * @array_of_surface_update: dc surface update pointer
401  *
402  */
403 static inline bool update_planes_and_stream_adapter(struct dc *dc,
404 						    int update_type,
405 						    int planes_count,
406 						    struct dc_stream_state *stream,
407 						    struct dc_stream_update *stream_update,
408 						    struct dc_surface_update *array_of_surface_update)
409 {
410 	sort(array_of_surface_update, planes_count,
411 	     sizeof(*array_of_surface_update), dm_plane_layer_index_cmp, NULL);
412 
413 	/*
414 	 * Previous frame finished and HW is ready for optimization.
415 	 */
416 	dc_post_update_surfaces_to_stream(dc);
417 
418 	return dc_update_planes_and_stream(dc,
419 					   array_of_surface_update,
420 					   planes_count,
421 					   stream,
422 					   stream_update);
423 }
424 
425 /**
426  * dm_pflip_high_irq() - Handle pageflip interrupt
427  * @interrupt_params: ignored
428  *
429  * Handles the pageflip interrupt by notifying all interested parties
430  * that the pageflip has been completed.
431  */
432 static void dm_pflip_high_irq(void *interrupt_params)
433 {
434 	struct amdgpu_crtc *amdgpu_crtc;
435 	struct common_irq_params *irq_params = interrupt_params;
436 	struct amdgpu_device *adev = irq_params->adev;
437 	struct drm_device *dev = adev_to_drm(adev);
438 	unsigned long flags;
439 	struct drm_pending_vblank_event *e;
440 	u32 vpos, hpos, v_blank_start, v_blank_end;
441 	bool vrr_active;
442 
443 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
444 
445 	/* IRQ could occur when in initial stage */
446 	/* TODO work and BO cleanup */
447 	if (amdgpu_crtc == NULL) {
448 		drm_dbg_state(dev, "CRTC is null, returning.\n");
449 		return;
450 	}
451 
452 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
453 
454 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED) {
455 		drm_dbg_state(dev,
456 			      "amdgpu_crtc->pflip_status = %d != AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p]\n",
457 			      amdgpu_crtc->pflip_status, AMDGPU_FLIP_SUBMITTED,
458 			      amdgpu_crtc->crtc_id, amdgpu_crtc);
459 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
460 		return;
461 	}
462 
463 	/* page flip completed. */
464 	e = amdgpu_crtc->event;
465 	amdgpu_crtc->event = NULL;
466 
467 	WARN_ON(!e);
468 
469 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(amdgpu_crtc);
470 
471 	/* Fixed refresh rate, or VRR scanout position outside front-porch? */
472 	if (!vrr_active ||
473 	    !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
474 				      &v_blank_end, &hpos, &vpos) ||
475 	    (vpos < v_blank_start)) {
476 		/* Update to correct count and vblank timestamp if racing with
477 		 * vblank irq. This also updates to the correct vblank timestamp
478 		 * even in VRR mode, as scanout is past the front-porch atm.
479 		 */
480 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
481 
482 		/* Wake up userspace by sending the pageflip event with proper
483 		 * count and timestamp of vblank of flip completion.
484 		 */
485 		if (e) {
486 			drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
487 
488 			/* Event sent, so done with vblank for this flip */
489 			drm_crtc_vblank_put(&amdgpu_crtc->base);
490 		}
491 	} else if (e) {
492 		/* VRR active and inside front-porch: vblank count and
493 		 * timestamp for pageflip event will only be up to date after
494 		 * drm_crtc_handle_vblank() has been executed from late vblank
495 		 * irq handler after start of back-porch (vline 0). We queue the
496 		 * pageflip event for send-out by drm_crtc_handle_vblank() with
497 		 * updated timestamp and count, once it runs after us.
498 		 *
499 		 * We need to open-code this instead of using the helper
500 		 * drm_crtc_arm_vblank_event(), as that helper would
501 		 * call drm_crtc_accurate_vblank_count(), which we must
502 		 * not call in VRR mode while we are in front-porch!
503 		 */
504 
505 		/* sequence will be replaced by real count during send-out. */
506 		e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
507 		e->pipe = amdgpu_crtc->crtc_id;
508 
509 		list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
510 		e = NULL;
511 	}
512 
513 	/* Keep track of vblank of this flip for flip throttling. We use the
514 	 * cooked hw counter, as that one incremented at start of this vblank
515 	 * of pageflip completion, so last_flip_vblank is the forbidden count
516 	 * for queueing new pageflips if vsync + VRR is enabled.
517 	 */
518 	amdgpu_crtc->dm_irq_params.last_flip_vblank =
519 		amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
520 
521 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
522 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
523 
524 	drm_dbg_state(dev,
525 		      "crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
526 		      amdgpu_crtc->crtc_id, amdgpu_crtc, vrr_active, (int)!e);
527 }
528 
529 static void dm_handle_vmin_vmax_update(struct work_struct *offload_work)
530 {
531 	struct vupdate_offload_work *work = container_of(offload_work, struct vupdate_offload_work, work);
532 	struct amdgpu_device *adev = work->adev;
533 	struct dc_stream_state *stream = work->stream;
534 	struct dc_crtc_timing_adjust *adjust = work->adjust;
535 
536 	mutex_lock(&adev->dm.dc_lock);
537 	dc_stream_adjust_vmin_vmax(adev->dm.dc, stream, adjust);
538 	mutex_unlock(&adev->dm.dc_lock);
539 
540 	dc_stream_release(stream);
541 	kfree(work->adjust);
542 	kfree(work);
543 }
544 
545 static void schedule_dc_vmin_vmax(struct amdgpu_device *adev,
546 	struct dc_stream_state *stream,
547 	struct dc_crtc_timing_adjust *adjust)
548 {
549 	struct vupdate_offload_work *offload_work = kzalloc(sizeof(*offload_work), GFP_NOWAIT);
550 	if (!offload_work) {
551 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate vupdate_offload_work\n");
552 		return;
553 	}
554 
555 	struct dc_crtc_timing_adjust *adjust_copy = kzalloc(sizeof(*adjust_copy), GFP_NOWAIT);
556 	if (!adjust_copy) {
557 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate adjust_copy\n");
558 		kfree(offload_work);
559 		return;
560 	}
561 
562 	dc_stream_retain(stream);
563 	memcpy(adjust_copy, adjust, sizeof(*adjust_copy));
564 
565 	INIT_WORK(&offload_work->work, dm_handle_vmin_vmax_update);
566 	offload_work->adev = adev;
567 	offload_work->stream = stream;
568 	offload_work->adjust = adjust_copy;
569 
570 	queue_work(system_wq, &offload_work->work);
571 }
572 
573 static void dm_vupdate_high_irq(void *interrupt_params)
574 {
575 	struct common_irq_params *irq_params = interrupt_params;
576 	struct amdgpu_device *adev = irq_params->adev;
577 	struct amdgpu_crtc *acrtc;
578 	struct drm_device *drm_dev;
579 	struct drm_vblank_crtc *vblank;
580 	ktime_t frame_duration_ns, previous_timestamp;
581 	unsigned long flags;
582 	int vrr_active;
583 
584 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
585 
586 	if (acrtc) {
587 		vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
588 		drm_dev = acrtc->base.dev;
589 		vblank = drm_crtc_vblank_crtc(&acrtc->base);
590 		previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
591 		frame_duration_ns = vblank->time - previous_timestamp;
592 
593 		if (frame_duration_ns > 0) {
594 			trace_amdgpu_refresh_rate_track(acrtc->base.index,
595 						frame_duration_ns,
596 						ktime_divns(NSEC_PER_SEC, frame_duration_ns));
597 			atomic64_set(&irq_params->previous_timestamp, vblank->time);
598 		}
599 
600 		drm_dbg_vbl(drm_dev,
601 			    "crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
602 			    vrr_active);
603 
604 		/* Core vblank handling is done here after end of front-porch in
605 		 * vrr mode, as vblank timestamping will give valid results
606 		 * while now done after front-porch. This will also deliver
607 		 * page-flip completion events that have been queued to us
608 		 * if a pageflip happened inside front-porch.
609 		 */
610 		if (vrr_active && acrtc->dm_irq_params.stream) {
611 			bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
612 			bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
613 			bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state
614 				== VRR_STATE_ACTIVE_VARIABLE;
615 
616 			amdgpu_dm_crtc_handle_vblank(acrtc);
617 
618 			/* BTR processing for pre-DCE12 ASICs */
619 			if (adev->family < AMDGPU_FAMILY_AI) {
620 				spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
621 				mod_freesync_handle_v_update(
622 				    adev->dm.freesync_module,
623 				    acrtc->dm_irq_params.stream,
624 				    &acrtc->dm_irq_params.vrr_params);
625 
626 				if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
627 					schedule_dc_vmin_vmax(adev,
628 						acrtc->dm_irq_params.stream,
629 						&acrtc->dm_irq_params.vrr_params.adjust);
630 				}
631 				spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
632 			}
633 		}
634 	}
635 }
636 
637 /**
638  * dm_crtc_high_irq() - Handles CRTC interrupt
639  * @interrupt_params: used for determining the CRTC instance
640  *
641  * Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
642  * event handler.
643  */
644 static void dm_crtc_high_irq(void *interrupt_params)
645 {
646 	struct common_irq_params *irq_params = interrupt_params;
647 	struct amdgpu_device *adev = irq_params->adev;
648 	struct drm_writeback_job *job;
649 	struct amdgpu_crtc *acrtc;
650 	unsigned long flags;
651 	int vrr_active;
652 
653 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
654 	if (!acrtc)
655 		return;
656 
657 	if (acrtc->wb_conn) {
658 		spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
659 
660 		if (acrtc->wb_pending) {
661 			job = list_first_entry_or_null(&acrtc->wb_conn->job_queue,
662 						       struct drm_writeback_job,
663 						       list_entry);
664 			acrtc->wb_pending = false;
665 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
666 
667 			if (job) {
668 				unsigned int v_total, refresh_hz;
669 				struct dc_stream_state *stream = acrtc->dm_irq_params.stream;
670 
671 				v_total = stream->adjust.v_total_max ?
672 					  stream->adjust.v_total_max : stream->timing.v_total;
673 				refresh_hz = div_u64((uint64_t) stream->timing.pix_clk_100hz *
674 					     100LL, (v_total * stream->timing.h_total));
675 				mdelay(1000 / refresh_hz);
676 
677 				drm_writeback_signal_completion(acrtc->wb_conn, 0);
678 				dc_stream_fc_disable_writeback(adev->dm.dc,
679 							       acrtc->dm_irq_params.stream, 0);
680 			}
681 		} else
682 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
683 	}
684 
685 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
686 
687 	drm_dbg_vbl(adev_to_drm(adev),
688 		    "crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
689 		    vrr_active, acrtc->dm_irq_params.active_planes);
690 
691 	/**
692 	 * Core vblank handling at start of front-porch is only possible
693 	 * in non-vrr mode, as only there vblank timestamping will give
694 	 * valid results while done in front-porch. Otherwise defer it
695 	 * to dm_vupdate_high_irq after end of front-porch.
696 	 */
697 	if (!vrr_active)
698 		amdgpu_dm_crtc_handle_vblank(acrtc);
699 
700 	/**
701 	 * Following stuff must happen at start of vblank, for crc
702 	 * computation and below-the-range btr support in vrr mode.
703 	 */
704 	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
705 
706 	/* BTR updates need to happen before VUPDATE on Vega and above. */
707 	if (adev->family < AMDGPU_FAMILY_AI)
708 		return;
709 
710 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
711 
712 	if (acrtc->dm_irq_params.stream &&
713 		acrtc->dm_irq_params.vrr_params.supported) {
714 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
715 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
716 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state == VRR_STATE_ACTIVE_VARIABLE;
717 
718 		mod_freesync_handle_v_update(adev->dm.freesync_module,
719 					     acrtc->dm_irq_params.stream,
720 					     &acrtc->dm_irq_params.vrr_params);
721 
722 		/* update vmin_vmax only if freesync is enabled, or only if PSR and REPLAY are disabled */
723 		if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
724 			schedule_dc_vmin_vmax(adev, acrtc->dm_irq_params.stream,
725 					&acrtc->dm_irq_params.vrr_params.adjust);
726 		}
727 	}
728 
729 	/*
730 	 * If there aren't any active_planes then DCH HUBP may be clock-gated.
731 	 * In that case, pageflip completion interrupts won't fire and pageflip
732 	 * completion events won't get delivered. Prevent this by sending
733 	 * pending pageflip events from here if a flip is still pending.
734 	 *
735 	 * If any planes are enabled, use dm_pflip_high_irq() instead, to
736 	 * avoid race conditions between flip programming and completion,
737 	 * which could cause too early flip completion events.
738 	 */
739 	if (adev->family >= AMDGPU_FAMILY_RV &&
740 	    acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
741 	    acrtc->dm_irq_params.active_planes == 0) {
742 		if (acrtc->event) {
743 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
744 			acrtc->event = NULL;
745 			drm_crtc_vblank_put(&acrtc->base);
746 		}
747 		acrtc->pflip_status = AMDGPU_FLIP_NONE;
748 	}
749 
750 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
751 }
752 
753 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
754 /**
755  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
756  * DCN generation ASICs
757  * @interrupt_params: interrupt parameters
758  *
759  * Used to set crc window/read out crc value at vertical line 0 position
760  */
761 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
762 {
763 	struct common_irq_params *irq_params = interrupt_params;
764 	struct amdgpu_device *adev = irq_params->adev;
765 	struct amdgpu_crtc *acrtc;
766 
767 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
768 
769 	if (!acrtc)
770 		return;
771 
772 	amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
773 }
774 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
775 
776 /**
777  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
778  * @adev: amdgpu_device pointer
779  * @notify: dmub notification structure
780  *
781  * Dmub AUX or SET_CONFIG command completion processing callback
782  * Copies dmub notification to DM which is to be read by AUX command.
783  * issuing thread and also signals the event to wake up the thread.
784  */
785 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
786 					struct dmub_notification *notify)
787 {
788 	if (adev->dm.dmub_notify)
789 		memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
790 	if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
791 		complete(&adev->dm.dmub_aux_transfer_done);
792 }
793 
794 static void dmub_aux_fused_io_callback(struct amdgpu_device *adev,
795 					struct dmub_notification *notify)
796 {
797 	if (!adev || !notify) {
798 		ASSERT(false);
799 		return;
800 	}
801 
802 	const struct dmub_cmd_fused_request *req = &notify->fused_request;
803 	const uint8_t ddc_line = req->u.aux.ddc_line;
804 
805 	if (ddc_line >= ARRAY_SIZE(adev->dm.fused_io)) {
806 		ASSERT(false);
807 		return;
808 	}
809 
810 	struct fused_io_sync *sync = &adev->dm.fused_io[ddc_line];
811 
812 	static_assert(sizeof(*req) <= sizeof(sync->reply_data), "Size mismatch");
813 	memcpy(sync->reply_data, req, sizeof(*req));
814 	complete(&sync->replied);
815 }
816 
817 /**
818  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
819  * @adev: amdgpu_device pointer
820  * @notify: dmub notification structure
821  *
822  * Dmub Hpd interrupt processing callback. Gets displayindex through the
823  * ink index and calls helper to do the processing.
824  */
825 static void dmub_hpd_callback(struct amdgpu_device *adev,
826 			      struct dmub_notification *notify)
827 {
828 	struct amdgpu_dm_connector *aconnector;
829 	struct amdgpu_dm_connector *hpd_aconnector = NULL;
830 	struct drm_connector *connector;
831 	struct drm_connector_list_iter iter;
832 	struct dc_link *link;
833 	u8 link_index = 0;
834 	struct drm_device *dev;
835 
836 	if (adev == NULL)
837 		return;
838 
839 	if (notify == NULL) {
840 		drm_err(adev_to_drm(adev), "DMUB HPD callback notification was NULL");
841 		return;
842 	}
843 
844 	if (notify->link_index > adev->dm.dc->link_count) {
845 		drm_err(adev_to_drm(adev), "DMUB HPD index (%u)is abnormal", notify->link_index);
846 		return;
847 	}
848 
849 	/* Skip DMUB HPD IRQ in suspend/resume. We will probe them later. */
850 	if (notify->type == DMUB_NOTIFICATION_HPD && adev->in_suspend) {
851 		drm_info(adev_to_drm(adev), "Skip DMUB HPD IRQ callback in suspend/resume\n");
852 		return;
853 	}
854 
855 	link_index = notify->link_index;
856 	link = adev->dm.dc->links[link_index];
857 	dev = adev->dm.ddev;
858 
859 	drm_connector_list_iter_begin(dev, &iter);
860 	drm_for_each_connector_iter(connector, &iter) {
861 
862 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
863 			continue;
864 
865 		aconnector = to_amdgpu_dm_connector(connector);
866 		if (link && aconnector->dc_link == link) {
867 			if (notify->type == DMUB_NOTIFICATION_HPD)
868 				drm_info(adev_to_drm(adev), "DMUB HPD IRQ callback: link_index=%u\n", link_index);
869 			else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
870 				drm_info(adev_to_drm(adev), "DMUB HPD RX IRQ callback: link_index=%u\n", link_index);
871 			else
872 				drm_warn(adev_to_drm(adev), "DMUB Unknown HPD callback type %d, link_index=%u\n",
873 						notify->type, link_index);
874 
875 			hpd_aconnector = aconnector;
876 			break;
877 		}
878 	}
879 	drm_connector_list_iter_end(&iter);
880 
881 	if (hpd_aconnector) {
882 		if (notify->type == DMUB_NOTIFICATION_HPD) {
883 			if (hpd_aconnector->dc_link->hpd_status == (notify->hpd_status == DP_HPD_PLUG))
884 				drm_warn(adev_to_drm(adev), "DMUB reported hpd status unchanged. link_index=%u\n", link_index);
885 			handle_hpd_irq_helper(hpd_aconnector);
886 		} else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ) {
887 			handle_hpd_rx_irq(hpd_aconnector);
888 		}
889 	}
890 }
891 
892 /**
893  * dmub_hpd_sense_callback - DMUB HPD sense processing callback.
894  * @adev: amdgpu_device pointer
895  * @notify: dmub notification structure
896  *
897  * HPD sense changes can occur during low power states and need to be
898  * notified from firmware to driver.
899  */
900 static void dmub_hpd_sense_callback(struct amdgpu_device *adev,
901 			      struct dmub_notification *notify)
902 {
903 	drm_dbg_driver(adev_to_drm(adev), "DMUB HPD SENSE callback.\n");
904 }
905 
906 /**
907  * register_dmub_notify_callback - Sets callback for DMUB notify
908  * @adev: amdgpu_device pointer
909  * @type: Type of dmub notification
910  * @callback: Dmub interrupt callback function
911  * @dmub_int_thread_offload: offload indicator
912  *
913  * API to register a dmub callback handler for a dmub notification
914  * Also sets indicator whether callback processing to be offloaded.
915  * to dmub interrupt handling thread
916  * Return: true if successfully registered, false if there is existing registration
917  */
918 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
919 					  enum dmub_notification_type type,
920 					  dmub_notify_interrupt_callback_t callback,
921 					  bool dmub_int_thread_offload)
922 {
923 	if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
924 		adev->dm.dmub_callback[type] = callback;
925 		adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
926 	} else
927 		return false;
928 
929 	return true;
930 }
931 
932 static void dm_handle_hpd_work(struct work_struct *work)
933 {
934 	struct dmub_hpd_work *dmub_hpd_wrk;
935 
936 	dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
937 
938 	if (!dmub_hpd_wrk->dmub_notify) {
939 		drm_err(adev_to_drm(dmub_hpd_wrk->adev), "dmub_hpd_wrk dmub_notify is NULL");
940 		return;
941 	}
942 
943 	if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
944 		dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
945 		dmub_hpd_wrk->dmub_notify);
946 	}
947 
948 	kfree(dmub_hpd_wrk->dmub_notify);
949 	kfree(dmub_hpd_wrk);
950 
951 }
952 
953 static const char *dmub_notification_type_str(enum dmub_notification_type e)
954 {
955 	switch (e) {
956 	case DMUB_NOTIFICATION_NO_DATA:
957 		return "NO_DATA";
958 	case DMUB_NOTIFICATION_AUX_REPLY:
959 		return "AUX_REPLY";
960 	case DMUB_NOTIFICATION_HPD:
961 		return "HPD";
962 	case DMUB_NOTIFICATION_HPD_IRQ:
963 		return "HPD_IRQ";
964 	case DMUB_NOTIFICATION_SET_CONFIG_REPLY:
965 		return "SET_CONFIG_REPLY";
966 	case DMUB_NOTIFICATION_DPIA_NOTIFICATION:
967 		return "DPIA_NOTIFICATION";
968 	case DMUB_NOTIFICATION_HPD_SENSE_NOTIFY:
969 		return "HPD_SENSE_NOTIFY";
970 	case DMUB_NOTIFICATION_FUSED_IO:
971 		return "FUSED_IO";
972 	default:
973 		return "<unknown>";
974 	}
975 }
976 
977 #define DMUB_TRACE_MAX_READ 64
978 /**
979  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
980  * @interrupt_params: used for determining the Outbox instance
981  *
982  * Handles the Outbox Interrupt
983  * event handler.
984  */
985 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
986 {
987 	struct dmub_notification notify = {0};
988 	struct common_irq_params *irq_params = interrupt_params;
989 	struct amdgpu_device *adev = irq_params->adev;
990 	struct amdgpu_display_manager *dm = &adev->dm;
991 	struct dmcub_trace_buf_entry entry = { 0 };
992 	u32 count = 0;
993 	struct dmub_hpd_work *dmub_hpd_wrk;
994 
995 	do {
996 		if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
997 			trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
998 							entry.param0, entry.param1);
999 
1000 			drm_dbg_driver(adev_to_drm(adev), "trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
1001 				 entry.trace_code, entry.tick_count, entry.param0, entry.param1);
1002 		} else
1003 			break;
1004 
1005 		count++;
1006 
1007 	} while (count <= DMUB_TRACE_MAX_READ);
1008 
1009 	if (count > DMUB_TRACE_MAX_READ)
1010 		drm_dbg_driver(adev_to_drm(adev), "Warning : count > DMUB_TRACE_MAX_READ");
1011 
1012 	if (dc_enable_dmub_notifications(adev->dm.dc) &&
1013 		irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
1014 
1015 		do {
1016 			dc_stat_get_dmub_notification(adev->dm.dc, &notify);
1017 			if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
1018 				drm_err(adev_to_drm(adev), "DM: notify type %d invalid!", notify.type);
1019 				continue;
1020 			}
1021 			if (!dm->dmub_callback[notify.type]) {
1022 				drm_warn(adev_to_drm(adev), "DMUB notification skipped due to no handler: type=%s\n",
1023 					dmub_notification_type_str(notify.type));
1024 				continue;
1025 			}
1026 			if (dm->dmub_thread_offload[notify.type] == true) {
1027 				dmub_hpd_wrk = kzalloc(sizeof(*dmub_hpd_wrk), GFP_ATOMIC);
1028 				if (!dmub_hpd_wrk) {
1029 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk");
1030 					return;
1031 				}
1032 				dmub_hpd_wrk->dmub_notify = kmemdup(&notify, sizeof(struct dmub_notification),
1033 								    GFP_ATOMIC);
1034 				if (!dmub_hpd_wrk->dmub_notify) {
1035 					kfree(dmub_hpd_wrk);
1036 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk->dmub_notify");
1037 					return;
1038 				}
1039 				INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
1040 				dmub_hpd_wrk->adev = adev;
1041 				queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
1042 			} else {
1043 				dm->dmub_callback[notify.type](adev, &notify);
1044 			}
1045 		} while (notify.pending_notification);
1046 	}
1047 }
1048 
1049 static int dm_set_clockgating_state(struct amdgpu_ip_block *ip_block,
1050 		  enum amd_clockgating_state state)
1051 {
1052 	return 0;
1053 }
1054 
1055 static int dm_set_powergating_state(struct amdgpu_ip_block *ip_block,
1056 		  enum amd_powergating_state state)
1057 {
1058 	return 0;
1059 }
1060 
1061 /* Prototypes of private functions */
1062 static int dm_early_init(struct amdgpu_ip_block *ip_block);
1063 
1064 /* Allocate memory for FBC compressed data  */
1065 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
1066 {
1067 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
1068 	struct dm_compressor_info *compressor = &adev->dm.compressor;
1069 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
1070 	struct drm_display_mode *mode;
1071 	unsigned long max_size = 0;
1072 
1073 	if (adev->dm.dc->fbc_compressor == NULL)
1074 		return;
1075 
1076 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
1077 		return;
1078 
1079 	if (compressor->bo_ptr)
1080 		return;
1081 
1082 
1083 	list_for_each_entry(mode, &connector->modes, head) {
1084 		if (max_size < (unsigned long) mode->htotal * mode->vtotal)
1085 			max_size = (unsigned long) mode->htotal * mode->vtotal;
1086 	}
1087 
1088 	if (max_size) {
1089 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
1090 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
1091 			    &compressor->gpu_addr, &compressor->cpu_addr);
1092 
1093 		if (r)
1094 			drm_err(adev_to_drm(adev), "DM: Failed to initialize FBC\n");
1095 		else {
1096 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
1097 			drm_info(adev_to_drm(adev), "DM: FBC alloc %lu\n", max_size*4);
1098 		}
1099 
1100 	}
1101 
1102 }
1103 
1104 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
1105 					  int pipe, bool *enabled,
1106 					  unsigned char *buf, int max_bytes)
1107 {
1108 	struct drm_device *dev = dev_get_drvdata(kdev);
1109 	struct amdgpu_device *adev = drm_to_adev(dev);
1110 	struct drm_connector *connector;
1111 	struct drm_connector_list_iter conn_iter;
1112 	struct amdgpu_dm_connector *aconnector;
1113 	int ret = 0;
1114 
1115 	*enabled = false;
1116 
1117 	mutex_lock(&adev->dm.audio_lock);
1118 
1119 	drm_connector_list_iter_begin(dev, &conn_iter);
1120 	drm_for_each_connector_iter(connector, &conn_iter) {
1121 
1122 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1123 			continue;
1124 
1125 		aconnector = to_amdgpu_dm_connector(connector);
1126 		if (aconnector->audio_inst != port)
1127 			continue;
1128 
1129 		*enabled = true;
1130 		mutex_lock(&connector->eld_mutex);
1131 		ret = drm_eld_size(connector->eld);
1132 		memcpy(buf, connector->eld, min(max_bytes, ret));
1133 		mutex_unlock(&connector->eld_mutex);
1134 
1135 		break;
1136 	}
1137 	drm_connector_list_iter_end(&conn_iter);
1138 
1139 	mutex_unlock(&adev->dm.audio_lock);
1140 
1141 	drm_dbg_kms(adev_to_drm(adev), "Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
1142 
1143 	return ret;
1144 }
1145 
1146 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
1147 	.get_eld = amdgpu_dm_audio_component_get_eld,
1148 };
1149 
1150 static int amdgpu_dm_audio_component_bind(struct device *kdev,
1151 				       struct device *hda_kdev, void *data)
1152 {
1153 	struct drm_device *dev = dev_get_drvdata(kdev);
1154 	struct amdgpu_device *adev = drm_to_adev(dev);
1155 	struct drm_audio_component *acomp = data;
1156 
1157 	acomp->ops = &amdgpu_dm_audio_component_ops;
1158 	acomp->dev = kdev;
1159 	adev->dm.audio_component = acomp;
1160 
1161 	return 0;
1162 }
1163 
1164 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
1165 					  struct device *hda_kdev, void *data)
1166 {
1167 	struct amdgpu_device *adev = drm_to_adev(dev_get_drvdata(kdev));
1168 	struct drm_audio_component *acomp = data;
1169 
1170 	acomp->ops = NULL;
1171 	acomp->dev = NULL;
1172 	adev->dm.audio_component = NULL;
1173 }
1174 
1175 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
1176 	.bind	= amdgpu_dm_audio_component_bind,
1177 	.unbind	= amdgpu_dm_audio_component_unbind,
1178 };
1179 
1180 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
1181 {
1182 	int i, ret;
1183 
1184 	if (!amdgpu_audio)
1185 		return 0;
1186 
1187 	adev->mode_info.audio.enabled = true;
1188 
1189 	adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
1190 
1191 	for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
1192 		adev->mode_info.audio.pin[i].channels = -1;
1193 		adev->mode_info.audio.pin[i].rate = -1;
1194 		adev->mode_info.audio.pin[i].bits_per_sample = -1;
1195 		adev->mode_info.audio.pin[i].status_bits = 0;
1196 		adev->mode_info.audio.pin[i].category_code = 0;
1197 		adev->mode_info.audio.pin[i].connected = false;
1198 		adev->mode_info.audio.pin[i].id =
1199 			adev->dm.dc->res_pool->audios[i]->inst;
1200 		adev->mode_info.audio.pin[i].offset = 0;
1201 	}
1202 
1203 	ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1204 	if (ret < 0)
1205 		return ret;
1206 
1207 	adev->dm.audio_registered = true;
1208 
1209 	return 0;
1210 }
1211 
1212 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
1213 {
1214 	if (!amdgpu_audio)
1215 		return;
1216 
1217 	if (!adev->mode_info.audio.enabled)
1218 		return;
1219 
1220 	if (adev->dm.audio_registered) {
1221 		component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1222 		adev->dm.audio_registered = false;
1223 	}
1224 
1225 	/* TODO: Disable audio? */
1226 
1227 	adev->mode_info.audio.enabled = false;
1228 }
1229 
1230 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
1231 {
1232 	struct drm_audio_component *acomp = adev->dm.audio_component;
1233 
1234 	if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
1235 		drm_dbg_kms(adev_to_drm(adev), "Notify ELD: %d\n", pin);
1236 
1237 		acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1238 						 pin, -1);
1239 	}
1240 }
1241 
1242 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1243 {
1244 	const struct dmcub_firmware_header_v1_0 *hdr;
1245 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1246 	struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1247 	const struct firmware *dmub_fw = adev->dm.dmub_fw;
1248 	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1249 	struct abm *abm = adev->dm.dc->res_pool->abm;
1250 	struct dc_context *ctx = adev->dm.dc->ctx;
1251 	struct dmub_srv_hw_params hw_params;
1252 	enum dmub_status status;
1253 	const unsigned char *fw_inst_const, *fw_bss_data;
1254 	u32 i, fw_inst_const_size, fw_bss_data_size;
1255 	bool has_hw_support;
1256 
1257 	if (!dmub_srv)
1258 		/* DMUB isn't supported on the ASIC. */
1259 		return 0;
1260 
1261 	if (!fb_info) {
1262 		drm_err(adev_to_drm(adev), "No framebuffer info for DMUB service.\n");
1263 		return -EINVAL;
1264 	}
1265 
1266 	if (!dmub_fw) {
1267 		/* Firmware required for DMUB support. */
1268 		drm_err(adev_to_drm(adev), "No firmware provided for DMUB.\n");
1269 		return -EINVAL;
1270 	}
1271 
1272 	/* initialize register offsets for ASICs with runtime initialization available */
1273 	if (dmub_srv->hw_funcs.init_reg_offsets)
1274 		dmub_srv->hw_funcs.init_reg_offsets(dmub_srv, ctx);
1275 
1276 	status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1277 	if (status != DMUB_STATUS_OK) {
1278 		drm_err(adev_to_drm(adev), "Error checking HW support for DMUB: %d\n", status);
1279 		return -EINVAL;
1280 	}
1281 
1282 	if (!has_hw_support) {
1283 		drm_info(adev_to_drm(adev), "DMUB unsupported on ASIC\n");
1284 		return 0;
1285 	}
1286 
1287 	/* Reset DMCUB if it was previously running - before we overwrite its memory. */
1288 	status = dmub_srv_hw_reset(dmub_srv);
1289 	if (status != DMUB_STATUS_OK)
1290 		drm_warn(adev_to_drm(adev), "Error resetting DMUB HW: %d\n", status);
1291 
1292 	hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1293 
1294 	fw_inst_const = dmub_fw->data +
1295 			le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1296 			PSP_HEADER_BYTES_256;
1297 
1298 	fw_bss_data = dmub_fw->data +
1299 		      le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1300 		      le32_to_cpu(hdr->inst_const_bytes);
1301 
1302 	/* Copy firmware and bios info into FB memory. */
1303 	fw_inst_const_size = adev->dm.fw_inst_size;
1304 
1305 	fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1306 
1307 	/* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1308 	 * amdgpu_ucode_init_single_fw will load dmub firmware
1309 	 * fw_inst_const part to cw0; otherwise, the firmware back door load
1310 	 * will be done by dm_dmub_hw_init
1311 	 */
1312 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1313 		memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1314 				fw_inst_const_size);
1315 	}
1316 
1317 	if (fw_bss_data_size)
1318 		memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1319 		       fw_bss_data, fw_bss_data_size);
1320 
1321 	/* Copy firmware bios info into FB memory. */
1322 	memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1323 	       adev->bios_size);
1324 
1325 	/* Reset regions that need to be reset. */
1326 	memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1327 	fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1328 
1329 	memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1330 	       fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1331 
1332 	memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1333 	       fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1334 
1335 	memset(fb_info->fb[DMUB_WINDOW_SHARED_STATE].cpu_addr, 0,
1336 	       fb_info->fb[DMUB_WINDOW_SHARED_STATE].size);
1337 
1338 	/* Initialize hardware. */
1339 	memset(&hw_params, 0, sizeof(hw_params));
1340 	hw_params.soc_fb_info.fb_base = adev->gmc.fb_start;
1341 	hw_params.soc_fb_info.fb_offset = adev->vm_manager.vram_base_offset;
1342 
1343 	/* backdoor load firmware and trigger dmub running */
1344 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1345 		hw_params.load_inst_const = true;
1346 
1347 	if (dmcu)
1348 		hw_params.psp_version = dmcu->psp_version;
1349 
1350 	for (i = 0; i < fb_info->num_fb; ++i)
1351 		hw_params.fb[i] = &fb_info->fb[i];
1352 
1353 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1354 	case IP_VERSION(3, 1, 3):
1355 	case IP_VERSION(3, 1, 4):
1356 	case IP_VERSION(3, 5, 0):
1357 	case IP_VERSION(3, 5, 1):
1358 	case IP_VERSION(3, 6, 0):
1359 	case IP_VERSION(4, 0, 1):
1360 		hw_params.dpia_supported = true;
1361 		hw_params.disable_dpia = adev->dm.dc->debug.dpia_debug.bits.disable_dpia;
1362 		break;
1363 	default:
1364 		break;
1365 	}
1366 
1367 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1368 	case IP_VERSION(3, 5, 0):
1369 	case IP_VERSION(3, 5, 1):
1370 	case IP_VERSION(3, 6, 0):
1371 		hw_params.ips_sequential_ono = adev->external_rev_id > 0x10;
1372 		hw_params.lower_hbr3_phy_ssc = true;
1373 		break;
1374 	default:
1375 		break;
1376 	}
1377 
1378 	status = dmub_srv_hw_init(dmub_srv, &hw_params);
1379 	if (status != DMUB_STATUS_OK) {
1380 		drm_err(adev_to_drm(adev), "Error initializing DMUB HW: %d\n", status);
1381 		return -EINVAL;
1382 	}
1383 
1384 	/* Wait for firmware load to finish. */
1385 	status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1386 	if (status != DMUB_STATUS_OK)
1387 		drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1388 
1389 	/* Init DMCU and ABM if available. */
1390 	if (dmcu && abm) {
1391 		dmcu->funcs->dmcu_init(dmcu);
1392 		abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1393 	}
1394 
1395 	if (!adev->dm.dc->ctx->dmub_srv)
1396 		adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1397 	if (!adev->dm.dc->ctx->dmub_srv) {
1398 		drm_err(adev_to_drm(adev), "Couldn't allocate DC DMUB server!\n");
1399 		return -ENOMEM;
1400 	}
1401 
1402 	drm_info(adev_to_drm(adev), "DMUB hardware initialized: version=0x%08X\n",
1403 		 adev->dm.dmcub_fw_version);
1404 
1405 	/* Keeping sanity checks off if
1406 	 * DCN31 >= 4.0.59.0
1407 	 * DCN314 >= 8.0.16.0
1408 	 * Otherwise, turn on sanity checks
1409 	 */
1410 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1411 	case IP_VERSION(3, 1, 2):
1412 	case IP_VERSION(3, 1, 3):
1413 		if (adev->dm.dmcub_fw_version &&
1414 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1415 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(4, 0, 59))
1416 				adev->dm.dc->debug.sanity_checks = true;
1417 		break;
1418 	case IP_VERSION(3, 1, 4):
1419 		if (adev->dm.dmcub_fw_version &&
1420 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1421 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(8, 0, 16))
1422 				adev->dm.dc->debug.sanity_checks = true;
1423 		break;
1424 	default:
1425 		break;
1426 	}
1427 
1428 	return 0;
1429 }
1430 
1431 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1432 {
1433 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1434 	enum dmub_status status;
1435 	bool init;
1436 	int r;
1437 
1438 	if (!dmub_srv) {
1439 		/* DMUB isn't supported on the ASIC. */
1440 		return;
1441 	}
1442 
1443 	status = dmub_srv_is_hw_init(dmub_srv, &init);
1444 	if (status != DMUB_STATUS_OK)
1445 		drm_warn(adev_to_drm(adev), "DMUB hardware init check failed: %d\n", status);
1446 
1447 	if (status == DMUB_STATUS_OK && init) {
1448 		/* Wait for firmware load to finish. */
1449 		status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1450 		if (status != DMUB_STATUS_OK)
1451 			drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1452 	} else {
1453 		/* Perform the full hardware initialization. */
1454 		r = dm_dmub_hw_init(adev);
1455 		if (r)
1456 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
1457 	}
1458 }
1459 
1460 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1461 {
1462 	u64 pt_base;
1463 	u32 logical_addr_low;
1464 	u32 logical_addr_high;
1465 	u32 agp_base, agp_bot, agp_top;
1466 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1467 
1468 	memset(pa_config, 0, sizeof(*pa_config));
1469 
1470 	agp_base = 0;
1471 	agp_bot = adev->gmc.agp_start >> 24;
1472 	agp_top = adev->gmc.agp_end >> 24;
1473 
1474 	/* AGP aperture is disabled */
1475 	if (agp_bot > agp_top) {
1476 		logical_addr_low = adev->gmc.fb_start >> 18;
1477 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1478 				       AMD_APU_IS_RENOIR |
1479 				       AMD_APU_IS_GREEN_SARDINE))
1480 			/*
1481 			 * Raven2 has a HW issue that it is unable to use the vram which
1482 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1483 			 * workaround that increase system aperture high address (add 1)
1484 			 * to get rid of the VM fault and hardware hang.
1485 			 */
1486 			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
1487 		else
1488 			logical_addr_high = adev->gmc.fb_end >> 18;
1489 	} else {
1490 		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1491 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1492 				       AMD_APU_IS_RENOIR |
1493 				       AMD_APU_IS_GREEN_SARDINE))
1494 			/*
1495 			 * Raven2 has a HW issue that it is unable to use the vram which
1496 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1497 			 * workaround that increase system aperture high address (add 1)
1498 			 * to get rid of the VM fault and hardware hang.
1499 			 */
1500 			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1501 		else
1502 			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1503 	}
1504 
1505 	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1506 
1507 	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
1508 						   AMDGPU_GPU_PAGE_SHIFT);
1509 	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
1510 						  AMDGPU_GPU_PAGE_SHIFT);
1511 	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
1512 						 AMDGPU_GPU_PAGE_SHIFT);
1513 	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
1514 						AMDGPU_GPU_PAGE_SHIFT);
1515 	page_table_base.high_part = upper_32_bits(pt_base);
1516 	page_table_base.low_part = lower_32_bits(pt_base);
1517 
1518 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1519 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1520 
1521 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
1522 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1523 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1524 
1525 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1526 	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
1527 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1528 
1529 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1530 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1531 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1532 
1533 	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
1534 
1535 }
1536 
1537 static void force_connector_state(
1538 	struct amdgpu_dm_connector *aconnector,
1539 	enum drm_connector_force force_state)
1540 {
1541 	struct drm_connector *connector = &aconnector->base;
1542 
1543 	mutex_lock(&connector->dev->mode_config.mutex);
1544 	aconnector->base.force = force_state;
1545 	mutex_unlock(&connector->dev->mode_config.mutex);
1546 
1547 	mutex_lock(&aconnector->hpd_lock);
1548 	drm_kms_helper_connector_hotplug_event(connector);
1549 	mutex_unlock(&aconnector->hpd_lock);
1550 }
1551 
1552 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1553 {
1554 	struct hpd_rx_irq_offload_work *offload_work;
1555 	struct amdgpu_dm_connector *aconnector;
1556 	struct dc_link *dc_link;
1557 	struct amdgpu_device *adev;
1558 	enum dc_connection_type new_connection_type = dc_connection_none;
1559 	unsigned long flags;
1560 	union test_response test_response;
1561 
1562 	memset(&test_response, 0, sizeof(test_response));
1563 
1564 	offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1565 	aconnector = offload_work->offload_wq->aconnector;
1566 	adev = offload_work->adev;
1567 
1568 	if (!aconnector) {
1569 		drm_err(adev_to_drm(adev), "Can't retrieve aconnector in hpd_rx_irq_offload_work");
1570 		goto skip;
1571 	}
1572 
1573 	dc_link = aconnector->dc_link;
1574 
1575 	mutex_lock(&aconnector->hpd_lock);
1576 	if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
1577 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
1578 	mutex_unlock(&aconnector->hpd_lock);
1579 
1580 	if (new_connection_type == dc_connection_none)
1581 		goto skip;
1582 
1583 	if (amdgpu_in_reset(adev))
1584 		goto skip;
1585 
1586 	if (offload_work->data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
1587 		offload_work->data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
1588 		dm_handle_mst_sideband_msg_ready_event(&aconnector->mst_mgr, DOWN_OR_UP_MSG_RDY_EVENT);
1589 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1590 		offload_work->offload_wq->is_handling_mst_msg_rdy_event = false;
1591 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1592 		goto skip;
1593 	}
1594 
1595 	mutex_lock(&adev->dm.dc_lock);
1596 	if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
1597 		dc_link_dp_handle_automated_test(dc_link);
1598 
1599 		if (aconnector->timing_changed) {
1600 			/* force connector disconnect and reconnect */
1601 			force_connector_state(aconnector, DRM_FORCE_OFF);
1602 			msleep(100);
1603 			force_connector_state(aconnector, DRM_FORCE_UNSPECIFIED);
1604 		}
1605 
1606 		test_response.bits.ACK = 1;
1607 
1608 		core_link_write_dpcd(
1609 		dc_link,
1610 		DP_TEST_RESPONSE,
1611 		&test_response.raw,
1612 		sizeof(test_response));
1613 	} else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1614 			dc_link_check_link_loss_status(dc_link, &offload_work->data) &&
1615 			dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1616 		/* offload_work->data is from handle_hpd_rx_irq->
1617 		 * schedule_hpd_rx_offload_work.this is defer handle
1618 		 * for hpd short pulse. upon here, link status may be
1619 		 * changed, need get latest link status from dpcd
1620 		 * registers. if link status is good, skip run link
1621 		 * training again.
1622 		 */
1623 		union hpd_irq_data irq_data;
1624 
1625 		memset(&irq_data, 0, sizeof(irq_data));
1626 
1627 		/* before dc_link_dp_handle_link_loss, allow new link lost handle
1628 		 * request be added to work queue if link lost at end of dc_link_
1629 		 * dp_handle_link_loss
1630 		 */
1631 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1632 		offload_work->offload_wq->is_handling_link_loss = false;
1633 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1634 
1635 		if ((dc_link_dp_read_hpd_rx_irq_data(dc_link, &irq_data) == DC_OK) &&
1636 			dc_link_check_link_loss_status(dc_link, &irq_data))
1637 			dc_link_dp_handle_link_loss(dc_link);
1638 	}
1639 	mutex_unlock(&adev->dm.dc_lock);
1640 
1641 skip:
1642 	kfree(offload_work);
1643 
1644 }
1645 
1646 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct amdgpu_device *adev)
1647 {
1648 	struct dc *dc = adev->dm.dc;
1649 	int max_caps = dc->caps.max_links;
1650 	int i = 0;
1651 	struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1652 
1653 	hpd_rx_offload_wq = kcalloc(max_caps, sizeof(*hpd_rx_offload_wq), GFP_KERNEL);
1654 
1655 	if (!hpd_rx_offload_wq)
1656 		return NULL;
1657 
1658 
1659 	for (i = 0; i < max_caps; i++) {
1660 		hpd_rx_offload_wq[i].wq =
1661 				    create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1662 
1663 		if (hpd_rx_offload_wq[i].wq == NULL) {
1664 			drm_err(adev_to_drm(adev), "create amdgpu_dm_hpd_rx_offload_wq fail!");
1665 			goto out_err;
1666 		}
1667 
1668 		spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
1669 	}
1670 
1671 	return hpd_rx_offload_wq;
1672 
1673 out_err:
1674 	for (i = 0; i < max_caps; i++) {
1675 		if (hpd_rx_offload_wq[i].wq)
1676 			destroy_workqueue(hpd_rx_offload_wq[i].wq);
1677 	}
1678 	kfree(hpd_rx_offload_wq);
1679 	return NULL;
1680 }
1681 
1682 struct amdgpu_stutter_quirk {
1683 	u16 chip_vendor;
1684 	u16 chip_device;
1685 	u16 subsys_vendor;
1686 	u16 subsys_device;
1687 	u8 revision;
1688 };
1689 
1690 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1691 	/* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1692 	{ 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1693 	{ 0, 0, 0, 0, 0 },
1694 };
1695 
1696 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1697 {
1698 	const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1699 
1700 	while (p && p->chip_device != 0) {
1701 		if (pdev->vendor == p->chip_vendor &&
1702 		    pdev->device == p->chip_device &&
1703 		    pdev->subsystem_vendor == p->subsys_vendor &&
1704 		    pdev->subsystem_device == p->subsys_device &&
1705 		    pdev->revision == p->revision) {
1706 			return true;
1707 		}
1708 		++p;
1709 	}
1710 	return false;
1711 }
1712 
1713 
1714 void*
1715 dm_allocate_gpu_mem(
1716 		struct amdgpu_device *adev,
1717 		enum dc_gpu_mem_alloc_type type,
1718 		size_t size,
1719 		long long *addr)
1720 {
1721 	struct dal_allocation *da;
1722 	u32 domain = (type == DC_MEM_ALLOC_TYPE_GART) ?
1723 		AMDGPU_GEM_DOMAIN_GTT : AMDGPU_GEM_DOMAIN_VRAM;
1724 	int ret;
1725 
1726 	da = kzalloc(sizeof(struct dal_allocation), GFP_KERNEL);
1727 	if (!da)
1728 		return NULL;
1729 
1730 	ret = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
1731 				      domain, &da->bo,
1732 				      &da->gpu_addr, &da->cpu_ptr);
1733 
1734 	*addr = da->gpu_addr;
1735 
1736 	if (ret) {
1737 		kfree(da);
1738 		return NULL;
1739 	}
1740 
1741 	/* add da to list in dm */
1742 	list_add(&da->list, &adev->dm.da_list);
1743 
1744 	return da->cpu_ptr;
1745 }
1746 
1747 void
1748 dm_free_gpu_mem(
1749 		struct amdgpu_device *adev,
1750 		enum dc_gpu_mem_alloc_type type,
1751 		void *pvMem)
1752 {
1753 	struct dal_allocation *da;
1754 
1755 	/* walk the da list in DM */
1756 	list_for_each_entry(da, &adev->dm.da_list, list) {
1757 		if (pvMem == da->cpu_ptr) {
1758 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
1759 			list_del(&da->list);
1760 			kfree(da);
1761 			break;
1762 		}
1763 	}
1764 
1765 }
1766 
1767 static enum dmub_status
1768 dm_dmub_send_vbios_gpint_command(struct amdgpu_device *adev,
1769 				 enum dmub_gpint_command command_code,
1770 				 uint16_t param,
1771 				 uint32_t timeout_us)
1772 {
1773 	union dmub_gpint_data_register reg, test;
1774 	uint32_t i;
1775 
1776 	/* Assume that VBIOS DMUB is ready to take commands */
1777 
1778 	reg.bits.status = 1;
1779 	reg.bits.command_code = command_code;
1780 	reg.bits.param = param;
1781 
1782 	cgs_write_register(adev->dm.cgs_device, 0x34c0 + 0x01f8, reg.all);
1783 
1784 	for (i = 0; i < timeout_us; ++i) {
1785 		udelay(1);
1786 
1787 		/* Check if our GPINT got acked */
1788 		reg.bits.status = 0;
1789 		test = (union dmub_gpint_data_register)
1790 			cgs_read_register(adev->dm.cgs_device, 0x34c0 + 0x01f8);
1791 
1792 		if (test.all == reg.all)
1793 			return DMUB_STATUS_OK;
1794 	}
1795 
1796 	return DMUB_STATUS_TIMEOUT;
1797 }
1798 
1799 static void *dm_dmub_get_vbios_bounding_box(struct amdgpu_device *adev)
1800 {
1801 	void *bb;
1802 	long long addr;
1803 	unsigned int bb_size;
1804 	int i = 0;
1805 	uint16_t chunk;
1806 	enum dmub_gpint_command send_addrs[] = {
1807 		DMUB_GPINT__SET_BB_ADDR_WORD0,
1808 		DMUB_GPINT__SET_BB_ADDR_WORD1,
1809 		DMUB_GPINT__SET_BB_ADDR_WORD2,
1810 		DMUB_GPINT__SET_BB_ADDR_WORD3,
1811 	};
1812 	enum dmub_status ret;
1813 
1814 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1815 	case IP_VERSION(4, 0, 1):
1816 		bb_size = sizeof(struct dml2_soc_bb);
1817 		break;
1818 	default:
1819 		return NULL;
1820 	}
1821 
1822 	bb =  dm_allocate_gpu_mem(adev,
1823 				  DC_MEM_ALLOC_TYPE_GART,
1824 				  bb_size,
1825 				  &addr);
1826 	if (!bb)
1827 		return NULL;
1828 
1829 	for (i = 0; i < 4; i++) {
1830 		/* Extract 16-bit chunk */
1831 		chunk = ((uint64_t) addr >> (i * 16)) & 0xFFFF;
1832 		/* Send the chunk */
1833 		ret = dm_dmub_send_vbios_gpint_command(adev, send_addrs[i], chunk, 30000);
1834 		if (ret != DMUB_STATUS_OK)
1835 			goto free_bb;
1836 	}
1837 
1838 	/* Now ask DMUB to copy the bb */
1839 	ret = dm_dmub_send_vbios_gpint_command(adev, DMUB_GPINT__BB_COPY, 1, 200000);
1840 	if (ret != DMUB_STATUS_OK)
1841 		goto free_bb;
1842 
1843 	return bb;
1844 
1845 free_bb:
1846 	dm_free_gpu_mem(adev, DC_MEM_ALLOC_TYPE_GART, (void *) bb);
1847 	return NULL;
1848 
1849 }
1850 
1851 static enum dmub_ips_disable_type dm_get_default_ips_mode(
1852 	struct amdgpu_device *adev)
1853 {
1854 	enum dmub_ips_disable_type ret = DMUB_IPS_ENABLE;
1855 
1856 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1857 	case IP_VERSION(3, 5, 0):
1858 	case IP_VERSION(3, 6, 0):
1859 	case IP_VERSION(3, 5, 1):
1860 		ret =  DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
1861 		break;
1862 	default:
1863 		/* ASICs older than DCN35 do not have IPSs */
1864 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 5, 0))
1865 			ret = DMUB_IPS_DISABLE_ALL;
1866 		break;
1867 	}
1868 
1869 	return ret;
1870 }
1871 
1872 static int amdgpu_dm_init(struct amdgpu_device *adev)
1873 {
1874 	struct dc_init_data init_data;
1875 	struct dc_callback_init init_params;
1876 	int r;
1877 
1878 	adev->dm.ddev = adev_to_drm(adev);
1879 	adev->dm.adev = adev;
1880 
1881 	/* Zero all the fields */
1882 	memset(&init_data, 0, sizeof(init_data));
1883 	memset(&init_params, 0, sizeof(init_params));
1884 
1885 	mutex_init(&adev->dm.dpia_aux_lock);
1886 	mutex_init(&adev->dm.dc_lock);
1887 	mutex_init(&adev->dm.audio_lock);
1888 
1889 	if (amdgpu_dm_irq_init(adev)) {
1890 		drm_err(adev_to_drm(adev), "failed to initialize DM IRQ support.\n");
1891 		goto error;
1892 	}
1893 
1894 	init_data.asic_id.chip_family = adev->family;
1895 
1896 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
1897 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
1898 	init_data.asic_id.chip_id = adev->pdev->device;
1899 
1900 	init_data.asic_id.vram_width = adev->gmc.vram_width;
1901 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
1902 	init_data.asic_id.atombios_base_address =
1903 		adev->mode_info.atom_context->bios;
1904 
1905 	init_data.driver = adev;
1906 
1907 	/* cgs_device was created in dm_sw_init() */
1908 	init_data.cgs_device = adev->dm.cgs_device;
1909 
1910 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
1911 
1912 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1913 	case IP_VERSION(2, 1, 0):
1914 		switch (adev->dm.dmcub_fw_version) {
1915 		case 0: /* development */
1916 		case 0x1: /* linux-firmware.git hash 6d9f399 */
1917 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
1918 			init_data.flags.disable_dmcu = false;
1919 			break;
1920 		default:
1921 			init_data.flags.disable_dmcu = true;
1922 		}
1923 		break;
1924 	case IP_VERSION(2, 0, 3):
1925 		init_data.flags.disable_dmcu = true;
1926 		break;
1927 	default:
1928 		break;
1929 	}
1930 
1931 	/* APU support S/G display by default except:
1932 	 * ASICs before Carrizo,
1933 	 * RAVEN1 (Users reported stability issue)
1934 	 */
1935 
1936 	if (adev->asic_type < CHIP_CARRIZO) {
1937 		init_data.flags.gpu_vm_support = false;
1938 	} else if (adev->asic_type == CHIP_RAVEN) {
1939 		if (adev->apu_flags & AMD_APU_IS_RAVEN)
1940 			init_data.flags.gpu_vm_support = false;
1941 		else
1942 			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
1943 	} else {
1944 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(2, 0, 3))
1945 			init_data.flags.gpu_vm_support = (amdgpu_sg_display == 1);
1946 		else
1947 			init_data.flags.gpu_vm_support =
1948 				(amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
1949 	}
1950 
1951 	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
1952 
1953 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
1954 		init_data.flags.fbc_support = true;
1955 
1956 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
1957 		init_data.flags.multi_mon_pp_mclk_switch = true;
1958 
1959 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
1960 		init_data.flags.disable_fractional_pwm = true;
1961 
1962 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
1963 		init_data.flags.edp_no_power_sequencing = true;
1964 
1965 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
1966 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
1967 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
1968 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
1969 
1970 	init_data.flags.seamless_boot_edp_requested = false;
1971 
1972 	if (amdgpu_device_seamless_boot_supported(adev)) {
1973 		init_data.flags.seamless_boot_edp_requested = true;
1974 		init_data.flags.allow_seamless_boot_optimization = true;
1975 		drm_dbg(adev->dm.ddev, "Seamless boot requested\n");
1976 	}
1977 
1978 	init_data.flags.enable_mipi_converter_optimization = true;
1979 
1980 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
1981 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
1982 	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
1983 
1984 	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
1985 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
1986 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS_DYNAMIC)
1987 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_DYNAMIC;
1988 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS2_DYNAMIC)
1989 		init_data.flags.disable_ips = DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
1990 	else if (amdgpu_dc_debug_mask & DC_FORCE_IPS_ENABLE)
1991 		init_data.flags.disable_ips = DMUB_IPS_ENABLE;
1992 	else
1993 		init_data.flags.disable_ips = dm_get_default_ips_mode(adev);
1994 
1995 	init_data.flags.disable_ips_in_vpb = 0;
1996 
1997 	/* DCN35 and above supports dynamic DTBCLK switch */
1998 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 5, 0))
1999 		init_data.flags.allow_0_dtb_clk = true;
2000 
2001 	/* Enable DWB for tested platforms only */
2002 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
2003 		init_data.num_virtual_links = 1;
2004 
2005 	retrieve_dmi_info(&adev->dm);
2006 	if (adev->dm.edp0_on_dp1_quirk)
2007 		init_data.flags.support_edp0_on_dp1 = true;
2008 
2009 	if (adev->dm.bb_from_dmub)
2010 		init_data.bb_from_dmub = adev->dm.bb_from_dmub;
2011 	else
2012 		init_data.bb_from_dmub = NULL;
2013 
2014 	/* Display Core create. */
2015 	adev->dm.dc = dc_create(&init_data);
2016 
2017 	if (adev->dm.dc) {
2018 		drm_info(adev_to_drm(adev), "Display Core v%s initialized on %s\n", DC_VER,
2019 			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
2020 	} else {
2021 		drm_info(adev_to_drm(adev), "Display Core failed to initialize with v%s!\n", DC_VER);
2022 		goto error;
2023 	}
2024 
2025 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
2026 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
2027 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
2028 	}
2029 
2030 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2031 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2032 	if (dm_should_disable_stutter(adev->pdev))
2033 		adev->dm.dc->debug.disable_stutter = true;
2034 
2035 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
2036 		adev->dm.dc->debug.disable_stutter = true;
2037 
2038 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
2039 		adev->dm.dc->debug.disable_dsc = true;
2040 
2041 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
2042 		adev->dm.dc->debug.disable_clock_gate = true;
2043 
2044 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
2045 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
2046 
2047 	if (amdgpu_dc_debug_mask & DC_DISABLE_SUBVP_FAMS) {
2048 		adev->dm.dc->debug.force_disable_subvp = true;
2049 		adev->dm.dc->debug.fams2_config.bits.enable = false;
2050 	}
2051 
2052 	if (amdgpu_dc_debug_mask & DC_ENABLE_DML2) {
2053 		adev->dm.dc->debug.using_dml2 = true;
2054 		adev->dm.dc->debug.using_dml21 = true;
2055 	}
2056 
2057 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_FORCE_FW_ENABLE)
2058 		adev->dm.dc->debug.hdcp_lc_force_fw_enable = true;
2059 
2060 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_ENABLE_SW_FALLBACK)
2061 		adev->dm.dc->debug.hdcp_lc_enable_sw_fallback = true;
2062 
2063 	if (amdgpu_dc_debug_mask & DC_SKIP_DETECTION_LT)
2064 		adev->dm.dc->debug.skip_detection_link_training = true;
2065 
2066 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
2067 
2068 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
2069 	adev->dm.dc->debug.ignore_cable_id = true;
2070 
2071 	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
2072 		drm_info(adev_to_drm(adev), "DP-HDMI FRL PCON supported\n");
2073 
2074 	r = dm_dmub_hw_init(adev);
2075 	if (r) {
2076 		drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
2077 		goto error;
2078 	}
2079 
2080 	dc_hardware_init(adev->dm.dc);
2081 
2082 	adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev);
2083 	if (!adev->dm.hpd_rx_offload_wq) {
2084 		drm_err(adev_to_drm(adev), "failed to create hpd rx offload workqueue.\n");
2085 		goto error;
2086 	}
2087 
2088 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
2089 		struct dc_phy_addr_space_config pa_config;
2090 
2091 		mmhub_read_system_context(adev, &pa_config);
2092 
2093 		// Call the DC init_memory func
2094 		dc_setup_system_context(adev->dm.dc, &pa_config);
2095 	}
2096 
2097 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
2098 	if (!adev->dm.freesync_module) {
2099 		drm_err(adev_to_drm(adev),
2100 		"failed to initialize freesync_module.\n");
2101 	} else
2102 		drm_dbg_driver(adev_to_drm(adev), "freesync_module init done %p.\n",
2103 				adev->dm.freesync_module);
2104 
2105 	amdgpu_dm_init_color_mod();
2106 
2107 	if (adev->dm.dc->caps.max_links > 0) {
2108 		adev->dm.vblank_control_workqueue =
2109 			create_singlethread_workqueue("dm_vblank_control_workqueue");
2110 		if (!adev->dm.vblank_control_workqueue)
2111 			drm_err(adev_to_drm(adev), "failed to initialize vblank_workqueue.\n");
2112 	}
2113 
2114 	if (adev->dm.dc->caps.ips_support &&
2115 	    adev->dm.dc->config.disable_ips != DMUB_IPS_DISABLE_ALL)
2116 		adev->dm.idle_workqueue = idle_create_workqueue(adev);
2117 
2118 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
2119 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
2120 
2121 		if (!adev->dm.hdcp_workqueue)
2122 			drm_err(adev_to_drm(adev), "failed to initialize hdcp_workqueue.\n");
2123 		else
2124 			drm_dbg_driver(adev_to_drm(adev),
2125 				       "hdcp_workqueue init done %p.\n",
2126 				       adev->dm.hdcp_workqueue);
2127 
2128 		dc_init_callbacks(adev->dm.dc, &init_params);
2129 	}
2130 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2131 		init_completion(&adev->dm.dmub_aux_transfer_done);
2132 		adev->dm.dmub_notify = kzalloc(sizeof(struct dmub_notification), GFP_KERNEL);
2133 		if (!adev->dm.dmub_notify) {
2134 			drm_info(adev_to_drm(adev), "fail to allocate adev->dm.dmub_notify");
2135 			goto error;
2136 		}
2137 
2138 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
2139 		if (!adev->dm.delayed_hpd_wq) {
2140 			drm_err(adev_to_drm(adev), "failed to create hpd offload workqueue.\n");
2141 			goto error;
2142 		}
2143 
2144 		amdgpu_dm_outbox_init(adev);
2145 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
2146 			dmub_aux_setconfig_callback, false)) {
2147 			drm_err(adev_to_drm(adev), "fail to register dmub aux callback");
2148 			goto error;
2149 		}
2150 
2151 		for (size_t i = 0; i < ARRAY_SIZE(adev->dm.fused_io); i++)
2152 			init_completion(&adev->dm.fused_io[i].replied);
2153 
2154 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_FUSED_IO,
2155 			dmub_aux_fused_io_callback, false)) {
2156 			drm_err(adev_to_drm(adev), "fail to register dmub fused io callback");
2157 			goto error;
2158 		}
2159 		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
2160 		 * It is expected that DMUB will resend any pending notifications at this point. Note
2161 		 * that hpd and hpd_irq handler registration are deferred to register_hpd_handlers() to
2162 		 * align legacy interface initialization sequence. Connection status will be proactivly
2163 		 * detected once in the amdgpu_dm_initialize_drm_device.
2164 		 */
2165 		dc_enable_dmub_outbox(adev->dm.dc);
2166 
2167 		/* DPIA trace goes to dmesg logs only if outbox is enabled */
2168 		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
2169 			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
2170 	}
2171 
2172 	if (amdgpu_dm_initialize_drm_device(adev)) {
2173 		drm_err(adev_to_drm(adev),
2174 		"failed to initialize sw for display support.\n");
2175 		goto error;
2176 	}
2177 
2178 	/* create fake encoders for MST */
2179 	dm_dp_create_fake_mst_encoders(adev);
2180 
2181 	/* TODO: Add_display_info? */
2182 
2183 	/* TODO use dynamic cursor width */
2184 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
2185 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
2186 
2187 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
2188 		drm_err(adev_to_drm(adev),
2189 		"failed to initialize vblank for display support.\n");
2190 		goto error;
2191 	}
2192 
2193 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2194 	amdgpu_dm_crtc_secure_display_create_contexts(adev);
2195 	if (!adev->dm.secure_display_ctx.crtc_ctx)
2196 		drm_err(adev_to_drm(adev), "failed to initialize secure display contexts.\n");
2197 
2198 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))
2199 		adev->dm.secure_display_ctx.support_mul_roi = true;
2200 
2201 #endif
2202 
2203 	drm_dbg_driver(adev_to_drm(adev), "KMS initialized.\n");
2204 
2205 	return 0;
2206 error:
2207 	amdgpu_dm_fini(adev);
2208 
2209 	return -EINVAL;
2210 }
2211 
2212 static int amdgpu_dm_early_fini(struct amdgpu_ip_block *ip_block)
2213 {
2214 	struct amdgpu_device *adev = ip_block->adev;
2215 
2216 	amdgpu_dm_audio_fini(adev);
2217 
2218 	return 0;
2219 }
2220 
2221 static void amdgpu_dm_fini(struct amdgpu_device *adev)
2222 {
2223 	int i;
2224 
2225 	if (adev->dm.vblank_control_workqueue) {
2226 		destroy_workqueue(adev->dm.vblank_control_workqueue);
2227 		adev->dm.vblank_control_workqueue = NULL;
2228 	}
2229 
2230 	if (adev->dm.idle_workqueue) {
2231 		if (adev->dm.idle_workqueue->running) {
2232 			adev->dm.idle_workqueue->enable = false;
2233 			flush_work(&adev->dm.idle_workqueue->work);
2234 		}
2235 
2236 		kfree(adev->dm.idle_workqueue);
2237 		adev->dm.idle_workqueue = NULL;
2238 	}
2239 
2240 	amdgpu_dm_destroy_drm_device(&adev->dm);
2241 
2242 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2243 	if (adev->dm.secure_display_ctx.crtc_ctx) {
2244 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
2245 			if (adev->dm.secure_display_ctx.crtc_ctx[i].crtc) {
2246 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].notify_ta_work);
2247 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].forward_roi_work);
2248 			}
2249 		}
2250 		kfree(adev->dm.secure_display_ctx.crtc_ctx);
2251 		adev->dm.secure_display_ctx.crtc_ctx = NULL;
2252 	}
2253 #endif
2254 	if (adev->dm.hdcp_workqueue) {
2255 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
2256 		adev->dm.hdcp_workqueue = NULL;
2257 	}
2258 
2259 	if (adev->dm.dc) {
2260 		dc_deinit_callbacks(adev->dm.dc);
2261 		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
2262 		if (dc_enable_dmub_notifications(adev->dm.dc)) {
2263 			kfree(adev->dm.dmub_notify);
2264 			adev->dm.dmub_notify = NULL;
2265 			destroy_workqueue(adev->dm.delayed_hpd_wq);
2266 			adev->dm.delayed_hpd_wq = NULL;
2267 		}
2268 	}
2269 
2270 	if (adev->dm.dmub_bo)
2271 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
2272 				      &adev->dm.dmub_bo_gpu_addr,
2273 				      &adev->dm.dmub_bo_cpu_addr);
2274 
2275 	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
2276 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
2277 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
2278 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
2279 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
2280 			}
2281 		}
2282 
2283 		kfree(adev->dm.hpd_rx_offload_wq);
2284 		adev->dm.hpd_rx_offload_wq = NULL;
2285 	}
2286 
2287 	/* DC Destroy TODO: Replace destroy DAL */
2288 	if (adev->dm.dc)
2289 		dc_destroy(&adev->dm.dc);
2290 	/*
2291 	 * TODO: pageflip, vlank interrupt
2292 	 *
2293 	 * amdgpu_dm_irq_fini(adev);
2294 	 */
2295 
2296 	if (adev->dm.cgs_device) {
2297 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
2298 		adev->dm.cgs_device = NULL;
2299 	}
2300 	if (adev->dm.freesync_module) {
2301 		mod_freesync_destroy(adev->dm.freesync_module);
2302 		adev->dm.freesync_module = NULL;
2303 	}
2304 
2305 	mutex_destroy(&adev->dm.audio_lock);
2306 	mutex_destroy(&adev->dm.dc_lock);
2307 	mutex_destroy(&adev->dm.dpia_aux_lock);
2308 }
2309 
2310 static int load_dmcu_fw(struct amdgpu_device *adev)
2311 {
2312 	const char *fw_name_dmcu = NULL;
2313 	int r;
2314 	const struct dmcu_firmware_header_v1_0 *hdr;
2315 
2316 	switch (adev->asic_type) {
2317 #if defined(CONFIG_DRM_AMD_DC_SI)
2318 	case CHIP_TAHITI:
2319 	case CHIP_PITCAIRN:
2320 	case CHIP_VERDE:
2321 	case CHIP_OLAND:
2322 #endif
2323 	case CHIP_BONAIRE:
2324 	case CHIP_HAWAII:
2325 	case CHIP_KAVERI:
2326 	case CHIP_KABINI:
2327 	case CHIP_MULLINS:
2328 	case CHIP_TONGA:
2329 	case CHIP_FIJI:
2330 	case CHIP_CARRIZO:
2331 	case CHIP_STONEY:
2332 	case CHIP_POLARIS11:
2333 	case CHIP_POLARIS10:
2334 	case CHIP_POLARIS12:
2335 	case CHIP_VEGAM:
2336 	case CHIP_VEGA10:
2337 	case CHIP_VEGA12:
2338 	case CHIP_VEGA20:
2339 		return 0;
2340 	case CHIP_NAVI12:
2341 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
2342 		break;
2343 	case CHIP_RAVEN:
2344 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
2345 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2346 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
2347 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2348 		else
2349 			return 0;
2350 		break;
2351 	default:
2352 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2353 		case IP_VERSION(2, 0, 2):
2354 		case IP_VERSION(2, 0, 3):
2355 		case IP_VERSION(2, 0, 0):
2356 		case IP_VERSION(2, 1, 0):
2357 		case IP_VERSION(3, 0, 0):
2358 		case IP_VERSION(3, 0, 2):
2359 		case IP_VERSION(3, 0, 3):
2360 		case IP_VERSION(3, 0, 1):
2361 		case IP_VERSION(3, 1, 2):
2362 		case IP_VERSION(3, 1, 3):
2363 		case IP_VERSION(3, 1, 4):
2364 		case IP_VERSION(3, 1, 5):
2365 		case IP_VERSION(3, 1, 6):
2366 		case IP_VERSION(3, 2, 0):
2367 		case IP_VERSION(3, 2, 1):
2368 		case IP_VERSION(3, 5, 0):
2369 		case IP_VERSION(3, 5, 1):
2370 		case IP_VERSION(3, 6, 0):
2371 		case IP_VERSION(4, 0, 1):
2372 			return 0;
2373 		default:
2374 			break;
2375 		}
2376 		drm_err(adev_to_drm(adev), "Unsupported ASIC type: 0x%X\n", adev->asic_type);
2377 		return -EINVAL;
2378 	}
2379 
2380 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
2381 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not supported on direct or SMU loading\n");
2382 		return 0;
2383 	}
2384 
2385 	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, AMDGPU_UCODE_REQUIRED,
2386 				 "%s", fw_name_dmcu);
2387 	if (r == -ENODEV) {
2388 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
2389 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not found\n");
2390 		adev->dm.fw_dmcu = NULL;
2391 		return 0;
2392 	}
2393 	if (r) {
2394 		drm_err(adev_to_drm(adev), "amdgpu_dm: Can't validate firmware \"%s\"\n",
2395 			fw_name_dmcu);
2396 		amdgpu_ucode_release(&adev->dm.fw_dmcu);
2397 		return r;
2398 	}
2399 
2400 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
2401 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
2402 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
2403 	adev->firmware.fw_size +=
2404 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2405 
2406 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
2407 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
2408 	adev->firmware.fw_size +=
2409 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2410 
2411 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
2412 
2413 	drm_dbg_kms(adev_to_drm(adev), "PSP loading DMCU firmware\n");
2414 
2415 	return 0;
2416 }
2417 
2418 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
2419 {
2420 	struct amdgpu_device *adev = ctx;
2421 
2422 	return dm_read_reg(adev->dm.dc->ctx, address);
2423 }
2424 
2425 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
2426 				     uint32_t value)
2427 {
2428 	struct amdgpu_device *adev = ctx;
2429 
2430 	return dm_write_reg(adev->dm.dc->ctx, address, value);
2431 }
2432 
2433 static int dm_dmub_sw_init(struct amdgpu_device *adev)
2434 {
2435 	struct dmub_srv_create_params create_params;
2436 	struct dmub_srv_fw_meta_info_params fw_meta_info_params;
2437 	struct dmub_srv_region_params region_params;
2438 	struct dmub_srv_region_info region_info;
2439 	struct dmub_srv_memory_params memory_params;
2440 	struct dmub_fw_meta_info fw_info;
2441 	struct dmub_srv_fb_info *fb_info;
2442 	struct dmub_srv *dmub_srv;
2443 	const struct dmcub_firmware_header_v1_0 *hdr;
2444 	enum dmub_asic dmub_asic;
2445 	enum dmub_status status;
2446 	static enum dmub_window_memory_type window_memory_type[DMUB_WINDOW_TOTAL] = {
2447 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_0_INST_CONST
2448 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_1_STACK
2449 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_2_BSS_DATA
2450 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_3_VBIOS
2451 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_4_MAILBOX
2452 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_5_TRACEBUFF
2453 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_6_FW_STATE
2454 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_7_SCRATCH_MEM
2455 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_IB_MEM
2456 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_SHARED_STATE
2457 	};
2458 	int r;
2459 
2460 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2461 	case IP_VERSION(2, 1, 0):
2462 		dmub_asic = DMUB_ASIC_DCN21;
2463 		break;
2464 	case IP_VERSION(3, 0, 0):
2465 		dmub_asic = DMUB_ASIC_DCN30;
2466 		break;
2467 	case IP_VERSION(3, 0, 1):
2468 		dmub_asic = DMUB_ASIC_DCN301;
2469 		break;
2470 	case IP_VERSION(3, 0, 2):
2471 		dmub_asic = DMUB_ASIC_DCN302;
2472 		break;
2473 	case IP_VERSION(3, 0, 3):
2474 		dmub_asic = DMUB_ASIC_DCN303;
2475 		break;
2476 	case IP_VERSION(3, 1, 2):
2477 	case IP_VERSION(3, 1, 3):
2478 		dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
2479 		break;
2480 	case IP_VERSION(3, 1, 4):
2481 		dmub_asic = DMUB_ASIC_DCN314;
2482 		break;
2483 	case IP_VERSION(3, 1, 5):
2484 		dmub_asic = DMUB_ASIC_DCN315;
2485 		break;
2486 	case IP_VERSION(3, 1, 6):
2487 		dmub_asic = DMUB_ASIC_DCN316;
2488 		break;
2489 	case IP_VERSION(3, 2, 0):
2490 		dmub_asic = DMUB_ASIC_DCN32;
2491 		break;
2492 	case IP_VERSION(3, 2, 1):
2493 		dmub_asic = DMUB_ASIC_DCN321;
2494 		break;
2495 	case IP_VERSION(3, 5, 0):
2496 	case IP_VERSION(3, 5, 1):
2497 		dmub_asic = DMUB_ASIC_DCN35;
2498 		break;
2499 	case IP_VERSION(3, 6, 0):
2500 		dmub_asic = DMUB_ASIC_DCN36;
2501 		break;
2502 	case IP_VERSION(4, 0, 1):
2503 		dmub_asic = DMUB_ASIC_DCN401;
2504 		break;
2505 
2506 	default:
2507 		/* ASIC doesn't support DMUB. */
2508 		return 0;
2509 	}
2510 
2511 	hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
2512 	adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
2513 
2514 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
2515 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
2516 			AMDGPU_UCODE_ID_DMCUB;
2517 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
2518 			adev->dm.dmub_fw;
2519 		adev->firmware.fw_size +=
2520 			ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
2521 
2522 		drm_info(adev_to_drm(adev), "Loading DMUB firmware via PSP: version=0x%08X\n",
2523 			 adev->dm.dmcub_fw_version);
2524 	}
2525 
2526 
2527 	adev->dm.dmub_srv = kzalloc(sizeof(*adev->dm.dmub_srv), GFP_KERNEL);
2528 	dmub_srv = adev->dm.dmub_srv;
2529 
2530 	if (!dmub_srv) {
2531 		drm_err(adev_to_drm(adev), "Failed to allocate DMUB service!\n");
2532 		return -ENOMEM;
2533 	}
2534 
2535 	memset(&create_params, 0, sizeof(create_params));
2536 	create_params.user_ctx = adev;
2537 	create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2538 	create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2539 	create_params.asic = dmub_asic;
2540 
2541 	/* Create the DMUB service. */
2542 	status = dmub_srv_create(dmub_srv, &create_params);
2543 	if (status != DMUB_STATUS_OK) {
2544 		drm_err(adev_to_drm(adev), "Error creating DMUB service: %d\n", status);
2545 		return -EINVAL;
2546 	}
2547 
2548 	/* Extract the FW meta info. */
2549 	memset(&fw_meta_info_params, 0, sizeof(fw_meta_info_params));
2550 
2551 	fw_meta_info_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2552 					      PSP_HEADER_BYTES_256;
2553 	fw_meta_info_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2554 	fw_meta_info_params.fw_inst_const = adev->dm.dmub_fw->data +
2555 					    le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2556 					    PSP_HEADER_BYTES_256;
2557 	fw_meta_info_params.fw_bss_data = region_params.bss_data_size ? adev->dm.dmub_fw->data +
2558 					  le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2559 					  le32_to_cpu(hdr->inst_const_bytes) : NULL;
2560 	fw_meta_info_params.custom_psp_footer_size = 0;
2561 
2562 	status = dmub_srv_get_fw_meta_info_from_raw_fw(&fw_meta_info_params, &fw_info);
2563 	if (status != DMUB_STATUS_OK) {
2564 		/* Skip returning early, just log the error. */
2565 		drm_err(adev_to_drm(adev), "Error getting DMUB FW meta info: %d\n", status);
2566 		// return -EINVAL;
2567 	}
2568 
2569 	/* Calculate the size of all the regions for the DMUB service. */
2570 	memset(&region_params, 0, sizeof(region_params));
2571 
2572 	region_params.inst_const_size = fw_meta_info_params.inst_const_size;
2573 	region_params.bss_data_size = fw_meta_info_params.bss_data_size;
2574 	region_params.vbios_size = adev->bios_size;
2575 	region_params.fw_bss_data = fw_meta_info_params.fw_bss_data;
2576 	region_params.fw_inst_const = fw_meta_info_params.fw_inst_const;
2577 	region_params.window_memory_type = window_memory_type;
2578 	region_params.fw_info = (status == DMUB_STATUS_OK) ? &fw_info : NULL;
2579 
2580 	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2581 					   &region_info);
2582 
2583 	if (status != DMUB_STATUS_OK) {
2584 		drm_err(adev_to_drm(adev), "Error calculating DMUB region info: %d\n", status);
2585 		return -EINVAL;
2586 	}
2587 
2588 	/*
2589 	 * Allocate a framebuffer based on the total size of all the regions.
2590 	 * TODO: Move this into GART.
2591 	 */
2592 	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2593 				    AMDGPU_GEM_DOMAIN_VRAM |
2594 				    AMDGPU_GEM_DOMAIN_GTT,
2595 				    &adev->dm.dmub_bo,
2596 				    &adev->dm.dmub_bo_gpu_addr,
2597 				    &adev->dm.dmub_bo_cpu_addr);
2598 	if (r)
2599 		return r;
2600 
2601 	/* Rebase the regions on the framebuffer address. */
2602 	memset(&memory_params, 0, sizeof(memory_params));
2603 	memory_params.cpu_fb_addr = adev->dm.dmub_bo_cpu_addr;
2604 	memory_params.gpu_fb_addr = adev->dm.dmub_bo_gpu_addr;
2605 	memory_params.region_info = &region_info;
2606 	memory_params.window_memory_type = window_memory_type;
2607 
2608 	adev->dm.dmub_fb_info =
2609 		kzalloc(sizeof(*adev->dm.dmub_fb_info), GFP_KERNEL);
2610 	fb_info = adev->dm.dmub_fb_info;
2611 
2612 	if (!fb_info) {
2613 		drm_err(adev_to_drm(adev),
2614 			"Failed to allocate framebuffer info for DMUB service!\n");
2615 		return -ENOMEM;
2616 	}
2617 
2618 	status = dmub_srv_calc_mem_info(dmub_srv, &memory_params, fb_info);
2619 	if (status != DMUB_STATUS_OK) {
2620 		drm_err(adev_to_drm(adev), "Error calculating DMUB FB info: %d\n", status);
2621 		return -EINVAL;
2622 	}
2623 
2624 	adev->dm.bb_from_dmub = dm_dmub_get_vbios_bounding_box(adev);
2625 	adev->dm.fw_inst_size = fw_meta_info_params.inst_const_size;
2626 
2627 	return 0;
2628 }
2629 
2630 static int dm_sw_init(struct amdgpu_ip_block *ip_block)
2631 {
2632 	struct amdgpu_device *adev = ip_block->adev;
2633 	int r;
2634 
2635 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
2636 
2637 	if (!adev->dm.cgs_device) {
2638 		drm_err(adev_to_drm(adev), "failed to create cgs device.\n");
2639 		return -EINVAL;
2640 	}
2641 
2642 	/* Moved from dm init since we need to use allocations for storing bounding box data */
2643 	INIT_LIST_HEAD(&adev->dm.da_list);
2644 
2645 	r = dm_dmub_sw_init(adev);
2646 	if (r)
2647 		return r;
2648 
2649 	return load_dmcu_fw(adev);
2650 }
2651 
2652 static int dm_sw_fini(struct amdgpu_ip_block *ip_block)
2653 {
2654 	struct amdgpu_device *adev = ip_block->adev;
2655 	struct dal_allocation *da;
2656 
2657 	list_for_each_entry(da, &adev->dm.da_list, list) {
2658 		if (adev->dm.bb_from_dmub == (void *) da->cpu_ptr) {
2659 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
2660 			list_del(&da->list);
2661 			kfree(da);
2662 			adev->dm.bb_from_dmub = NULL;
2663 			break;
2664 		}
2665 	}
2666 
2667 
2668 	kfree(adev->dm.dmub_fb_info);
2669 	adev->dm.dmub_fb_info = NULL;
2670 
2671 	if (adev->dm.dmub_srv) {
2672 		dmub_srv_destroy(adev->dm.dmub_srv);
2673 		kfree(adev->dm.dmub_srv);
2674 		adev->dm.dmub_srv = NULL;
2675 	}
2676 
2677 	amdgpu_ucode_release(&adev->dm.dmub_fw);
2678 	amdgpu_ucode_release(&adev->dm.fw_dmcu);
2679 
2680 	return 0;
2681 }
2682 
2683 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2684 {
2685 	struct amdgpu_dm_connector *aconnector;
2686 	struct drm_connector *connector;
2687 	struct drm_connector_list_iter iter;
2688 	int ret = 0;
2689 
2690 	drm_connector_list_iter_begin(dev, &iter);
2691 	drm_for_each_connector_iter(connector, &iter) {
2692 
2693 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2694 			continue;
2695 
2696 		aconnector = to_amdgpu_dm_connector(connector);
2697 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
2698 		    aconnector->mst_mgr.aux) {
2699 			drm_dbg_kms(dev, "DM_MST: starting TM on aconnector: %p [id: %d]\n",
2700 					 aconnector,
2701 					 aconnector->base.base.id);
2702 
2703 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2704 			if (ret < 0) {
2705 				drm_err(dev, "DM_MST: Failed to start MST\n");
2706 				aconnector->dc_link->type =
2707 					dc_connection_single;
2708 				ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2709 								     aconnector->dc_link);
2710 				break;
2711 			}
2712 		}
2713 	}
2714 	drm_connector_list_iter_end(&iter);
2715 
2716 	return ret;
2717 }
2718 
2719 static int dm_late_init(struct amdgpu_ip_block *ip_block)
2720 {
2721 	struct amdgpu_device *adev = ip_block->adev;
2722 
2723 	struct dmcu_iram_parameters params;
2724 	unsigned int linear_lut[16];
2725 	int i;
2726 	struct dmcu *dmcu = NULL;
2727 
2728 	dmcu = adev->dm.dc->res_pool->dmcu;
2729 
2730 	for (i = 0; i < 16; i++)
2731 		linear_lut[i] = 0xFFFF * i / 15;
2732 
2733 	params.set = 0;
2734 	params.backlight_ramping_override = false;
2735 	params.backlight_ramping_start = 0xCCCC;
2736 	params.backlight_ramping_reduction = 0xCCCCCCCC;
2737 	params.backlight_lut_array_size = 16;
2738 	params.backlight_lut_array = linear_lut;
2739 
2740 	/* Min backlight level after ABM reduction,  Don't allow below 1%
2741 	 * 0xFFFF x 0.01 = 0x28F
2742 	 */
2743 	params.min_abm_backlight = 0x28F;
2744 	/* In the case where abm is implemented on dmcub,
2745 	 * dmcu object will be null.
2746 	 * ABM 2.4 and up are implemented on dmcub.
2747 	 */
2748 	if (dmcu) {
2749 		if (!dmcu_load_iram(dmcu, params))
2750 			return -EINVAL;
2751 	} else if (adev->dm.dc->ctx->dmub_srv) {
2752 		struct dc_link *edp_links[MAX_NUM_EDP];
2753 		int edp_num;
2754 
2755 		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
2756 		for (i = 0; i < edp_num; i++) {
2757 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
2758 				return -EINVAL;
2759 		}
2760 	}
2761 
2762 	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
2763 }
2764 
2765 static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
2766 {
2767 	u8 buf[UUID_SIZE];
2768 	guid_t guid;
2769 	int ret;
2770 
2771 	mutex_lock(&mgr->lock);
2772 	if (!mgr->mst_primary)
2773 		goto out_fail;
2774 
2775 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
2776 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2777 		goto out_fail;
2778 	}
2779 
2780 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
2781 				 DP_MST_EN |
2782 				 DP_UP_REQ_EN |
2783 				 DP_UPSTREAM_IS_SRC);
2784 	if (ret < 0) {
2785 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
2786 		goto out_fail;
2787 	}
2788 
2789 	/* Some hubs forget their guids after they resume */
2790 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, buf, sizeof(buf));
2791 	if (ret != sizeof(buf)) {
2792 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2793 		goto out_fail;
2794 	}
2795 
2796 	import_guid(&guid, buf);
2797 
2798 	if (guid_is_null(&guid)) {
2799 		guid_gen(&guid);
2800 		export_guid(buf, &guid);
2801 
2802 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, buf, sizeof(buf));
2803 
2804 		if (ret != sizeof(buf)) {
2805 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
2806 			goto out_fail;
2807 		}
2808 	}
2809 
2810 	guid_copy(&mgr->mst_primary->guid, &guid);
2811 
2812 out_fail:
2813 	mutex_unlock(&mgr->lock);
2814 }
2815 
2816 void hdmi_cec_unset_edid(struct amdgpu_dm_connector *aconnector)
2817 {
2818 	struct cec_notifier *n = aconnector->notifier;
2819 
2820 	if (!n)
2821 		return;
2822 
2823 	cec_notifier_phys_addr_invalidate(n);
2824 }
2825 
2826 void hdmi_cec_set_edid(struct amdgpu_dm_connector *aconnector)
2827 {
2828 	struct drm_connector *connector = &aconnector->base;
2829 	struct cec_notifier *n = aconnector->notifier;
2830 
2831 	if (!n)
2832 		return;
2833 
2834 	cec_notifier_set_phys_addr(n,
2835 				   connector->display_info.source_physical_address);
2836 }
2837 
2838 static void s3_handle_hdmi_cec(struct drm_device *ddev, bool suspend)
2839 {
2840 	struct amdgpu_dm_connector *aconnector;
2841 	struct drm_connector *connector;
2842 	struct drm_connector_list_iter conn_iter;
2843 
2844 	drm_connector_list_iter_begin(ddev, &conn_iter);
2845 	drm_for_each_connector_iter(connector, &conn_iter) {
2846 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2847 			continue;
2848 
2849 		aconnector = to_amdgpu_dm_connector(connector);
2850 		if (suspend)
2851 			hdmi_cec_unset_edid(aconnector);
2852 		else
2853 			hdmi_cec_set_edid(aconnector);
2854 	}
2855 	drm_connector_list_iter_end(&conn_iter);
2856 }
2857 
2858 static void s3_handle_mst(struct drm_device *dev, bool suspend)
2859 {
2860 	struct amdgpu_dm_connector *aconnector;
2861 	struct drm_connector *connector;
2862 	struct drm_connector_list_iter iter;
2863 	struct drm_dp_mst_topology_mgr *mgr;
2864 
2865 	drm_connector_list_iter_begin(dev, &iter);
2866 	drm_for_each_connector_iter(connector, &iter) {
2867 
2868 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2869 			continue;
2870 
2871 		aconnector = to_amdgpu_dm_connector(connector);
2872 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
2873 		    aconnector->mst_root)
2874 			continue;
2875 
2876 		mgr = &aconnector->mst_mgr;
2877 
2878 		if (suspend) {
2879 			drm_dp_mst_topology_mgr_suspend(mgr);
2880 		} else {
2881 			/* if extended timeout is supported in hardware,
2882 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
2883 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
2884 			 */
2885 			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
2886 			if (!dp_is_lttpr_present(aconnector->dc_link))
2887 				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
2888 
2889 			/* TODO: move resume_mst_branch_status() into drm mst resume again
2890 			 * once topology probing work is pulled out from mst resume into mst
2891 			 * resume 2nd step. mst resume 2nd step should be called after old
2892 			 * state getting restored (i.e. drm_atomic_helper_resume()).
2893 			 */
2894 			resume_mst_branch_status(mgr);
2895 		}
2896 	}
2897 	drm_connector_list_iter_end(&iter);
2898 }
2899 
2900 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
2901 {
2902 	int ret = 0;
2903 
2904 	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
2905 	 * on window driver dc implementation.
2906 	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
2907 	 * should be passed to smu during boot up and resume from s3.
2908 	 * boot up: dc calculate dcn watermark clock settings within dc_create,
2909 	 * dcn20_resource_construct
2910 	 * then call pplib functions below to pass the settings to smu:
2911 	 * smu_set_watermarks_for_clock_ranges
2912 	 * smu_set_watermarks_table
2913 	 * navi10_set_watermarks_table
2914 	 * smu_write_watermarks_table
2915 	 *
2916 	 * For Renoir, clock settings of dcn watermark are also fixed values.
2917 	 * dc has implemented different flow for window driver:
2918 	 * dc_hardware_init / dc_set_power_state
2919 	 * dcn10_init_hw
2920 	 * notify_wm_ranges
2921 	 * set_wm_ranges
2922 	 * -- Linux
2923 	 * smu_set_watermarks_for_clock_ranges
2924 	 * renoir_set_watermarks_table
2925 	 * smu_write_watermarks_table
2926 	 *
2927 	 * For Linux,
2928 	 * dc_hardware_init -> amdgpu_dm_init
2929 	 * dc_set_power_state --> dm_resume
2930 	 *
2931 	 * therefore, this function apply to navi10/12/14 but not Renoir
2932 	 * *
2933 	 */
2934 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2935 	case IP_VERSION(2, 0, 2):
2936 	case IP_VERSION(2, 0, 0):
2937 		break;
2938 	default:
2939 		return 0;
2940 	}
2941 
2942 	ret = amdgpu_dpm_write_watermarks_table(adev);
2943 	if (ret) {
2944 		drm_err(adev_to_drm(adev), "Failed to update WMTABLE!\n");
2945 		return ret;
2946 	}
2947 
2948 	return 0;
2949 }
2950 
2951 static int dm_oem_i2c_hw_init(struct amdgpu_device *adev)
2952 {
2953 	struct amdgpu_display_manager *dm = &adev->dm;
2954 	struct amdgpu_i2c_adapter *oem_i2c;
2955 	struct ddc_service *oem_ddc_service;
2956 	int r;
2957 
2958 	oem_ddc_service = dc_get_oem_i2c_device(adev->dm.dc);
2959 	if (oem_ddc_service) {
2960 		oem_i2c = create_i2c(oem_ddc_service, true);
2961 		if (!oem_i2c) {
2962 			drm_info(adev_to_drm(adev), "Failed to create oem i2c adapter data\n");
2963 			return -ENOMEM;
2964 		}
2965 
2966 		r = devm_i2c_add_adapter(adev->dev, &oem_i2c->base);
2967 		if (r) {
2968 			drm_info(adev_to_drm(adev), "Failed to register oem i2c\n");
2969 			kfree(oem_i2c);
2970 			return r;
2971 		}
2972 		dm->oem_i2c = oem_i2c;
2973 	}
2974 
2975 	return 0;
2976 }
2977 
2978 /**
2979  * dm_hw_init() - Initialize DC device
2980  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
2981  *
2982  * Initialize the &struct amdgpu_display_manager device. This involves calling
2983  * the initializers of each DM component, then populating the struct with them.
2984  *
2985  * Although the function implies hardware initialization, both hardware and
2986  * software are initialized here. Splitting them out to their relevant init
2987  * hooks is a future TODO item.
2988  *
2989  * Some notable things that are initialized here:
2990  *
2991  * - Display Core, both software and hardware
2992  * - DC modules that we need (freesync and color management)
2993  * - DRM software states
2994  * - Interrupt sources and handlers
2995  * - Vblank support
2996  * - Debug FS entries, if enabled
2997  */
2998 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
2999 {
3000 	struct amdgpu_device *adev = ip_block->adev;
3001 	int r;
3002 
3003 	/* Create DAL display manager */
3004 	r = amdgpu_dm_init(adev);
3005 	if (r)
3006 		return r;
3007 	amdgpu_dm_hpd_init(adev);
3008 
3009 	r = dm_oem_i2c_hw_init(adev);
3010 	if (r)
3011 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
3012 
3013 	return 0;
3014 }
3015 
3016 /**
3017  * dm_hw_fini() - Teardown DC device
3018  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3019  *
3020  * Teardown components within &struct amdgpu_display_manager that require
3021  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
3022  * were loaded. Also flush IRQ workqueues and disable them.
3023  */
3024 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
3025 {
3026 	struct amdgpu_device *adev = ip_block->adev;
3027 
3028 	amdgpu_dm_hpd_fini(adev);
3029 
3030 	amdgpu_dm_irq_fini(adev);
3031 	amdgpu_dm_fini(adev);
3032 	return 0;
3033 }
3034 
3035 
3036 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
3037 				 struct dc_state *state, bool enable)
3038 {
3039 	enum dc_irq_source irq_source;
3040 	struct amdgpu_crtc *acrtc;
3041 	int rc = -EBUSY;
3042 	int i = 0;
3043 
3044 	for (i = 0; i < state->stream_count; i++) {
3045 		acrtc = get_crtc_by_otg_inst(
3046 				adev, state->stream_status[i].primary_otg_inst);
3047 
3048 		if (acrtc && state->stream_status[i].plane_count != 0) {
3049 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
3050 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3051 			if (rc)
3052 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
3053 					 enable ? "enable" : "disable");
3054 
3055 			if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
3056 				if (enable) {
3057 					if (amdgpu_dm_crtc_vrr_active(
3058 							to_dm_crtc_state(acrtc->base.state)))
3059 						rc = amdgpu_dm_crtc_set_vupdate_irq(
3060 							&acrtc->base, true);
3061 				} else
3062 					rc = amdgpu_dm_crtc_set_vupdate_irq(
3063 							&acrtc->base, false);
3064 
3065 				if (rc)
3066 					drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
3067 						enable ? "en" : "dis");
3068 			}
3069 
3070 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3071 			/* During gpu-reset we disable and then enable vblank irq, so
3072 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
3073 			 */
3074 			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
3075 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
3076 		}
3077 	}
3078 
3079 }
3080 
3081 DEFINE_FREE(state_release, struct dc_state *, if (_T) dc_state_release(_T))
3082 
3083 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
3084 {
3085 	struct dc_state *context __free(state_release) = NULL;
3086 	int i;
3087 	struct dc_stream_state *del_streams[MAX_PIPES];
3088 	int del_streams_count = 0;
3089 	struct dc_commit_streams_params params = {};
3090 
3091 	memset(del_streams, 0, sizeof(del_streams));
3092 
3093 	context = dc_state_create_current_copy(dc);
3094 	if (context == NULL)
3095 		return DC_ERROR_UNEXPECTED;
3096 
3097 	/* First remove from context all streams */
3098 	for (i = 0; i < context->stream_count; i++) {
3099 		struct dc_stream_state *stream = context->streams[i];
3100 
3101 		del_streams[del_streams_count++] = stream;
3102 	}
3103 
3104 	/* Remove all planes for removed streams and then remove the streams */
3105 	for (i = 0; i < del_streams_count; i++) {
3106 		enum dc_status res;
3107 
3108 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
3109 			return DC_FAIL_DETACH_SURFACES;
3110 
3111 		res = dc_state_remove_stream(dc, context, del_streams[i]);
3112 		if (res != DC_OK)
3113 			return res;
3114 	}
3115 
3116 	params.streams = context->streams;
3117 	params.stream_count = context->stream_count;
3118 
3119 	return dc_commit_streams(dc, &params);
3120 }
3121 
3122 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
3123 {
3124 	int i;
3125 
3126 	if (dm->hpd_rx_offload_wq) {
3127 		for (i = 0; i < dm->dc->caps.max_links; i++)
3128 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
3129 	}
3130 }
3131 
3132 static int dm_cache_state(struct amdgpu_device *adev)
3133 {
3134 	int r;
3135 
3136 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
3137 	if (IS_ERR(adev->dm.cached_state)) {
3138 		r = PTR_ERR(adev->dm.cached_state);
3139 		adev->dm.cached_state = NULL;
3140 	}
3141 
3142 	return adev->dm.cached_state ? 0 : r;
3143 }
3144 
3145 static void dm_destroy_cached_state(struct amdgpu_device *adev)
3146 {
3147 	struct amdgpu_display_manager *dm = &adev->dm;
3148 	struct drm_device *ddev = adev_to_drm(adev);
3149 	struct dm_plane_state *dm_new_plane_state;
3150 	struct drm_plane_state *new_plane_state;
3151 	struct dm_crtc_state *dm_new_crtc_state;
3152 	struct drm_crtc_state *new_crtc_state;
3153 	struct drm_plane *plane;
3154 	struct drm_crtc *crtc;
3155 	int i;
3156 
3157 	if (!dm->cached_state)
3158 		return;
3159 
3160 	/* Force mode set in atomic commit */
3161 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3162 		new_crtc_state->active_changed = true;
3163 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3164 		reset_freesync_config_for_crtc(dm_new_crtc_state);
3165 	}
3166 
3167 	/*
3168 	 * atomic_check is expected to create the dc states. We need to release
3169 	 * them here, since they were duplicated as part of the suspend
3170 	 * procedure.
3171 	 */
3172 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3173 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3174 		if (dm_new_crtc_state->stream) {
3175 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
3176 			dc_stream_release(dm_new_crtc_state->stream);
3177 			dm_new_crtc_state->stream = NULL;
3178 		}
3179 		dm_new_crtc_state->base.color_mgmt_changed = true;
3180 	}
3181 
3182 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
3183 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
3184 		if (dm_new_plane_state->dc_state) {
3185 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
3186 			dc_plane_state_release(dm_new_plane_state->dc_state);
3187 			dm_new_plane_state->dc_state = NULL;
3188 		}
3189 	}
3190 
3191 	drm_atomic_helper_resume(ddev, dm->cached_state);
3192 
3193 	dm->cached_state = NULL;
3194 }
3195 
3196 static int dm_suspend(struct amdgpu_ip_block *ip_block)
3197 {
3198 	struct amdgpu_device *adev = ip_block->adev;
3199 	struct amdgpu_display_manager *dm = &adev->dm;
3200 
3201 	if (amdgpu_in_reset(adev)) {
3202 		enum dc_status res;
3203 
3204 		mutex_lock(&dm->dc_lock);
3205 
3206 		dc_allow_idle_optimizations(adev->dm.dc, false);
3207 
3208 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
3209 
3210 		if (dm->cached_dc_state)
3211 			dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
3212 
3213 		res = amdgpu_dm_commit_zero_streams(dm->dc);
3214 		if (res != DC_OK) {
3215 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
3216 			return -EINVAL;
3217 		}
3218 
3219 		amdgpu_dm_irq_suspend(adev);
3220 
3221 		hpd_rx_irq_work_suspend(dm);
3222 
3223 		return 0;
3224 	}
3225 
3226 	if (!adev->dm.cached_state) {
3227 		int r = dm_cache_state(adev);
3228 
3229 		if (r)
3230 			return r;
3231 	}
3232 
3233 	s3_handle_hdmi_cec(adev_to_drm(adev), true);
3234 
3235 	s3_handle_mst(adev_to_drm(adev), true);
3236 
3237 	amdgpu_dm_irq_suspend(adev);
3238 
3239 	hpd_rx_irq_work_suspend(dm);
3240 
3241 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
3242 
3243 	if (dm->dc->caps.ips_support && adev->in_s0ix)
3244 		dc_allow_idle_optimizations(dm->dc, true);
3245 
3246 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
3247 
3248 	return 0;
3249 }
3250 
3251 struct drm_connector *
3252 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
3253 					     struct drm_crtc *crtc)
3254 {
3255 	u32 i;
3256 	struct drm_connector_state *new_con_state;
3257 	struct drm_connector *connector;
3258 	struct drm_crtc *crtc_from_state;
3259 
3260 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3261 		crtc_from_state = new_con_state->crtc;
3262 
3263 		if (crtc_from_state == crtc)
3264 			return connector;
3265 	}
3266 
3267 	return NULL;
3268 }
3269 
3270 static void emulated_link_detect(struct dc_link *link)
3271 {
3272 	struct dc_sink_init_data sink_init_data = { 0 };
3273 	struct display_sink_capability sink_caps = { 0 };
3274 	enum dc_edid_status edid_status;
3275 	struct dc_context *dc_ctx = link->ctx;
3276 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
3277 	struct dc_sink *sink = NULL;
3278 	struct dc_sink *prev_sink = NULL;
3279 
3280 	link->type = dc_connection_none;
3281 	prev_sink = link->local_sink;
3282 
3283 	if (prev_sink)
3284 		dc_sink_release(prev_sink);
3285 
3286 	switch (link->connector_signal) {
3287 	case SIGNAL_TYPE_HDMI_TYPE_A: {
3288 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3289 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
3290 		break;
3291 	}
3292 
3293 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
3294 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3295 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
3296 		break;
3297 	}
3298 
3299 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
3300 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3301 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
3302 		break;
3303 	}
3304 
3305 	case SIGNAL_TYPE_LVDS: {
3306 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3307 		sink_caps.signal = SIGNAL_TYPE_LVDS;
3308 		break;
3309 	}
3310 
3311 	case SIGNAL_TYPE_EDP: {
3312 		sink_caps.transaction_type =
3313 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3314 		sink_caps.signal = SIGNAL_TYPE_EDP;
3315 		break;
3316 	}
3317 
3318 	case SIGNAL_TYPE_DISPLAY_PORT: {
3319 		sink_caps.transaction_type =
3320 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3321 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
3322 		break;
3323 	}
3324 
3325 	default:
3326 		drm_err(dev, "Invalid connector type! signal:%d\n",
3327 			link->connector_signal);
3328 		return;
3329 	}
3330 
3331 	sink_init_data.link = link;
3332 	sink_init_data.sink_signal = sink_caps.signal;
3333 
3334 	sink = dc_sink_create(&sink_init_data);
3335 	if (!sink) {
3336 		drm_err(dev, "Failed to create sink!\n");
3337 		return;
3338 	}
3339 
3340 	/* dc_sink_create returns a new reference */
3341 	link->local_sink = sink;
3342 
3343 	edid_status = dm_helpers_read_local_edid(
3344 			link->ctx,
3345 			link,
3346 			sink);
3347 
3348 	if (edid_status != EDID_OK)
3349 		drm_err(dev, "Failed to read EDID\n");
3350 
3351 }
3352 
3353 static void dm_gpureset_commit_state(struct dc_state *dc_state,
3354 				     struct amdgpu_display_manager *dm)
3355 {
3356 	struct {
3357 		struct dc_surface_update surface_updates[MAX_SURFACES];
3358 		struct dc_plane_info plane_infos[MAX_SURFACES];
3359 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3360 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3361 		struct dc_stream_update stream_update;
3362 	} *bundle __free(kfree);
3363 	int k, m;
3364 
3365 	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
3366 
3367 	if (!bundle) {
3368 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
3369 		return;
3370 	}
3371 
3372 	for (k = 0; k < dc_state->stream_count; k++) {
3373 		bundle->stream_update.stream = dc_state->streams[k];
3374 
3375 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
3376 			bundle->surface_updates[m].surface =
3377 				dc_state->stream_status[k].plane_states[m];
3378 			bundle->surface_updates[m].surface->force_full_update =
3379 				true;
3380 		}
3381 
3382 		update_planes_and_stream_adapter(dm->dc,
3383 					 UPDATE_TYPE_FULL,
3384 					 dc_state->stream_status[k].plane_count,
3385 					 dc_state->streams[k],
3386 					 &bundle->stream_update,
3387 					 bundle->surface_updates);
3388 	}
3389 }
3390 
3391 static void apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
3392 					    struct dc_sink *sink)
3393 {
3394 	struct dc_panel_patch *ppatch = NULL;
3395 
3396 	if (!sink)
3397 		return;
3398 
3399 	ppatch = &sink->edid_caps.panel_patch;
3400 	if (ppatch->wait_after_dpcd_poweroff_ms) {
3401 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
3402 		drm_dbg_driver(adev_to_drm(adev),
3403 			       "%s: adding a %ds delay as w/a for panel\n",
3404 			       __func__,
3405 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
3406 	}
3407 }
3408 
3409 /**
3410  * amdgpu_dm_dump_links_and_sinks - Debug dump of all DC links and their sinks
3411  * @adev: amdgpu device pointer
3412  *
3413  * Iterates through all DC links and dumps information about local and remote
3414  * (MST) sinks. Should be called after connector detection is complete to see
3415  * the final state of all links.
3416  */
3417 static void amdgpu_dm_dump_links_and_sinks(struct amdgpu_device *adev)
3418 {
3419 	struct dc *dc = adev->dm.dc;
3420 	struct drm_device *dev = adev_to_drm(adev);
3421 	int li;
3422 
3423 	if (!dc)
3424 		return;
3425 
3426 	for (li = 0; li < dc->link_count; li++) {
3427 		struct dc_link *l = dc->links[li];
3428 		const char *name = NULL;
3429 		int rs;
3430 
3431 		if (!l)
3432 			continue;
3433 		if (l->local_sink && l->local_sink->edid_caps.display_name[0])
3434 			name = l->local_sink->edid_caps.display_name;
3435 		else
3436 			name = "n/a";
3437 
3438 		drm_dbg_kms(dev,
3439 			"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",
3440 			li,
3441 			l->local_sink,
3442 			l->type,
3443 			l->local_sink ? l->local_sink->sink_signal : SIGNAL_TYPE_NONE,
3444 			l->sink_count,
3445 			name,
3446 			l->dpcd_caps.is_mst_capable,
3447 			l->mst_stream_alloc_table.stream_count);
3448 
3449 		/* Dump remote (MST) sinks if any */
3450 		for (rs = 0; rs < l->sink_count; rs++) {
3451 			struct dc_sink *rsink = l->remote_sinks[rs];
3452 			const char *rname = NULL;
3453 
3454 			if (!rsink)
3455 				continue;
3456 			if (rsink->edid_caps.display_name[0])
3457 				rname = rsink->edid_caps.display_name;
3458 			else
3459 				rname = "n/a";
3460 			drm_dbg_kms(dev,
3461 				"  REMOTE_SINK[%d:%d]: sink=%p signal=%d edid_name=%s\n",
3462 				li, rs,
3463 				rsink,
3464 				rsink->sink_signal,
3465 				rname);
3466 		}
3467 	}
3468 }
3469 
3470 static int dm_resume(struct amdgpu_ip_block *ip_block)
3471 {
3472 	struct amdgpu_device *adev = ip_block->adev;
3473 	struct drm_device *ddev = adev_to_drm(adev);
3474 	struct amdgpu_display_manager *dm = &adev->dm;
3475 	struct amdgpu_dm_connector *aconnector;
3476 	struct drm_connector *connector;
3477 	struct drm_connector_list_iter iter;
3478 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
3479 	enum dc_connection_type new_connection_type = dc_connection_none;
3480 	struct dc_state *dc_state;
3481 	int i, r, j;
3482 	struct dc_commit_streams_params commit_params = {};
3483 
3484 	if (dm->dc->caps.ips_support) {
3485 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
3486 	}
3487 
3488 	if (amdgpu_in_reset(adev)) {
3489 		dc_state = dm->cached_dc_state;
3490 
3491 		/*
3492 		 * The dc->current_state is backed up into dm->cached_dc_state
3493 		 * before we commit 0 streams.
3494 		 *
3495 		 * DC will clear link encoder assignments on the real state
3496 		 * but the changes won't propagate over to the copy we made
3497 		 * before the 0 streams commit.
3498 		 *
3499 		 * DC expects that link encoder assignments are *not* valid
3500 		 * when committing a state, so as a workaround we can copy
3501 		 * off of the current state.
3502 		 *
3503 		 * We lose the previous assignments, but we had already
3504 		 * commit 0 streams anyway.
3505 		 */
3506 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
3507 
3508 		r = dm_dmub_hw_init(adev);
3509 		if (r) {
3510 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
3511 			return r;
3512 		}
3513 
3514 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3515 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3516 
3517 		dc_resume(dm->dc);
3518 
3519 		amdgpu_dm_irq_resume_early(adev);
3520 
3521 		for (i = 0; i < dc_state->stream_count; i++) {
3522 			dc_state->streams[i]->mode_changed = true;
3523 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
3524 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
3525 					= 0xffffffff;
3526 			}
3527 		}
3528 
3529 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3530 			amdgpu_dm_outbox_init(adev);
3531 			dc_enable_dmub_outbox(adev->dm.dc);
3532 		}
3533 
3534 		commit_params.streams = dc_state->streams;
3535 		commit_params.stream_count = dc_state->stream_count;
3536 		dc_exit_ips_for_hw_access(dm->dc);
3537 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
3538 
3539 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
3540 
3541 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
3542 
3543 		dc_state_release(dm->cached_dc_state);
3544 		dm->cached_dc_state = NULL;
3545 
3546 		amdgpu_dm_irq_resume_late(adev);
3547 
3548 		mutex_unlock(&dm->dc_lock);
3549 
3550 		/* set the backlight after a reset */
3551 		for (i = 0; i < dm->num_of_edps; i++) {
3552 			if (dm->backlight_dev[i])
3553 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
3554 		}
3555 
3556 		return 0;
3557 	}
3558 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
3559 	dc_state_release(dm_state->context);
3560 	dm_state->context = dc_state_create(dm->dc, NULL);
3561 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
3562 
3563 	/* Before powering on DC we need to re-initialize DMUB. */
3564 	dm_dmub_hw_resume(adev);
3565 
3566 	/* Re-enable outbox interrupts for DPIA. */
3567 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3568 		amdgpu_dm_outbox_init(adev);
3569 		dc_enable_dmub_outbox(adev->dm.dc);
3570 	}
3571 
3572 	/* power on hardware */
3573 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3574 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3575 
3576 	/* program HPD filter */
3577 	dc_resume(dm->dc);
3578 
3579 	/*
3580 	 * early enable HPD Rx IRQ, should be done before set mode as short
3581 	 * pulse interrupts are used for MST
3582 	 */
3583 	amdgpu_dm_irq_resume_early(adev);
3584 
3585 	s3_handle_hdmi_cec(ddev, false);
3586 
3587 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
3588 	s3_handle_mst(ddev, false);
3589 
3590 	/* Do detection*/
3591 	drm_connector_list_iter_begin(ddev, &iter);
3592 	drm_for_each_connector_iter(connector, &iter) {
3593 		bool ret;
3594 
3595 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3596 			continue;
3597 
3598 		aconnector = to_amdgpu_dm_connector(connector);
3599 
3600 		if (!aconnector->dc_link)
3601 			continue;
3602 
3603 		/*
3604 		 * this is the case when traversing through already created end sink
3605 		 * MST connectors, should be skipped
3606 		 */
3607 		if (aconnector->mst_root)
3608 			continue;
3609 
3610 		guard(mutex)(&aconnector->hpd_lock);
3611 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3612 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3613 
3614 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3615 			emulated_link_detect(aconnector->dc_link);
3616 		} else {
3617 			guard(mutex)(&dm->dc_lock);
3618 			dc_exit_ips_for_hw_access(dm->dc);
3619 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
3620 			if (ret) {
3621 				/* w/a delay for certain panels */
3622 				apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3623 			}
3624 		}
3625 
3626 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
3627 			aconnector->fake_enable = false;
3628 
3629 		if (aconnector->dc_sink)
3630 			dc_sink_release(aconnector->dc_sink);
3631 		aconnector->dc_sink = NULL;
3632 		amdgpu_dm_update_connector_after_detect(aconnector);
3633 	}
3634 	drm_connector_list_iter_end(&iter);
3635 
3636 	dm_destroy_cached_state(adev);
3637 
3638 	/* Do mst topology probing after resuming cached state*/
3639 	drm_connector_list_iter_begin(ddev, &iter);
3640 	drm_for_each_connector_iter(connector, &iter) {
3641 		bool init = false;
3642 
3643 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3644 			continue;
3645 
3646 		aconnector = to_amdgpu_dm_connector(connector);
3647 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3648 		    aconnector->mst_root)
3649 			continue;
3650 
3651 		scoped_guard(mutex, &aconnector->mst_mgr.lock) {
3652 			init = !aconnector->mst_mgr.mst_primary;
3653 		}
3654 		if (init)
3655 			dm_helpers_dp_mst_start_top_mgr(aconnector->dc_link->ctx,
3656 				aconnector->dc_link, false);
3657 		else
3658 			drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
3659 	}
3660 	drm_connector_list_iter_end(&iter);
3661 
3662 	/* Debug dump: list all DC links and their associated sinks after detection
3663 	 * is complete for all connectors. This provides a comprehensive view of the
3664 	 * final state without repeating the dump for each connector.
3665 	 */
3666 	amdgpu_dm_dump_links_and_sinks(adev);
3667 
3668 	amdgpu_dm_irq_resume_late(adev);
3669 
3670 	amdgpu_dm_smu_write_watermarks_table(adev);
3671 
3672 	drm_kms_helper_hotplug_event(ddev);
3673 
3674 	return 0;
3675 }
3676 
3677 /**
3678  * DOC: DM Lifecycle
3679  *
3680  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
3681  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
3682  * the base driver's device list to be initialized and torn down accordingly.
3683  *
3684  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
3685  */
3686 
3687 static const struct amd_ip_funcs amdgpu_dm_funcs = {
3688 	.name = "dm",
3689 	.early_init = dm_early_init,
3690 	.late_init = dm_late_init,
3691 	.sw_init = dm_sw_init,
3692 	.sw_fini = dm_sw_fini,
3693 	.early_fini = amdgpu_dm_early_fini,
3694 	.hw_init = dm_hw_init,
3695 	.hw_fini = dm_hw_fini,
3696 	.suspend = dm_suspend,
3697 	.resume = dm_resume,
3698 	.is_idle = dm_is_idle,
3699 	.wait_for_idle = dm_wait_for_idle,
3700 	.check_soft_reset = dm_check_soft_reset,
3701 	.soft_reset = dm_soft_reset,
3702 	.set_clockgating_state = dm_set_clockgating_state,
3703 	.set_powergating_state = dm_set_powergating_state,
3704 };
3705 
3706 const struct amdgpu_ip_block_version dm_ip_block = {
3707 	.type = AMD_IP_BLOCK_TYPE_DCE,
3708 	.major = 1,
3709 	.minor = 0,
3710 	.rev = 0,
3711 	.funcs = &amdgpu_dm_funcs,
3712 };
3713 
3714 
3715 /**
3716  * DOC: atomic
3717  *
3718  * *WIP*
3719  */
3720 
3721 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
3722 	.fb_create = amdgpu_display_user_framebuffer_create,
3723 	.get_format_info = amdgpu_dm_plane_get_format_info,
3724 	.atomic_check = amdgpu_dm_atomic_check,
3725 	.atomic_commit = drm_atomic_helper_commit,
3726 };
3727 
3728 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
3729 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
3730 	.atomic_commit_setup = amdgpu_dm_atomic_setup_commit,
3731 };
3732 
3733 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
3734 {
3735 	const struct drm_panel_backlight_quirk *panel_backlight_quirk;
3736 	struct amdgpu_dm_backlight_caps *caps;
3737 	struct drm_connector *conn_base;
3738 	struct amdgpu_device *adev;
3739 	struct drm_luminance_range_info *luminance_range;
3740 	struct drm_device *drm;
3741 
3742 	if (aconnector->bl_idx == -1 ||
3743 	    aconnector->dc_link->connector_signal != SIGNAL_TYPE_EDP)
3744 		return;
3745 
3746 	conn_base = &aconnector->base;
3747 	drm = conn_base->dev;
3748 	adev = drm_to_adev(drm);
3749 
3750 	caps = &adev->dm.backlight_caps[aconnector->bl_idx];
3751 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
3752 	caps->aux_support = false;
3753 
3754 	drm_object_property_set_value(&conn_base->base,
3755 				      adev_to_drm(adev)->mode_config.panel_type_property,
3756 				      caps->ext_caps->bits.oled ? DRM_MODE_PANEL_TYPE_OLED : DRM_MODE_PANEL_TYPE_UNKNOWN);
3757 
3758 	if (caps->ext_caps->bits.oled == 1
3759 	    /*
3760 	     * ||
3761 	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
3762 	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
3763 	     */)
3764 		caps->aux_support = true;
3765 
3766 	if (amdgpu_backlight == 0)
3767 		caps->aux_support = false;
3768 	else if (amdgpu_backlight == 1)
3769 		caps->aux_support = true;
3770 	if (caps->aux_support)
3771 		aconnector->dc_link->backlight_control_type = BACKLIGHT_CONTROL_AMD_AUX;
3772 
3773 	luminance_range = &conn_base->display_info.luminance_range;
3774 
3775 	if (luminance_range->max_luminance)
3776 		caps->aux_max_input_signal = luminance_range->max_luminance;
3777 	else
3778 		caps->aux_max_input_signal = 512;
3779 
3780 	if (luminance_range->min_luminance)
3781 		caps->aux_min_input_signal = luminance_range->min_luminance;
3782 	else
3783 		caps->aux_min_input_signal = 1;
3784 
3785 	panel_backlight_quirk =
3786 		drm_get_panel_backlight_quirk(aconnector->drm_edid);
3787 	if (!IS_ERR_OR_NULL(panel_backlight_quirk)) {
3788 		if (panel_backlight_quirk->min_brightness) {
3789 			caps->min_input_signal =
3790 				panel_backlight_quirk->min_brightness - 1;
3791 			drm_info(drm,
3792 				 "Applying panel backlight quirk, min_brightness: %d\n",
3793 				 caps->min_input_signal);
3794 		}
3795 		if (panel_backlight_quirk->brightness_mask) {
3796 			drm_info(drm,
3797 				 "Applying panel backlight quirk, brightness_mask: 0x%X\n",
3798 				 panel_backlight_quirk->brightness_mask);
3799 			caps->brightness_mask =
3800 				panel_backlight_quirk->brightness_mask;
3801 		}
3802 	}
3803 }
3804 
3805 DEFINE_FREE(sink_release, struct dc_sink *, if (_T) dc_sink_release(_T))
3806 
3807 void amdgpu_dm_update_connector_after_detect(
3808 		struct amdgpu_dm_connector *aconnector)
3809 {
3810 	struct drm_connector *connector = &aconnector->base;
3811 	struct dc_sink *sink __free(sink_release) = NULL;
3812 	struct drm_device *dev = connector->dev;
3813 
3814 	/* MST handled by drm_mst framework */
3815 	if (aconnector->mst_mgr.mst_state == true)
3816 		return;
3817 
3818 	sink = aconnector->dc_link->local_sink;
3819 	if (sink)
3820 		dc_sink_retain(sink);
3821 
3822 	/*
3823 	 * Edid mgmt connector gets first update only in mode_valid hook and then
3824 	 * the connector sink is set to either fake or physical sink depends on link status.
3825 	 * Skip if already done during boot.
3826 	 */
3827 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
3828 			&& aconnector->dc_em_sink) {
3829 
3830 		/*
3831 		 * For S3 resume with headless use eml_sink to fake stream
3832 		 * because on resume connector->sink is set to NULL
3833 		 */
3834 		guard(mutex)(&dev->mode_config.mutex);
3835 
3836 		if (sink) {
3837 			if (aconnector->dc_sink) {
3838 				amdgpu_dm_update_freesync_caps(connector, NULL);
3839 				/*
3840 				 * retain and release below are used to
3841 				 * bump up refcount for sink because the link doesn't point
3842 				 * to it anymore after disconnect, so on next crtc to connector
3843 				 * reshuffle by UMD we will get into unwanted dc_sink release
3844 				 */
3845 				dc_sink_release(aconnector->dc_sink);
3846 			}
3847 			aconnector->dc_sink = sink;
3848 			dc_sink_retain(aconnector->dc_sink);
3849 			amdgpu_dm_update_freesync_caps(connector,
3850 					aconnector->drm_edid);
3851 		} else {
3852 			amdgpu_dm_update_freesync_caps(connector, NULL);
3853 			if (!aconnector->dc_sink) {
3854 				aconnector->dc_sink = aconnector->dc_em_sink;
3855 				dc_sink_retain(aconnector->dc_sink);
3856 			}
3857 		}
3858 
3859 		return;
3860 	}
3861 
3862 	/*
3863 	 * TODO: temporary guard to look for proper fix
3864 	 * if this sink is MST sink, we should not do anything
3865 	 */
3866 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
3867 		return;
3868 
3869 	if (aconnector->dc_sink == sink) {
3870 		/*
3871 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
3872 		 * Do nothing!!
3873 		 */
3874 		drm_dbg_kms(dev, "DCHPD: connector_id=%d: dc_sink didn't change.\n",
3875 				 aconnector->connector_id);
3876 		return;
3877 	}
3878 
3879 	drm_dbg_kms(dev, "DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
3880 		    aconnector->connector_id, aconnector->dc_sink, sink);
3881 
3882 	/* When polling, DRM has already locked the mutex for us. */
3883 	if (!drm_kms_helper_is_poll_worker())
3884 		mutex_lock(&dev->mode_config.mutex);
3885 
3886 	/*
3887 	 * 1. Update status of the drm connector
3888 	 * 2. Send an event and let userspace tell us what to do
3889 	 */
3890 	if (sink) {
3891 		/*
3892 		 * TODO: check if we still need the S3 mode update workaround.
3893 		 * If yes, put it here.
3894 		 */
3895 		if (aconnector->dc_sink) {
3896 			amdgpu_dm_update_freesync_caps(connector, NULL);
3897 			dc_sink_release(aconnector->dc_sink);
3898 		}
3899 
3900 		aconnector->dc_sink = sink;
3901 		dc_sink_retain(aconnector->dc_sink);
3902 		if (sink->dc_edid.length == 0) {
3903 			aconnector->drm_edid = NULL;
3904 			hdmi_cec_unset_edid(aconnector);
3905 			if (aconnector->dc_link->aux_mode) {
3906 				drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
3907 			}
3908 		} else {
3909 			const struct edid *edid = (const struct edid *)sink->dc_edid.raw_edid;
3910 
3911 			aconnector->drm_edid = drm_edid_alloc(edid, sink->dc_edid.length);
3912 			drm_edid_connector_update(connector, aconnector->drm_edid);
3913 
3914 			hdmi_cec_set_edid(aconnector);
3915 			if (aconnector->dc_link->aux_mode)
3916 				drm_dp_cec_attach(&aconnector->dm_dp_aux.aux,
3917 						  connector->display_info.source_physical_address);
3918 		}
3919 
3920 		if (!aconnector->timing_requested) {
3921 			aconnector->timing_requested =
3922 				kzalloc(sizeof(struct dc_crtc_timing), GFP_KERNEL);
3923 			if (!aconnector->timing_requested)
3924 				drm_err(dev,
3925 					"failed to create aconnector->requested_timing\n");
3926 		}
3927 
3928 		amdgpu_dm_update_freesync_caps(connector, aconnector->drm_edid);
3929 		update_connector_ext_caps(aconnector);
3930 	} else {
3931 		hdmi_cec_unset_edid(aconnector);
3932 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
3933 		amdgpu_dm_update_freesync_caps(connector, NULL);
3934 		aconnector->num_modes = 0;
3935 		dc_sink_release(aconnector->dc_sink);
3936 		aconnector->dc_sink = NULL;
3937 		drm_edid_free(aconnector->drm_edid);
3938 		aconnector->drm_edid = NULL;
3939 		kfree(aconnector->timing_requested);
3940 		aconnector->timing_requested = NULL;
3941 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
3942 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
3943 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
3944 	}
3945 
3946 	update_subconnector_property(aconnector);
3947 
3948 	/* When polling, the mutex will be unlocked for us by DRM. */
3949 	if (!drm_kms_helper_is_poll_worker())
3950 		mutex_unlock(&dev->mode_config.mutex);
3951 }
3952 
3953 static bool are_sinks_equal(const struct dc_sink *sink1, const struct dc_sink *sink2)
3954 {
3955 	if (!sink1 || !sink2)
3956 		return false;
3957 	if (sink1->sink_signal != sink2->sink_signal)
3958 		return false;
3959 
3960 	if (sink1->dc_edid.length != sink2->dc_edid.length)
3961 		return false;
3962 
3963 	if (memcmp(sink1->dc_edid.raw_edid, sink2->dc_edid.raw_edid,
3964 		   sink1->dc_edid.length) != 0)
3965 		return false;
3966 	return true;
3967 }
3968 
3969 
3970 /**
3971  * DOC: hdmi_hpd_debounce_work
3972  *
3973  * HDMI HPD debounce delay in milliseconds. When an HDMI display toggles HPD
3974  * (such as during power save transitions), this delay determines how long to
3975  * wait before processing the HPD event. This allows distinguishing between a
3976  * physical unplug (>hdmi_hpd_debounce_delay)
3977  * and a spontaneous RX HPD toggle (<hdmi_hpd_debounce_delay).
3978  *
3979  * If the toggle is less than this delay, the driver compares sink capabilities
3980  * and permits a hotplug event if they changed.
3981  *
3982  * The default value of 1500ms was chosen based on experimental testing with
3983  * various monitors that exhibit spontaneous HPD toggling behavior.
3984  */
3985 static void hdmi_hpd_debounce_work(struct work_struct *work)
3986 {
3987 	struct amdgpu_dm_connector *aconnector =
3988 		container_of(to_delayed_work(work), struct amdgpu_dm_connector,
3989 			     hdmi_hpd_debounce_work);
3990 	struct drm_connector *connector = &aconnector->base;
3991 	struct drm_device *dev = connector->dev;
3992 	struct amdgpu_device *adev = drm_to_adev(dev);
3993 	struct dc *dc = aconnector->dc_link->ctx->dc;
3994 	bool fake_reconnect = false;
3995 	bool reallow_idle = false;
3996 	bool ret = false;
3997 	guard(mutex)(&aconnector->hpd_lock);
3998 
3999 	/* Re-detect the display */
4000 	scoped_guard(mutex, &adev->dm.dc_lock) {
4001 		if (dc->caps.ips_support && dc->ctx->dmub_srv->idle_allowed) {
4002 			dc_allow_idle_optimizations(dc, false);
4003 			reallow_idle = true;
4004 		}
4005 		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4006 	}
4007 
4008 	if (ret) {
4009 		/* Apply workaround delay for certain panels */
4010 		apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4011 		/* Compare sinks to determine if this was a spontaneous HPD toggle */
4012 		if (are_sinks_equal(aconnector->dc_link->local_sink, aconnector->hdmi_prev_sink)) {
4013 			/*
4014 			* Sinks match - this was a spontaneous HDMI HPD toggle.
4015 			*/
4016 			drm_dbg_kms(dev, "HDMI HPD: Sink unchanged after debounce, internal re-enable\n");
4017 			fake_reconnect = true;
4018 		}
4019 
4020 		/* Update connector state */
4021 		amdgpu_dm_update_connector_after_detect(aconnector);
4022 
4023 		drm_modeset_lock_all(dev);
4024 		dm_restore_drm_connector_state(dev, connector);
4025 		drm_modeset_unlock_all(dev);
4026 
4027 		/* Only notify OS if sink actually changed */
4028 		if (!fake_reconnect && aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4029 			drm_kms_helper_hotplug_event(dev);
4030 	}
4031 
4032 	/* Release the cached sink reference */
4033 	if (aconnector->hdmi_prev_sink) {
4034 		dc_sink_release(aconnector->hdmi_prev_sink);
4035 		aconnector->hdmi_prev_sink = NULL;
4036 	}
4037 
4038 	scoped_guard(mutex, &adev->dm.dc_lock) {
4039 		if (reallow_idle && dc->caps.ips_support)
4040 			dc_allow_idle_optimizations(dc, true);
4041 	}
4042 }
4043 
4044 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
4045 {
4046 	struct drm_connector *connector = &aconnector->base;
4047 	struct drm_device *dev = connector->dev;
4048 	enum dc_connection_type new_connection_type = dc_connection_none;
4049 	struct amdgpu_device *adev = drm_to_adev(dev);
4050 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
4051 	struct dc *dc = aconnector->dc_link->ctx->dc;
4052 	bool ret = false;
4053 	bool debounce_required = false;
4054 
4055 	if (adev->dm.disable_hpd_irq)
4056 		return;
4057 
4058 	/*
4059 	 * In case of failure or MST no need to update connector status or notify the OS
4060 	 * since (for MST case) MST does this in its own context.
4061 	 */
4062 	guard(mutex)(&aconnector->hpd_lock);
4063 
4064 	if (adev->dm.hdcp_workqueue) {
4065 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
4066 		dm_con_state->update_hdcp = true;
4067 	}
4068 	if (aconnector->fake_enable)
4069 		aconnector->fake_enable = false;
4070 
4071 	aconnector->timing_changed = false;
4072 
4073 	if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
4074 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4075 
4076 	/*
4077 	 * Check for HDMI disconnect with debounce enabled.
4078 	 */
4079 	debounce_required = (aconnector->hdmi_hpd_debounce_delay_ms > 0 &&
4080 			      dc_is_hdmi_signal(aconnector->dc_link->connector_signal) &&
4081 			      new_connection_type == dc_connection_none &&
4082 			      aconnector->dc_link->local_sink != NULL);
4083 
4084 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
4085 		emulated_link_detect(aconnector->dc_link);
4086 
4087 		drm_modeset_lock_all(dev);
4088 		dm_restore_drm_connector_state(dev, connector);
4089 		drm_modeset_unlock_all(dev);
4090 
4091 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4092 			drm_kms_helper_connector_hotplug_event(connector);
4093 	} else if (debounce_required) {
4094 		/*
4095 		 * HDMI disconnect detected - schedule delayed work instead of
4096 		 * processing immediately. This allows us to coalesce spurious
4097 		 * HDMI signals from physical unplugs.
4098 		 */
4099 		drm_dbg_kms(dev, "HDMI HPD: Disconnect detected, scheduling debounce work (%u ms)\n",
4100 			    aconnector->hdmi_hpd_debounce_delay_ms);
4101 
4102 		/* Cache the current sink for later comparison */
4103 		if (aconnector->hdmi_prev_sink)
4104 			dc_sink_release(aconnector->hdmi_prev_sink);
4105 		aconnector->hdmi_prev_sink = aconnector->dc_link->local_sink;
4106 		if (aconnector->hdmi_prev_sink)
4107 			dc_sink_retain(aconnector->hdmi_prev_sink);
4108 
4109 		/* Schedule delayed detection. */
4110 		if (mod_delayed_work(system_wq,
4111 				 &aconnector->hdmi_hpd_debounce_work,
4112 				 msecs_to_jiffies(aconnector->hdmi_hpd_debounce_delay_ms)))
4113 			drm_dbg_kms(dev, "HDMI HPD: Re-scheduled debounce work\n");
4114 
4115 	} else {
4116 
4117 		/* If the aconnector->hdmi_hpd_debounce_work is scheduled, exit early */
4118 		if (delayed_work_pending(&aconnector->hdmi_hpd_debounce_work))
4119 			return;
4120 
4121 		scoped_guard(mutex, &adev->dm.dc_lock) {
4122 			dc_exit_ips_for_hw_access(dc);
4123 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4124 		}
4125 		if (ret) {
4126 			/* w/a delay for certain panels */
4127 			apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4128 			amdgpu_dm_update_connector_after_detect(aconnector);
4129 
4130 			drm_modeset_lock_all(dev);
4131 			dm_restore_drm_connector_state(dev, connector);
4132 			drm_modeset_unlock_all(dev);
4133 
4134 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4135 				drm_kms_helper_connector_hotplug_event(connector);
4136 		}
4137 	}
4138 }
4139 
4140 static void handle_hpd_irq(void *param)
4141 {
4142 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4143 
4144 	handle_hpd_irq_helper(aconnector);
4145 
4146 }
4147 
4148 static void schedule_hpd_rx_offload_work(struct amdgpu_device *adev, struct hpd_rx_irq_offload_work_queue *offload_wq,
4149 							union hpd_irq_data hpd_irq_data)
4150 {
4151 	struct hpd_rx_irq_offload_work *offload_work =
4152 				kzalloc(sizeof(*offload_work), GFP_KERNEL);
4153 
4154 	if (!offload_work) {
4155 		drm_err(adev_to_drm(adev), "Failed to allocate hpd_rx_irq_offload_work.\n");
4156 		return;
4157 	}
4158 
4159 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
4160 	offload_work->data = hpd_irq_data;
4161 	offload_work->offload_wq = offload_wq;
4162 	offload_work->adev = adev;
4163 
4164 	queue_work(offload_wq->wq, &offload_work->work);
4165 	drm_dbg_kms(adev_to_drm(adev), "queue work to handle hpd_rx offload work");
4166 }
4167 
4168 static void handle_hpd_rx_irq(void *param)
4169 {
4170 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4171 	struct drm_connector *connector = &aconnector->base;
4172 	struct drm_device *dev = connector->dev;
4173 	struct dc_link *dc_link = aconnector->dc_link;
4174 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
4175 	bool result = false;
4176 	enum dc_connection_type new_connection_type = dc_connection_none;
4177 	struct amdgpu_device *adev = drm_to_adev(dev);
4178 	union hpd_irq_data hpd_irq_data;
4179 	bool link_loss = false;
4180 	bool has_left_work = false;
4181 	int idx = dc_link->link_index;
4182 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
4183 	struct dc *dc = aconnector->dc_link->ctx->dc;
4184 
4185 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
4186 
4187 	if (adev->dm.disable_hpd_irq)
4188 		return;
4189 
4190 	/*
4191 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
4192 	 * conflict, after implement i2c helper, this mutex should be
4193 	 * retired.
4194 	 */
4195 	mutex_lock(&aconnector->hpd_lock);
4196 
4197 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
4198 						&link_loss, true, &has_left_work);
4199 
4200 	if (!has_left_work)
4201 		goto out;
4202 
4203 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
4204 		schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4205 		goto out;
4206 	}
4207 
4208 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
4209 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
4210 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
4211 			bool skip = false;
4212 
4213 			/*
4214 			 * DOWN_REP_MSG_RDY is also handled by polling method
4215 			 * mgr->cbs->poll_hpd_irq()
4216 			 */
4217 			spin_lock(&offload_wq->offload_lock);
4218 			skip = offload_wq->is_handling_mst_msg_rdy_event;
4219 
4220 			if (!skip)
4221 				offload_wq->is_handling_mst_msg_rdy_event = true;
4222 
4223 			spin_unlock(&offload_wq->offload_lock);
4224 
4225 			if (!skip)
4226 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4227 
4228 			goto out;
4229 		}
4230 
4231 		if (link_loss) {
4232 			bool skip = false;
4233 
4234 			spin_lock(&offload_wq->offload_lock);
4235 			skip = offload_wq->is_handling_link_loss;
4236 
4237 			if (!skip)
4238 				offload_wq->is_handling_link_loss = true;
4239 
4240 			spin_unlock(&offload_wq->offload_lock);
4241 
4242 			if (!skip)
4243 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4244 
4245 			goto out;
4246 		}
4247 	}
4248 
4249 out:
4250 	if (result && !is_mst_root_connector) {
4251 		/* Downstream Port status changed. */
4252 		if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
4253 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4254 
4255 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4256 			emulated_link_detect(dc_link);
4257 
4258 			if (aconnector->fake_enable)
4259 				aconnector->fake_enable = false;
4260 
4261 			amdgpu_dm_update_connector_after_detect(aconnector);
4262 
4263 
4264 			drm_modeset_lock_all(dev);
4265 			dm_restore_drm_connector_state(dev, connector);
4266 			drm_modeset_unlock_all(dev);
4267 
4268 			drm_kms_helper_connector_hotplug_event(connector);
4269 		} else {
4270 			bool ret = false;
4271 
4272 			mutex_lock(&adev->dm.dc_lock);
4273 			dc_exit_ips_for_hw_access(dc);
4274 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
4275 			mutex_unlock(&adev->dm.dc_lock);
4276 
4277 			if (ret) {
4278 				if (aconnector->fake_enable)
4279 					aconnector->fake_enable = false;
4280 
4281 				amdgpu_dm_update_connector_after_detect(aconnector);
4282 
4283 				drm_modeset_lock_all(dev);
4284 				dm_restore_drm_connector_state(dev, connector);
4285 				drm_modeset_unlock_all(dev);
4286 
4287 				drm_kms_helper_connector_hotplug_event(connector);
4288 			}
4289 		}
4290 	}
4291 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
4292 		if (adev->dm.hdcp_workqueue)
4293 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
4294 	}
4295 
4296 	if (dc_link->type != dc_connection_mst_branch)
4297 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
4298 
4299 	mutex_unlock(&aconnector->hpd_lock);
4300 }
4301 
4302 static int register_hpd_handlers(struct amdgpu_device *adev)
4303 {
4304 	struct drm_device *dev = adev_to_drm(adev);
4305 	struct drm_connector *connector;
4306 	struct amdgpu_dm_connector *aconnector;
4307 	const struct dc_link *dc_link;
4308 	struct dc_interrupt_params int_params = {0};
4309 
4310 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4311 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4312 
4313 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
4314 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD,
4315 			dmub_hpd_callback, true)) {
4316 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4317 			return -EINVAL;
4318 		}
4319 
4320 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ,
4321 			dmub_hpd_callback, true)) {
4322 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4323 			return -EINVAL;
4324 		}
4325 
4326 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_SENSE_NOTIFY,
4327 			dmub_hpd_sense_callback, true)) {
4328 			drm_err(adev_to_drm(adev), "fail to register dmub hpd sense callback");
4329 			return -EINVAL;
4330 		}
4331 	}
4332 
4333 	list_for_each_entry(connector,
4334 			&dev->mode_config.connector_list, head)	{
4335 
4336 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
4337 			continue;
4338 
4339 		aconnector = to_amdgpu_dm_connector(connector);
4340 		dc_link = aconnector->dc_link;
4341 
4342 		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
4343 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4344 			int_params.irq_source = dc_link->irq_source_hpd;
4345 
4346 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4347 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1 ||
4348 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6) {
4349 				drm_err(adev_to_drm(adev), "Failed to register hpd irq!\n");
4350 				return -EINVAL;
4351 			}
4352 
4353 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4354 				handle_hpd_irq, (void *) aconnector))
4355 				return -ENOMEM;
4356 		}
4357 
4358 		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
4359 
4360 			/* Also register for DP short pulse (hpd_rx). */
4361 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4362 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
4363 
4364 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4365 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1RX ||
4366 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6RX) {
4367 				drm_err(adev_to_drm(adev), "Failed to register hpd rx irq!\n");
4368 				return -EINVAL;
4369 			}
4370 
4371 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4372 				handle_hpd_rx_irq, (void *) aconnector))
4373 				return -ENOMEM;
4374 		}
4375 	}
4376 	return 0;
4377 }
4378 
4379 #if defined(CONFIG_DRM_AMD_DC_SI)
4380 /* Register IRQ sources and initialize IRQ callbacks */
4381 static int dce60_register_irq_handlers(struct amdgpu_device *adev)
4382 {
4383 	struct dc *dc = adev->dm.dc;
4384 	struct common_irq_params *c_irq_params;
4385 	struct dc_interrupt_params int_params = {0};
4386 	int r;
4387 	int i;
4388 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4389 
4390 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4391 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4392 
4393 	/*
4394 	 * Actions of amdgpu_irq_add_id():
4395 	 * 1. Register a set() function with base driver.
4396 	 *    Base driver will call set() function to enable/disable an
4397 	 *    interrupt in DC hardware.
4398 	 * 2. Register amdgpu_dm_irq_handler().
4399 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4400 	 *    coming from DC hardware.
4401 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4402 	 *    for acknowledging and handling.
4403 	 */
4404 
4405 	/* Use VBLANK interrupt */
4406 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
4407 		r = amdgpu_irq_add_id(adev, client_id, i + 1, &adev->crtc_irq);
4408 		if (r) {
4409 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4410 			return r;
4411 		}
4412 
4413 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4414 		int_params.irq_source =
4415 			dc_interrupt_to_irq_source(dc, i + 1, 0);
4416 
4417 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4418 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4419 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4420 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4421 			return -EINVAL;
4422 		}
4423 
4424 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4425 
4426 		c_irq_params->adev = adev;
4427 		c_irq_params->irq_src = int_params.irq_source;
4428 
4429 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4430 			dm_crtc_high_irq, c_irq_params))
4431 			return -ENOMEM;
4432 	}
4433 
4434 	/* Use GRPH_PFLIP interrupt */
4435 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4436 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4437 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4438 		if (r) {
4439 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4440 			return r;
4441 		}
4442 
4443 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4444 		int_params.irq_source =
4445 			dc_interrupt_to_irq_source(dc, i, 0);
4446 
4447 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4448 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4449 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4450 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4451 			return -EINVAL;
4452 		}
4453 
4454 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4455 
4456 		c_irq_params->adev = adev;
4457 		c_irq_params->irq_src = int_params.irq_source;
4458 
4459 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4460 			dm_pflip_high_irq, c_irq_params))
4461 			return -ENOMEM;
4462 	}
4463 
4464 	/* HPD */
4465 	r = amdgpu_irq_add_id(adev, client_id,
4466 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4467 	if (r) {
4468 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4469 		return r;
4470 	}
4471 
4472 	r = register_hpd_handlers(adev);
4473 
4474 	return r;
4475 }
4476 #endif
4477 
4478 /* Register IRQ sources and initialize IRQ callbacks */
4479 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
4480 {
4481 	struct dc *dc = adev->dm.dc;
4482 	struct common_irq_params *c_irq_params;
4483 	struct dc_interrupt_params int_params = {0};
4484 	int r;
4485 	int i;
4486 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4487 
4488 	if (adev->family >= AMDGPU_FAMILY_AI)
4489 		client_id = SOC15_IH_CLIENTID_DCE;
4490 
4491 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4492 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4493 
4494 	/*
4495 	 * Actions of amdgpu_irq_add_id():
4496 	 * 1. Register a set() function with base driver.
4497 	 *    Base driver will call set() function to enable/disable an
4498 	 *    interrupt in DC hardware.
4499 	 * 2. Register amdgpu_dm_irq_handler().
4500 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4501 	 *    coming from DC hardware.
4502 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4503 	 *    for acknowledging and handling.
4504 	 */
4505 
4506 	/* Use VBLANK interrupt */
4507 	for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
4508 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
4509 		if (r) {
4510 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4511 			return r;
4512 		}
4513 
4514 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4515 		int_params.irq_source =
4516 			dc_interrupt_to_irq_source(dc, i, 0);
4517 
4518 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4519 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4520 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4521 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4522 			return -EINVAL;
4523 		}
4524 
4525 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4526 
4527 		c_irq_params->adev = adev;
4528 		c_irq_params->irq_src = int_params.irq_source;
4529 
4530 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4531 			dm_crtc_high_irq, c_irq_params))
4532 			return -ENOMEM;
4533 	}
4534 
4535 	/* Use VUPDATE interrupt */
4536 	for (i = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT; i <= VISLANDS30_IV_SRCID_D6_V_UPDATE_INT; i += 2) {
4537 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->vupdate_irq);
4538 		if (r) {
4539 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4540 			return r;
4541 		}
4542 
4543 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4544 		int_params.irq_source =
4545 			dc_interrupt_to_irq_source(dc, i, 0);
4546 
4547 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4548 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4549 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4550 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4551 			return -EINVAL;
4552 		}
4553 
4554 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4555 
4556 		c_irq_params->adev = adev;
4557 		c_irq_params->irq_src = int_params.irq_source;
4558 
4559 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4560 			dm_vupdate_high_irq, c_irq_params))
4561 			return -ENOMEM;
4562 	}
4563 
4564 	/* Use GRPH_PFLIP interrupt */
4565 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4566 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4567 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4568 		if (r) {
4569 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4570 			return r;
4571 		}
4572 
4573 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4574 		int_params.irq_source =
4575 			dc_interrupt_to_irq_source(dc, i, 0);
4576 
4577 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4578 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4579 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4580 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4581 			return -EINVAL;
4582 		}
4583 
4584 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4585 
4586 		c_irq_params->adev = adev;
4587 		c_irq_params->irq_src = int_params.irq_source;
4588 
4589 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4590 			dm_pflip_high_irq, c_irq_params))
4591 			return -ENOMEM;
4592 	}
4593 
4594 	/* HPD */
4595 	r = amdgpu_irq_add_id(adev, client_id,
4596 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4597 	if (r) {
4598 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4599 		return r;
4600 	}
4601 
4602 	r = register_hpd_handlers(adev);
4603 
4604 	return r;
4605 }
4606 
4607 /* Register IRQ sources and initialize IRQ callbacks */
4608 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
4609 {
4610 	struct dc *dc = adev->dm.dc;
4611 	struct common_irq_params *c_irq_params;
4612 	struct dc_interrupt_params int_params = {0};
4613 	int r;
4614 	int i;
4615 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4616 	static const unsigned int vrtl_int_srcid[] = {
4617 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
4618 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
4619 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
4620 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
4621 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
4622 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
4623 	};
4624 #endif
4625 
4626 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4627 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4628 
4629 	/*
4630 	 * Actions of amdgpu_irq_add_id():
4631 	 * 1. Register a set() function with base driver.
4632 	 *    Base driver will call set() function to enable/disable an
4633 	 *    interrupt in DC hardware.
4634 	 * 2. Register amdgpu_dm_irq_handler().
4635 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4636 	 *    coming from DC hardware.
4637 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4638 	 *    for acknowledging and handling.
4639 	 */
4640 
4641 	/* Use VSTARTUP interrupt */
4642 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
4643 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
4644 			i++) {
4645 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
4646 
4647 		if (r) {
4648 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4649 			return r;
4650 		}
4651 
4652 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4653 		int_params.irq_source =
4654 			dc_interrupt_to_irq_source(dc, i, 0);
4655 
4656 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4657 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4658 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4659 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4660 			return -EINVAL;
4661 		}
4662 
4663 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4664 
4665 		c_irq_params->adev = adev;
4666 		c_irq_params->irq_src = int_params.irq_source;
4667 
4668 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4669 			dm_crtc_high_irq, c_irq_params))
4670 			return -ENOMEM;
4671 	}
4672 
4673 	/* Use otg vertical line interrupt */
4674 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4675 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
4676 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
4677 				vrtl_int_srcid[i], &adev->vline0_irq);
4678 
4679 		if (r) {
4680 			drm_err(adev_to_drm(adev), "Failed to add vline0 irq id!\n");
4681 			return r;
4682 		}
4683 
4684 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4685 		int_params.irq_source =
4686 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
4687 
4688 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4689 			int_params.irq_source < DC_IRQ_SOURCE_DC1_VLINE0 ||
4690 			int_params.irq_source > DC_IRQ_SOURCE_DC6_VLINE0) {
4691 			drm_err(adev_to_drm(adev), "Failed to register vline0 irq!\n");
4692 			return -EINVAL;
4693 		}
4694 
4695 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
4696 					- DC_IRQ_SOURCE_DC1_VLINE0];
4697 
4698 		c_irq_params->adev = adev;
4699 		c_irq_params->irq_src = int_params.irq_source;
4700 
4701 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4702 			dm_dcn_vertical_interrupt0_high_irq,
4703 			c_irq_params))
4704 			return -ENOMEM;
4705 	}
4706 #endif
4707 
4708 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
4709 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
4710 	 * to trigger at end of each vblank, regardless of state of the lock,
4711 	 * matching DCE behaviour.
4712 	 */
4713 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
4714 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
4715 	     i++) {
4716 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
4717 
4718 		if (r) {
4719 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4720 			return r;
4721 		}
4722 
4723 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4724 		int_params.irq_source =
4725 			dc_interrupt_to_irq_source(dc, i, 0);
4726 
4727 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4728 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4729 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4730 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4731 			return -EINVAL;
4732 		}
4733 
4734 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4735 
4736 		c_irq_params->adev = adev;
4737 		c_irq_params->irq_src = int_params.irq_source;
4738 
4739 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4740 			dm_vupdate_high_irq, c_irq_params))
4741 			return -ENOMEM;
4742 	}
4743 
4744 	/* Use GRPH_PFLIP interrupt */
4745 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
4746 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
4747 			i++) {
4748 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
4749 		if (r) {
4750 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4751 			return r;
4752 		}
4753 
4754 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4755 		int_params.irq_source =
4756 			dc_interrupt_to_irq_source(dc, i, 0);
4757 
4758 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4759 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4760 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4761 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4762 			return -EINVAL;
4763 		}
4764 
4765 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4766 
4767 		c_irq_params->adev = adev;
4768 		c_irq_params->irq_src = int_params.irq_source;
4769 
4770 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4771 			dm_pflip_high_irq, c_irq_params))
4772 			return -ENOMEM;
4773 	}
4774 
4775 	/* HPD */
4776 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
4777 			&adev->hpd_irq);
4778 	if (r) {
4779 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4780 		return r;
4781 	}
4782 
4783 	r = register_hpd_handlers(adev);
4784 
4785 	return r;
4786 }
4787 /* Register Outbox IRQ sources and initialize IRQ callbacks */
4788 static int register_outbox_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, i;
4794 
4795 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4796 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4797 
4798 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
4799 			&adev->dmub_outbox_irq);
4800 	if (r) {
4801 		drm_err(adev_to_drm(adev), "Failed to add outbox irq id!\n");
4802 		return r;
4803 	}
4804 
4805 	if (dc->ctx->dmub_srv) {
4806 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
4807 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4808 		int_params.irq_source =
4809 		dc_interrupt_to_irq_source(dc, i, 0);
4810 
4811 		c_irq_params = &adev->dm.dmub_outbox_params[0];
4812 
4813 		c_irq_params->adev = adev;
4814 		c_irq_params->irq_src = int_params.irq_source;
4815 
4816 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4817 			dm_dmub_outbox1_low_irq, c_irq_params))
4818 			return -ENOMEM;
4819 	}
4820 
4821 	return 0;
4822 }
4823 
4824 /*
4825  * Acquires the lock for the atomic state object and returns
4826  * the new atomic state.
4827  *
4828  * This should only be called during atomic check.
4829  */
4830 int dm_atomic_get_state(struct drm_atomic_state *state,
4831 			struct dm_atomic_state **dm_state)
4832 {
4833 	struct drm_device *dev = state->dev;
4834 	struct amdgpu_device *adev = drm_to_adev(dev);
4835 	struct amdgpu_display_manager *dm = &adev->dm;
4836 	struct drm_private_state *priv_state;
4837 
4838 	if (*dm_state)
4839 		return 0;
4840 
4841 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
4842 	if (IS_ERR(priv_state))
4843 		return PTR_ERR(priv_state);
4844 
4845 	*dm_state = to_dm_atomic_state(priv_state);
4846 
4847 	return 0;
4848 }
4849 
4850 static struct dm_atomic_state *
4851 dm_atomic_get_new_state(struct drm_atomic_state *state)
4852 {
4853 	struct drm_device *dev = state->dev;
4854 	struct amdgpu_device *adev = drm_to_adev(dev);
4855 	struct amdgpu_display_manager *dm = &adev->dm;
4856 	struct drm_private_obj *obj;
4857 	struct drm_private_state *new_obj_state;
4858 	int i;
4859 
4860 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
4861 		if (obj->funcs == dm->atomic_obj.funcs)
4862 			return to_dm_atomic_state(new_obj_state);
4863 	}
4864 
4865 	return NULL;
4866 }
4867 
4868 static struct drm_private_state *
4869 dm_atomic_duplicate_state(struct drm_private_obj *obj)
4870 {
4871 	struct dm_atomic_state *old_state, *new_state;
4872 
4873 	new_state = kzalloc(sizeof(*new_state), GFP_KERNEL);
4874 	if (!new_state)
4875 		return NULL;
4876 
4877 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
4878 
4879 	old_state = to_dm_atomic_state(obj->state);
4880 
4881 	if (old_state && old_state->context)
4882 		new_state->context = dc_state_create_copy(old_state->context);
4883 
4884 	if (!new_state->context) {
4885 		kfree(new_state);
4886 		return NULL;
4887 	}
4888 
4889 	return &new_state->base;
4890 }
4891 
4892 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
4893 				    struct drm_private_state *state)
4894 {
4895 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4896 
4897 	if (dm_state && dm_state->context)
4898 		dc_state_release(dm_state->context);
4899 
4900 	kfree(dm_state);
4901 }
4902 
4903 static struct drm_private_state_funcs dm_atomic_state_funcs = {
4904 	.atomic_duplicate_state = dm_atomic_duplicate_state,
4905 	.atomic_destroy_state = dm_atomic_destroy_state,
4906 };
4907 
4908 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
4909 {
4910 	struct dm_atomic_state *state;
4911 	int r;
4912 
4913 	adev->mode_info.mode_config_initialized = true;
4914 
4915 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
4916 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
4917 
4918 	adev_to_drm(adev)->mode_config.max_width = 16384;
4919 	adev_to_drm(adev)->mode_config.max_height = 16384;
4920 
4921 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
4922 	if (adev->asic_type == CHIP_HAWAII)
4923 		/* disable prefer shadow for now due to hibernation issues */
4924 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
4925 	else
4926 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
4927 	/* indicates support for immediate flip */
4928 	adev_to_drm(adev)->mode_config.async_page_flip = true;
4929 
4930 	state = kzalloc(sizeof(*state), GFP_KERNEL);
4931 	if (!state)
4932 		return -ENOMEM;
4933 
4934 	state->context = dc_state_create_current_copy(adev->dm.dc);
4935 	if (!state->context) {
4936 		kfree(state);
4937 		return -ENOMEM;
4938 	}
4939 
4940 	drm_atomic_private_obj_init(adev_to_drm(adev),
4941 				    &adev->dm.atomic_obj,
4942 				    &state->base,
4943 				    &dm_atomic_state_funcs);
4944 
4945 	r = amdgpu_display_modeset_create_props(adev);
4946 	if (r) {
4947 		dc_state_release(state->context);
4948 		kfree(state);
4949 		return r;
4950 	}
4951 
4952 #ifdef AMD_PRIVATE_COLOR
4953 	if (amdgpu_dm_create_color_properties(adev)) {
4954 		dc_state_release(state->context);
4955 		kfree(state);
4956 		return -ENOMEM;
4957 	}
4958 #endif
4959 
4960 	r = amdgpu_dm_audio_init(adev);
4961 	if (r) {
4962 		dc_state_release(state->context);
4963 		kfree(state);
4964 		return r;
4965 	}
4966 
4967 	return 0;
4968 }
4969 
4970 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
4971 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
4972 #define AMDGPU_DM_MIN_SPREAD ((AMDGPU_DM_DEFAULT_MAX_BACKLIGHT - AMDGPU_DM_DEFAULT_MIN_BACKLIGHT) / 2)
4973 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
4974 
4975 static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
4976 					    int bl_idx)
4977 {
4978 	struct amdgpu_dm_backlight_caps *caps = &dm->backlight_caps[bl_idx];
4979 
4980 	if (caps->caps_valid)
4981 		return;
4982 
4983 #if defined(CONFIG_ACPI)
4984 	amdgpu_acpi_get_backlight_caps(caps);
4985 
4986 	/* validate the firmware value is sane */
4987 	if (caps->caps_valid) {
4988 		int spread = caps->max_input_signal - caps->min_input_signal;
4989 
4990 		if (caps->max_input_signal > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
4991 		    caps->min_input_signal < 0 ||
4992 		    spread > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
4993 		    spread < AMDGPU_DM_MIN_SPREAD) {
4994 			drm_dbg_kms(adev_to_drm(dm->adev), "DM: Invalid backlight caps: min=%d, max=%d\n",
4995 				      caps->min_input_signal, caps->max_input_signal);
4996 			caps->caps_valid = false;
4997 		}
4998 	}
4999 
5000 	if (!caps->caps_valid) {
5001 		caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5002 		caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5003 		caps->caps_valid = true;
5004 	}
5005 #else
5006 	if (caps->aux_support)
5007 		return;
5008 
5009 	caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5010 	caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5011 	caps->caps_valid = true;
5012 #endif
5013 }
5014 
5015 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
5016 				unsigned int *min, unsigned int *max)
5017 {
5018 	if (!caps)
5019 		return 0;
5020 
5021 	if (caps->aux_support) {
5022 		// Firmware limits are in nits, DC API wants millinits.
5023 		*max = 1000 * caps->aux_max_input_signal;
5024 		*min = 1000 * caps->aux_min_input_signal;
5025 	} else {
5026 		// Firmware limits are 8-bit, PWM control is 16-bit.
5027 		*max = 0x101 * caps->max_input_signal;
5028 		*min = 0x101 * caps->min_input_signal;
5029 	}
5030 	return 1;
5031 }
5032 
5033 /* Rescale from [min..max] to [0..AMDGPU_MAX_BL_LEVEL] */
5034 static inline u32 scale_input_to_fw(int min, int max, u64 input)
5035 {
5036 	return DIV_ROUND_CLOSEST_ULL(input * AMDGPU_MAX_BL_LEVEL, max - min);
5037 }
5038 
5039 /* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [min..max] */
5040 static inline u32 scale_fw_to_input(int min, int max, u64 input)
5041 {
5042 	return min + DIV_ROUND_CLOSEST_ULL(input * (max - min), AMDGPU_MAX_BL_LEVEL);
5043 }
5044 
5045 static void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps,
5046 				      unsigned int min, unsigned int max,
5047 				      uint32_t *user_brightness)
5048 {
5049 	u32 brightness = scale_input_to_fw(min, max, *user_brightness);
5050 	u8 lower_signal, upper_signal, upper_lum, lower_lum, lum;
5051 	int left, right;
5052 
5053 	if (amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)
5054 		return;
5055 
5056 	if (!caps->data_points)
5057 		return;
5058 
5059 	/*
5060 	 * Handle the case where brightness is below the first data point
5061 	 * Interpolate between (0,0) and (first_signal, first_lum)
5062 	 */
5063 	if (brightness < caps->luminance_data[0].input_signal) {
5064 		lum = DIV_ROUND_CLOSEST(caps->luminance_data[0].luminance * brightness,
5065 					caps->luminance_data[0].input_signal);
5066 		goto scale;
5067 	}
5068 
5069 	left = 0;
5070 	right = caps->data_points - 1;
5071 	while (left <= right) {
5072 		int mid = left + (right - left) / 2;
5073 		u8 signal = caps->luminance_data[mid].input_signal;
5074 
5075 		/* Exact match found */
5076 		if (signal == brightness) {
5077 			lum = caps->luminance_data[mid].luminance;
5078 			goto scale;
5079 		}
5080 
5081 		if (signal < brightness)
5082 			left = mid + 1;
5083 		else
5084 			right = mid - 1;
5085 	}
5086 
5087 	/* verify bound */
5088 	if (left >= caps->data_points)
5089 		left = caps->data_points - 1;
5090 
5091 	/* At this point, left > right */
5092 	lower_signal = caps->luminance_data[right].input_signal;
5093 	upper_signal = caps->luminance_data[left].input_signal;
5094 	lower_lum = caps->luminance_data[right].luminance;
5095 	upper_lum = caps->luminance_data[left].luminance;
5096 
5097 	/* interpolate */
5098 	if (right == left || !lower_lum)
5099 		lum = upper_lum;
5100 	else
5101 		lum = lower_lum + DIV_ROUND_CLOSEST((upper_lum - lower_lum) *
5102 						    (brightness - lower_signal),
5103 						    upper_signal - lower_signal);
5104 scale:
5105 	*user_brightness = scale_fw_to_input(min, max,
5106 					     DIV_ROUND_CLOSEST(lum * brightness, 101));
5107 }
5108 
5109 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
5110 					uint32_t brightness)
5111 {
5112 	unsigned int min, max;
5113 
5114 	if (!get_brightness_range(caps, &min, &max))
5115 		return brightness;
5116 
5117 	convert_custom_brightness(caps, min, max, &brightness);
5118 
5119 	// Rescale 0..max to min..max
5120 	return min + DIV_ROUND_CLOSEST_ULL((u64)(max - min) * brightness, max);
5121 }
5122 
5123 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
5124 				      uint32_t brightness)
5125 {
5126 	unsigned int min, max;
5127 
5128 	if (!get_brightness_range(caps, &min, &max))
5129 		return brightness;
5130 
5131 	if (brightness < min)
5132 		return 0;
5133 	// Rescale min..max to 0..max
5134 	return DIV_ROUND_CLOSEST_ULL((u64)max * (brightness - min),
5135 				 max - min);
5136 }
5137 
5138 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
5139 					 int bl_idx,
5140 					 u32 user_brightness)
5141 {
5142 	struct amdgpu_dm_backlight_caps *caps;
5143 	struct dc_link *link;
5144 	u32 brightness;
5145 	bool rc, reallow_idle = false;
5146 	struct drm_connector *connector;
5147 
5148 	list_for_each_entry(connector, &dm->ddev->mode_config.connector_list, head) {
5149 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5150 
5151 		if (aconnector->bl_idx != bl_idx)
5152 			continue;
5153 
5154 		/* if connector is off, save the brightness for next time it's on */
5155 		if (!aconnector->base.encoder) {
5156 			dm->brightness[bl_idx] = user_brightness;
5157 			dm->actual_brightness[bl_idx] = 0;
5158 			return;
5159 		}
5160 	}
5161 
5162 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5163 	caps = &dm->backlight_caps[bl_idx];
5164 
5165 	dm->brightness[bl_idx] = user_brightness;
5166 	/* update scratch register */
5167 	if (bl_idx == 0)
5168 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
5169 	brightness = convert_brightness_from_user(caps, dm->brightness[bl_idx]);
5170 	link = (struct dc_link *)dm->backlight_link[bl_idx];
5171 
5172 	/* Apply brightness quirk */
5173 	if (caps->brightness_mask)
5174 		brightness |= caps->brightness_mask;
5175 
5176 	/* Change brightness based on AUX property */
5177 	mutex_lock(&dm->dc_lock);
5178 	if (dm->dc->caps.ips_support && dm->dc->ctx->dmub_srv->idle_allowed) {
5179 		dc_allow_idle_optimizations(dm->dc, false);
5180 		reallow_idle = true;
5181 	}
5182 
5183 	if (trace_amdgpu_dm_brightness_enabled()) {
5184 		trace_amdgpu_dm_brightness(__builtin_return_address(0),
5185 					   user_brightness,
5186 					   brightness,
5187 					   caps->aux_support,
5188 					   power_supply_is_system_supplied() > 0);
5189 	}
5190 
5191 	if (caps->aux_support) {
5192 		rc = dc_link_set_backlight_level_nits(link, true, brightness,
5193 						      AUX_BL_DEFAULT_TRANSITION_TIME_MS);
5194 		if (!rc)
5195 			DRM_DEBUG("DM: Failed to update backlight via AUX on eDP[%d]\n", bl_idx);
5196 	} else {
5197 		struct set_backlight_level_params backlight_level_params = { 0 };
5198 
5199 		backlight_level_params.backlight_pwm_u16_16 = brightness;
5200 		backlight_level_params.transition_time_in_ms = 0;
5201 
5202 		rc = dc_link_set_backlight_level(link, &backlight_level_params);
5203 		if (!rc)
5204 			DRM_DEBUG("DM: Failed to update backlight on eDP[%d]\n", bl_idx);
5205 	}
5206 
5207 	if (dm->dc->caps.ips_support && reallow_idle)
5208 		dc_allow_idle_optimizations(dm->dc, true);
5209 
5210 	mutex_unlock(&dm->dc_lock);
5211 
5212 	if (rc)
5213 		dm->actual_brightness[bl_idx] = user_brightness;
5214 }
5215 
5216 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
5217 {
5218 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5219 	int i;
5220 
5221 	for (i = 0; i < dm->num_of_edps; i++) {
5222 		if (bd == dm->backlight_dev[i])
5223 			break;
5224 	}
5225 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5226 		i = 0;
5227 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
5228 
5229 	return 0;
5230 }
5231 
5232 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
5233 					 int bl_idx)
5234 {
5235 	int ret;
5236 	struct amdgpu_dm_backlight_caps caps;
5237 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
5238 
5239 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5240 	caps = dm->backlight_caps[bl_idx];
5241 
5242 	if (caps.aux_support) {
5243 		u32 avg, peak;
5244 
5245 		if (!dc_link_get_backlight_level_nits(link, &avg, &peak))
5246 			return dm->brightness[bl_idx];
5247 		return convert_brightness_to_user(&caps, avg);
5248 	}
5249 
5250 	ret = dc_link_get_backlight_level(link);
5251 
5252 	if (ret == DC_ERROR_UNEXPECTED)
5253 		return dm->brightness[bl_idx];
5254 
5255 	return convert_brightness_to_user(&caps, ret);
5256 }
5257 
5258 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
5259 {
5260 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5261 	int i;
5262 
5263 	for (i = 0; i < dm->num_of_edps; i++) {
5264 		if (bd == dm->backlight_dev[i])
5265 			break;
5266 	}
5267 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5268 		i = 0;
5269 	return amdgpu_dm_backlight_get_level(dm, i);
5270 }
5271 
5272 static const struct backlight_ops amdgpu_dm_backlight_ops = {
5273 	.options = BL_CORE_SUSPENDRESUME,
5274 	.get_brightness = amdgpu_dm_backlight_get_brightness,
5275 	.update_status	= amdgpu_dm_backlight_update_status,
5276 };
5277 
5278 static void
5279 amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector *aconnector)
5280 {
5281 	struct drm_device *drm = aconnector->base.dev;
5282 	struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
5283 	struct backlight_properties props = { 0 };
5284 	struct amdgpu_dm_backlight_caps *caps;
5285 	char bl_name[16];
5286 	int min, max;
5287 	int real_brightness;
5288 	int init_brightness;
5289 
5290 	if (aconnector->bl_idx == -1)
5291 		return;
5292 
5293 	if (!acpi_video_backlight_use_native()) {
5294 		drm_info(drm, "Skipping amdgpu DM backlight registration\n");
5295 		/* Try registering an ACPI video backlight device instead. */
5296 		acpi_video_register_backlight();
5297 		return;
5298 	}
5299 
5300 	caps = &dm->backlight_caps[aconnector->bl_idx];
5301 	if (get_brightness_range(caps, &min, &max)) {
5302 		if (power_supply_is_system_supplied() > 0)
5303 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->ac_level, 100);
5304 		else
5305 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->dc_level, 100);
5306 		/* min is zero, so max needs to be adjusted */
5307 		props.max_brightness = max - min;
5308 		drm_dbg(drm, "Backlight caps: min: %d, max: %d, ac %d, dc %d\n", min, max,
5309 			caps->ac_level, caps->dc_level);
5310 	} else
5311 		props.brightness = props.max_brightness = MAX_BACKLIGHT_LEVEL;
5312 
5313 	init_brightness = props.brightness;
5314 
5315 	if (caps->data_points && !(amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)) {
5316 		drm_info(drm, "Using custom brightness curve\n");
5317 		props.scale = BACKLIGHT_SCALE_NON_LINEAR;
5318 	} else
5319 		props.scale = BACKLIGHT_SCALE_LINEAR;
5320 	props.type = BACKLIGHT_RAW;
5321 
5322 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
5323 		 drm->primary->index + aconnector->bl_idx);
5324 
5325 	dm->backlight_dev[aconnector->bl_idx] =
5326 		backlight_device_register(bl_name, aconnector->base.kdev, dm,
5327 					  &amdgpu_dm_backlight_ops, &props);
5328 	dm->brightness[aconnector->bl_idx] = props.brightness;
5329 
5330 	if (IS_ERR(dm->backlight_dev[aconnector->bl_idx])) {
5331 		drm_err(drm, "DM: Backlight registration failed!\n");
5332 		dm->backlight_dev[aconnector->bl_idx] = NULL;
5333 	} else {
5334 		/*
5335 		 * dm->brightness[x] can be inconsistent just after startup until
5336 		 * ops.get_brightness is called.
5337 		 */
5338 		real_brightness =
5339 			amdgpu_dm_backlight_ops.get_brightness(dm->backlight_dev[aconnector->bl_idx]);
5340 
5341 		if (real_brightness != init_brightness) {
5342 			dm->actual_brightness[aconnector->bl_idx] = real_brightness;
5343 			dm->brightness[aconnector->bl_idx] = real_brightness;
5344 		}
5345 		drm_dbg_driver(drm, "DM: Registered Backlight device: %s\n", bl_name);
5346 	}
5347 }
5348 
5349 static int initialize_plane(struct amdgpu_display_manager *dm,
5350 			    struct amdgpu_mode_info *mode_info, int plane_id,
5351 			    enum drm_plane_type plane_type,
5352 			    const struct dc_plane_cap *plane_cap)
5353 {
5354 	struct drm_plane *plane;
5355 	unsigned long possible_crtcs;
5356 	int ret = 0;
5357 
5358 	plane = kzalloc(sizeof(struct drm_plane), GFP_KERNEL);
5359 	if (!plane) {
5360 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
5361 		return -ENOMEM;
5362 	}
5363 	plane->type = plane_type;
5364 
5365 	/*
5366 	 * HACK: IGT tests expect that the primary plane for a CRTC
5367 	 * can only have one possible CRTC. Only expose support for
5368 	 * any CRTC if they're not going to be used as a primary plane
5369 	 * for a CRTC - like overlay or underlay planes.
5370 	 */
5371 	possible_crtcs = 1 << plane_id;
5372 	if (plane_id >= dm->dc->caps.max_streams)
5373 		possible_crtcs = 0xff;
5374 
5375 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
5376 
5377 	if (ret) {
5378 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
5379 		kfree(plane);
5380 		return ret;
5381 	}
5382 
5383 	if (mode_info)
5384 		mode_info->planes[plane_id] = plane;
5385 
5386 	return ret;
5387 }
5388 
5389 
5390 static void setup_backlight_device(struct amdgpu_display_manager *dm,
5391 				   struct amdgpu_dm_connector *aconnector)
5392 {
5393 	struct amdgpu_dm_backlight_caps *caps;
5394 	struct dc_link *link = aconnector->dc_link;
5395 	int bl_idx = dm->num_of_edps;
5396 
5397 	if (!(link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) ||
5398 	    link->type == dc_connection_none)
5399 		return;
5400 
5401 	if (dm->num_of_edps >= AMDGPU_DM_MAX_NUM_EDP) {
5402 		drm_warn(adev_to_drm(dm->adev), "Too much eDP connections, skipping backlight setup for additional eDPs\n");
5403 		return;
5404 	}
5405 
5406 	aconnector->bl_idx = bl_idx;
5407 
5408 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5409 	dm->backlight_link[bl_idx] = link;
5410 	dm->num_of_edps++;
5411 
5412 	update_connector_ext_caps(aconnector);
5413 	caps = &dm->backlight_caps[aconnector->bl_idx];
5414 
5415 	/* Only offer ABM property when non-OLED and user didn't turn off by module parameter */
5416 	if (!caps->ext_caps->bits.oled && amdgpu_dm_abm_level < 0)
5417 		drm_object_attach_property(&aconnector->base.base,
5418 					   dm->adev->mode_info.abm_level_property,
5419 					   ABM_SYSFS_CONTROL);
5420 }
5421 
5422 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
5423 
5424 /*
5425  * In this architecture, the association
5426  * connector -> encoder -> crtc
5427  * id not really requried. The crtc and connector will hold the
5428  * display_index as an abstraction to use with DAL component
5429  *
5430  * Returns 0 on success
5431  */
5432 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
5433 {
5434 	struct amdgpu_display_manager *dm = &adev->dm;
5435 	s32 i;
5436 	struct amdgpu_dm_connector *aconnector = NULL;
5437 	struct amdgpu_encoder *aencoder = NULL;
5438 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5439 	u32 link_cnt;
5440 	s32 primary_planes;
5441 	enum dc_connection_type new_connection_type = dc_connection_none;
5442 	const struct dc_plane_cap *plane;
5443 	bool psr_feature_enabled = false;
5444 	bool replay_feature_enabled = false;
5445 	int max_overlay = dm->dc->caps.max_slave_planes;
5446 
5447 	dm->display_indexes_num = dm->dc->caps.max_streams;
5448 	/* Update the actual used number of crtc */
5449 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
5450 
5451 	amdgpu_dm_set_irq_funcs(adev);
5452 
5453 	link_cnt = dm->dc->caps.max_links;
5454 	if (amdgpu_dm_mode_config_init(dm->adev)) {
5455 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
5456 		return -EINVAL;
5457 	}
5458 
5459 	/* There is one primary plane per CRTC */
5460 	primary_planes = dm->dc->caps.max_streams;
5461 	if (primary_planes > AMDGPU_MAX_PLANES) {
5462 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
5463 		return -EINVAL;
5464 	}
5465 
5466 	/*
5467 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
5468 	 * Order is reversed to match iteration order in atomic check.
5469 	 */
5470 	for (i = (primary_planes - 1); i >= 0; i--) {
5471 		plane = &dm->dc->caps.planes[i];
5472 
5473 		if (initialize_plane(dm, mode_info, i,
5474 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
5475 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
5476 			goto fail;
5477 		}
5478 	}
5479 
5480 	/*
5481 	 * Initialize overlay planes, index starting after primary planes.
5482 	 * These planes have a higher DRM index than the primary planes since
5483 	 * they should be considered as having a higher z-order.
5484 	 * Order is reversed to match iteration order in atomic check.
5485 	 *
5486 	 * Only support DCN for now, and only expose one so we don't encourage
5487 	 * userspace to use up all the pipes.
5488 	 */
5489 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
5490 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
5491 
5492 		/* Do not create overlay if MPO disabled */
5493 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
5494 			break;
5495 
5496 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
5497 			continue;
5498 
5499 		if (!plane->pixel_format_support.argb8888)
5500 			continue;
5501 
5502 		if (max_overlay-- == 0)
5503 			break;
5504 
5505 		if (initialize_plane(dm, NULL, primary_planes + i,
5506 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
5507 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
5508 			goto fail;
5509 		}
5510 	}
5511 
5512 	for (i = 0; i < dm->dc->caps.max_streams; i++)
5513 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
5514 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
5515 			goto fail;
5516 		}
5517 
5518 	/* Use Outbox interrupt */
5519 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5520 	case IP_VERSION(3, 0, 0):
5521 	case IP_VERSION(3, 1, 2):
5522 	case IP_VERSION(3, 1, 3):
5523 	case IP_VERSION(3, 1, 4):
5524 	case IP_VERSION(3, 1, 5):
5525 	case IP_VERSION(3, 1, 6):
5526 	case IP_VERSION(3, 2, 0):
5527 	case IP_VERSION(3, 2, 1):
5528 	case IP_VERSION(2, 1, 0):
5529 	case IP_VERSION(3, 5, 0):
5530 	case IP_VERSION(3, 5, 1):
5531 	case IP_VERSION(3, 6, 0):
5532 	case IP_VERSION(4, 0, 1):
5533 		if (register_outbox_irq_handlers(dm->adev)) {
5534 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5535 			goto fail;
5536 		}
5537 		break;
5538 	default:
5539 		drm_dbg_kms(adev_to_drm(adev), "Unsupported DCN IP version for outbox: 0x%X\n",
5540 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
5541 	}
5542 
5543 	/* Determine whether to enable PSR support by default. */
5544 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
5545 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5546 		case IP_VERSION(3, 1, 2):
5547 		case IP_VERSION(3, 1, 3):
5548 		case IP_VERSION(3, 1, 4):
5549 		case IP_VERSION(3, 1, 5):
5550 		case IP_VERSION(3, 1, 6):
5551 		case IP_VERSION(3, 2, 0):
5552 		case IP_VERSION(3, 2, 1):
5553 		case IP_VERSION(3, 5, 0):
5554 		case IP_VERSION(3, 5, 1):
5555 		case IP_VERSION(3, 6, 0):
5556 		case IP_VERSION(4, 0, 1):
5557 			psr_feature_enabled = true;
5558 			break;
5559 		default:
5560 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
5561 			break;
5562 		}
5563 	}
5564 
5565 	/* Determine whether to enable Replay support by default. */
5566 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
5567 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5568 		case IP_VERSION(3, 1, 4):
5569 		case IP_VERSION(3, 2, 0):
5570 		case IP_VERSION(3, 2, 1):
5571 		case IP_VERSION(3, 5, 0):
5572 		case IP_VERSION(3, 5, 1):
5573 		case IP_VERSION(3, 6, 0):
5574 			replay_feature_enabled = true;
5575 			break;
5576 
5577 		default:
5578 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
5579 			break;
5580 		}
5581 	}
5582 
5583 	if (link_cnt > MAX_LINKS) {
5584 		drm_err(adev_to_drm(adev),
5585 			"KMS: Cannot support more than %d display indexes\n",
5586 				MAX_LINKS);
5587 		goto fail;
5588 	}
5589 
5590 	/* loops over all connectors on the board */
5591 	for (i = 0; i < link_cnt; i++) {
5592 		struct dc_link *link = NULL;
5593 
5594 		link = dc_get_link_at_index(dm->dc, i);
5595 
5596 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
5597 			struct amdgpu_dm_wb_connector *wbcon = kzalloc(sizeof(*wbcon), GFP_KERNEL);
5598 
5599 			if (!wbcon) {
5600 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
5601 				continue;
5602 			}
5603 
5604 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
5605 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
5606 				kfree(wbcon);
5607 				continue;
5608 			}
5609 
5610 			link->psr_settings.psr_feature_enabled = false;
5611 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
5612 
5613 			continue;
5614 		}
5615 
5616 		aconnector = kzalloc(sizeof(*aconnector), GFP_KERNEL);
5617 		if (!aconnector)
5618 			goto fail;
5619 
5620 		aencoder = kzalloc(sizeof(*aencoder), GFP_KERNEL);
5621 		if (!aencoder)
5622 			goto fail;
5623 
5624 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
5625 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
5626 			goto fail;
5627 		}
5628 
5629 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
5630 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
5631 			goto fail;
5632 		}
5633 
5634 		if (dm->hpd_rx_offload_wq)
5635 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
5636 				aconnector;
5637 
5638 		if (!dc_link_detect_connection_type(link, &new_connection_type))
5639 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
5640 
5641 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
5642 			emulated_link_detect(link);
5643 			amdgpu_dm_update_connector_after_detect(aconnector);
5644 		} else {
5645 			bool ret = false;
5646 
5647 			mutex_lock(&dm->dc_lock);
5648 			dc_exit_ips_for_hw_access(dm->dc);
5649 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
5650 			mutex_unlock(&dm->dc_lock);
5651 
5652 			if (ret) {
5653 				amdgpu_dm_update_connector_after_detect(aconnector);
5654 				setup_backlight_device(dm, aconnector);
5655 
5656 				/* Disable PSR if Replay can be enabled */
5657 				if (replay_feature_enabled)
5658 					if (amdgpu_dm_set_replay_caps(link, aconnector))
5659 						psr_feature_enabled = false;
5660 
5661 				if (psr_feature_enabled) {
5662 					amdgpu_dm_set_psr_caps(link);
5663 					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",
5664 						 aconnector->base.name,
5665 						 link->psr_settings.psr_feature_enabled,
5666 						 link->psr_settings.psr_version,
5667 						 link->dpcd_caps.psr_info.psr_version,
5668 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
5669 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
5670 				}
5671 			}
5672 		}
5673 		amdgpu_set_panel_orientation(&aconnector->base);
5674 	}
5675 
5676 	/* Debug dump: list all DC links and their associated sinks after detection
5677 	 * is complete for all connectors. This provides a comprehensive view of the
5678 	 * final state without repeating the dump for each connector.
5679 	 */
5680 	amdgpu_dm_dump_links_and_sinks(adev);
5681 
5682 	/* Software is initialized. Now we can register interrupt handlers. */
5683 	switch (adev->asic_type) {
5684 #if defined(CONFIG_DRM_AMD_DC_SI)
5685 	case CHIP_TAHITI:
5686 	case CHIP_PITCAIRN:
5687 	case CHIP_VERDE:
5688 	case CHIP_OLAND:
5689 		if (dce60_register_irq_handlers(dm->adev)) {
5690 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5691 			goto fail;
5692 		}
5693 		break;
5694 #endif
5695 	case CHIP_BONAIRE:
5696 	case CHIP_HAWAII:
5697 	case CHIP_KAVERI:
5698 	case CHIP_KABINI:
5699 	case CHIP_MULLINS:
5700 	case CHIP_TONGA:
5701 	case CHIP_FIJI:
5702 	case CHIP_CARRIZO:
5703 	case CHIP_STONEY:
5704 	case CHIP_POLARIS11:
5705 	case CHIP_POLARIS10:
5706 	case CHIP_POLARIS12:
5707 	case CHIP_VEGAM:
5708 	case CHIP_VEGA10:
5709 	case CHIP_VEGA12:
5710 	case CHIP_VEGA20:
5711 		if (dce110_register_irq_handlers(dm->adev)) {
5712 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5713 			goto fail;
5714 		}
5715 		break;
5716 	default:
5717 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5718 		case IP_VERSION(1, 0, 0):
5719 		case IP_VERSION(1, 0, 1):
5720 		case IP_VERSION(2, 0, 2):
5721 		case IP_VERSION(2, 0, 3):
5722 		case IP_VERSION(2, 0, 0):
5723 		case IP_VERSION(2, 1, 0):
5724 		case IP_VERSION(3, 0, 0):
5725 		case IP_VERSION(3, 0, 2):
5726 		case IP_VERSION(3, 0, 3):
5727 		case IP_VERSION(3, 0, 1):
5728 		case IP_VERSION(3, 1, 2):
5729 		case IP_VERSION(3, 1, 3):
5730 		case IP_VERSION(3, 1, 4):
5731 		case IP_VERSION(3, 1, 5):
5732 		case IP_VERSION(3, 1, 6):
5733 		case IP_VERSION(3, 2, 0):
5734 		case IP_VERSION(3, 2, 1):
5735 		case IP_VERSION(3, 5, 0):
5736 		case IP_VERSION(3, 5, 1):
5737 		case IP_VERSION(3, 6, 0):
5738 		case IP_VERSION(4, 0, 1):
5739 			if (dcn10_register_irq_handlers(dm->adev)) {
5740 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5741 				goto fail;
5742 			}
5743 			break;
5744 		default:
5745 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
5746 					amdgpu_ip_version(adev, DCE_HWIP, 0));
5747 			goto fail;
5748 		}
5749 		break;
5750 	}
5751 
5752 	return 0;
5753 fail:
5754 	kfree(aencoder);
5755 	kfree(aconnector);
5756 
5757 	return -EINVAL;
5758 }
5759 
5760 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
5761 {
5762 	if (dm->atomic_obj.state)
5763 		drm_atomic_private_obj_fini(&dm->atomic_obj);
5764 }
5765 
5766 /******************************************************************************
5767  * amdgpu_display_funcs functions
5768  *****************************************************************************/
5769 
5770 /*
5771  * dm_bandwidth_update - program display watermarks
5772  *
5773  * @adev: amdgpu_device pointer
5774  *
5775  * Calculate and program the display watermarks and line buffer allocation.
5776  */
5777 static void dm_bandwidth_update(struct amdgpu_device *adev)
5778 {
5779 	/* TODO: implement later */
5780 }
5781 
5782 static const struct amdgpu_display_funcs dm_display_funcs = {
5783 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
5784 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
5785 	.backlight_set_level = NULL, /* never called for DC */
5786 	.backlight_get_level = NULL, /* never called for DC */
5787 	.hpd_sense = NULL,/* called unconditionally */
5788 	.hpd_set_polarity = NULL, /* called unconditionally */
5789 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
5790 	.page_flip_get_scanoutpos =
5791 		dm_crtc_get_scanoutpos,/* called unconditionally */
5792 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
5793 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
5794 };
5795 
5796 #if defined(CONFIG_DEBUG_KERNEL_DC)
5797 
5798 static ssize_t s3_debug_store(struct device *device,
5799 			      struct device_attribute *attr,
5800 			      const char *buf,
5801 			      size_t count)
5802 {
5803 	int ret;
5804 	int s3_state;
5805 	struct drm_device *drm_dev = dev_get_drvdata(device);
5806 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
5807 	struct amdgpu_ip_block *ip_block;
5808 
5809 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
5810 	if (!ip_block)
5811 		return -EINVAL;
5812 
5813 	ret = kstrtoint(buf, 0, &s3_state);
5814 
5815 	if (ret == 0) {
5816 		if (s3_state) {
5817 			dm_resume(ip_block);
5818 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
5819 		} else
5820 			dm_suspend(ip_block);
5821 	}
5822 
5823 	return ret == 0 ? count : 0;
5824 }
5825 
5826 DEVICE_ATTR_WO(s3_debug);
5827 
5828 #endif
5829 
5830 static int dm_init_microcode(struct amdgpu_device *adev)
5831 {
5832 	char *fw_name_dmub;
5833 	int r;
5834 
5835 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5836 	case IP_VERSION(2, 1, 0):
5837 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
5838 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
5839 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
5840 		break;
5841 	case IP_VERSION(3, 0, 0):
5842 		if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(10, 3, 0))
5843 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
5844 		else
5845 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
5846 		break;
5847 	case IP_VERSION(3, 0, 1):
5848 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
5849 		break;
5850 	case IP_VERSION(3, 0, 2):
5851 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
5852 		break;
5853 	case IP_VERSION(3, 0, 3):
5854 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
5855 		break;
5856 	case IP_VERSION(3, 1, 2):
5857 	case IP_VERSION(3, 1, 3):
5858 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
5859 		break;
5860 	case IP_VERSION(3, 1, 4):
5861 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
5862 		break;
5863 	case IP_VERSION(3, 1, 5):
5864 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
5865 		break;
5866 	case IP_VERSION(3, 1, 6):
5867 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
5868 		break;
5869 	case IP_VERSION(3, 2, 0):
5870 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
5871 		break;
5872 	case IP_VERSION(3, 2, 1):
5873 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
5874 		break;
5875 	case IP_VERSION(3, 5, 0):
5876 		fw_name_dmub = FIRMWARE_DCN_35_DMUB;
5877 		break;
5878 	case IP_VERSION(3, 5, 1):
5879 		fw_name_dmub = FIRMWARE_DCN_351_DMUB;
5880 		break;
5881 	case IP_VERSION(3, 6, 0):
5882 		fw_name_dmub = FIRMWARE_DCN_36_DMUB;
5883 		break;
5884 	case IP_VERSION(4, 0, 1):
5885 		fw_name_dmub = FIRMWARE_DCN_401_DMUB;
5886 		break;
5887 	default:
5888 		/* ASIC doesn't support DMUB. */
5889 		return 0;
5890 	}
5891 	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, AMDGPU_UCODE_REQUIRED,
5892 				 "%s", fw_name_dmub);
5893 	return r;
5894 }
5895 
5896 static int dm_early_init(struct amdgpu_ip_block *ip_block)
5897 {
5898 	struct amdgpu_device *adev = ip_block->adev;
5899 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5900 	struct atom_context *ctx = mode_info->atom_context;
5901 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
5902 	u16 data_offset;
5903 
5904 	/* if there is no object header, skip DM */
5905 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
5906 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
5907 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
5908 		return -ENOENT;
5909 	}
5910 
5911 	switch (adev->asic_type) {
5912 #if defined(CONFIG_DRM_AMD_DC_SI)
5913 	case CHIP_TAHITI:
5914 	case CHIP_PITCAIRN:
5915 	case CHIP_VERDE:
5916 		adev->mode_info.num_crtc = 6;
5917 		adev->mode_info.num_hpd = 6;
5918 		adev->mode_info.num_dig = 6;
5919 		break;
5920 	case CHIP_OLAND:
5921 		adev->mode_info.num_crtc = 2;
5922 		adev->mode_info.num_hpd = 2;
5923 		adev->mode_info.num_dig = 2;
5924 		break;
5925 #endif
5926 	case CHIP_BONAIRE:
5927 	case CHIP_HAWAII:
5928 		adev->mode_info.num_crtc = 6;
5929 		adev->mode_info.num_hpd = 6;
5930 		adev->mode_info.num_dig = 6;
5931 		break;
5932 	case CHIP_KAVERI:
5933 		adev->mode_info.num_crtc = 4;
5934 		adev->mode_info.num_hpd = 6;
5935 		adev->mode_info.num_dig = 7;
5936 		break;
5937 	case CHIP_KABINI:
5938 	case CHIP_MULLINS:
5939 		adev->mode_info.num_crtc = 2;
5940 		adev->mode_info.num_hpd = 6;
5941 		adev->mode_info.num_dig = 6;
5942 		break;
5943 	case CHIP_FIJI:
5944 	case CHIP_TONGA:
5945 		adev->mode_info.num_crtc = 6;
5946 		adev->mode_info.num_hpd = 6;
5947 		adev->mode_info.num_dig = 7;
5948 		break;
5949 	case CHIP_CARRIZO:
5950 		adev->mode_info.num_crtc = 3;
5951 		adev->mode_info.num_hpd = 6;
5952 		adev->mode_info.num_dig = 9;
5953 		break;
5954 	case CHIP_STONEY:
5955 		adev->mode_info.num_crtc = 2;
5956 		adev->mode_info.num_hpd = 6;
5957 		adev->mode_info.num_dig = 9;
5958 		break;
5959 	case CHIP_POLARIS11:
5960 	case CHIP_POLARIS12:
5961 		adev->mode_info.num_crtc = 5;
5962 		adev->mode_info.num_hpd = 5;
5963 		adev->mode_info.num_dig = 5;
5964 		break;
5965 	case CHIP_POLARIS10:
5966 	case CHIP_VEGAM:
5967 		adev->mode_info.num_crtc = 6;
5968 		adev->mode_info.num_hpd = 6;
5969 		adev->mode_info.num_dig = 6;
5970 		break;
5971 	case CHIP_VEGA10:
5972 	case CHIP_VEGA12:
5973 	case CHIP_VEGA20:
5974 		adev->mode_info.num_crtc = 6;
5975 		adev->mode_info.num_hpd = 6;
5976 		adev->mode_info.num_dig = 6;
5977 		break;
5978 	default:
5979 
5980 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5981 		case IP_VERSION(2, 0, 2):
5982 		case IP_VERSION(3, 0, 0):
5983 			adev->mode_info.num_crtc = 6;
5984 			adev->mode_info.num_hpd = 6;
5985 			adev->mode_info.num_dig = 6;
5986 			break;
5987 		case IP_VERSION(2, 0, 0):
5988 		case IP_VERSION(3, 0, 2):
5989 			adev->mode_info.num_crtc = 5;
5990 			adev->mode_info.num_hpd = 5;
5991 			adev->mode_info.num_dig = 5;
5992 			break;
5993 		case IP_VERSION(2, 0, 3):
5994 		case IP_VERSION(3, 0, 3):
5995 			adev->mode_info.num_crtc = 2;
5996 			adev->mode_info.num_hpd = 2;
5997 			adev->mode_info.num_dig = 2;
5998 			break;
5999 		case IP_VERSION(1, 0, 0):
6000 		case IP_VERSION(1, 0, 1):
6001 		case IP_VERSION(3, 0, 1):
6002 		case IP_VERSION(2, 1, 0):
6003 		case IP_VERSION(3, 1, 2):
6004 		case IP_VERSION(3, 1, 3):
6005 		case IP_VERSION(3, 1, 4):
6006 		case IP_VERSION(3, 1, 5):
6007 		case IP_VERSION(3, 1, 6):
6008 		case IP_VERSION(3, 2, 0):
6009 		case IP_VERSION(3, 2, 1):
6010 		case IP_VERSION(3, 5, 0):
6011 		case IP_VERSION(3, 5, 1):
6012 		case IP_VERSION(3, 6, 0):
6013 		case IP_VERSION(4, 0, 1):
6014 			adev->mode_info.num_crtc = 4;
6015 			adev->mode_info.num_hpd = 4;
6016 			adev->mode_info.num_dig = 4;
6017 			break;
6018 		default:
6019 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
6020 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6021 			return -EINVAL;
6022 		}
6023 		break;
6024 	}
6025 
6026 	if (adev->mode_info.funcs == NULL)
6027 		adev->mode_info.funcs = &dm_display_funcs;
6028 
6029 	/*
6030 	 * Note: Do NOT change adev->audio_endpt_rreg and
6031 	 * adev->audio_endpt_wreg because they are initialised in
6032 	 * amdgpu_device_init()
6033 	 */
6034 #if defined(CONFIG_DEBUG_KERNEL_DC)
6035 	device_create_file(
6036 		adev_to_drm(adev)->dev,
6037 		&dev_attr_s3_debug);
6038 #endif
6039 	adev->dc_enabled = true;
6040 
6041 	return dm_init_microcode(adev);
6042 }
6043 
6044 static bool modereset_required(struct drm_crtc_state *crtc_state)
6045 {
6046 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
6047 }
6048 
6049 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
6050 {
6051 	drm_encoder_cleanup(encoder);
6052 	kfree(encoder);
6053 }
6054 
6055 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
6056 	.destroy = amdgpu_dm_encoder_destroy,
6057 };
6058 
6059 static int
6060 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
6061 			    const enum surface_pixel_format format,
6062 			    enum dc_color_space *color_space)
6063 {
6064 	bool full_range;
6065 
6066 	*color_space = COLOR_SPACE_SRGB;
6067 
6068 	/* Ignore properties when DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE is set */
6069 	if (plane_state->state && plane_state->state->plane_color_pipeline)
6070 		return 0;
6071 
6072 	/* DRM color properties only affect non-RGB formats. */
6073 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
6074 		return 0;
6075 
6076 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
6077 
6078 	switch (plane_state->color_encoding) {
6079 	case DRM_COLOR_YCBCR_BT601:
6080 		if (full_range)
6081 			*color_space = COLOR_SPACE_YCBCR601;
6082 		else
6083 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
6084 		break;
6085 
6086 	case DRM_COLOR_YCBCR_BT709:
6087 		if (full_range)
6088 			*color_space = COLOR_SPACE_YCBCR709;
6089 		else
6090 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
6091 		break;
6092 
6093 	case DRM_COLOR_YCBCR_BT2020:
6094 		if (full_range)
6095 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
6096 		else
6097 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6098 		break;
6099 
6100 	default:
6101 		return -EINVAL;
6102 	}
6103 
6104 	return 0;
6105 }
6106 
6107 static int
6108 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
6109 			    const struct drm_plane_state *plane_state,
6110 			    const u64 tiling_flags,
6111 			    struct dc_plane_info *plane_info,
6112 			    struct dc_plane_address *address,
6113 			    bool tmz_surface)
6114 {
6115 	const struct drm_framebuffer *fb = plane_state->fb;
6116 	const struct amdgpu_framebuffer *afb =
6117 		to_amdgpu_framebuffer(plane_state->fb);
6118 	int ret;
6119 
6120 	memset(plane_info, 0, sizeof(*plane_info));
6121 
6122 	switch (fb->format->format) {
6123 	case DRM_FORMAT_C8:
6124 		plane_info->format =
6125 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
6126 		break;
6127 	case DRM_FORMAT_RGB565:
6128 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
6129 		break;
6130 	case DRM_FORMAT_XRGB8888:
6131 	case DRM_FORMAT_ARGB8888:
6132 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6133 		break;
6134 	case DRM_FORMAT_XRGB2101010:
6135 	case DRM_FORMAT_ARGB2101010:
6136 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
6137 		break;
6138 	case DRM_FORMAT_XBGR2101010:
6139 	case DRM_FORMAT_ABGR2101010:
6140 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
6141 		break;
6142 	case DRM_FORMAT_XBGR8888:
6143 	case DRM_FORMAT_ABGR8888:
6144 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
6145 		break;
6146 	case DRM_FORMAT_NV21:
6147 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
6148 		break;
6149 	case DRM_FORMAT_NV12:
6150 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
6151 		break;
6152 	case DRM_FORMAT_P010:
6153 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
6154 		break;
6155 	case DRM_FORMAT_XRGB16161616F:
6156 	case DRM_FORMAT_ARGB16161616F:
6157 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
6158 		break;
6159 	case DRM_FORMAT_XBGR16161616F:
6160 	case DRM_FORMAT_ABGR16161616F:
6161 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
6162 		break;
6163 	case DRM_FORMAT_XRGB16161616:
6164 	case DRM_FORMAT_ARGB16161616:
6165 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
6166 		break;
6167 	case DRM_FORMAT_XBGR16161616:
6168 	case DRM_FORMAT_ABGR16161616:
6169 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
6170 		break;
6171 	default:
6172 		drm_err(adev_to_drm(adev),
6173 			"Unsupported screen format %p4cc\n",
6174 			&fb->format->format);
6175 		return -EINVAL;
6176 	}
6177 
6178 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
6179 	case DRM_MODE_ROTATE_0:
6180 		plane_info->rotation = ROTATION_ANGLE_0;
6181 		break;
6182 	case DRM_MODE_ROTATE_90:
6183 		plane_info->rotation = ROTATION_ANGLE_90;
6184 		break;
6185 	case DRM_MODE_ROTATE_180:
6186 		plane_info->rotation = ROTATION_ANGLE_180;
6187 		break;
6188 	case DRM_MODE_ROTATE_270:
6189 		plane_info->rotation = ROTATION_ANGLE_270;
6190 		break;
6191 	default:
6192 		plane_info->rotation = ROTATION_ANGLE_0;
6193 		break;
6194 	}
6195 
6196 
6197 	plane_info->visible = true;
6198 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
6199 
6200 	plane_info->layer_index = plane_state->normalized_zpos;
6201 
6202 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
6203 					  &plane_info->color_space);
6204 	if (ret)
6205 		return ret;
6206 
6207 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
6208 					   plane_info->rotation, tiling_flags,
6209 					   &plane_info->tiling_info,
6210 					   &plane_info->plane_size,
6211 					   &plane_info->dcc, address,
6212 					   tmz_surface);
6213 	if (ret)
6214 		return ret;
6215 
6216 	amdgpu_dm_plane_fill_blending_from_plane_state(
6217 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
6218 		&plane_info->global_alpha, &plane_info->global_alpha_value);
6219 
6220 	return 0;
6221 }
6222 
6223 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
6224 				    struct dc_plane_state *dc_plane_state,
6225 				    struct drm_plane_state *plane_state,
6226 				    struct drm_crtc_state *crtc_state)
6227 {
6228 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6229 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
6230 	struct dc_scaling_info scaling_info;
6231 	struct dc_plane_info plane_info;
6232 	int ret;
6233 
6234 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
6235 	if (ret)
6236 		return ret;
6237 
6238 	dc_plane_state->src_rect = scaling_info.src_rect;
6239 	dc_plane_state->dst_rect = scaling_info.dst_rect;
6240 	dc_plane_state->clip_rect = scaling_info.clip_rect;
6241 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
6242 
6243 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
6244 					  afb->tiling_flags,
6245 					  &plane_info,
6246 					  &dc_plane_state->address,
6247 					  afb->tmz_surface);
6248 	if (ret)
6249 		return ret;
6250 
6251 	dc_plane_state->format = plane_info.format;
6252 	dc_plane_state->color_space = plane_info.color_space;
6253 	dc_plane_state->format = plane_info.format;
6254 	dc_plane_state->plane_size = plane_info.plane_size;
6255 	dc_plane_state->rotation = plane_info.rotation;
6256 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
6257 	dc_plane_state->stereo_format = plane_info.stereo_format;
6258 	dc_plane_state->tiling_info = plane_info.tiling_info;
6259 	dc_plane_state->visible = plane_info.visible;
6260 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
6261 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
6262 	dc_plane_state->global_alpha = plane_info.global_alpha;
6263 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
6264 	dc_plane_state->dcc = plane_info.dcc;
6265 	dc_plane_state->layer_index = plane_info.layer_index;
6266 	dc_plane_state->flip_int_enabled = true;
6267 
6268 	/*
6269 	 * Always set input transfer function, since plane state is refreshed
6270 	 * every time.
6271 	 */
6272 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
6273 						plane_state,
6274 						dc_plane_state);
6275 	if (ret)
6276 		return ret;
6277 
6278 	return 0;
6279 }
6280 
6281 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
6282 				      struct rect *dirty_rect, int32_t x,
6283 				      s32 y, s32 width, s32 height,
6284 				      int *i, bool ffu)
6285 {
6286 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
6287 
6288 	dirty_rect->x = x;
6289 	dirty_rect->y = y;
6290 	dirty_rect->width = width;
6291 	dirty_rect->height = height;
6292 
6293 	if (ffu)
6294 		drm_dbg(plane->dev,
6295 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
6296 			plane->base.id, width, height);
6297 	else
6298 		drm_dbg(plane->dev,
6299 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
6300 			plane->base.id, x, y, width, height);
6301 
6302 	(*i)++;
6303 }
6304 
6305 /**
6306  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
6307  *
6308  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
6309  *         remote fb
6310  * @old_plane_state: Old state of @plane
6311  * @new_plane_state: New state of @plane
6312  * @crtc_state: New state of CRTC connected to the @plane
6313  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
6314  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
6315  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
6316  *             that have changed will be updated. If PSR SU is not enabled,
6317  *             or if damage clips are not available, the entire screen will be updated.
6318  * @dirty_regions_changed: dirty regions changed
6319  *
6320  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
6321  * (referred to as "damage clips" in DRM nomenclature) that require updating on
6322  * the eDP remote buffer. The responsibility of specifying the dirty regions is
6323  * amdgpu_dm's.
6324  *
6325  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
6326  * plane with regions that require flushing to the eDP remote buffer. In
6327  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
6328  * implicitly provide damage clips without any client support via the plane
6329  * bounds.
6330  */
6331 static void fill_dc_dirty_rects(struct drm_plane *plane,
6332 				struct drm_plane_state *old_plane_state,
6333 				struct drm_plane_state *new_plane_state,
6334 				struct drm_crtc_state *crtc_state,
6335 				struct dc_flip_addrs *flip_addrs,
6336 				bool is_psr_su,
6337 				bool *dirty_regions_changed)
6338 {
6339 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6340 	struct rect *dirty_rects = flip_addrs->dirty_rects;
6341 	u32 num_clips;
6342 	struct drm_mode_rect *clips;
6343 	bool bb_changed;
6344 	bool fb_changed;
6345 	u32 i = 0;
6346 	*dirty_regions_changed = false;
6347 
6348 	/*
6349 	 * Cursor plane has it's own dirty rect update interface. See
6350 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
6351 	 */
6352 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
6353 		return;
6354 
6355 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
6356 		goto ffu;
6357 
6358 	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
6359 	clips = drm_plane_get_damage_clips(new_plane_state);
6360 
6361 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
6362 						   is_psr_su)))
6363 		goto ffu;
6364 
6365 	if (!dm_crtc_state->mpo_requested) {
6366 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
6367 			goto ffu;
6368 
6369 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
6370 			fill_dc_dirty_rect(new_plane_state->plane,
6371 					   &dirty_rects[flip_addrs->dirty_rect_count],
6372 					   clips->x1, clips->y1,
6373 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
6374 					   &flip_addrs->dirty_rect_count,
6375 					   false);
6376 		return;
6377 	}
6378 
6379 	/*
6380 	 * MPO is requested. Add entire plane bounding box to dirty rects if
6381 	 * flipped to or damaged.
6382 	 *
6383 	 * If plane is moved or resized, also add old bounding box to dirty
6384 	 * rects.
6385 	 */
6386 	fb_changed = old_plane_state->fb->base.id !=
6387 		     new_plane_state->fb->base.id;
6388 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
6389 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
6390 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
6391 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
6392 
6393 	drm_dbg(plane->dev,
6394 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
6395 		new_plane_state->plane->base.id,
6396 		bb_changed, fb_changed, num_clips);
6397 
6398 	*dirty_regions_changed = bb_changed;
6399 
6400 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
6401 		goto ffu;
6402 
6403 	if (bb_changed) {
6404 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6405 				   new_plane_state->crtc_x,
6406 				   new_plane_state->crtc_y,
6407 				   new_plane_state->crtc_w,
6408 				   new_plane_state->crtc_h, &i, false);
6409 
6410 		/* Add old plane bounding-box if plane is moved or resized */
6411 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6412 				   old_plane_state->crtc_x,
6413 				   old_plane_state->crtc_y,
6414 				   old_plane_state->crtc_w,
6415 				   old_plane_state->crtc_h, &i, false);
6416 	}
6417 
6418 	if (num_clips) {
6419 		for (; i < num_clips; clips++)
6420 			fill_dc_dirty_rect(new_plane_state->plane,
6421 					   &dirty_rects[i], clips->x1,
6422 					   clips->y1, clips->x2 - clips->x1,
6423 					   clips->y2 - clips->y1, &i, false);
6424 	} else if (fb_changed && !bb_changed) {
6425 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6426 				   new_plane_state->crtc_x,
6427 				   new_plane_state->crtc_y,
6428 				   new_plane_state->crtc_w,
6429 				   new_plane_state->crtc_h, &i, false);
6430 	}
6431 
6432 	flip_addrs->dirty_rect_count = i;
6433 	return;
6434 
6435 ffu:
6436 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
6437 			   dm_crtc_state->base.mode.crtc_hdisplay,
6438 			   dm_crtc_state->base.mode.crtc_vdisplay,
6439 			   &flip_addrs->dirty_rect_count, true);
6440 }
6441 
6442 static void update_stream_scaling_settings(struct drm_device *dev,
6443 					   const struct drm_display_mode *mode,
6444 					   const struct dm_connector_state *dm_state,
6445 					   struct dc_stream_state *stream)
6446 {
6447 	enum amdgpu_rmx_type rmx_type;
6448 
6449 	struct rect src = { 0 }; /* viewport in composition space*/
6450 	struct rect dst = { 0 }; /* stream addressable area */
6451 
6452 	/* no mode. nothing to be done */
6453 	if (!mode)
6454 		return;
6455 
6456 	/* Full screen scaling by default */
6457 	src.width = mode->hdisplay;
6458 	src.height = mode->vdisplay;
6459 	dst.width = stream->timing.h_addressable;
6460 	dst.height = stream->timing.v_addressable;
6461 
6462 	if (dm_state) {
6463 		rmx_type = dm_state->scaling;
6464 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
6465 			if (src.width * dst.height <
6466 					src.height * dst.width) {
6467 				/* height needs less upscaling/more downscaling */
6468 				dst.width = src.width *
6469 						dst.height / src.height;
6470 			} else {
6471 				/* width needs less upscaling/more downscaling */
6472 				dst.height = src.height *
6473 						dst.width / src.width;
6474 			}
6475 		} else if (rmx_type == RMX_CENTER) {
6476 			dst = src;
6477 		}
6478 
6479 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
6480 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
6481 
6482 		if (dm_state->underscan_enable) {
6483 			dst.x += dm_state->underscan_hborder / 2;
6484 			dst.y += dm_state->underscan_vborder / 2;
6485 			dst.width -= dm_state->underscan_hborder;
6486 			dst.height -= dm_state->underscan_vborder;
6487 		}
6488 	}
6489 
6490 	stream->src = src;
6491 	stream->dst = dst;
6492 
6493 	drm_dbg_kms(dev, "Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
6494 		    dst.x, dst.y, dst.width, dst.height);
6495 
6496 }
6497 
6498 static enum dc_color_depth
6499 convert_color_depth_from_display_info(const struct drm_connector *connector,
6500 				      bool is_y420, int requested_bpc)
6501 {
6502 	u8 bpc;
6503 
6504 	if (is_y420) {
6505 		bpc = 8;
6506 
6507 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
6508 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
6509 			bpc = 16;
6510 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
6511 			bpc = 12;
6512 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
6513 			bpc = 10;
6514 	} else {
6515 		bpc = (uint8_t)connector->display_info.bpc;
6516 		/* Assume 8 bpc by default if no bpc is specified. */
6517 		bpc = bpc ? bpc : 8;
6518 	}
6519 
6520 	if (requested_bpc > 0) {
6521 		/*
6522 		 * Cap display bpc based on the user requested value.
6523 		 *
6524 		 * The value for state->max_bpc may not correctly updated
6525 		 * depending on when the connector gets added to the state
6526 		 * or if this was called outside of atomic check, so it
6527 		 * can't be used directly.
6528 		 */
6529 		bpc = min_t(u8, bpc, requested_bpc);
6530 
6531 		/* Round down to the nearest even number. */
6532 		bpc = bpc - (bpc & 1);
6533 	}
6534 
6535 	switch (bpc) {
6536 	case 0:
6537 		/*
6538 		 * Temporary Work around, DRM doesn't parse color depth for
6539 		 * EDID revision before 1.4
6540 		 * TODO: Fix edid parsing
6541 		 */
6542 		return COLOR_DEPTH_888;
6543 	case 6:
6544 		return COLOR_DEPTH_666;
6545 	case 8:
6546 		return COLOR_DEPTH_888;
6547 	case 10:
6548 		return COLOR_DEPTH_101010;
6549 	case 12:
6550 		return COLOR_DEPTH_121212;
6551 	case 14:
6552 		return COLOR_DEPTH_141414;
6553 	case 16:
6554 		return COLOR_DEPTH_161616;
6555 	default:
6556 		return COLOR_DEPTH_UNDEFINED;
6557 	}
6558 }
6559 
6560 static enum dc_aspect_ratio
6561 get_aspect_ratio(const struct drm_display_mode *mode_in)
6562 {
6563 	/* 1-1 mapping, since both enums follow the HDMI spec. */
6564 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
6565 }
6566 
6567 static enum dc_color_space
6568 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
6569 		       const struct drm_connector_state *connector_state)
6570 {
6571 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
6572 
6573 	switch (connector_state->colorspace) {
6574 	case DRM_MODE_COLORIMETRY_BT601_YCC:
6575 		if (dc_crtc_timing->flags.Y_ONLY)
6576 			color_space = COLOR_SPACE_YCBCR601_LIMITED;
6577 		else
6578 			color_space = COLOR_SPACE_YCBCR601;
6579 		break;
6580 	case DRM_MODE_COLORIMETRY_BT709_YCC:
6581 		if (dc_crtc_timing->flags.Y_ONLY)
6582 			color_space = COLOR_SPACE_YCBCR709_LIMITED;
6583 		else
6584 			color_space = COLOR_SPACE_YCBCR709;
6585 		break;
6586 	case DRM_MODE_COLORIMETRY_OPRGB:
6587 		color_space = COLOR_SPACE_ADOBERGB;
6588 		break;
6589 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
6590 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
6591 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
6592 			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
6593 		else
6594 			color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6595 		break;
6596 	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
6597 	default:
6598 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
6599 			color_space = COLOR_SPACE_SRGB;
6600 			if (connector_state->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_LIMITED)
6601 				color_space = COLOR_SPACE_SRGB_LIMITED;
6602 		/*
6603 		 * 27030khz is the separation point between HDTV and SDTV
6604 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
6605 		 * respectively
6606 		 */
6607 		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
6608 			if (dc_crtc_timing->flags.Y_ONLY)
6609 				color_space =
6610 					COLOR_SPACE_YCBCR709_LIMITED;
6611 			else
6612 				color_space = COLOR_SPACE_YCBCR709;
6613 		} else {
6614 			if (dc_crtc_timing->flags.Y_ONLY)
6615 				color_space =
6616 					COLOR_SPACE_YCBCR601_LIMITED;
6617 			else
6618 				color_space = COLOR_SPACE_YCBCR601;
6619 		}
6620 		break;
6621 	}
6622 
6623 	return color_space;
6624 }
6625 
6626 static enum display_content_type
6627 get_output_content_type(const struct drm_connector_state *connector_state)
6628 {
6629 	switch (connector_state->content_type) {
6630 	default:
6631 	case DRM_MODE_CONTENT_TYPE_NO_DATA:
6632 		return DISPLAY_CONTENT_TYPE_NO_DATA;
6633 	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
6634 		return DISPLAY_CONTENT_TYPE_GRAPHICS;
6635 	case DRM_MODE_CONTENT_TYPE_PHOTO:
6636 		return DISPLAY_CONTENT_TYPE_PHOTO;
6637 	case DRM_MODE_CONTENT_TYPE_CINEMA:
6638 		return DISPLAY_CONTENT_TYPE_CINEMA;
6639 	case DRM_MODE_CONTENT_TYPE_GAME:
6640 		return DISPLAY_CONTENT_TYPE_GAME;
6641 	}
6642 }
6643 
6644 static bool adjust_colour_depth_from_display_info(
6645 	struct dc_crtc_timing *timing_out,
6646 	const struct drm_display_info *info)
6647 {
6648 	enum dc_color_depth depth = timing_out->display_color_depth;
6649 	int normalized_clk;
6650 
6651 	do {
6652 		normalized_clk = timing_out->pix_clk_100hz / 10;
6653 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
6654 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
6655 			normalized_clk /= 2;
6656 		/* Adjusting pix clock following on HDMI spec based on colour depth */
6657 		switch (depth) {
6658 		case COLOR_DEPTH_888:
6659 			break;
6660 		case COLOR_DEPTH_101010:
6661 			normalized_clk = (normalized_clk * 30) / 24;
6662 			break;
6663 		case COLOR_DEPTH_121212:
6664 			normalized_clk = (normalized_clk * 36) / 24;
6665 			break;
6666 		case COLOR_DEPTH_161616:
6667 			normalized_clk = (normalized_clk * 48) / 24;
6668 			break;
6669 		default:
6670 			/* The above depths are the only ones valid for HDMI. */
6671 			return false;
6672 		}
6673 		if (normalized_clk <= info->max_tmds_clock) {
6674 			timing_out->display_color_depth = depth;
6675 			return true;
6676 		}
6677 	} while (--depth > COLOR_DEPTH_666);
6678 	return false;
6679 }
6680 
6681 static void fill_stream_properties_from_drm_display_mode(
6682 	struct dc_stream_state *stream,
6683 	const struct drm_display_mode *mode_in,
6684 	const struct drm_connector *connector,
6685 	const struct drm_connector_state *connector_state,
6686 	const struct dc_stream_state *old_stream,
6687 	int requested_bpc)
6688 {
6689 	struct dc_crtc_timing *timing_out = &stream->timing;
6690 	const struct drm_display_info *info = &connector->display_info;
6691 	struct amdgpu_dm_connector *aconnector = NULL;
6692 	struct hdmi_vendor_infoframe hv_frame;
6693 	struct hdmi_avi_infoframe avi_frame;
6694 	ssize_t err;
6695 
6696 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
6697 		aconnector = to_amdgpu_dm_connector(connector);
6698 
6699 	memset(&hv_frame, 0, sizeof(hv_frame));
6700 	memset(&avi_frame, 0, sizeof(avi_frame));
6701 
6702 	timing_out->h_border_left = 0;
6703 	timing_out->h_border_right = 0;
6704 	timing_out->v_border_top = 0;
6705 	timing_out->v_border_bottom = 0;
6706 	/* TODO: un-hardcode */
6707 	if (drm_mode_is_420_only(info, mode_in)
6708 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6709 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6710 	else if (drm_mode_is_420_also(info, mode_in)
6711 			&& aconnector
6712 			&& aconnector->force_yuv420_output)
6713 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6714 	else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCBCR422)
6715 			&& aconnector
6716 			&& aconnector->force_yuv422_output)
6717 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR422;
6718 	else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCBCR444)
6719 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6720 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
6721 	else
6722 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
6723 
6724 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
6725 	timing_out->display_color_depth = convert_color_depth_from_display_info(
6726 		connector,
6727 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
6728 		requested_bpc);
6729 	timing_out->scan_type = SCANNING_TYPE_NODATA;
6730 	timing_out->hdmi_vic = 0;
6731 
6732 	if (old_stream) {
6733 		timing_out->vic = old_stream->timing.vic;
6734 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
6735 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
6736 	} else {
6737 		timing_out->vic = drm_match_cea_mode(mode_in);
6738 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
6739 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
6740 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
6741 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
6742 	}
6743 
6744 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
6745 		err = drm_hdmi_avi_infoframe_from_display_mode(&avi_frame,
6746 							       (struct drm_connector *)connector,
6747 							       mode_in);
6748 		if (err < 0)
6749 			drm_warn_once(connector->dev, "Failed to setup avi infoframe on connector %s: %zd\n",
6750 				      connector->name, err);
6751 		timing_out->vic = avi_frame.video_code;
6752 		err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame,
6753 								  (struct drm_connector *)connector,
6754 								  mode_in);
6755 		if (err < 0)
6756 			drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n",
6757 				      connector->name, err);
6758 		timing_out->hdmi_vic = hv_frame.vic;
6759 	}
6760 
6761 	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
6762 		timing_out->h_addressable = mode_in->hdisplay;
6763 		timing_out->h_total = mode_in->htotal;
6764 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
6765 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
6766 		timing_out->v_total = mode_in->vtotal;
6767 		timing_out->v_addressable = mode_in->vdisplay;
6768 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
6769 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
6770 		timing_out->pix_clk_100hz = mode_in->clock * 10;
6771 	} else {
6772 		timing_out->h_addressable = mode_in->crtc_hdisplay;
6773 		timing_out->h_total = mode_in->crtc_htotal;
6774 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
6775 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
6776 		timing_out->v_total = mode_in->crtc_vtotal;
6777 		timing_out->v_addressable = mode_in->crtc_vdisplay;
6778 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
6779 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
6780 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
6781 	}
6782 
6783 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
6784 
6785 	stream->out_transfer_func.type = TF_TYPE_PREDEFINED;
6786 	stream->out_transfer_func.tf = TRANSFER_FUNCTION_SRGB;
6787 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
6788 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
6789 		    drm_mode_is_420_also(info, mode_in) &&
6790 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
6791 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6792 			adjust_colour_depth_from_display_info(timing_out, info);
6793 		}
6794 	}
6795 
6796 	stream->output_color_space = get_output_color_space(timing_out, connector_state);
6797 	stream->content_type = get_output_content_type(connector_state);
6798 }
6799 
6800 static void fill_audio_info(struct audio_info *audio_info,
6801 			    const struct drm_connector *drm_connector,
6802 			    const struct dc_sink *dc_sink)
6803 {
6804 	int i = 0;
6805 	int cea_revision = 0;
6806 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
6807 
6808 	audio_info->manufacture_id = edid_caps->manufacturer_id;
6809 	audio_info->product_id = edid_caps->product_id;
6810 
6811 	cea_revision = drm_connector->display_info.cea_rev;
6812 
6813 	strscpy(audio_info->display_name,
6814 		edid_caps->display_name,
6815 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
6816 
6817 	if (cea_revision >= 3) {
6818 		audio_info->mode_count = edid_caps->audio_mode_count;
6819 
6820 		for (i = 0; i < audio_info->mode_count; ++i) {
6821 			audio_info->modes[i].format_code =
6822 					(enum audio_format_code)
6823 					(edid_caps->audio_modes[i].format_code);
6824 			audio_info->modes[i].channel_count =
6825 					edid_caps->audio_modes[i].channel_count;
6826 			audio_info->modes[i].sample_rates.all =
6827 					edid_caps->audio_modes[i].sample_rate;
6828 			audio_info->modes[i].sample_size =
6829 					edid_caps->audio_modes[i].sample_size;
6830 		}
6831 	}
6832 
6833 	audio_info->flags.all = edid_caps->speaker_flags;
6834 
6835 	/* TODO: We only check for the progressive mode, check for interlace mode too */
6836 	if (drm_connector->latency_present[0]) {
6837 		audio_info->video_latency = drm_connector->video_latency[0];
6838 		audio_info->audio_latency = drm_connector->audio_latency[0];
6839 	}
6840 
6841 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
6842 
6843 }
6844 
6845 static void
6846 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
6847 				      struct drm_display_mode *dst_mode)
6848 {
6849 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
6850 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
6851 	dst_mode->crtc_clock = src_mode->crtc_clock;
6852 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
6853 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
6854 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
6855 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
6856 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
6857 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
6858 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
6859 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
6860 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
6861 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
6862 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
6863 }
6864 
6865 static void
6866 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
6867 					const struct drm_display_mode *native_mode,
6868 					bool scale_enabled)
6869 {
6870 	if (scale_enabled || (
6871 	    native_mode->clock == drm_mode->clock &&
6872 	    native_mode->htotal == drm_mode->htotal &&
6873 	    native_mode->vtotal == drm_mode->vtotal)) {
6874 		if (native_mode->crtc_clock)
6875 			copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
6876 	} else {
6877 		/* no scaling nor amdgpu inserted, no need to patch */
6878 	}
6879 }
6880 
6881 static struct dc_sink *
6882 create_fake_sink(struct drm_device *dev, struct dc_link *link)
6883 {
6884 	struct dc_sink_init_data sink_init_data = { 0 };
6885 	struct dc_sink *sink = NULL;
6886 
6887 	sink_init_data.link = link;
6888 	sink_init_data.sink_signal = link->connector_signal;
6889 
6890 	sink = dc_sink_create(&sink_init_data);
6891 	if (!sink) {
6892 		drm_err(dev, "Failed to create sink!\n");
6893 		return NULL;
6894 	}
6895 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
6896 
6897 	return sink;
6898 }
6899 
6900 static void set_multisync_trigger_params(
6901 		struct dc_stream_state *stream)
6902 {
6903 	struct dc_stream_state *master = NULL;
6904 
6905 	if (stream->triggered_crtc_reset.enabled) {
6906 		master = stream->triggered_crtc_reset.event_source;
6907 		stream->triggered_crtc_reset.event =
6908 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
6909 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
6910 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
6911 	}
6912 }
6913 
6914 static void set_master_stream(struct dc_stream_state *stream_set[],
6915 			      int stream_count)
6916 {
6917 	int j, highest_rfr = 0, master_stream = 0;
6918 
6919 	for (j = 0;  j < stream_count; j++) {
6920 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
6921 			int refresh_rate = 0;
6922 
6923 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
6924 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
6925 			if (refresh_rate > highest_rfr) {
6926 				highest_rfr = refresh_rate;
6927 				master_stream = j;
6928 			}
6929 		}
6930 	}
6931 	for (j = 0;  j < stream_count; j++) {
6932 		if (stream_set[j])
6933 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
6934 	}
6935 }
6936 
6937 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
6938 {
6939 	int i = 0;
6940 	struct dc_stream_state *stream;
6941 
6942 	if (context->stream_count < 2)
6943 		return;
6944 	for (i = 0; i < context->stream_count ; i++) {
6945 		if (!context->streams[i])
6946 			continue;
6947 		/*
6948 		 * TODO: add a function to read AMD VSDB bits and set
6949 		 * crtc_sync_master.multi_sync_enabled flag
6950 		 * For now it's set to false
6951 		 */
6952 	}
6953 
6954 	set_master_stream(context->streams, context->stream_count);
6955 
6956 	for (i = 0; i < context->stream_count ; i++) {
6957 		stream = context->streams[i];
6958 
6959 		if (!stream)
6960 			continue;
6961 
6962 		set_multisync_trigger_params(stream);
6963 	}
6964 }
6965 
6966 /**
6967  * DOC: FreeSync Video
6968  *
6969  * When a userspace application wants to play a video, the content follows a
6970  * standard format definition that usually specifies the FPS for that format.
6971  * The below list illustrates some video format and the expected FPS,
6972  * respectively:
6973  *
6974  * - TV/NTSC (23.976 FPS)
6975  * - Cinema (24 FPS)
6976  * - TV/PAL (25 FPS)
6977  * - TV/NTSC (29.97 FPS)
6978  * - TV/NTSC (30 FPS)
6979  * - Cinema HFR (48 FPS)
6980  * - TV/PAL (50 FPS)
6981  * - Commonly used (60 FPS)
6982  * - Multiples of 24 (48,72,96 FPS)
6983  *
6984  * The list of standards video format is not huge and can be added to the
6985  * connector modeset list beforehand. With that, userspace can leverage
6986  * FreeSync to extends the front porch in order to attain the target refresh
6987  * rate. Such a switch will happen seamlessly, without screen blanking or
6988  * reprogramming of the output in any other way. If the userspace requests a
6989  * modesetting change compatible with FreeSync modes that only differ in the
6990  * refresh rate, DC will skip the full update and avoid blink during the
6991  * transition. For example, the video player can change the modesetting from
6992  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
6993  * causing any display blink. This same concept can be applied to a mode
6994  * setting change.
6995  */
6996 static struct drm_display_mode *
6997 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
6998 		bool use_probed_modes)
6999 {
7000 	struct drm_display_mode *m, *m_pref = NULL;
7001 	u16 current_refresh, highest_refresh;
7002 	struct list_head *list_head = use_probed_modes ?
7003 		&aconnector->base.probed_modes :
7004 		&aconnector->base.modes;
7005 
7006 	if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
7007 		return NULL;
7008 
7009 	if (aconnector->freesync_vid_base.clock != 0)
7010 		return &aconnector->freesync_vid_base;
7011 
7012 	/* Find the preferred mode */
7013 	list_for_each_entry(m, list_head, head) {
7014 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
7015 			m_pref = m;
7016 			break;
7017 		}
7018 	}
7019 
7020 	if (!m_pref) {
7021 		/* Probably an EDID with no preferred mode. Fallback to first entry */
7022 		m_pref = list_first_entry_or_null(
7023 				&aconnector->base.modes, struct drm_display_mode, head);
7024 		if (!m_pref) {
7025 			drm_dbg_driver(aconnector->base.dev, "No preferred mode found in EDID\n");
7026 			return NULL;
7027 		}
7028 	}
7029 
7030 	highest_refresh = drm_mode_vrefresh(m_pref);
7031 
7032 	/*
7033 	 * Find the mode with highest refresh rate with same resolution.
7034 	 * For some monitors, preferred mode is not the mode with highest
7035 	 * supported refresh rate.
7036 	 */
7037 	list_for_each_entry(m, list_head, head) {
7038 		current_refresh  = drm_mode_vrefresh(m);
7039 
7040 		if (m->hdisplay == m_pref->hdisplay &&
7041 		    m->vdisplay == m_pref->vdisplay &&
7042 		    highest_refresh < current_refresh) {
7043 			highest_refresh = current_refresh;
7044 			m_pref = m;
7045 		}
7046 	}
7047 
7048 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
7049 	return m_pref;
7050 }
7051 
7052 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
7053 		struct amdgpu_dm_connector *aconnector)
7054 {
7055 	struct drm_display_mode *high_mode;
7056 	int timing_diff;
7057 
7058 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
7059 	if (!high_mode || !mode)
7060 		return false;
7061 
7062 	timing_diff = high_mode->vtotal - mode->vtotal;
7063 
7064 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
7065 	    high_mode->hdisplay != mode->hdisplay ||
7066 	    high_mode->vdisplay != mode->vdisplay ||
7067 	    high_mode->hsync_start != mode->hsync_start ||
7068 	    high_mode->hsync_end != mode->hsync_end ||
7069 	    high_mode->htotal != mode->htotal ||
7070 	    high_mode->hskew != mode->hskew ||
7071 	    high_mode->vscan != mode->vscan ||
7072 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
7073 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
7074 		return false;
7075 	else
7076 		return true;
7077 }
7078 
7079 #if defined(CONFIG_DRM_AMD_DC_FP)
7080 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
7081 			    struct dc_sink *sink, struct dc_stream_state *stream,
7082 			    struct dsc_dec_dpcd_caps *dsc_caps)
7083 {
7084 	stream->timing.flags.DSC = 0;
7085 	dsc_caps->is_dsc_supported = false;
7086 
7087 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
7088 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
7089 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
7090 			sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
7091 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7092 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7093 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7094 				dsc_caps);
7095 	}
7096 }
7097 
7098 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
7099 				    struct dc_sink *sink, struct dc_stream_state *stream,
7100 				    struct dsc_dec_dpcd_caps *dsc_caps,
7101 				    uint32_t max_dsc_target_bpp_limit_override)
7102 {
7103 	const struct dc_link_settings *verified_link_cap = NULL;
7104 	u32 link_bw_in_kbps;
7105 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
7106 	struct dc *dc = sink->ctx->dc;
7107 	struct dc_dsc_bw_range bw_range = {0};
7108 	struct dc_dsc_config dsc_cfg = {0};
7109 	struct dc_dsc_config_options dsc_options = {0};
7110 
7111 	dc_dsc_get_default_config_option(dc, &dsc_options);
7112 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7113 
7114 	verified_link_cap = dc_link_get_link_cap(stream->link);
7115 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
7116 	edp_min_bpp_x16 = 8 * 16;
7117 	edp_max_bpp_x16 = 8 * 16;
7118 
7119 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
7120 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
7121 
7122 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
7123 		edp_min_bpp_x16 = edp_max_bpp_x16;
7124 
7125 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
7126 				dc->debug.dsc_min_slice_height_override,
7127 				edp_min_bpp_x16, edp_max_bpp_x16,
7128 				dsc_caps,
7129 				&stream->timing,
7130 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7131 				&bw_range)) {
7132 
7133 		if (bw_range.max_kbps < link_bw_in_kbps) {
7134 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7135 					dsc_caps,
7136 					&dsc_options,
7137 					0,
7138 					&stream->timing,
7139 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7140 					&dsc_cfg)) {
7141 				stream->timing.dsc_cfg = dsc_cfg;
7142 				stream->timing.flags.DSC = 1;
7143 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
7144 			}
7145 			return;
7146 		}
7147 	}
7148 
7149 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7150 				dsc_caps,
7151 				&dsc_options,
7152 				link_bw_in_kbps,
7153 				&stream->timing,
7154 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7155 				&dsc_cfg)) {
7156 		stream->timing.dsc_cfg = dsc_cfg;
7157 		stream->timing.flags.DSC = 1;
7158 	}
7159 }
7160 
7161 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
7162 					struct dc_sink *sink, struct dc_stream_state *stream,
7163 					struct dsc_dec_dpcd_caps *dsc_caps)
7164 {
7165 	struct drm_connector *drm_connector = &aconnector->base;
7166 	u32 link_bandwidth_kbps;
7167 	struct dc *dc = sink->ctx->dc;
7168 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
7169 	u32 dsc_max_supported_bw_in_kbps;
7170 	u32 max_dsc_target_bpp_limit_override =
7171 		drm_connector->display_info.max_dsc_bpp;
7172 	struct dc_dsc_config_options dsc_options = {0};
7173 
7174 	dc_dsc_get_default_config_option(dc, &dsc_options);
7175 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7176 
7177 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
7178 							dc_link_get_link_cap(aconnector->dc_link));
7179 
7180 	/* Set DSC policy according to dsc_clock_en */
7181 	dc_dsc_policy_set_enable_dsc_when_not_needed(
7182 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
7183 
7184 	if (sink->sink_signal == SIGNAL_TYPE_EDP &&
7185 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
7186 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
7187 
7188 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
7189 
7190 	} else if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
7191 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
7192 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7193 						dsc_caps,
7194 						&dsc_options,
7195 						link_bandwidth_kbps,
7196 						&stream->timing,
7197 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7198 						&stream->timing.dsc_cfg)) {
7199 				stream->timing.flags.DSC = 1;
7200 				drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from SST RX\n",
7201 							__func__, drm_connector->name);
7202 			}
7203 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7204 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
7205 					dc_link_get_highest_encoding_format(aconnector->dc_link));
7206 			max_supported_bw_in_kbps = link_bandwidth_kbps;
7207 			dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
7208 
7209 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
7210 					max_supported_bw_in_kbps > 0 &&
7211 					dsc_max_supported_bw_in_kbps > 0)
7212 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7213 						dsc_caps,
7214 						&dsc_options,
7215 						dsc_max_supported_bw_in_kbps,
7216 						&stream->timing,
7217 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7218 						&stream->timing.dsc_cfg)) {
7219 					stream->timing.flags.DSC = 1;
7220 					drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from DP-HDMI PCON\n",
7221 									 __func__, drm_connector->name);
7222 				}
7223 		}
7224 	}
7225 
7226 	/* Overwrite the stream flag if DSC is enabled through debugfs */
7227 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
7228 		stream->timing.flags.DSC = 1;
7229 
7230 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
7231 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
7232 
7233 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
7234 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
7235 
7236 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
7237 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
7238 }
7239 #endif
7240 
7241 static struct dc_stream_state *
7242 create_stream_for_sink(struct drm_connector *connector,
7243 		       const struct drm_display_mode *drm_mode,
7244 		       const struct dm_connector_state *dm_state,
7245 		       const struct dc_stream_state *old_stream,
7246 		       int requested_bpc)
7247 {
7248 	struct drm_device *dev = connector->dev;
7249 	struct amdgpu_dm_connector *aconnector = NULL;
7250 	struct drm_display_mode *preferred_mode = NULL;
7251 	const struct drm_connector_state *con_state = &dm_state->base;
7252 	struct dc_stream_state *stream = NULL;
7253 	struct drm_display_mode mode;
7254 	struct drm_display_mode saved_mode;
7255 	struct drm_display_mode *freesync_mode = NULL;
7256 	bool native_mode_found = false;
7257 	bool recalculate_timing = false;
7258 	bool scale = dm_state->scaling != RMX_OFF;
7259 	int mode_refresh;
7260 	int preferred_refresh = 0;
7261 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
7262 #if defined(CONFIG_DRM_AMD_DC_FP)
7263 	struct dsc_dec_dpcd_caps dsc_caps;
7264 #endif
7265 	struct dc_link *link = NULL;
7266 	struct dc_sink *sink = NULL;
7267 
7268 	drm_mode_init(&mode, drm_mode);
7269 	memset(&saved_mode, 0, sizeof(saved_mode));
7270 
7271 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK) {
7272 		aconnector = NULL;
7273 		aconnector = to_amdgpu_dm_connector(connector);
7274 		link = aconnector->dc_link;
7275 	} else {
7276 		struct drm_writeback_connector *wbcon = NULL;
7277 		struct amdgpu_dm_wb_connector *dm_wbcon = NULL;
7278 
7279 		wbcon = drm_connector_to_writeback(connector);
7280 		dm_wbcon = to_amdgpu_dm_wb_connector(wbcon);
7281 		link = dm_wbcon->link;
7282 	}
7283 
7284 	if (!aconnector || !aconnector->dc_sink) {
7285 		sink = create_fake_sink(dev, link);
7286 		if (!sink)
7287 			return stream;
7288 
7289 	} else {
7290 		sink = aconnector->dc_sink;
7291 		dc_sink_retain(sink);
7292 	}
7293 
7294 	stream = dc_create_stream_for_sink(sink);
7295 
7296 	if (stream == NULL) {
7297 		drm_err(dev, "Failed to create stream for sink!\n");
7298 		goto finish;
7299 	}
7300 
7301 	/* We leave this NULL for writeback connectors */
7302 	stream->dm_stream_context = aconnector;
7303 
7304 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
7305 		connector->display_info.hdmi.scdc.scrambling.low_rates;
7306 
7307 	list_for_each_entry(preferred_mode, &connector->modes, head) {
7308 		/* Search for preferred mode */
7309 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
7310 			native_mode_found = true;
7311 			break;
7312 		}
7313 	}
7314 	if (!native_mode_found)
7315 		preferred_mode = list_first_entry_or_null(
7316 				&connector->modes,
7317 				struct drm_display_mode,
7318 				head);
7319 
7320 	mode_refresh = drm_mode_vrefresh(&mode);
7321 
7322 	if (preferred_mode == NULL) {
7323 		/*
7324 		 * This may not be an error, the use case is when we have no
7325 		 * usermode calls to reset and set mode upon hotplug. In this
7326 		 * case, we call set mode ourselves to restore the previous mode
7327 		 * and the modelist may not be filled in time.
7328 		 */
7329 		drm_dbg_driver(dev, "No preferred mode found\n");
7330 	} else if (aconnector) {
7331 		recalculate_timing = amdgpu_freesync_vid_mode &&
7332 				 is_freesync_video_mode(&mode, aconnector);
7333 		if (recalculate_timing) {
7334 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
7335 			drm_mode_copy(&saved_mode, &mode);
7336 			saved_mode.picture_aspect_ratio = mode.picture_aspect_ratio;
7337 			drm_mode_copy(&mode, freesync_mode);
7338 			mode.picture_aspect_ratio = saved_mode.picture_aspect_ratio;
7339 		} else {
7340 			decide_crtc_timing_for_drm_display_mode(
7341 					&mode, preferred_mode, scale);
7342 
7343 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
7344 		}
7345 	}
7346 
7347 	if (recalculate_timing)
7348 		drm_mode_set_crtcinfo(&saved_mode, 0);
7349 
7350 	/*
7351 	 * If scaling is enabled and refresh rate didn't change
7352 	 * we copy the vic and polarities of the old timings
7353 	 */
7354 	if (!scale || mode_refresh != preferred_refresh)
7355 		fill_stream_properties_from_drm_display_mode(
7356 			stream, &mode, connector, con_state, NULL,
7357 			requested_bpc);
7358 	else
7359 		fill_stream_properties_from_drm_display_mode(
7360 			stream, &mode, connector, con_state, old_stream,
7361 			requested_bpc);
7362 
7363 	/* The rest isn't needed for writeback connectors */
7364 	if (!aconnector)
7365 		goto finish;
7366 
7367 	if (aconnector->timing_changed) {
7368 		drm_dbg(aconnector->base.dev,
7369 			"overriding timing for automated test, bpc %d, changing to %d\n",
7370 			stream->timing.display_color_depth,
7371 			aconnector->timing_requested->display_color_depth);
7372 		stream->timing = *aconnector->timing_requested;
7373 	}
7374 
7375 #if defined(CONFIG_DRM_AMD_DC_FP)
7376 	/* SST DSC determination policy */
7377 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
7378 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
7379 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
7380 #endif
7381 
7382 	update_stream_scaling_settings(dev, &mode, dm_state, stream);
7383 
7384 	fill_audio_info(
7385 		&stream->audio_info,
7386 		connector,
7387 		sink);
7388 
7389 	update_stream_signal(stream, sink);
7390 
7391 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
7392 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket);
7393 
7394 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT ||
7395 	    stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
7396 	    stream->signal == SIGNAL_TYPE_EDP) {
7397 		const struct dc_edid_caps *edid_caps;
7398 		unsigned int disable_colorimetry = 0;
7399 
7400 		if (aconnector->dc_sink) {
7401 			edid_caps = &aconnector->dc_sink->edid_caps;
7402 			disable_colorimetry = edid_caps->panel_patch.disable_colorimetry;
7403 		}
7404 
7405 		//
7406 		// should decide stream support vsc sdp colorimetry capability
7407 		// before building vsc info packet
7408 		//
7409 		stream->use_vsc_sdp_for_colorimetry = stream->link->dpcd_caps.dpcd_rev.raw >= 0x14 &&
7410 						      stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED &&
7411 						      !disable_colorimetry;
7412 
7413 		if (stream->out_transfer_func.tf == TRANSFER_FUNCTION_GAMMA22)
7414 			tf = TRANSFER_FUNC_GAMMA_22;
7415 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
7416 		aconnector->sr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
7417 
7418 	}
7419 finish:
7420 	dc_sink_release(sink);
7421 
7422 	return stream;
7423 }
7424 
7425 /**
7426  * amdgpu_dm_connector_poll - Poll a connector to see if it's connected to a display
7427  * @aconnector: DM connector to poll (owns @base drm_connector and @dc_link)
7428  * @force: if true, force polling even when DAC load detection was used
7429  *
7430  * Used for connectors that don't support HPD (hotplug detection) to
7431  * periodically check whether the connector is connected to a display.
7432  *
7433  * When connection was determined via DAC load detection, we avoid
7434  * re-running it on normal polls to prevent visible glitches, unless
7435  * @force is set.
7436  *
7437  * Return: The probed connector status (connected/disconnected/unknown).
7438  */
7439 static enum drm_connector_status
7440 amdgpu_dm_connector_poll(struct amdgpu_dm_connector *aconnector, bool force)
7441 {
7442 	struct drm_connector *connector = &aconnector->base;
7443 	struct drm_device *dev = connector->dev;
7444 	struct amdgpu_device *adev = drm_to_adev(dev);
7445 	struct dc_link *link = aconnector->dc_link;
7446 	enum dc_connection_type conn_type = dc_connection_none;
7447 	enum drm_connector_status status = connector_status_disconnected;
7448 
7449 	/* When we determined the connection using DAC load detection,
7450 	 * do NOT poll the connector do detect disconnect because
7451 	 * that would run DAC load detection again which can cause
7452 	 * visible visual glitches.
7453 	 *
7454 	 * Only allow to poll such a connector again when forcing.
7455 	 */
7456 	if (!force && link->local_sink && link->type == dc_connection_analog_load)
7457 		return connector->status;
7458 
7459 	mutex_lock(&aconnector->hpd_lock);
7460 
7461 	if (dc_link_detect_connection_type(aconnector->dc_link, &conn_type) &&
7462 	    conn_type != dc_connection_none) {
7463 		mutex_lock(&adev->dm.dc_lock);
7464 
7465 		/* Only call full link detection when a sink isn't created yet,
7466 		 * ie. just when the display is plugged in, otherwise we risk flickering.
7467 		 */
7468 		if (link->local_sink ||
7469 			dc_link_detect(link, DETECT_REASON_HPD))
7470 			status = connector_status_connected;
7471 
7472 		mutex_unlock(&adev->dm.dc_lock);
7473 	}
7474 
7475 	if (connector->status != status) {
7476 		if (status == connector_status_disconnected) {
7477 			if (link->local_sink)
7478 				dc_sink_release(link->local_sink);
7479 
7480 			link->local_sink = NULL;
7481 			link->dpcd_sink_count = 0;
7482 			link->type = dc_connection_none;
7483 		}
7484 
7485 		amdgpu_dm_update_connector_after_detect(aconnector);
7486 	}
7487 
7488 	mutex_unlock(&aconnector->hpd_lock);
7489 	return status;
7490 }
7491 
7492 /**
7493  * amdgpu_dm_connector_detect() - Detect whether a DRM connector is connected to a display
7494  *
7495  * A connector is considered connected when it has a sink that is not NULL.
7496  * For connectors that support HPD (hotplug detection), the connection is
7497  * handled in the HPD interrupt.
7498  * For connectors that may not support HPD, such as analog connectors,
7499  * DRM will call this function repeatedly to poll them.
7500  *
7501  * Notes:
7502  * 1. This interface is NOT called in context of HPD irq.
7503  * 2. This interface *is called* in context of user-mode ioctl. Which
7504  *    makes it a bad place for *any* MST-related activity.
7505  *
7506  * @connector: The DRM connector we are checking. We convert it to
7507  *             amdgpu_dm_connector so we can read the DC link and state.
7508  * @force:     If true, do a full detect again. This is used even when
7509  *             a lighter check would normally be used to avoid flicker.
7510  *
7511  * Return: The connector status (connected, disconnected, or unknown).
7512  *
7513  */
7514 static enum drm_connector_status
7515 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
7516 {
7517 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7518 
7519 	update_subconnector_property(aconnector);
7520 
7521 	if (aconnector->base.force == DRM_FORCE_ON ||
7522 		aconnector->base.force == DRM_FORCE_ON_DIGITAL)
7523 		return connector_status_connected;
7524 	else if (aconnector->base.force == DRM_FORCE_OFF)
7525 		return connector_status_disconnected;
7526 
7527 	/* Poll analog connectors and only when either
7528 	 * disconnected or connected to an analog display.
7529 	 */
7530 	if (drm_kms_helper_is_poll_worker() &&
7531 		dc_connector_supports_analog(aconnector->dc_link->link_id.id) &&
7532 		(!aconnector->dc_sink || aconnector->dc_sink->edid_caps.analog))
7533 		return amdgpu_dm_connector_poll(aconnector, force);
7534 
7535 	return (aconnector->dc_sink ? connector_status_connected :
7536 			connector_status_disconnected);
7537 }
7538 
7539 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
7540 					    struct drm_connector_state *connector_state,
7541 					    struct drm_property *property,
7542 					    uint64_t val)
7543 {
7544 	struct drm_device *dev = connector->dev;
7545 	struct amdgpu_device *adev = drm_to_adev(dev);
7546 	struct dm_connector_state *dm_old_state =
7547 		to_dm_connector_state(connector->state);
7548 	struct dm_connector_state *dm_new_state =
7549 		to_dm_connector_state(connector_state);
7550 
7551 	int ret = -EINVAL;
7552 
7553 	if (property == dev->mode_config.scaling_mode_property) {
7554 		enum amdgpu_rmx_type rmx_type;
7555 
7556 		switch (val) {
7557 		case DRM_MODE_SCALE_CENTER:
7558 			rmx_type = RMX_CENTER;
7559 			break;
7560 		case DRM_MODE_SCALE_ASPECT:
7561 			rmx_type = RMX_ASPECT;
7562 			break;
7563 		case DRM_MODE_SCALE_FULLSCREEN:
7564 			rmx_type = RMX_FULL;
7565 			break;
7566 		case DRM_MODE_SCALE_NONE:
7567 		default:
7568 			rmx_type = RMX_OFF;
7569 			break;
7570 		}
7571 
7572 		if (dm_old_state->scaling == rmx_type)
7573 			return 0;
7574 
7575 		dm_new_state->scaling = rmx_type;
7576 		ret = 0;
7577 	} else if (property == adev->mode_info.underscan_hborder_property) {
7578 		dm_new_state->underscan_hborder = val;
7579 		ret = 0;
7580 	} else if (property == adev->mode_info.underscan_vborder_property) {
7581 		dm_new_state->underscan_vborder = val;
7582 		ret = 0;
7583 	} else if (property == adev->mode_info.underscan_property) {
7584 		dm_new_state->underscan_enable = val;
7585 		ret = 0;
7586 	} else if (property == adev->mode_info.abm_level_property) {
7587 		switch (val) {
7588 		case ABM_SYSFS_CONTROL:
7589 			dm_new_state->abm_sysfs_forbidden = false;
7590 			break;
7591 		case ABM_LEVEL_OFF:
7592 			dm_new_state->abm_sysfs_forbidden = true;
7593 			dm_new_state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7594 			break;
7595 		default:
7596 			dm_new_state->abm_sysfs_forbidden = true;
7597 			dm_new_state->abm_level = val;
7598 		}
7599 		ret = 0;
7600 	}
7601 
7602 	return ret;
7603 }
7604 
7605 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
7606 					    const struct drm_connector_state *state,
7607 					    struct drm_property *property,
7608 					    uint64_t *val)
7609 {
7610 	struct drm_device *dev = connector->dev;
7611 	struct amdgpu_device *adev = drm_to_adev(dev);
7612 	struct dm_connector_state *dm_state =
7613 		to_dm_connector_state(state);
7614 	int ret = -EINVAL;
7615 
7616 	if (property == dev->mode_config.scaling_mode_property) {
7617 		switch (dm_state->scaling) {
7618 		case RMX_CENTER:
7619 			*val = DRM_MODE_SCALE_CENTER;
7620 			break;
7621 		case RMX_ASPECT:
7622 			*val = DRM_MODE_SCALE_ASPECT;
7623 			break;
7624 		case RMX_FULL:
7625 			*val = DRM_MODE_SCALE_FULLSCREEN;
7626 			break;
7627 		case RMX_OFF:
7628 		default:
7629 			*val = DRM_MODE_SCALE_NONE;
7630 			break;
7631 		}
7632 		ret = 0;
7633 	} else if (property == adev->mode_info.underscan_hborder_property) {
7634 		*val = dm_state->underscan_hborder;
7635 		ret = 0;
7636 	} else if (property == adev->mode_info.underscan_vborder_property) {
7637 		*val = dm_state->underscan_vborder;
7638 		ret = 0;
7639 	} else if (property == adev->mode_info.underscan_property) {
7640 		*val = dm_state->underscan_enable;
7641 		ret = 0;
7642 	} else if (property == adev->mode_info.abm_level_property) {
7643 		if (!dm_state->abm_sysfs_forbidden)
7644 			*val = ABM_SYSFS_CONTROL;
7645 		else
7646 			*val = (dm_state->abm_level != ABM_LEVEL_IMMEDIATE_DISABLE) ?
7647 				dm_state->abm_level : 0;
7648 		ret = 0;
7649 	}
7650 
7651 	return ret;
7652 }
7653 
7654 /**
7655  * DOC: panel power savings
7656  *
7657  * The display manager allows you to set your desired **panel power savings**
7658  * level (between 0-4, with 0 representing off), e.g. using the following::
7659  *
7660  *   # echo 3 > /sys/class/drm/card0-eDP-1/amdgpu/panel_power_savings
7661  *
7662  * Modifying this value can have implications on color accuracy, so tread
7663  * carefully.
7664  */
7665 
7666 static ssize_t panel_power_savings_show(struct device *device,
7667 					struct device_attribute *attr,
7668 					char *buf)
7669 {
7670 	struct drm_connector *connector = dev_get_drvdata(device);
7671 	struct drm_device *dev = connector->dev;
7672 	u8 val;
7673 
7674 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
7675 	val = to_dm_connector_state(connector->state)->abm_level ==
7676 		ABM_LEVEL_IMMEDIATE_DISABLE ? 0 :
7677 		to_dm_connector_state(connector->state)->abm_level;
7678 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
7679 
7680 	return sysfs_emit(buf, "%u\n", val);
7681 }
7682 
7683 static ssize_t panel_power_savings_store(struct device *device,
7684 					 struct device_attribute *attr,
7685 					 const char *buf, size_t count)
7686 {
7687 	struct drm_connector *connector = dev_get_drvdata(device);
7688 	struct drm_device *dev = connector->dev;
7689 	long val;
7690 	int ret;
7691 
7692 	ret = kstrtol(buf, 0, &val);
7693 
7694 	if (ret)
7695 		return ret;
7696 
7697 	if (val < 0 || val > 4)
7698 		return -EINVAL;
7699 
7700 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
7701 	if (to_dm_connector_state(connector->state)->abm_sysfs_forbidden)
7702 		ret = -EBUSY;
7703 	else
7704 		to_dm_connector_state(connector->state)->abm_level = val ?:
7705 			ABM_LEVEL_IMMEDIATE_DISABLE;
7706 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
7707 
7708 	if (ret)
7709 		return ret;
7710 
7711 	drm_kms_helper_hotplug_event(dev);
7712 
7713 	return count;
7714 }
7715 
7716 static DEVICE_ATTR_RW(panel_power_savings);
7717 
7718 static struct attribute *amdgpu_attrs[] = {
7719 	&dev_attr_panel_power_savings.attr,
7720 	NULL
7721 };
7722 
7723 static const struct attribute_group amdgpu_group = {
7724 	.name = "amdgpu",
7725 	.attrs = amdgpu_attrs
7726 };
7727 
7728 static bool
7729 amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector *amdgpu_dm_connector)
7730 {
7731 	if (amdgpu_dm_abm_level >= 0)
7732 		return false;
7733 
7734 	if (amdgpu_dm_connector->base.connector_type != DRM_MODE_CONNECTOR_eDP)
7735 		return false;
7736 
7737 	/* check for OLED panels */
7738 	if (amdgpu_dm_connector->bl_idx >= 0) {
7739 		struct drm_device *drm = amdgpu_dm_connector->base.dev;
7740 		struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
7741 		struct amdgpu_dm_backlight_caps *caps;
7742 
7743 		caps = &dm->backlight_caps[amdgpu_dm_connector->bl_idx];
7744 		if (caps->aux_support)
7745 			return false;
7746 	}
7747 
7748 	return true;
7749 }
7750 
7751 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
7752 {
7753 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
7754 
7755 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector))
7756 		sysfs_remove_group(&connector->kdev->kobj, &amdgpu_group);
7757 
7758 	cec_notifier_conn_unregister(amdgpu_dm_connector->notifier);
7759 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
7760 }
7761 
7762 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
7763 {
7764 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7765 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
7766 	struct amdgpu_display_manager *dm = &adev->dm;
7767 
7768 	/*
7769 	 * Call only if mst_mgr was initialized before since it's not done
7770 	 * for all connector types.
7771 	 */
7772 	if (aconnector->mst_mgr.dev)
7773 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
7774 
7775 	/* Cancel and flush any pending HDMI HPD debounce work */
7776 	if (aconnector->hdmi_hpd_debounce_delay_ms) {
7777 		cancel_delayed_work_sync(&aconnector->hdmi_hpd_debounce_work);
7778 		if (aconnector->hdmi_prev_sink) {
7779 			dc_sink_release(aconnector->hdmi_prev_sink);
7780 			aconnector->hdmi_prev_sink = NULL;
7781 		}
7782 	}
7783 
7784 	if (aconnector->bl_idx != -1) {
7785 		backlight_device_unregister(dm->backlight_dev[aconnector->bl_idx]);
7786 		dm->backlight_dev[aconnector->bl_idx] = NULL;
7787 	}
7788 
7789 	if (aconnector->dc_em_sink)
7790 		dc_sink_release(aconnector->dc_em_sink);
7791 	aconnector->dc_em_sink = NULL;
7792 	if (aconnector->dc_sink)
7793 		dc_sink_release(aconnector->dc_sink);
7794 	aconnector->dc_sink = NULL;
7795 
7796 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
7797 	drm_connector_unregister(connector);
7798 	drm_connector_cleanup(connector);
7799 	kfree(aconnector->dm_dp_aux.aux.name);
7800 
7801 	kfree(connector);
7802 }
7803 
7804 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
7805 {
7806 	struct dm_connector_state *state =
7807 		to_dm_connector_state(connector->state);
7808 
7809 	if (connector->state)
7810 		__drm_atomic_helper_connector_destroy_state(connector->state);
7811 
7812 	kfree(state);
7813 
7814 	state = kzalloc(sizeof(*state), GFP_KERNEL);
7815 
7816 	if (state) {
7817 		state->scaling = RMX_OFF;
7818 		state->underscan_enable = false;
7819 		state->underscan_hborder = 0;
7820 		state->underscan_vborder = 0;
7821 		state->base.max_requested_bpc = 8;
7822 		state->vcpi_slots = 0;
7823 		state->pbn = 0;
7824 
7825 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) {
7826 			if (amdgpu_dm_abm_level <= 0)
7827 				state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7828 			else
7829 				state->abm_level = amdgpu_dm_abm_level;
7830 		}
7831 
7832 		__drm_atomic_helper_connector_reset(connector, &state->base);
7833 	}
7834 }
7835 
7836 struct drm_connector_state *
7837 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
7838 {
7839 	struct dm_connector_state *state =
7840 		to_dm_connector_state(connector->state);
7841 
7842 	struct dm_connector_state *new_state =
7843 			kmemdup(state, sizeof(*state), GFP_KERNEL);
7844 
7845 	if (!new_state)
7846 		return NULL;
7847 
7848 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
7849 
7850 	new_state->freesync_capable = state->freesync_capable;
7851 	new_state->abm_level = state->abm_level;
7852 	new_state->scaling = state->scaling;
7853 	new_state->underscan_enable = state->underscan_enable;
7854 	new_state->underscan_hborder = state->underscan_hborder;
7855 	new_state->underscan_vborder = state->underscan_vborder;
7856 	new_state->vcpi_slots = state->vcpi_slots;
7857 	new_state->pbn = state->pbn;
7858 	return &new_state->base;
7859 }
7860 
7861 static int
7862 amdgpu_dm_connector_late_register(struct drm_connector *connector)
7863 {
7864 	struct amdgpu_dm_connector *amdgpu_dm_connector =
7865 		to_amdgpu_dm_connector(connector);
7866 	int r;
7867 
7868 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector)) {
7869 		r = sysfs_create_group(&connector->kdev->kobj,
7870 				       &amdgpu_group);
7871 		if (r)
7872 			return r;
7873 	}
7874 
7875 	amdgpu_dm_register_backlight_device(amdgpu_dm_connector);
7876 
7877 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
7878 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
7879 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
7880 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
7881 		if (r)
7882 			return r;
7883 	}
7884 
7885 #if defined(CONFIG_DEBUG_FS)
7886 	connector_debugfs_init(amdgpu_dm_connector);
7887 #endif
7888 
7889 	return 0;
7890 }
7891 
7892 static void amdgpu_dm_connector_funcs_force(struct drm_connector *connector)
7893 {
7894 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7895 	struct dc_link *dc_link = aconnector->dc_link;
7896 	struct dc_sink *dc_em_sink = aconnector->dc_em_sink;
7897 	const struct drm_edid *drm_edid;
7898 	struct i2c_adapter *ddc;
7899 	struct drm_device *dev = connector->dev;
7900 
7901 	if (dc_link && dc_link->aux_mode)
7902 		ddc = &aconnector->dm_dp_aux.aux.ddc;
7903 	else
7904 		ddc = &aconnector->i2c->base;
7905 
7906 	drm_edid = drm_edid_read_ddc(connector, ddc);
7907 	drm_edid_connector_update(connector, drm_edid);
7908 	if (!drm_edid) {
7909 		drm_err(dev, "No EDID found on connector: %s.\n", connector->name);
7910 		return;
7911 	}
7912 
7913 	aconnector->drm_edid = drm_edid;
7914 	/* Update emulated (virtual) sink's EDID */
7915 	if (dc_em_sink && dc_link) {
7916 		// FIXME: Get rid of drm_edid_raw()
7917 		const struct edid *edid = drm_edid_raw(drm_edid);
7918 
7919 		memset(&dc_em_sink->edid_caps, 0, sizeof(struct dc_edid_caps));
7920 		memmove(dc_em_sink->dc_edid.raw_edid, edid,
7921 			(edid->extensions + 1) * EDID_LENGTH);
7922 		dm_helpers_parse_edid_caps(
7923 			dc_link,
7924 			&dc_em_sink->dc_edid,
7925 			&dc_em_sink->edid_caps);
7926 	}
7927 }
7928 
7929 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
7930 	.reset = amdgpu_dm_connector_funcs_reset,
7931 	.detect = amdgpu_dm_connector_detect,
7932 	.fill_modes = drm_helper_probe_single_connector_modes,
7933 	.destroy = amdgpu_dm_connector_destroy,
7934 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
7935 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
7936 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
7937 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
7938 	.late_register = amdgpu_dm_connector_late_register,
7939 	.early_unregister = amdgpu_dm_connector_unregister,
7940 	.force = amdgpu_dm_connector_funcs_force
7941 };
7942 
7943 static int get_modes(struct drm_connector *connector)
7944 {
7945 	return amdgpu_dm_connector_get_modes(connector);
7946 }
7947 
7948 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
7949 {
7950 	struct drm_connector *connector = &aconnector->base;
7951 	struct dc_link *dc_link = aconnector->dc_link;
7952 	struct dc_sink_init_data init_params = {
7953 			.link = aconnector->dc_link,
7954 			.sink_signal = SIGNAL_TYPE_VIRTUAL
7955 	};
7956 	const struct drm_edid *drm_edid;
7957 	const struct edid *edid;
7958 	struct i2c_adapter *ddc;
7959 
7960 	if (dc_link && dc_link->aux_mode)
7961 		ddc = &aconnector->dm_dp_aux.aux.ddc;
7962 	else
7963 		ddc = &aconnector->i2c->base;
7964 
7965 	drm_edid = drm_edid_read_ddc(connector, ddc);
7966 	drm_edid_connector_update(connector, drm_edid);
7967 	if (!drm_edid) {
7968 		drm_err(connector->dev, "No EDID found on connector: %s.\n", connector->name);
7969 		return;
7970 	}
7971 
7972 	if (connector->display_info.is_hdmi)
7973 		init_params.sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
7974 
7975 	aconnector->drm_edid = drm_edid;
7976 
7977 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
7978 	aconnector->dc_em_sink = dc_link_add_remote_sink(
7979 		aconnector->dc_link,
7980 		(uint8_t *)edid,
7981 		(edid->extensions + 1) * EDID_LENGTH,
7982 		&init_params);
7983 
7984 	if (aconnector->base.force == DRM_FORCE_ON) {
7985 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
7986 		aconnector->dc_link->local_sink :
7987 		aconnector->dc_em_sink;
7988 		if (aconnector->dc_sink)
7989 			dc_sink_retain(aconnector->dc_sink);
7990 	}
7991 }
7992 
7993 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
7994 {
7995 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
7996 
7997 	/*
7998 	 * In case of headless boot with force on for DP managed connector
7999 	 * Those settings have to be != 0 to get initial modeset
8000 	 */
8001 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
8002 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
8003 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
8004 	}
8005 
8006 	create_eml_sink(aconnector);
8007 }
8008 
8009 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
8010 						struct dc_stream_state *stream)
8011 {
8012 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
8013 	struct dc_plane_state *dc_plane_state = NULL;
8014 	struct dc_state *dc_state = NULL;
8015 
8016 	if (!stream)
8017 		goto cleanup;
8018 
8019 	dc_plane_state = dc_create_plane_state(dc);
8020 	if (!dc_plane_state)
8021 		goto cleanup;
8022 
8023 	dc_state = dc_state_create(dc, NULL);
8024 	if (!dc_state)
8025 		goto cleanup;
8026 
8027 	/* populate stream to plane */
8028 	dc_plane_state->src_rect.height  = stream->src.height;
8029 	dc_plane_state->src_rect.width   = stream->src.width;
8030 	dc_plane_state->dst_rect.height  = stream->src.height;
8031 	dc_plane_state->dst_rect.width   = stream->src.width;
8032 	dc_plane_state->clip_rect.height = stream->src.height;
8033 	dc_plane_state->clip_rect.width  = stream->src.width;
8034 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
8035 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
8036 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
8037 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
8038 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
8039 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
8040 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
8041 	dc_plane_state->rotation = ROTATION_ANGLE_0;
8042 	dc_plane_state->is_tiling_rotated = false;
8043 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
8044 
8045 	dc_result = dc_validate_stream(dc, stream);
8046 	if (dc_result == DC_OK)
8047 		dc_result = dc_validate_plane(dc, dc_plane_state);
8048 
8049 	if (dc_result == DC_OK)
8050 		dc_result = dc_state_add_stream(dc, dc_state, stream);
8051 
8052 	if (dc_result == DC_OK && !dc_state_add_plane(
8053 						dc,
8054 						stream,
8055 						dc_plane_state,
8056 						dc_state))
8057 		dc_result = DC_FAIL_ATTACH_SURFACES;
8058 
8059 	if (dc_result == DC_OK)
8060 		dc_result = dc_validate_global_state(dc, dc_state, DC_VALIDATE_MODE_ONLY);
8061 
8062 cleanup:
8063 	if (dc_state)
8064 		dc_state_release(dc_state);
8065 
8066 	if (dc_plane_state)
8067 		dc_plane_state_release(dc_plane_state);
8068 
8069 	return dc_result;
8070 }
8071 
8072 struct dc_stream_state *
8073 create_validate_stream_for_sink(struct drm_connector *connector,
8074 				const struct drm_display_mode *drm_mode,
8075 				const struct dm_connector_state *dm_state,
8076 				const struct dc_stream_state *old_stream)
8077 {
8078 	struct amdgpu_dm_connector *aconnector = NULL;
8079 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8080 	struct dc_stream_state *stream;
8081 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
8082 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
8083 	enum dc_status dc_result = DC_OK;
8084 	uint8_t bpc_limit = 6;
8085 
8086 	if (!dm_state)
8087 		return NULL;
8088 
8089 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
8090 		aconnector = to_amdgpu_dm_connector(connector);
8091 
8092 	if (aconnector &&
8093 	    (aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
8094 	     aconnector->dc_link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER))
8095 		bpc_limit = 8;
8096 
8097 	do {
8098 		drm_dbg_kms(connector->dev, "Trying with %d bpc\n", requested_bpc);
8099 		stream = create_stream_for_sink(connector, drm_mode,
8100 						dm_state, old_stream,
8101 						requested_bpc);
8102 		if (stream == NULL) {
8103 			drm_err(adev_to_drm(adev), "Failed to create stream for sink!\n");
8104 			break;
8105 		}
8106 
8107 		dc_result = dc_validate_stream(adev->dm.dc, stream);
8108 
8109 		if (!aconnector) /* writeback connector */
8110 			return stream;
8111 
8112 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
8113 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
8114 
8115 		if (dc_result == DC_OK)
8116 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
8117 
8118 		if (dc_result != DC_OK) {
8119 			drm_dbg_kms(connector->dev, "Pruned mode %d x %d (clk %d) %s %s -- %s\n",
8120 				      drm_mode->hdisplay,
8121 				      drm_mode->vdisplay,
8122 				      drm_mode->clock,
8123 				      dc_pixel_encoding_to_str(stream->timing.pixel_encoding),
8124 				      dc_color_depth_to_str(stream->timing.display_color_depth),
8125 				      dc_status_to_str(dc_result));
8126 
8127 			dc_stream_release(stream);
8128 			stream = NULL;
8129 			requested_bpc -= 2; /* lower bpc to retry validation */
8130 		}
8131 
8132 	} while (stream == NULL && requested_bpc >= bpc_limit);
8133 
8134 	switch (dc_result) {
8135 	/*
8136 	 * If we failed to validate DP bandwidth stream with the requested RGB color depth,
8137 	 * we try to fallback and configure in order:
8138 	 * YUV422 (8bpc, 6bpc)
8139 	 * YUV420 (8bpc, 6bpc)
8140 	 */
8141 	case DC_FAIL_ENC_VALIDATE:
8142 	case DC_EXCEED_DONGLE_CAP:
8143 	case DC_NO_DP_LINK_BANDWIDTH:
8144 		/* recursively entered twice and already tried both YUV422 and YUV420 */
8145 		if (aconnector->force_yuv422_output && aconnector->force_yuv420_output)
8146 			break;
8147 		/* first failure; try YUV422 */
8148 		if (!aconnector->force_yuv422_output) {
8149 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV422\n",
8150 				    __func__, __LINE__, dc_result);
8151 			aconnector->force_yuv422_output = true;
8152 		/* recursively entered and YUV422 failed, try YUV420 */
8153 		} else if (!aconnector->force_yuv420_output) {
8154 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV420\n",
8155 				    __func__, __LINE__, dc_result);
8156 			aconnector->force_yuv420_output = true;
8157 		}
8158 		stream = create_validate_stream_for_sink(connector, drm_mode,
8159 							 dm_state, old_stream);
8160 		aconnector->force_yuv422_output = false;
8161 		aconnector->force_yuv420_output = false;
8162 		break;
8163 	case DC_OK:
8164 		break;
8165 	default:
8166 		drm_dbg_kms(connector->dev, "%s:%d Unhandled validation failure %d\n",
8167 			    __func__, __LINE__, dc_result);
8168 		break;
8169 	}
8170 
8171 	return stream;
8172 }
8173 
8174 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
8175 				   const struct drm_display_mode *mode)
8176 {
8177 	int result = MODE_ERROR;
8178 	struct dc_sink *dc_sink;
8179 	struct drm_display_mode *test_mode;
8180 	/* TODO: Unhardcode stream count */
8181 	struct dc_stream_state *stream;
8182 	/* we always have an amdgpu_dm_connector here since we got
8183 	 * here via the amdgpu_dm_connector_helper_funcs
8184 	 */
8185 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8186 
8187 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
8188 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
8189 		return result;
8190 
8191 	/*
8192 	 * Only run this the first time mode_valid is called to initilialize
8193 	 * EDID mgmt
8194 	 */
8195 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
8196 		!aconnector->dc_em_sink)
8197 		handle_edid_mgmt(aconnector);
8198 
8199 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
8200 
8201 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
8202 				aconnector->base.force != DRM_FORCE_ON) {
8203 		drm_err(connector->dev, "dc_sink is NULL!\n");
8204 		goto fail;
8205 	}
8206 
8207 	test_mode = drm_mode_duplicate(connector->dev, mode);
8208 	if (!test_mode)
8209 		goto fail;
8210 
8211 	drm_mode_set_crtcinfo(test_mode, 0);
8212 
8213 	stream = create_validate_stream_for_sink(connector, test_mode,
8214 						 to_dm_connector_state(connector->state),
8215 						 NULL);
8216 	drm_mode_destroy(connector->dev, test_mode);
8217 	if (stream) {
8218 		dc_stream_release(stream);
8219 		result = MODE_OK;
8220 	}
8221 
8222 fail:
8223 	/* TODO: error handling*/
8224 	return result;
8225 }
8226 
8227 static int fill_hdr_info_packet(const struct drm_connector_state *state,
8228 				struct dc_info_packet *out)
8229 {
8230 	struct hdmi_drm_infoframe frame;
8231 	unsigned char buf[30]; /* 26 + 4 */
8232 	ssize_t len;
8233 	int ret, i;
8234 
8235 	memset(out, 0, sizeof(*out));
8236 
8237 	if (!state->hdr_output_metadata)
8238 		return 0;
8239 
8240 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
8241 	if (ret)
8242 		return ret;
8243 
8244 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
8245 	if (len < 0)
8246 		return (int)len;
8247 
8248 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
8249 	if (len != 30)
8250 		return -EINVAL;
8251 
8252 	/* Prepare the infopacket for DC. */
8253 	switch (state->connector->connector_type) {
8254 	case DRM_MODE_CONNECTOR_HDMIA:
8255 		out->hb0 = 0x87; /* type */
8256 		out->hb1 = 0x01; /* version */
8257 		out->hb2 = 0x1A; /* length */
8258 		out->sb[0] = buf[3]; /* checksum */
8259 		i = 1;
8260 		break;
8261 
8262 	case DRM_MODE_CONNECTOR_DisplayPort:
8263 	case DRM_MODE_CONNECTOR_eDP:
8264 		out->hb0 = 0x00; /* sdp id, zero */
8265 		out->hb1 = 0x87; /* type */
8266 		out->hb2 = 0x1D; /* payload len - 1 */
8267 		out->hb3 = (0x13 << 2); /* sdp version */
8268 		out->sb[0] = 0x01; /* version */
8269 		out->sb[1] = 0x1A; /* length */
8270 		i = 2;
8271 		break;
8272 
8273 	default:
8274 		return -EINVAL;
8275 	}
8276 
8277 	memcpy(&out->sb[i], &buf[4], 26);
8278 	out->valid = true;
8279 
8280 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
8281 		       sizeof(out->sb), false);
8282 
8283 	return 0;
8284 }
8285 
8286 static int
8287 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
8288 				 struct drm_atomic_state *state)
8289 {
8290 	struct drm_connector_state *new_con_state =
8291 		drm_atomic_get_new_connector_state(state, conn);
8292 	struct drm_connector_state *old_con_state =
8293 		drm_atomic_get_old_connector_state(state, conn);
8294 	struct drm_crtc *crtc = new_con_state->crtc;
8295 	struct drm_crtc_state *new_crtc_state;
8296 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
8297 	int ret;
8298 
8299 	if (WARN_ON(unlikely(!old_con_state || !new_con_state)))
8300 		return -EINVAL;
8301 
8302 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
8303 
8304 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
8305 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
8306 		if (ret < 0)
8307 			return ret;
8308 	}
8309 
8310 	if (!crtc)
8311 		return 0;
8312 
8313 	if (new_con_state->privacy_screen_sw_state != old_con_state->privacy_screen_sw_state) {
8314 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8315 		if (IS_ERR(new_crtc_state))
8316 			return PTR_ERR(new_crtc_state);
8317 
8318 		new_crtc_state->mode_changed = true;
8319 	}
8320 
8321 	if (new_con_state->colorspace != old_con_state->colorspace) {
8322 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8323 		if (IS_ERR(new_crtc_state))
8324 			return PTR_ERR(new_crtc_state);
8325 
8326 		new_crtc_state->mode_changed = true;
8327 	}
8328 
8329 	if (new_con_state->content_type != old_con_state->content_type) {
8330 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8331 		if (IS_ERR(new_crtc_state))
8332 			return PTR_ERR(new_crtc_state);
8333 
8334 		new_crtc_state->mode_changed = true;
8335 	}
8336 
8337 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
8338 		struct dc_info_packet hdr_infopacket;
8339 
8340 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
8341 		if (ret)
8342 			return ret;
8343 
8344 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8345 		if (IS_ERR(new_crtc_state))
8346 			return PTR_ERR(new_crtc_state);
8347 
8348 		/*
8349 		 * DC considers the stream backends changed if the
8350 		 * static metadata changes. Forcing the modeset also
8351 		 * gives a simple way for userspace to switch from
8352 		 * 8bpc to 10bpc when setting the metadata to enter
8353 		 * or exit HDR.
8354 		 *
8355 		 * Changing the static metadata after it's been
8356 		 * set is permissible, however. So only force a
8357 		 * modeset if we're entering or exiting HDR.
8358 		 */
8359 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
8360 			!old_con_state->hdr_output_metadata ||
8361 			!new_con_state->hdr_output_metadata;
8362 	}
8363 
8364 	return 0;
8365 }
8366 
8367 static const struct drm_connector_helper_funcs
8368 amdgpu_dm_connector_helper_funcs = {
8369 	/*
8370 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
8371 	 * modes will be filtered by drm_mode_validate_size(), and those modes
8372 	 * are missing after user start lightdm. So we need to renew modes list.
8373 	 * in get_modes call back, not just return the modes count
8374 	 */
8375 	.get_modes = get_modes,
8376 	.mode_valid = amdgpu_dm_connector_mode_valid,
8377 	.atomic_check = amdgpu_dm_connector_atomic_check,
8378 };
8379 
8380 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
8381 {
8382 
8383 }
8384 
8385 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
8386 {
8387 	switch (display_color_depth) {
8388 	case COLOR_DEPTH_666:
8389 		return 6;
8390 	case COLOR_DEPTH_888:
8391 		return 8;
8392 	case COLOR_DEPTH_101010:
8393 		return 10;
8394 	case COLOR_DEPTH_121212:
8395 		return 12;
8396 	case COLOR_DEPTH_141414:
8397 		return 14;
8398 	case COLOR_DEPTH_161616:
8399 		return 16;
8400 	default:
8401 		break;
8402 	}
8403 	return 0;
8404 }
8405 
8406 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
8407 					  struct drm_crtc_state *crtc_state,
8408 					  struct drm_connector_state *conn_state)
8409 {
8410 	struct drm_atomic_state *state = crtc_state->state;
8411 	struct drm_connector *connector = conn_state->connector;
8412 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8413 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
8414 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
8415 	struct drm_dp_mst_topology_mgr *mst_mgr;
8416 	struct drm_dp_mst_port *mst_port;
8417 	struct drm_dp_mst_topology_state *mst_state;
8418 	enum dc_color_depth color_depth;
8419 	int clock, bpp = 0;
8420 	bool is_y420 = false;
8421 
8422 	if ((connector->connector_type == DRM_MODE_CONNECTOR_eDP) ||
8423 	    (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)) {
8424 		struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8425 		struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8426 		enum drm_mode_status result;
8427 
8428 		result = drm_crtc_helper_mode_valid_fixed(encoder->crtc, adjusted_mode, native_mode);
8429 		if (result != MODE_OK && dm_new_connector_state->scaling == RMX_OFF) {
8430 			drm_dbg_driver(encoder->dev,
8431 				       "mode %dx%d@%dHz is not native, enabling scaling\n",
8432 				       adjusted_mode->hdisplay, adjusted_mode->vdisplay,
8433 				       drm_mode_vrefresh(adjusted_mode));
8434 			dm_new_connector_state->scaling = RMX_ASPECT;
8435 		}
8436 		return 0;
8437 	}
8438 
8439 	if (!aconnector->mst_output_port)
8440 		return 0;
8441 
8442 	mst_port = aconnector->mst_output_port;
8443 	mst_mgr = &aconnector->mst_root->mst_mgr;
8444 
8445 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
8446 		return 0;
8447 
8448 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
8449 	if (IS_ERR(mst_state))
8450 		return PTR_ERR(mst_state);
8451 
8452 	mst_state->pbn_div.full = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
8453 
8454 	if (!state->duplicated) {
8455 		int max_bpc = conn_state->max_requested_bpc;
8456 
8457 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
8458 			  aconnector->force_yuv420_output;
8459 		color_depth = convert_color_depth_from_display_info(connector,
8460 								    is_y420,
8461 								    max_bpc);
8462 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
8463 		clock = adjusted_mode->clock;
8464 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
8465 	}
8466 
8467 	dm_new_connector_state->vcpi_slots =
8468 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
8469 					      dm_new_connector_state->pbn);
8470 	if (dm_new_connector_state->vcpi_slots < 0) {
8471 		drm_dbg_atomic(connector->dev, "failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
8472 		return dm_new_connector_state->vcpi_slots;
8473 	}
8474 	return 0;
8475 }
8476 
8477 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
8478 	.disable = dm_encoder_helper_disable,
8479 	.atomic_check = dm_encoder_helper_atomic_check
8480 };
8481 
8482 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state *state,
8483 					    struct dc_state *dc_state,
8484 					    struct dsc_mst_fairness_vars *vars)
8485 {
8486 	struct dc_stream_state *stream = NULL;
8487 	struct drm_connector *connector;
8488 	struct drm_connector_state *new_con_state;
8489 	struct amdgpu_dm_connector *aconnector;
8490 	struct dm_connector_state *dm_conn_state;
8491 	int i, j, ret;
8492 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
8493 
8494 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8495 
8496 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
8497 			continue;
8498 
8499 		aconnector = to_amdgpu_dm_connector(connector);
8500 
8501 		if (!aconnector->mst_output_port)
8502 			continue;
8503 
8504 		if (!new_con_state || !new_con_state->crtc)
8505 			continue;
8506 
8507 		dm_conn_state = to_dm_connector_state(new_con_state);
8508 
8509 		for (j = 0; j < dc_state->stream_count; j++) {
8510 			stream = dc_state->streams[j];
8511 			if (!stream)
8512 				continue;
8513 
8514 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
8515 				break;
8516 
8517 			stream = NULL;
8518 		}
8519 
8520 		if (!stream)
8521 			continue;
8522 
8523 		pbn_div = dm_mst_get_pbn_divider(stream->link);
8524 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
8525 		for (j = 0; j < dc_state->stream_count; j++) {
8526 			if (vars[j].aconnector == aconnector) {
8527 				pbn = vars[j].pbn;
8528 				break;
8529 			}
8530 		}
8531 
8532 		if (j == dc_state->stream_count || pbn_div == 0)
8533 			continue;
8534 
8535 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
8536 
8537 		if (stream->timing.flags.DSC != 1) {
8538 			dm_conn_state->pbn = pbn;
8539 			dm_conn_state->vcpi_slots = slot_num;
8540 
8541 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
8542 							   dm_conn_state->pbn, false);
8543 			if (ret < 0)
8544 				return ret;
8545 
8546 			continue;
8547 		}
8548 
8549 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
8550 		if (vcpi < 0)
8551 			return vcpi;
8552 
8553 		dm_conn_state->pbn = pbn;
8554 		dm_conn_state->vcpi_slots = vcpi;
8555 	}
8556 	return 0;
8557 }
8558 
8559 static int to_drm_connector_type(enum signal_type st, uint32_t connector_id)
8560 {
8561 	switch (st) {
8562 	case SIGNAL_TYPE_HDMI_TYPE_A:
8563 		return DRM_MODE_CONNECTOR_HDMIA;
8564 	case SIGNAL_TYPE_EDP:
8565 		return DRM_MODE_CONNECTOR_eDP;
8566 	case SIGNAL_TYPE_LVDS:
8567 		return DRM_MODE_CONNECTOR_LVDS;
8568 	case SIGNAL_TYPE_RGB:
8569 		return DRM_MODE_CONNECTOR_VGA;
8570 	case SIGNAL_TYPE_DISPLAY_PORT:
8571 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
8572 		return DRM_MODE_CONNECTOR_DisplayPort;
8573 	case SIGNAL_TYPE_DVI_DUAL_LINK:
8574 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
8575 		if (connector_id == CONNECTOR_ID_SINGLE_LINK_DVII ||
8576 			connector_id == CONNECTOR_ID_DUAL_LINK_DVII)
8577 			return DRM_MODE_CONNECTOR_DVII;
8578 
8579 		return DRM_MODE_CONNECTOR_DVID;
8580 	case SIGNAL_TYPE_VIRTUAL:
8581 		return DRM_MODE_CONNECTOR_VIRTUAL;
8582 
8583 	default:
8584 		return DRM_MODE_CONNECTOR_Unknown;
8585 	}
8586 }
8587 
8588 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
8589 {
8590 	struct drm_encoder *encoder;
8591 
8592 	/* There is only one encoder per connector */
8593 	drm_connector_for_each_possible_encoder(connector, encoder)
8594 		return encoder;
8595 
8596 	return NULL;
8597 }
8598 
8599 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
8600 {
8601 	struct drm_encoder *encoder;
8602 	struct amdgpu_encoder *amdgpu_encoder;
8603 
8604 	encoder = amdgpu_dm_connector_to_encoder(connector);
8605 
8606 	if (encoder == NULL)
8607 		return;
8608 
8609 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8610 
8611 	amdgpu_encoder->native_mode.clock = 0;
8612 
8613 	if (!list_empty(&connector->probed_modes)) {
8614 		struct drm_display_mode *preferred_mode = NULL;
8615 
8616 		list_for_each_entry(preferred_mode,
8617 				    &connector->probed_modes,
8618 				    head) {
8619 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
8620 				amdgpu_encoder->native_mode = *preferred_mode;
8621 
8622 			break;
8623 		}
8624 
8625 	}
8626 }
8627 
8628 static struct drm_display_mode *
8629 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
8630 			     const char *name,
8631 			     int hdisplay, int vdisplay)
8632 {
8633 	struct drm_device *dev = encoder->dev;
8634 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8635 	struct drm_display_mode *mode = NULL;
8636 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8637 
8638 	mode = drm_mode_duplicate(dev, native_mode);
8639 
8640 	if (mode == NULL)
8641 		return NULL;
8642 
8643 	mode->hdisplay = hdisplay;
8644 	mode->vdisplay = vdisplay;
8645 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8646 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
8647 
8648 	return mode;
8649 
8650 }
8651 
8652 static const struct amdgpu_dm_mode_size {
8653 	char name[DRM_DISPLAY_MODE_LEN];
8654 	int w;
8655 	int h;
8656 } common_modes[] = {
8657 	{  "640x480",  640,  480},
8658 	{  "800x600",  800,  600},
8659 	{ "1024x768", 1024,  768},
8660 	{ "1280x720", 1280,  720},
8661 	{ "1280x800", 1280,  800},
8662 	{"1280x1024", 1280, 1024},
8663 	{ "1440x900", 1440,  900},
8664 	{"1680x1050", 1680, 1050},
8665 	{"1600x1200", 1600, 1200},
8666 	{"1920x1080", 1920, 1080},
8667 	{"1920x1200", 1920, 1200}
8668 };
8669 
8670 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
8671 						 struct drm_connector *connector)
8672 {
8673 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8674 	struct drm_display_mode *mode = NULL;
8675 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8676 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8677 				to_amdgpu_dm_connector(connector);
8678 	int i;
8679 	int n;
8680 
8681 	if ((connector->connector_type != DRM_MODE_CONNECTOR_eDP) &&
8682 	    (connector->connector_type != DRM_MODE_CONNECTOR_LVDS))
8683 		return;
8684 
8685 	n = ARRAY_SIZE(common_modes);
8686 
8687 	for (i = 0; i < n; i++) {
8688 		struct drm_display_mode *curmode = NULL;
8689 		bool mode_existed = false;
8690 
8691 		if (common_modes[i].w > native_mode->hdisplay ||
8692 		    common_modes[i].h > native_mode->vdisplay ||
8693 		   (common_modes[i].w == native_mode->hdisplay &&
8694 		    common_modes[i].h == native_mode->vdisplay))
8695 			continue;
8696 
8697 		list_for_each_entry(curmode, &connector->probed_modes, head) {
8698 			if (common_modes[i].w == curmode->hdisplay &&
8699 			    common_modes[i].h == curmode->vdisplay) {
8700 				mode_existed = true;
8701 				break;
8702 			}
8703 		}
8704 
8705 		if (mode_existed)
8706 			continue;
8707 
8708 		mode = amdgpu_dm_create_common_mode(encoder,
8709 				common_modes[i].name, common_modes[i].w,
8710 				common_modes[i].h);
8711 		if (!mode)
8712 			continue;
8713 
8714 		drm_mode_probed_add(connector, mode);
8715 		amdgpu_dm_connector->num_modes++;
8716 	}
8717 }
8718 
8719 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
8720 {
8721 	struct drm_encoder *encoder;
8722 	struct amdgpu_encoder *amdgpu_encoder;
8723 	const struct drm_display_mode *native_mode;
8724 
8725 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
8726 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
8727 		return;
8728 
8729 	mutex_lock(&connector->dev->mode_config.mutex);
8730 	amdgpu_dm_connector_get_modes(connector);
8731 	mutex_unlock(&connector->dev->mode_config.mutex);
8732 
8733 	encoder = amdgpu_dm_connector_to_encoder(connector);
8734 	if (!encoder)
8735 		return;
8736 
8737 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8738 
8739 	native_mode = &amdgpu_encoder->native_mode;
8740 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
8741 		return;
8742 
8743 	drm_connector_set_panel_orientation_with_quirk(connector,
8744 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
8745 						       native_mode->hdisplay,
8746 						       native_mode->vdisplay);
8747 }
8748 
8749 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
8750 					      const struct drm_edid *drm_edid)
8751 {
8752 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8753 			to_amdgpu_dm_connector(connector);
8754 
8755 	if (drm_edid) {
8756 		/* empty probed_modes */
8757 		INIT_LIST_HEAD(&connector->probed_modes);
8758 		amdgpu_dm_connector->num_modes =
8759 				drm_edid_connector_add_modes(connector);
8760 
8761 		/* sorting the probed modes before calling function
8762 		 * amdgpu_dm_get_native_mode() since EDID can have
8763 		 * more than one preferred mode. The modes that are
8764 		 * later in the probed mode list could be of higher
8765 		 * and preferred resolution. For example, 3840x2160
8766 		 * resolution in base EDID preferred timing and 4096x2160
8767 		 * preferred resolution in DID extension block later.
8768 		 */
8769 		drm_mode_sort(&connector->probed_modes);
8770 		amdgpu_dm_get_native_mode(connector);
8771 
8772 		/* Freesync capabilities are reset by calling
8773 		 * drm_edid_connector_add_modes() and need to be
8774 		 * restored here.
8775 		 */
8776 		amdgpu_dm_update_freesync_caps(connector, drm_edid);
8777 	} else {
8778 		amdgpu_dm_connector->num_modes = 0;
8779 	}
8780 }
8781 
8782 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
8783 			      struct drm_display_mode *mode)
8784 {
8785 	struct drm_display_mode *m;
8786 
8787 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
8788 		if (drm_mode_equal(m, mode))
8789 			return true;
8790 	}
8791 
8792 	return false;
8793 }
8794 
8795 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
8796 {
8797 	const struct drm_display_mode *m;
8798 	struct drm_display_mode *new_mode;
8799 	uint i;
8800 	u32 new_modes_count = 0;
8801 
8802 	/* Standard FPS values
8803 	 *
8804 	 * 23.976       - TV/NTSC
8805 	 * 24           - Cinema
8806 	 * 25           - TV/PAL
8807 	 * 29.97        - TV/NTSC
8808 	 * 30           - TV/NTSC
8809 	 * 48           - Cinema HFR
8810 	 * 50           - TV/PAL
8811 	 * 60           - Commonly used
8812 	 * 48,72,96,120 - Multiples of 24
8813 	 */
8814 	static const u32 common_rates[] = {
8815 		23976, 24000, 25000, 29970, 30000,
8816 		48000, 50000, 60000, 72000, 96000, 120000
8817 	};
8818 
8819 	/*
8820 	 * Find mode with highest refresh rate with the same resolution
8821 	 * as the preferred mode. Some monitors report a preferred mode
8822 	 * with lower resolution than the highest refresh rate supported.
8823 	 */
8824 
8825 	m = get_highest_refresh_rate_mode(aconnector, true);
8826 	if (!m)
8827 		return 0;
8828 
8829 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
8830 		u64 target_vtotal, target_vtotal_diff;
8831 		u64 num, den;
8832 
8833 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
8834 			continue;
8835 
8836 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
8837 		    common_rates[i] > aconnector->max_vfreq * 1000)
8838 			continue;
8839 
8840 		num = (unsigned long long)m->clock * 1000 * 1000;
8841 		den = common_rates[i] * (unsigned long long)m->htotal;
8842 		target_vtotal = div_u64(num, den);
8843 		target_vtotal_diff = target_vtotal - m->vtotal;
8844 
8845 		/* Check for illegal modes */
8846 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
8847 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
8848 		    m->vtotal + target_vtotal_diff < m->vsync_end)
8849 			continue;
8850 
8851 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
8852 		if (!new_mode)
8853 			goto out;
8854 
8855 		new_mode->vtotal += (u16)target_vtotal_diff;
8856 		new_mode->vsync_start += (u16)target_vtotal_diff;
8857 		new_mode->vsync_end += (u16)target_vtotal_diff;
8858 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8859 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
8860 
8861 		if (!is_duplicate_mode(aconnector, new_mode)) {
8862 			drm_mode_probed_add(&aconnector->base, new_mode);
8863 			new_modes_count += 1;
8864 		} else
8865 			drm_mode_destroy(aconnector->base.dev, new_mode);
8866 	}
8867  out:
8868 	return new_modes_count;
8869 }
8870 
8871 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
8872 						   const struct drm_edid *drm_edid)
8873 {
8874 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8875 		to_amdgpu_dm_connector(connector);
8876 
8877 	if (!(amdgpu_freesync_vid_mode && drm_edid))
8878 		return;
8879 
8880 	if (!amdgpu_dm_connector->dc_sink || !amdgpu_dm_connector->dc_link)
8881 		return;
8882 
8883 	if (!dc_supports_vrr(amdgpu_dm_connector->dc_sink->ctx->dce_version))
8884 		return;
8885 
8886 	if (dc_connector_supports_analog(amdgpu_dm_connector->dc_link->link_id.id) &&
8887 	    amdgpu_dm_connector->dc_sink->edid_caps.analog)
8888 		return;
8889 
8890 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
8891 		amdgpu_dm_connector->num_modes +=
8892 			add_fs_modes(amdgpu_dm_connector);
8893 }
8894 
8895 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
8896 {
8897 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8898 			to_amdgpu_dm_connector(connector);
8899 	struct dc_link *dc_link = amdgpu_dm_connector->dc_link;
8900 	struct drm_encoder *encoder;
8901 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
8902 	struct dc_link_settings *verified_link_cap = &dc_link->verified_link_cap;
8903 	const struct dc *dc = dc_link->dc;
8904 
8905 	encoder = amdgpu_dm_connector_to_encoder(connector);
8906 
8907 	if (!drm_edid) {
8908 		amdgpu_dm_connector->num_modes =
8909 				drm_add_modes_noedid(connector, 640, 480);
8910 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
8911 			amdgpu_dm_connector->num_modes +=
8912 				drm_add_modes_noedid(connector, 1920, 1080);
8913 
8914 		if (amdgpu_dm_connector->dc_sink &&
8915 		    amdgpu_dm_connector->dc_sink->edid_caps.analog &&
8916 		    dc_connector_supports_analog(dc_link->link_id.id)) {
8917 			/* Analog monitor connected by DAC load detection.
8918 			 * Add common modes. It will be up to the user to select one that works.
8919 			 */
8920 			for (int i = 0; i < ARRAY_SIZE(common_modes); i++)
8921 				amdgpu_dm_connector->num_modes += drm_add_modes_noedid(
8922 					connector, common_modes[i].w, common_modes[i].h);
8923 		}
8924 	} else {
8925 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
8926 		if (encoder)
8927 			amdgpu_dm_connector_add_common_modes(encoder, connector);
8928 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
8929 	}
8930 	amdgpu_dm_fbc_init(connector);
8931 
8932 	return amdgpu_dm_connector->num_modes;
8933 }
8934 
8935 static const u32 supported_colorspaces =
8936 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
8937 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
8938 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
8939 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
8940 
8941 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
8942 				     struct amdgpu_dm_connector *aconnector,
8943 				     int connector_type,
8944 				     struct dc_link *link,
8945 				     int link_index)
8946 {
8947 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
8948 
8949 	/*
8950 	 * Some of the properties below require access to state, like bpc.
8951 	 * Allocate some default initial connector state with our reset helper.
8952 	 */
8953 	if (aconnector->base.funcs->reset)
8954 		aconnector->base.funcs->reset(&aconnector->base);
8955 
8956 	aconnector->connector_id = link_index;
8957 	aconnector->bl_idx = -1;
8958 	aconnector->dc_link = link;
8959 	aconnector->base.interlace_allowed = false;
8960 	aconnector->base.doublescan_allowed = false;
8961 	aconnector->base.stereo_allowed = false;
8962 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
8963 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
8964 	aconnector->audio_inst = -1;
8965 	aconnector->pack_sdp_v1_3 = false;
8966 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
8967 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
8968 	mutex_init(&aconnector->hpd_lock);
8969 	mutex_init(&aconnector->handle_mst_msg_ready);
8970 
8971 	/*
8972 	 * If HDMI HPD debounce delay is set, use the minimum between selected
8973 	 * value and AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS
8974 	 */
8975 	if (amdgpu_hdmi_hpd_debounce_delay_ms) {
8976 		aconnector->hdmi_hpd_debounce_delay_ms = min(amdgpu_hdmi_hpd_debounce_delay_ms,
8977 							     AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS);
8978 		INIT_DELAYED_WORK(&aconnector->hdmi_hpd_debounce_work, hdmi_hpd_debounce_work);
8979 		aconnector->hdmi_prev_sink = NULL;
8980 	} else {
8981 		aconnector->hdmi_hpd_debounce_delay_ms = 0;
8982 	}
8983 
8984 	/*
8985 	 * configure support HPD hot plug connector_>polled default value is 0
8986 	 * which means HPD hot plug not supported
8987 	 */
8988 	switch (connector_type) {
8989 	case DRM_MODE_CONNECTOR_HDMIA:
8990 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
8991 		aconnector->base.ycbcr_420_allowed =
8992 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
8993 		break;
8994 	case DRM_MODE_CONNECTOR_DisplayPort:
8995 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
8996 		link->link_enc = link_enc_cfg_get_link_enc(link);
8997 		ASSERT(link->link_enc);
8998 		if (link->link_enc)
8999 			aconnector->base.ycbcr_420_allowed =
9000 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
9001 		break;
9002 	case DRM_MODE_CONNECTOR_DVID:
9003 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9004 		break;
9005 	case DRM_MODE_CONNECTOR_DVII:
9006 	case DRM_MODE_CONNECTOR_VGA:
9007 		aconnector->base.polled =
9008 			DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT;
9009 		break;
9010 	default:
9011 		break;
9012 	}
9013 
9014 	drm_object_attach_property(&aconnector->base.base,
9015 				dm->ddev->mode_config.scaling_mode_property,
9016 				DRM_MODE_SCALE_NONE);
9017 
9018 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA
9019 		|| (connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root))
9020 		drm_connector_attach_broadcast_rgb_property(&aconnector->base);
9021 
9022 	drm_object_attach_property(&aconnector->base.base,
9023 				adev->mode_info.underscan_property,
9024 				UNDERSCAN_OFF);
9025 	drm_object_attach_property(&aconnector->base.base,
9026 				adev->mode_info.underscan_hborder_property,
9027 				0);
9028 	drm_object_attach_property(&aconnector->base.base,
9029 				adev->mode_info.underscan_vborder_property,
9030 				0);
9031 
9032 	if (!aconnector->mst_root)
9033 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
9034 
9035 	aconnector->base.state->max_bpc = 16;
9036 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
9037 
9038 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9039 		/* Content Type is currently only implemented for HDMI. */
9040 		drm_connector_attach_content_type_property(&aconnector->base);
9041 	}
9042 
9043 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9044 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
9045 			drm_connector_attach_colorspace_property(&aconnector->base);
9046 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
9047 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
9048 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
9049 			drm_connector_attach_colorspace_property(&aconnector->base);
9050 	}
9051 
9052 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9053 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
9054 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
9055 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
9056 
9057 		if (!aconnector->mst_root)
9058 			drm_connector_attach_vrr_capable_property(&aconnector->base);
9059 
9060 		if (adev->dm.hdcp_workqueue)
9061 			drm_connector_attach_content_protection_property(&aconnector->base, true);
9062 	}
9063 
9064 	if (connector_type == DRM_MODE_CONNECTOR_eDP) {
9065 		struct drm_privacy_screen *privacy_screen;
9066 
9067 		drm_connector_attach_panel_type_property(&aconnector->base);
9068 
9069 		privacy_screen = drm_privacy_screen_get(adev_to_drm(adev)->dev, NULL);
9070 		if (!IS_ERR(privacy_screen)) {
9071 			drm_connector_attach_privacy_screen_provider(&aconnector->base,
9072 								     privacy_screen);
9073 		} else if (PTR_ERR(privacy_screen) != -ENODEV) {
9074 			drm_warn(adev_to_drm(adev), "Error getting privacy-screen\n");
9075 		}
9076 	}
9077 }
9078 
9079 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
9080 			      struct i2c_msg *msgs, int num)
9081 {
9082 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
9083 	struct ddc_service *ddc_service = i2c->ddc_service;
9084 	struct i2c_command cmd;
9085 	int i;
9086 	int result = -EIO;
9087 
9088 	if (!ddc_service->ddc_pin)
9089 		return result;
9090 
9091 	cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
9092 
9093 	if (!cmd.payloads)
9094 		return result;
9095 
9096 	cmd.number_of_payloads = num;
9097 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
9098 	cmd.speed = 100;
9099 
9100 	for (i = 0; i < num; i++) {
9101 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
9102 		cmd.payloads[i].address = msgs[i].addr;
9103 		cmd.payloads[i].length = msgs[i].len;
9104 		cmd.payloads[i].data = msgs[i].buf;
9105 	}
9106 
9107 	if (i2c->oem) {
9108 		if (dc_submit_i2c_oem(
9109 			    ddc_service->ctx->dc,
9110 			    &cmd))
9111 			result = num;
9112 	} else {
9113 		if (dc_submit_i2c(
9114 			    ddc_service->ctx->dc,
9115 			    ddc_service->link->link_index,
9116 			    &cmd))
9117 			result = num;
9118 	}
9119 
9120 	kfree(cmd.payloads);
9121 	return result;
9122 }
9123 
9124 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
9125 {
9126 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
9127 }
9128 
9129 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
9130 	.master_xfer = amdgpu_dm_i2c_xfer,
9131 	.functionality = amdgpu_dm_i2c_func,
9132 };
9133 
9134 static struct amdgpu_i2c_adapter *
9135 create_i2c(struct ddc_service *ddc_service, bool oem)
9136 {
9137 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
9138 	struct amdgpu_i2c_adapter *i2c;
9139 
9140 	i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
9141 	if (!i2c)
9142 		return NULL;
9143 	i2c->base.owner = THIS_MODULE;
9144 	i2c->base.dev.parent = &adev->pdev->dev;
9145 	i2c->base.algo = &amdgpu_dm_i2c_algo;
9146 	if (oem)
9147 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c OEM bus");
9148 	else
9149 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d",
9150 			 ddc_service->link->link_index);
9151 	i2c_set_adapdata(&i2c->base, i2c);
9152 	i2c->ddc_service = ddc_service;
9153 	i2c->oem = oem;
9154 
9155 	return i2c;
9156 }
9157 
9158 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
9159 {
9160 	struct cec_connector_info conn_info;
9161 	struct drm_device *ddev = aconnector->base.dev;
9162 	struct device *hdmi_dev = ddev->dev;
9163 
9164 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
9165 		drm_info(ddev, "HDMI-CEC feature masked\n");
9166 		return -EINVAL;
9167 	}
9168 
9169 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
9170 	aconnector->notifier =
9171 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
9172 	if (!aconnector->notifier) {
9173 		drm_err(ddev, "Failed to create cec notifier\n");
9174 		return -ENOMEM;
9175 	}
9176 
9177 	return 0;
9178 }
9179 
9180 /*
9181  * Note: this function assumes that dc_link_detect() was called for the
9182  * dc_link which will be represented by this aconnector.
9183  */
9184 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
9185 				    struct amdgpu_dm_connector *aconnector,
9186 				    u32 link_index,
9187 				    struct amdgpu_encoder *aencoder)
9188 {
9189 	int res = 0;
9190 	int connector_type;
9191 	struct dc *dc = dm->dc;
9192 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
9193 	struct amdgpu_i2c_adapter *i2c;
9194 
9195 	/* Not needed for writeback connector */
9196 	link->priv = aconnector;
9197 
9198 
9199 	i2c = create_i2c(link->ddc, false);
9200 	if (!i2c) {
9201 		drm_err(adev_to_drm(dm->adev), "Failed to create i2c adapter data\n");
9202 		return -ENOMEM;
9203 	}
9204 
9205 	aconnector->i2c = i2c;
9206 	res = devm_i2c_add_adapter(dm->adev->dev, &i2c->base);
9207 
9208 	if (res) {
9209 		drm_err(adev_to_drm(dm->adev), "Failed to register hw i2c %d\n", link->link_index);
9210 		goto out_free;
9211 	}
9212 
9213 	connector_type = to_drm_connector_type(link->connector_signal, link->link_id.id);
9214 
9215 	res = drm_connector_init_with_ddc(
9216 			dm->ddev,
9217 			&aconnector->base,
9218 			&amdgpu_dm_connector_funcs,
9219 			connector_type,
9220 			&i2c->base);
9221 
9222 	if (res) {
9223 		drm_err(adev_to_drm(dm->adev), "connector_init failed\n");
9224 		aconnector->connector_id = -1;
9225 		goto out_free;
9226 	}
9227 
9228 	drm_connector_helper_add(
9229 			&aconnector->base,
9230 			&amdgpu_dm_connector_helper_funcs);
9231 
9232 	amdgpu_dm_connector_init_helper(
9233 		dm,
9234 		aconnector,
9235 		connector_type,
9236 		link,
9237 		link_index);
9238 
9239 	drm_connector_attach_encoder(
9240 		&aconnector->base, &aencoder->base);
9241 
9242 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9243 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
9244 		amdgpu_dm_initialize_hdmi_connector(aconnector);
9245 
9246 	if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
9247 		|| connector_type == DRM_MODE_CONNECTOR_eDP)
9248 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
9249 
9250 out_free:
9251 	if (res) {
9252 		kfree(i2c);
9253 		aconnector->i2c = NULL;
9254 	}
9255 	return res;
9256 }
9257 
9258 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
9259 {
9260 	switch (adev->mode_info.num_crtc) {
9261 	case 1:
9262 		return 0x1;
9263 	case 2:
9264 		return 0x3;
9265 	case 3:
9266 		return 0x7;
9267 	case 4:
9268 		return 0xf;
9269 	case 5:
9270 		return 0x1f;
9271 	case 6:
9272 	default:
9273 		return 0x3f;
9274 	}
9275 }
9276 
9277 static int amdgpu_dm_encoder_init(struct drm_device *dev,
9278 				  struct amdgpu_encoder *aencoder,
9279 				  uint32_t link_index)
9280 {
9281 	struct amdgpu_device *adev = drm_to_adev(dev);
9282 
9283 	int res = drm_encoder_init(dev,
9284 				   &aencoder->base,
9285 				   &amdgpu_dm_encoder_funcs,
9286 				   DRM_MODE_ENCODER_TMDS,
9287 				   NULL);
9288 
9289 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
9290 
9291 	if (!res)
9292 		aencoder->encoder_id = link_index;
9293 	else
9294 		aencoder->encoder_id = -1;
9295 
9296 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
9297 
9298 	return res;
9299 }
9300 
9301 static void manage_dm_interrupts(struct amdgpu_device *adev,
9302 				 struct amdgpu_crtc *acrtc,
9303 				 struct dm_crtc_state *acrtc_state)
9304 {	/*
9305 	 * We cannot be sure that the frontend index maps to the same
9306 	 * backend index - some even map to more than one.
9307 	 * So we have to go through the CRTC to find the right IRQ.
9308 	 */
9309 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
9310 			adev,
9311 			acrtc->crtc_id);
9312 	struct drm_device *dev = adev_to_drm(adev);
9313 
9314 	struct drm_vblank_crtc_config config = {0};
9315 	struct dc_crtc_timing *timing;
9316 	int offdelay;
9317 
9318 	if (acrtc_state) {
9319 		timing = &acrtc_state->stream->timing;
9320 
9321 		/*
9322 		 * Depending on when the HW latching event of double-buffered
9323 		 * registers happen relative to the PSR SDP deadline, and how
9324 		 * bad the Panel clock has drifted since the last ALPM off
9325 		 * event, there can be up to 3 frames of delay between sending
9326 		 * the PSR exit cmd to DMUB fw, and when the panel starts
9327 		 * displaying live frames.
9328 		 *
9329 		 * We can set:
9330 		 *
9331 		 * 20/100 * offdelay_ms = 3_frames_ms
9332 		 * => offdelay_ms = 5 * 3_frames_ms
9333 		 *
9334 		 * This ensures that `3_frames_ms` will only be experienced as a
9335 		 * 20% delay on top how long the display has been static, and
9336 		 * thus make the delay less perceivable.
9337 		 */
9338 		if (acrtc_state->stream->link->psr_settings.psr_version <
9339 		    DC_PSR_VERSION_UNSUPPORTED) {
9340 			offdelay = DIV64_U64_ROUND_UP((u64)5 * 3 * 10 *
9341 						      timing->v_total *
9342 						      timing->h_total,
9343 						      timing->pix_clk_100hz);
9344 			config.offdelay_ms = offdelay ?: 30;
9345 		} else if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
9346 			   IP_VERSION(3, 5, 0) ||
9347 			   !(adev->flags & AMD_IS_APU)) {
9348 			/*
9349 			 * Older HW and DGPU have issues with instant off;
9350 			 * use a 2 frame offdelay.
9351 			 */
9352 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
9353 						      timing->v_total *
9354 						      timing->h_total,
9355 						      timing->pix_clk_100hz);
9356 
9357 			config.offdelay_ms = offdelay ?: 30;
9358 		} else {
9359 			/* offdelay_ms = 0 will never disable vblank */
9360 			config.offdelay_ms = 1;
9361 			config.disable_immediate = true;
9362 		}
9363 
9364 		drm_crtc_vblank_on_config(&acrtc->base,
9365 					  &config);
9366 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_get.*/
9367 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9368 		case IP_VERSION(3, 0, 0):
9369 		case IP_VERSION(3, 0, 2):
9370 		case IP_VERSION(3, 0, 3):
9371 		case IP_VERSION(3, 2, 0):
9372 			if (amdgpu_irq_get(adev, &adev->pageflip_irq, irq_type))
9373 				drm_err(dev, "DM_IRQ: Cannot get pageflip irq!\n");
9374 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9375 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
9376 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
9377 #endif
9378 		}
9379 
9380 	} else {
9381 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
9382 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9383 		case IP_VERSION(3, 0, 0):
9384 		case IP_VERSION(3, 0, 2):
9385 		case IP_VERSION(3, 0, 3):
9386 		case IP_VERSION(3, 2, 0):
9387 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9388 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
9389 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
9390 #endif
9391 			if (amdgpu_irq_put(adev, &adev->pageflip_irq, irq_type))
9392 				drm_err(dev, "DM_IRQ: Cannot put pageflip irq!\n");
9393 		}
9394 
9395 		drm_crtc_vblank_off(&acrtc->base);
9396 	}
9397 }
9398 
9399 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
9400 				      struct amdgpu_crtc *acrtc)
9401 {
9402 	int irq_type =
9403 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
9404 
9405 	/**
9406 	 * This reads the current state for the IRQ and force reapplies
9407 	 * the setting to hardware.
9408 	 */
9409 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
9410 }
9411 
9412 static bool
9413 is_scaling_state_different(const struct dm_connector_state *dm_state,
9414 			   const struct dm_connector_state *old_dm_state)
9415 {
9416 	if (dm_state->scaling != old_dm_state->scaling)
9417 		return true;
9418 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
9419 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
9420 			return true;
9421 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
9422 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
9423 			return true;
9424 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
9425 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
9426 		return true;
9427 	return false;
9428 }
9429 
9430 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
9431 					    struct drm_crtc_state *old_crtc_state,
9432 					    struct drm_connector_state *new_conn_state,
9433 					    struct drm_connector_state *old_conn_state,
9434 					    const struct drm_connector *connector,
9435 					    struct hdcp_workqueue *hdcp_w)
9436 {
9437 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
9438 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
9439 
9440 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
9441 		connector->index, connector->status, connector->dpms);
9442 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
9443 		old_conn_state->content_protection, new_conn_state->content_protection);
9444 
9445 	if (old_crtc_state)
9446 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9447 		old_crtc_state->enable,
9448 		old_crtc_state->active,
9449 		old_crtc_state->mode_changed,
9450 		old_crtc_state->active_changed,
9451 		old_crtc_state->connectors_changed);
9452 
9453 	if (new_crtc_state)
9454 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9455 		new_crtc_state->enable,
9456 		new_crtc_state->active,
9457 		new_crtc_state->mode_changed,
9458 		new_crtc_state->active_changed,
9459 		new_crtc_state->connectors_changed);
9460 
9461 	/* hdcp content type change */
9462 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
9463 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
9464 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9465 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
9466 		return true;
9467 	}
9468 
9469 	/* CP is being re enabled, ignore this */
9470 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
9471 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9472 		if (new_crtc_state && new_crtc_state->mode_changed) {
9473 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9474 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
9475 			return true;
9476 		}
9477 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
9478 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
9479 		return false;
9480 	}
9481 
9482 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
9483 	 *
9484 	 * Handles:	UNDESIRED -> ENABLED
9485 	 */
9486 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
9487 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
9488 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9489 
9490 	/* Stream removed and re-enabled
9491 	 *
9492 	 * Can sometimes overlap with the HPD case,
9493 	 * thus set update_hdcp to false to avoid
9494 	 * setting HDCP multiple times.
9495 	 *
9496 	 * Handles:	DESIRED -> DESIRED (Special case)
9497 	 */
9498 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
9499 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
9500 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9501 		dm_con_state->update_hdcp = false;
9502 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
9503 			__func__);
9504 		return true;
9505 	}
9506 
9507 	/* Hot-plug, headless s3, dpms
9508 	 *
9509 	 * Only start HDCP if the display is connected/enabled.
9510 	 * update_hdcp flag will be set to false until the next
9511 	 * HPD comes in.
9512 	 *
9513 	 * Handles:	DESIRED -> DESIRED (Special case)
9514 	 */
9515 	if (dm_con_state->update_hdcp &&
9516 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
9517 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
9518 		dm_con_state->update_hdcp = false;
9519 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
9520 			__func__);
9521 		return true;
9522 	}
9523 
9524 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
9525 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9526 			if (new_crtc_state && new_crtc_state->mode_changed) {
9527 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
9528 					__func__);
9529 				return true;
9530 			}
9531 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
9532 				__func__);
9533 			return false;
9534 		}
9535 
9536 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
9537 		return false;
9538 	}
9539 
9540 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9541 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
9542 			__func__);
9543 		return true;
9544 	}
9545 
9546 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
9547 	return false;
9548 }
9549 
9550 static void remove_stream(struct amdgpu_device *adev,
9551 			  struct amdgpu_crtc *acrtc,
9552 			  struct dc_stream_state *stream)
9553 {
9554 	/* this is the update mode case */
9555 
9556 	acrtc->otg_inst = -1;
9557 	acrtc->enabled = false;
9558 }
9559 
9560 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
9561 {
9562 
9563 	assert_spin_locked(&acrtc->base.dev->event_lock);
9564 	WARN_ON(acrtc->event);
9565 
9566 	acrtc->event = acrtc->base.state->event;
9567 
9568 	/* Set the flip status */
9569 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
9570 
9571 	/* Mark this event as consumed */
9572 	acrtc->base.state->event = NULL;
9573 
9574 	drm_dbg_state(acrtc->base.dev,
9575 		      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
9576 		      acrtc->crtc_id);
9577 }
9578 
9579 static void update_freesync_state_on_stream(
9580 	struct amdgpu_display_manager *dm,
9581 	struct dm_crtc_state *new_crtc_state,
9582 	struct dc_stream_state *new_stream,
9583 	struct dc_plane_state *surface,
9584 	u32 flip_timestamp_in_us)
9585 {
9586 	struct mod_vrr_params vrr_params;
9587 	struct dc_info_packet vrr_infopacket = {0};
9588 	struct amdgpu_device *adev = dm->adev;
9589 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9590 	unsigned long flags;
9591 	bool pack_sdp_v1_3 = false;
9592 	struct amdgpu_dm_connector *aconn;
9593 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
9594 
9595 	if (!new_stream)
9596 		return;
9597 
9598 	/*
9599 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9600 	 * For now it's sufficient to just guard against these conditions.
9601 	 */
9602 
9603 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9604 		return;
9605 
9606 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9607 	vrr_params = acrtc->dm_irq_params.vrr_params;
9608 
9609 	if (surface) {
9610 		mod_freesync_handle_preflip(
9611 			dm->freesync_module,
9612 			surface,
9613 			new_stream,
9614 			flip_timestamp_in_us,
9615 			&vrr_params);
9616 
9617 		if (adev->family < AMDGPU_FAMILY_AI &&
9618 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
9619 			mod_freesync_handle_v_update(dm->freesync_module,
9620 						     new_stream, &vrr_params);
9621 
9622 			/* Need to call this before the frame ends. */
9623 			dc_stream_adjust_vmin_vmax(dm->dc,
9624 						   new_crtc_state->stream,
9625 						   &vrr_params.adjust);
9626 		}
9627 	}
9628 
9629 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
9630 
9631 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
9632 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
9633 
9634 		if (aconn->vsdb_info.amd_vsdb_version == 1)
9635 			packet_type = PACKET_TYPE_FS_V1;
9636 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
9637 			packet_type = PACKET_TYPE_FS_V2;
9638 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
9639 			packet_type = PACKET_TYPE_FS_V3;
9640 
9641 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
9642 					&new_stream->adaptive_sync_infopacket);
9643 	}
9644 
9645 	mod_freesync_build_vrr_infopacket(
9646 		dm->freesync_module,
9647 		new_stream,
9648 		&vrr_params,
9649 		packet_type,
9650 		TRANSFER_FUNC_UNKNOWN,
9651 		&vrr_infopacket,
9652 		pack_sdp_v1_3);
9653 
9654 	new_crtc_state->freesync_vrr_info_changed |=
9655 		(memcmp(&new_crtc_state->vrr_infopacket,
9656 			&vrr_infopacket,
9657 			sizeof(vrr_infopacket)) != 0);
9658 
9659 	acrtc->dm_irq_params.vrr_params = vrr_params;
9660 	new_crtc_state->vrr_infopacket = vrr_infopacket;
9661 
9662 	new_stream->vrr_infopacket = vrr_infopacket;
9663 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
9664 
9665 	if (new_crtc_state->freesync_vrr_info_changed)
9666 		drm_dbg_kms(adev_to_drm(adev), "VRR packet update: crtc=%u enabled=%d state=%d",
9667 			      new_crtc_state->base.crtc->base.id,
9668 			      (int)new_crtc_state->base.vrr_enabled,
9669 			      (int)vrr_params.state);
9670 
9671 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9672 }
9673 
9674 static void update_stream_irq_parameters(
9675 	struct amdgpu_display_manager *dm,
9676 	struct dm_crtc_state *new_crtc_state)
9677 {
9678 	struct dc_stream_state *new_stream = new_crtc_state->stream;
9679 	struct mod_vrr_params vrr_params;
9680 	struct mod_freesync_config config = new_crtc_state->freesync_config;
9681 	struct amdgpu_device *adev = dm->adev;
9682 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9683 	unsigned long flags;
9684 
9685 	if (!new_stream)
9686 		return;
9687 
9688 	/*
9689 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9690 	 * For now it's sufficient to just guard against these conditions.
9691 	 */
9692 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9693 		return;
9694 
9695 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9696 	vrr_params = acrtc->dm_irq_params.vrr_params;
9697 
9698 	if (new_crtc_state->vrr_supported &&
9699 	    config.min_refresh_in_uhz &&
9700 	    config.max_refresh_in_uhz) {
9701 		/*
9702 		 * if freesync compatible mode was set, config.state will be set
9703 		 * in atomic check
9704 		 */
9705 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
9706 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
9707 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
9708 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
9709 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
9710 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
9711 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
9712 		} else {
9713 			config.state = new_crtc_state->base.vrr_enabled ?
9714 						     VRR_STATE_ACTIVE_VARIABLE :
9715 						     VRR_STATE_INACTIVE;
9716 		}
9717 	} else {
9718 		config.state = VRR_STATE_UNSUPPORTED;
9719 	}
9720 
9721 	mod_freesync_build_vrr_params(dm->freesync_module,
9722 				      new_stream,
9723 				      &config, &vrr_params);
9724 
9725 	new_crtc_state->freesync_config = config;
9726 	/* Copy state for access from DM IRQ handler */
9727 	acrtc->dm_irq_params.freesync_config = config;
9728 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
9729 	acrtc->dm_irq_params.vrr_params = vrr_params;
9730 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9731 }
9732 
9733 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
9734 					    struct dm_crtc_state *new_state)
9735 {
9736 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
9737 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
9738 
9739 	if (!old_vrr_active && new_vrr_active) {
9740 		/* Transition VRR inactive -> active:
9741 		 * While VRR is active, we must not disable vblank irq, as a
9742 		 * reenable after disable would compute bogus vblank/pflip
9743 		 * timestamps if it likely happened inside display front-porch.
9744 		 *
9745 		 * We also need vupdate irq for the actual core vblank handling
9746 		 * at end of vblank.
9747 		 */
9748 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
9749 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
9750 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR off->on: Get vblank ref\n",
9751 				 __func__, new_state->base.crtc->base.id);
9752 	} else if (old_vrr_active && !new_vrr_active) {
9753 		/* Transition VRR active -> inactive:
9754 		 * Allow vblank irq disable again for fixed refresh rate.
9755 		 */
9756 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
9757 		drm_crtc_vblank_put(new_state->base.crtc);
9758 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR on->off: Drop vblank ref\n",
9759 				 __func__, new_state->base.crtc->base.id);
9760 	}
9761 }
9762 
9763 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
9764 {
9765 	struct drm_plane *plane;
9766 	struct drm_plane_state *old_plane_state;
9767 	int i;
9768 
9769 	/*
9770 	 * TODO: Make this per-stream so we don't issue redundant updates for
9771 	 * commits with multiple streams.
9772 	 */
9773 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
9774 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
9775 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
9776 }
9777 
9778 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
9779 {
9780 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
9781 
9782 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
9783 }
9784 
9785 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
9786 				    struct drm_plane_state *old_plane_state,
9787 				    struct dc_stream_update *update)
9788 {
9789 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
9790 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
9791 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
9792 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
9793 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
9794 	uint64_t address = afb ? afb->address : 0;
9795 	struct dc_cursor_position position = {0};
9796 	struct dc_cursor_attributes attributes;
9797 	int ret;
9798 
9799 	if (!plane->state->fb && !old_plane_state->fb)
9800 		return;
9801 
9802 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
9803 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
9804 		       plane->state->crtc_h);
9805 
9806 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
9807 	if (ret)
9808 		return;
9809 
9810 	if (!position.enable) {
9811 		/* turn off cursor */
9812 		if (crtc_state && crtc_state->stream) {
9813 			dc_stream_set_cursor_position(crtc_state->stream,
9814 						      &position);
9815 			update->cursor_position = &crtc_state->stream->cursor_position;
9816 		}
9817 		return;
9818 	}
9819 
9820 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
9821 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
9822 
9823 	memset(&attributes, 0, sizeof(attributes));
9824 	attributes.address.high_part = upper_32_bits(address);
9825 	attributes.address.low_part  = lower_32_bits(address);
9826 	attributes.width             = plane->state->crtc_w;
9827 	attributes.height            = plane->state->crtc_h;
9828 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
9829 	attributes.rotation_angle    = 0;
9830 	attributes.attribute_flags.value = 0;
9831 
9832 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
9833 	 * legacy gamma setup.
9834 	 */
9835 	if (crtc_state->cm_is_degamma_srgb &&
9836 	    adev->dm.dc->caps.color.dpp.gamma_corr)
9837 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
9838 
9839 	if (afb)
9840 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
9841 
9842 	if (crtc_state->stream) {
9843 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
9844 						     &attributes))
9845 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
9846 
9847 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
9848 
9849 		if (!dc_stream_set_cursor_position(crtc_state->stream,
9850 						   &position))
9851 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
9852 
9853 		update->cursor_position = &crtc_state->stream->cursor_position;
9854 	}
9855 }
9856 
9857 static void amdgpu_dm_enable_self_refresh(struct amdgpu_crtc *acrtc_attach,
9858 					  const struct dm_crtc_state *acrtc_state,
9859 					  const u64 current_ts)
9860 {
9861 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
9862 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
9863 	struct amdgpu_dm_connector *aconn =
9864 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
9865 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
9866 
9867 	if (acrtc_state->update_type > UPDATE_TYPE_FAST) {
9868 		if (pr->config.replay_supported && !pr->replay_feature_enabled)
9869 			amdgpu_dm_link_setup_replay(acrtc_state->stream->link, aconn);
9870 		else if (psr->psr_version != DC_PSR_VERSION_UNSUPPORTED &&
9871 			     !psr->psr_feature_enabled)
9872 			if (!aconn->disallow_edp_enter_psr)
9873 				amdgpu_dm_link_setup_psr(acrtc_state->stream);
9874 	}
9875 
9876 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
9877 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
9878 	    (psr->psr_feature_enabled || pr->config.replay_supported)) {
9879 		if (aconn->sr_skip_count > 0)
9880 			aconn->sr_skip_count--;
9881 
9882 		/* Allow SR when skip count is 0. */
9883 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
9884 
9885 		/*
9886 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
9887 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
9888 		 * can be enabled immediately once OS demonstrates an
9889 		 * adequate number of fast atomic commits to notify KMD
9890 		 * of update events. See `vblank_control_worker()`.
9891 		 */
9892 		if (!vrr_active &&
9893 		    acrtc_attach->dm_irq_params.allow_sr_entry &&
9894 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
9895 		    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
9896 #endif
9897 		    (current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
9898 			if (pr->replay_feature_enabled && !pr->replay_allow_active)
9899 				amdgpu_dm_replay_enable(acrtc_state->stream, true);
9900 			if (psr->psr_version == DC_PSR_VERSION_SU_1 &&
9901 			    !psr->psr_allow_active && !aconn->disallow_edp_enter_psr)
9902 				amdgpu_dm_psr_enable(acrtc_state->stream);
9903 		}
9904 	} else {
9905 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
9906 	}
9907 }
9908 
9909 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
9910 				    struct drm_device *dev,
9911 				    struct amdgpu_display_manager *dm,
9912 				    struct drm_crtc *pcrtc,
9913 				    bool wait_for_vblank)
9914 {
9915 	u32 i;
9916 	u64 timestamp_ns = ktime_get_ns();
9917 	struct drm_plane *plane;
9918 	struct drm_plane_state *old_plane_state, *new_plane_state;
9919 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
9920 	struct drm_crtc_state *new_pcrtc_state =
9921 			drm_atomic_get_new_crtc_state(state, pcrtc);
9922 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
9923 	struct dm_crtc_state *dm_old_crtc_state =
9924 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
9925 	int planes_count = 0, vpos, hpos;
9926 	unsigned long flags;
9927 	u32 target_vblank, last_flip_vblank;
9928 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
9929 	bool cursor_update = false;
9930 	bool pflip_present = false;
9931 	bool dirty_rects_changed = false;
9932 	bool updated_planes_and_streams = false;
9933 	struct {
9934 		struct dc_surface_update surface_updates[MAX_SURFACES];
9935 		struct dc_plane_info plane_infos[MAX_SURFACES];
9936 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
9937 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
9938 		struct dc_stream_update stream_update;
9939 	} *bundle;
9940 
9941 	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
9942 
9943 	if (!bundle) {
9944 		drm_err(dev, "Failed to allocate update bundle\n");
9945 		goto cleanup;
9946 	}
9947 
9948 	/*
9949 	 * Disable the cursor first if we're disabling all the planes.
9950 	 * It'll remain on the screen after the planes are re-enabled
9951 	 * if we don't.
9952 	 *
9953 	 * If the cursor is transitioning from native to overlay mode, the
9954 	 * native cursor needs to be disabled first.
9955 	 */
9956 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
9957 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
9958 		struct dc_cursor_position cursor_position = {0};
9959 
9960 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
9961 						   &cursor_position))
9962 			drm_err(dev, "DC failed to disable native cursor\n");
9963 
9964 		bundle->stream_update.cursor_position =
9965 				&acrtc_state->stream->cursor_position;
9966 	}
9967 
9968 	if (acrtc_state->active_planes == 0 &&
9969 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
9970 		amdgpu_dm_commit_cursors(state);
9971 
9972 	/* update planes when needed */
9973 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
9974 		struct drm_crtc *crtc = new_plane_state->crtc;
9975 		struct drm_crtc_state *new_crtc_state;
9976 		struct drm_framebuffer *fb = new_plane_state->fb;
9977 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
9978 		bool plane_needs_flip;
9979 		struct dc_plane_state *dc_plane;
9980 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
9981 
9982 		/* Cursor plane is handled after stream updates */
9983 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
9984 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
9985 			if ((fb && crtc == pcrtc) ||
9986 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
9987 				cursor_update = true;
9988 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
9989 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
9990 			}
9991 
9992 			continue;
9993 		}
9994 
9995 		if (!fb || !crtc || pcrtc != crtc)
9996 			continue;
9997 
9998 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
9999 		if (!new_crtc_state->active)
10000 			continue;
10001 
10002 		dc_plane = dm_new_plane_state->dc_state;
10003 		if (!dc_plane)
10004 			continue;
10005 
10006 		bundle->surface_updates[planes_count].surface = dc_plane;
10007 		if (new_pcrtc_state->color_mgmt_changed) {
10008 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
10009 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
10010 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
10011 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
10012 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
10013 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
10014 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
10015 		}
10016 
10017 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
10018 				     &bundle->scaling_infos[planes_count]);
10019 
10020 		bundle->surface_updates[planes_count].scaling_info =
10021 			&bundle->scaling_infos[planes_count];
10022 
10023 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
10024 
10025 		pflip_present = pflip_present || plane_needs_flip;
10026 
10027 		if (!plane_needs_flip) {
10028 			planes_count += 1;
10029 			continue;
10030 		}
10031 
10032 		fill_dc_plane_info_and_addr(
10033 			dm->adev, new_plane_state,
10034 			afb->tiling_flags,
10035 			&bundle->plane_infos[planes_count],
10036 			&bundle->flip_addrs[planes_count].address,
10037 			afb->tmz_surface);
10038 
10039 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
10040 				 new_plane_state->plane->index,
10041 				 bundle->plane_infos[planes_count].dcc.enable);
10042 
10043 		bundle->surface_updates[planes_count].plane_info =
10044 			&bundle->plane_infos[planes_count];
10045 
10046 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
10047 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
10048 			fill_dc_dirty_rects(plane, old_plane_state,
10049 					    new_plane_state, new_crtc_state,
10050 					    &bundle->flip_addrs[planes_count],
10051 					    acrtc_state->stream->link->psr_settings.psr_version ==
10052 					    DC_PSR_VERSION_SU_1,
10053 					    &dirty_rects_changed);
10054 
10055 			/*
10056 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
10057 			 * and enabled it again after dirty regions are stable to avoid video glitch.
10058 			 * PSR-SU will be enabled in vblank_control_worker() if user pause the video
10059 			 * during the PSR-SU was disabled.
10060 			 */
10061 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
10062 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
10063 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
10064 			    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
10065 #endif
10066 			    dirty_rects_changed) {
10067 				mutex_lock(&dm->dc_lock);
10068 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
10069 				timestamp_ns;
10070 				if (acrtc_state->stream->link->psr_settings.psr_allow_active)
10071 					amdgpu_dm_psr_disable(acrtc_state->stream, true);
10072 				mutex_unlock(&dm->dc_lock);
10073 			}
10074 		}
10075 
10076 		/*
10077 		 * Only allow immediate flips for fast updates that don't
10078 		 * change memory domain, FB pitch, DCC state, rotation or
10079 		 * mirroring.
10080 		 *
10081 		 * dm_crtc_helper_atomic_check() only accepts async flips with
10082 		 * fast updates.
10083 		 */
10084 		if (crtc->state->async_flip &&
10085 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
10086 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
10087 			drm_warn_once(state->dev,
10088 				      "[PLANE:%d:%s] async flip with non-fast update\n",
10089 				      plane->base.id, plane->name);
10090 
10091 		bundle->flip_addrs[planes_count].flip_immediate =
10092 			crtc->state->async_flip &&
10093 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
10094 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
10095 
10096 		timestamp_ns = ktime_get_ns();
10097 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
10098 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
10099 		bundle->surface_updates[planes_count].surface = dc_plane;
10100 
10101 		if (!bundle->surface_updates[planes_count].surface) {
10102 			drm_err(dev, "No surface for CRTC: id=%d\n",
10103 					acrtc_attach->crtc_id);
10104 			continue;
10105 		}
10106 
10107 		if (plane == pcrtc->primary)
10108 			update_freesync_state_on_stream(
10109 				dm,
10110 				acrtc_state,
10111 				acrtc_state->stream,
10112 				dc_plane,
10113 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
10114 
10115 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
10116 				 __func__,
10117 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
10118 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
10119 
10120 		planes_count += 1;
10121 
10122 	}
10123 
10124 	if (pflip_present) {
10125 		if (!vrr_active) {
10126 			/* Use old throttling in non-vrr fixed refresh rate mode
10127 			 * to keep flip scheduling based on target vblank counts
10128 			 * working in a backwards compatible way, e.g., for
10129 			 * clients using the GLX_OML_sync_control extension or
10130 			 * DRI3/Present extension with defined target_msc.
10131 			 */
10132 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
10133 		} else {
10134 			/* For variable refresh rate mode only:
10135 			 * Get vblank of last completed flip to avoid > 1 vrr
10136 			 * flips per video frame by use of throttling, but allow
10137 			 * flip programming anywhere in the possibly large
10138 			 * variable vrr vblank interval for fine-grained flip
10139 			 * timing control and more opportunity to avoid stutter
10140 			 * on late submission of flips.
10141 			 */
10142 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10143 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
10144 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10145 		}
10146 
10147 		target_vblank = last_flip_vblank + wait_for_vblank;
10148 
10149 		/*
10150 		 * Wait until we're out of the vertical blank period before the one
10151 		 * targeted by the flip
10152 		 */
10153 		while ((acrtc_attach->enabled &&
10154 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
10155 							    0, &vpos, &hpos, NULL,
10156 							    NULL, &pcrtc->hwmode)
10157 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
10158 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
10159 			(int)(target_vblank -
10160 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
10161 			usleep_range(1000, 1100);
10162 		}
10163 
10164 		/**
10165 		 * Prepare the flip event for the pageflip interrupt to handle.
10166 		 *
10167 		 * This only works in the case where we've already turned on the
10168 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
10169 		 * from 0 -> n planes we have to skip a hardware generated event
10170 		 * and rely on sending it from software.
10171 		 */
10172 		if (acrtc_attach->base.state->event &&
10173 		    acrtc_state->active_planes > 0) {
10174 			drm_crtc_vblank_get(pcrtc);
10175 
10176 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10177 
10178 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
10179 			prepare_flip_isr(acrtc_attach);
10180 
10181 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10182 		}
10183 
10184 		if (acrtc_state->stream) {
10185 			if (acrtc_state->freesync_vrr_info_changed)
10186 				bundle->stream_update.vrr_infopacket =
10187 					&acrtc_state->stream->vrr_infopacket;
10188 		}
10189 	} else if (cursor_update && acrtc_state->active_planes > 0) {
10190 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10191 		if (acrtc_attach->base.state->event) {
10192 			drm_crtc_vblank_get(pcrtc);
10193 			acrtc_attach->event = acrtc_attach->base.state->event;
10194 			acrtc_attach->base.state->event = NULL;
10195 		}
10196 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10197 	}
10198 
10199 	/* Update the planes if changed or disable if we don't have any. */
10200 	if ((planes_count || acrtc_state->active_planes == 0) &&
10201 		acrtc_state->stream) {
10202 		/*
10203 		 * If PSR or idle optimizations are enabled then flush out
10204 		 * any pending work before hardware programming.
10205 		 */
10206 		if (dm->vblank_control_workqueue)
10207 			flush_workqueue(dm->vblank_control_workqueue);
10208 
10209 		bundle->stream_update.stream = acrtc_state->stream;
10210 		if (new_pcrtc_state->mode_changed) {
10211 			bundle->stream_update.src = acrtc_state->stream->src;
10212 			bundle->stream_update.dst = acrtc_state->stream->dst;
10213 		}
10214 
10215 		if (new_pcrtc_state->color_mgmt_changed) {
10216 			/*
10217 			 * TODO: This isn't fully correct since we've actually
10218 			 * already modified the stream in place.
10219 			 */
10220 			bundle->stream_update.gamut_remap =
10221 				&acrtc_state->stream->gamut_remap_matrix;
10222 			bundle->stream_update.output_csc_transform =
10223 				&acrtc_state->stream->csc_color_matrix;
10224 			bundle->stream_update.out_transfer_func =
10225 				&acrtc_state->stream->out_transfer_func;
10226 			bundle->stream_update.lut3d_func =
10227 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
10228 			bundle->stream_update.func_shaper =
10229 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
10230 		}
10231 
10232 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
10233 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
10234 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
10235 
10236 		mutex_lock(&dm->dc_lock);
10237 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) || vrr_active) {
10238 			if (acrtc_state->stream->link->replay_settings.replay_allow_active)
10239 				amdgpu_dm_replay_disable(acrtc_state->stream);
10240 			if (acrtc_state->stream->link->psr_settings.psr_allow_active)
10241 				amdgpu_dm_psr_disable(acrtc_state->stream, true);
10242 		}
10243 		mutex_unlock(&dm->dc_lock);
10244 
10245 		/*
10246 		 * If FreeSync state on the stream has changed then we need to
10247 		 * re-adjust the min/max bounds now that DC doesn't handle this
10248 		 * as part of commit.
10249 		 */
10250 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
10251 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10252 			dc_stream_adjust_vmin_vmax(
10253 				dm->dc, acrtc_state->stream,
10254 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
10255 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10256 		}
10257 		mutex_lock(&dm->dc_lock);
10258 		update_planes_and_stream_adapter(dm->dc,
10259 					 acrtc_state->update_type,
10260 					 planes_count,
10261 					 acrtc_state->stream,
10262 					 &bundle->stream_update,
10263 					 bundle->surface_updates);
10264 		updated_planes_and_streams = true;
10265 
10266 		/**
10267 		 * Enable or disable the interrupts on the backend.
10268 		 *
10269 		 * Most pipes are put into power gating when unused.
10270 		 *
10271 		 * When power gating is enabled on a pipe we lose the
10272 		 * interrupt enablement state when power gating is disabled.
10273 		 *
10274 		 * So we need to update the IRQ control state in hardware
10275 		 * whenever the pipe turns on (since it could be previously
10276 		 * power gated) or off (since some pipes can't be power gated
10277 		 * on some ASICs).
10278 		 */
10279 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
10280 			dm_update_pflip_irq_state(drm_to_adev(dev),
10281 						  acrtc_attach);
10282 
10283 		amdgpu_dm_enable_self_refresh(acrtc_attach, acrtc_state, timestamp_ns);
10284 		mutex_unlock(&dm->dc_lock);
10285 	}
10286 
10287 	/*
10288 	 * Update cursor state *after* programming all the planes.
10289 	 * This avoids redundant programming in the case where we're going
10290 	 * to be disabling a single plane - those pipes are being disabled.
10291 	 */
10292 	if (acrtc_state->active_planes &&
10293 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
10294 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10295 		amdgpu_dm_commit_cursors(state);
10296 
10297 cleanup:
10298 	kfree(bundle);
10299 }
10300 
10301 static void amdgpu_dm_commit_audio(struct drm_device *dev,
10302 				   struct drm_atomic_state *state)
10303 {
10304 	struct amdgpu_device *adev = drm_to_adev(dev);
10305 	struct amdgpu_dm_connector *aconnector;
10306 	struct drm_connector *connector;
10307 	struct drm_connector_state *old_con_state, *new_con_state;
10308 	struct drm_crtc_state *new_crtc_state;
10309 	struct dm_crtc_state *new_dm_crtc_state;
10310 	const struct dc_stream_status *status;
10311 	int i, inst;
10312 
10313 	/* Notify device removals. */
10314 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10315 		if (old_con_state->crtc != new_con_state->crtc) {
10316 			/* CRTC changes require notification. */
10317 			goto notify;
10318 		}
10319 
10320 		if (!new_con_state->crtc)
10321 			continue;
10322 
10323 		new_crtc_state = drm_atomic_get_new_crtc_state(
10324 			state, new_con_state->crtc);
10325 
10326 		if (!new_crtc_state)
10327 			continue;
10328 
10329 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10330 			continue;
10331 
10332 notify:
10333 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10334 			continue;
10335 
10336 		aconnector = to_amdgpu_dm_connector(connector);
10337 
10338 		mutex_lock(&adev->dm.audio_lock);
10339 		inst = aconnector->audio_inst;
10340 		aconnector->audio_inst = -1;
10341 		mutex_unlock(&adev->dm.audio_lock);
10342 
10343 		amdgpu_dm_audio_eld_notify(adev, inst);
10344 	}
10345 
10346 	/* Notify audio device additions. */
10347 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10348 		if (!new_con_state->crtc)
10349 			continue;
10350 
10351 		new_crtc_state = drm_atomic_get_new_crtc_state(
10352 			state, new_con_state->crtc);
10353 
10354 		if (!new_crtc_state)
10355 			continue;
10356 
10357 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10358 			continue;
10359 
10360 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
10361 		if (!new_dm_crtc_state->stream)
10362 			continue;
10363 
10364 		status = dc_stream_get_status(new_dm_crtc_state->stream);
10365 		if (!status)
10366 			continue;
10367 
10368 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10369 			continue;
10370 
10371 		aconnector = to_amdgpu_dm_connector(connector);
10372 
10373 		mutex_lock(&adev->dm.audio_lock);
10374 		inst = status->audio_inst;
10375 		aconnector->audio_inst = inst;
10376 		mutex_unlock(&adev->dm.audio_lock);
10377 
10378 		amdgpu_dm_audio_eld_notify(adev, inst);
10379 	}
10380 }
10381 
10382 /*
10383  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
10384  * @crtc_state: the DRM CRTC state
10385  * @stream_state: the DC stream state.
10386  *
10387  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
10388  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
10389  */
10390 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
10391 						struct dc_stream_state *stream_state)
10392 {
10393 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
10394 }
10395 
10396 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
10397 			      struct dm_crtc_state *crtc_state)
10398 {
10399 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
10400 }
10401 
10402 static void amdgpu_dm_commit_streams(struct drm_atomic_state *state,
10403 					struct dc_state *dc_state)
10404 {
10405 	struct drm_device *dev = state->dev;
10406 	struct amdgpu_device *adev = drm_to_adev(dev);
10407 	struct amdgpu_display_manager *dm = &adev->dm;
10408 	struct drm_crtc *crtc;
10409 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10410 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10411 	struct drm_connector_state *old_con_state;
10412 	struct drm_connector *connector;
10413 	bool mode_set_reset_required = false;
10414 	u32 i;
10415 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
10416 	bool set_backlight_level = false;
10417 
10418 	/* Disable writeback */
10419 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
10420 		struct dm_connector_state *dm_old_con_state;
10421 		struct amdgpu_crtc *acrtc;
10422 
10423 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
10424 			continue;
10425 
10426 		old_crtc_state = NULL;
10427 
10428 		dm_old_con_state = to_dm_connector_state(old_con_state);
10429 		if (!dm_old_con_state->base.crtc)
10430 			continue;
10431 
10432 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
10433 		if (acrtc)
10434 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10435 
10436 		if (!acrtc || !acrtc->wb_enabled)
10437 			continue;
10438 
10439 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10440 
10441 		dm_clear_writeback(dm, dm_old_crtc_state);
10442 		acrtc->wb_enabled = false;
10443 	}
10444 
10445 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
10446 				      new_crtc_state, i) {
10447 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10448 
10449 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10450 
10451 		if (old_crtc_state->active &&
10452 		    (!new_crtc_state->active ||
10453 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10454 			manage_dm_interrupts(adev, acrtc, NULL);
10455 			dc_stream_release(dm_old_crtc_state->stream);
10456 		}
10457 	}
10458 
10459 	drm_atomic_helper_calc_timestamping_constants(state);
10460 
10461 	/* update changed items */
10462 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10463 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10464 
10465 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10466 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10467 
10468 		drm_dbg_state(state->dev,
10469 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
10470 			acrtc->crtc_id,
10471 			new_crtc_state->enable,
10472 			new_crtc_state->active,
10473 			new_crtc_state->planes_changed,
10474 			new_crtc_state->mode_changed,
10475 			new_crtc_state->active_changed,
10476 			new_crtc_state->connectors_changed);
10477 
10478 		/* Disable cursor if disabling crtc */
10479 		if (old_crtc_state->active && !new_crtc_state->active) {
10480 			struct dc_cursor_position position;
10481 
10482 			memset(&position, 0, sizeof(position));
10483 			mutex_lock(&dm->dc_lock);
10484 			dc_exit_ips_for_hw_access(dm->dc);
10485 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
10486 			mutex_unlock(&dm->dc_lock);
10487 		}
10488 
10489 		/* Copy all transient state flags into dc state */
10490 		if (dm_new_crtc_state->stream) {
10491 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
10492 							    dm_new_crtc_state->stream);
10493 		}
10494 
10495 		/* handles headless hotplug case, updating new_state and
10496 		 * aconnector as needed
10497 		 */
10498 
10499 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
10500 
10501 			drm_dbg_atomic(dev,
10502 				       "Atomic commit: SET crtc id %d: [%p]\n",
10503 				       acrtc->crtc_id, acrtc);
10504 
10505 			if (!dm_new_crtc_state->stream) {
10506 				/*
10507 				 * this could happen because of issues with
10508 				 * userspace notifications delivery.
10509 				 * In this case userspace tries to set mode on
10510 				 * display which is disconnected in fact.
10511 				 * dc_sink is NULL in this case on aconnector.
10512 				 * We expect reset mode will come soon.
10513 				 *
10514 				 * This can also happen when unplug is done
10515 				 * during resume sequence ended
10516 				 *
10517 				 * In this case, we want to pretend we still
10518 				 * have a sink to keep the pipe running so that
10519 				 * hw state is consistent with the sw state
10520 				 */
10521 				drm_dbg_atomic(dev,
10522 					       "Failed to create new stream for crtc %d\n",
10523 						acrtc->base.base.id);
10524 				continue;
10525 			}
10526 
10527 			if (dm_old_crtc_state->stream)
10528 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10529 
10530 			pm_runtime_get_noresume(dev->dev);
10531 
10532 			acrtc->enabled = true;
10533 			acrtc->hw_mode = new_crtc_state->mode;
10534 			crtc->hwmode = new_crtc_state->mode;
10535 			mode_set_reset_required = true;
10536 			set_backlight_level = true;
10537 		} else if (modereset_required(new_crtc_state)) {
10538 			drm_dbg_atomic(dev,
10539 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
10540 				       acrtc->crtc_id, acrtc);
10541 			/* i.e. reset mode */
10542 			if (dm_old_crtc_state->stream)
10543 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10544 
10545 			mode_set_reset_required = true;
10546 		}
10547 	} /* for_each_crtc_in_state() */
10548 
10549 	/* if there mode set or reset, disable eDP PSR, Replay */
10550 	if (mode_set_reset_required) {
10551 		if (dm->vblank_control_workqueue)
10552 			flush_workqueue(dm->vblank_control_workqueue);
10553 
10554 		amdgpu_dm_replay_disable_all(dm);
10555 		amdgpu_dm_psr_disable_all(dm);
10556 	}
10557 
10558 	dm_enable_per_frame_crtc_master_sync(dc_state);
10559 	mutex_lock(&dm->dc_lock);
10560 	dc_exit_ips_for_hw_access(dm->dc);
10561 	WARN_ON(!dc_commit_streams(dm->dc, &params));
10562 
10563 	/* Allow idle optimization when vblank count is 0 for display off */
10564 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
10565 		dc_allow_idle_optimizations(dm->dc, true);
10566 	mutex_unlock(&dm->dc_lock);
10567 
10568 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10569 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10570 
10571 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10572 
10573 		if (dm_new_crtc_state->stream != NULL) {
10574 			const struct dc_stream_status *status =
10575 					dc_stream_get_status(dm_new_crtc_state->stream);
10576 
10577 			if (!status)
10578 				status = dc_state_get_stream_status(dc_state,
10579 									 dm_new_crtc_state->stream);
10580 			if (!status)
10581 				drm_err(dev,
10582 					"got no status for stream %p on acrtc%p\n",
10583 					dm_new_crtc_state->stream, acrtc);
10584 			else
10585 				acrtc->otg_inst = status->primary_otg_inst;
10586 		}
10587 	}
10588 
10589 	/* During boot up and resume the DC layer will reset the panel brightness
10590 	 * to fix a flicker issue.
10591 	 * It will cause the dm->actual_brightness is not the current panel brightness
10592 	 * level. (the dm->brightness is the correct panel level)
10593 	 * So we set the backlight level with dm->brightness value after set mode
10594 	 */
10595 	if (set_backlight_level) {
10596 		for (i = 0; i < dm->num_of_edps; i++) {
10597 			if (dm->backlight_dev[i])
10598 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
10599 		}
10600 	}
10601 }
10602 
10603 static void dm_set_writeback(struct amdgpu_display_manager *dm,
10604 			      struct dm_crtc_state *crtc_state,
10605 			      struct drm_connector *connector,
10606 			      struct drm_connector_state *new_con_state)
10607 {
10608 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
10609 	struct amdgpu_device *adev = dm->adev;
10610 	struct amdgpu_crtc *acrtc;
10611 	struct dc_writeback_info *wb_info;
10612 	struct pipe_ctx *pipe = NULL;
10613 	struct amdgpu_framebuffer *afb;
10614 	int i = 0;
10615 
10616 	wb_info = kzalloc(sizeof(*wb_info), GFP_KERNEL);
10617 	if (!wb_info) {
10618 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
10619 		return;
10620 	}
10621 
10622 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
10623 	if (!acrtc) {
10624 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
10625 		kfree(wb_info);
10626 		return;
10627 	}
10628 
10629 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
10630 	if (!afb) {
10631 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
10632 		kfree(wb_info);
10633 		return;
10634 	}
10635 
10636 	for (i = 0; i < MAX_PIPES; i++) {
10637 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
10638 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
10639 			break;
10640 		}
10641 	}
10642 
10643 	/* fill in wb_info */
10644 	wb_info->wb_enabled = true;
10645 
10646 	wb_info->dwb_pipe_inst = 0;
10647 	wb_info->dwb_params.dwbscl_black_color = 0;
10648 	wb_info->dwb_params.hdr_mult = 0x1F000;
10649 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
10650 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
10651 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
10652 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
10653 
10654 	/* width & height from crtc */
10655 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
10656 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
10657 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
10658 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
10659 
10660 	wb_info->dwb_params.cnv_params.crop_en = false;
10661 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
10662 
10663 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
10664 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
10665 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
10666 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
10667 
10668 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
10669 
10670 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
10671 
10672 	wb_info->dwb_params.scaler_taps.h_taps = 4;
10673 	wb_info->dwb_params.scaler_taps.v_taps = 4;
10674 	wb_info->dwb_params.scaler_taps.h_taps_c = 2;
10675 	wb_info->dwb_params.scaler_taps.v_taps_c = 2;
10676 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
10677 
10678 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
10679 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
10680 
10681 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
10682 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
10683 		wb_info->mcif_buf_params.chroma_address[i] = 0;
10684 	}
10685 
10686 	wb_info->mcif_buf_params.p_vmid = 1;
10687 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
10688 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
10689 		wb_info->mcif_warmup_params.region_size =
10690 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
10691 	}
10692 	wb_info->mcif_warmup_params.p_vmid = 1;
10693 	wb_info->writeback_source_plane = pipe->plane_state;
10694 
10695 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
10696 
10697 	acrtc->wb_pending = true;
10698 	acrtc->wb_conn = wb_conn;
10699 	drm_writeback_queue_job(wb_conn, new_con_state);
10700 }
10701 
10702 static void amdgpu_dm_update_hdcp(struct drm_atomic_state *state)
10703 {
10704 	struct drm_connector_state *old_con_state, *new_con_state;
10705 	struct drm_device *dev = state->dev;
10706 	struct drm_connector *connector;
10707 	struct amdgpu_device *adev = drm_to_adev(dev);
10708 	int i;
10709 
10710 	if (!adev->dm.hdcp_workqueue)
10711 		return;
10712 
10713 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10714 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10715 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10716 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10717 		struct dm_crtc_state *dm_new_crtc_state;
10718 		struct amdgpu_dm_connector *aconnector;
10719 
10720 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10721 			continue;
10722 
10723 		aconnector = to_amdgpu_dm_connector(connector);
10724 
10725 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
10726 
10727 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
10728 			connector->index, connector->status, connector->dpms);
10729 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
10730 			old_con_state->content_protection, new_con_state->content_protection);
10731 
10732 		if (aconnector->dc_sink) {
10733 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
10734 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
10735 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
10736 				aconnector->dc_sink->edid_caps.display_name);
10737 			}
10738 		}
10739 
10740 		new_crtc_state = NULL;
10741 		old_crtc_state = NULL;
10742 
10743 		if (acrtc) {
10744 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
10745 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10746 		}
10747 
10748 		if (old_crtc_state)
10749 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
10750 			old_crtc_state->enable,
10751 			old_crtc_state->active,
10752 			old_crtc_state->mode_changed,
10753 			old_crtc_state->active_changed,
10754 			old_crtc_state->connectors_changed);
10755 
10756 		if (new_crtc_state)
10757 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
10758 			new_crtc_state->enable,
10759 			new_crtc_state->active,
10760 			new_crtc_state->mode_changed,
10761 			new_crtc_state->active_changed,
10762 			new_crtc_state->connectors_changed);
10763 
10764 
10765 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10766 
10767 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
10768 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
10769 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
10770 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
10771 			dm_new_con_state->update_hdcp = true;
10772 			continue;
10773 		}
10774 
10775 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
10776 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
10777 			/* when display is unplugged from mst hub, connctor will
10778 			 * be destroyed within dm_dp_mst_connector_destroy. connector
10779 			 * hdcp perperties, like type, undesired, desired, enabled,
10780 			 * will be lost. So, save hdcp properties into hdcp_work within
10781 			 * amdgpu_dm_atomic_commit_tail. if the same display is
10782 			 * plugged back with same display index, its hdcp properties
10783 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
10784 			 */
10785 
10786 			bool enable_encryption = false;
10787 
10788 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
10789 				enable_encryption = true;
10790 
10791 			if (aconnector->dc_link && aconnector->dc_sink &&
10792 				aconnector->dc_link->type == dc_connection_mst_branch) {
10793 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
10794 				struct hdcp_workqueue *hdcp_w =
10795 					&hdcp_work[aconnector->dc_link->link_index];
10796 
10797 				hdcp_w->hdcp_content_type[connector->index] =
10798 					new_con_state->hdcp_content_type;
10799 				hdcp_w->content_protection[connector->index] =
10800 					new_con_state->content_protection;
10801 			}
10802 
10803 			if (new_crtc_state && new_crtc_state->mode_changed &&
10804 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
10805 				enable_encryption = true;
10806 
10807 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
10808 
10809 			if (aconnector->dc_link)
10810 				hdcp_update_display(
10811 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
10812 					new_con_state->hdcp_content_type, enable_encryption);
10813 		}
10814 	}
10815 }
10816 
10817 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_state *state)
10818 {
10819 	struct drm_crtc *crtc;
10820 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10821 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10822 	int i, ret;
10823 
10824 	ret = drm_dp_mst_atomic_setup_commit(state);
10825 	if (ret)
10826 		return ret;
10827 
10828 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10829 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10830 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10831 		/*
10832 		 * Color management settings. We also update color properties
10833 		 * when a modeset is needed, to ensure it gets reprogrammed.
10834 		 */
10835 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
10836 		    (dm_new_crtc_state->base.color_mgmt_changed ||
10837 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
10838 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10839 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
10840 			if (ret) {
10841 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
10842 				return ret;
10843 			}
10844 		}
10845 	}
10846 
10847 	return 0;
10848 }
10849 
10850 /**
10851  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
10852  * @state: The atomic state to commit
10853  *
10854  * This will tell DC to commit the constructed DC state from atomic_check,
10855  * programming the hardware. Any failures here implies a hardware failure, since
10856  * atomic check should have filtered anything non-kosher.
10857  */
10858 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
10859 {
10860 	struct drm_device *dev = state->dev;
10861 	struct amdgpu_device *adev = drm_to_adev(dev);
10862 	struct amdgpu_display_manager *dm = &adev->dm;
10863 	struct dm_atomic_state *dm_state;
10864 	struct dc_state *dc_state = NULL;
10865 	u32 i, j;
10866 	struct drm_crtc *crtc;
10867 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10868 	unsigned long flags;
10869 	bool wait_for_vblank = true;
10870 	struct drm_connector *connector;
10871 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
10872 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10873 	int crtc_disable_count = 0;
10874 
10875 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
10876 
10877 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
10878 	drm_dp_mst_atomic_wait_for_dependencies(state);
10879 
10880 	dm_state = dm_atomic_get_new_state(state);
10881 	if (dm_state && dm_state->context) {
10882 		dc_state = dm_state->context;
10883 		amdgpu_dm_commit_streams(state, dc_state);
10884 	}
10885 
10886 	amdgpu_dm_update_hdcp(state);
10887 
10888 	/* Handle connector state changes */
10889 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10890 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10891 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
10892 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10893 		struct dc_surface_update *dummy_updates;
10894 		struct dc_stream_update stream_update;
10895 		struct dc_info_packet hdr_packet;
10896 		struct dc_stream_status *status = NULL;
10897 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
10898 
10899 		memset(&stream_update, 0, sizeof(stream_update));
10900 
10901 		if (acrtc) {
10902 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
10903 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10904 		}
10905 
10906 		/* Skip any modesets/resets */
10907 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
10908 			continue;
10909 
10910 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10911 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10912 
10913 		scaling_changed = is_scaling_state_different(dm_new_con_state,
10914 							     dm_old_con_state);
10915 
10916 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
10917 			(dm_old_crtc_state->stream->output_color_space !=
10918 				get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
10919 			output_color_space_changed = true;
10920 
10921 		abm_changed = dm_new_crtc_state->abm_level !=
10922 			      dm_old_crtc_state->abm_level;
10923 
10924 		hdr_changed =
10925 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
10926 
10927 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
10928 			continue;
10929 
10930 		stream_update.stream = dm_new_crtc_state->stream;
10931 		if (scaling_changed) {
10932 			update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
10933 					dm_new_con_state, dm_new_crtc_state->stream);
10934 
10935 			stream_update.src = dm_new_crtc_state->stream->src;
10936 			stream_update.dst = dm_new_crtc_state->stream->dst;
10937 		}
10938 
10939 		if (output_color_space_changed) {
10940 			dm_new_crtc_state->stream->output_color_space
10941 				= get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
10942 
10943 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
10944 		}
10945 
10946 		if (abm_changed) {
10947 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
10948 
10949 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
10950 		}
10951 
10952 		if (hdr_changed) {
10953 			fill_hdr_info_packet(new_con_state, &hdr_packet);
10954 			stream_update.hdr_static_metadata = &hdr_packet;
10955 		}
10956 
10957 		status = dc_stream_get_status(dm_new_crtc_state->stream);
10958 
10959 		if (WARN_ON(!status))
10960 			continue;
10961 
10962 		WARN_ON(!status->plane_count);
10963 
10964 		/*
10965 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
10966 		 * Here we create an empty update on each plane.
10967 		 * To fix this, DC should permit updating only stream properties.
10968 		 */
10969 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
10970 		if (!dummy_updates) {
10971 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
10972 			continue;
10973 		}
10974 		for (j = 0; j < status->plane_count; j++)
10975 			dummy_updates[j].surface = status->plane_states[0];
10976 
10977 		sort(dummy_updates, status->plane_count,
10978 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
10979 
10980 		mutex_lock(&dm->dc_lock);
10981 		dc_exit_ips_for_hw_access(dm->dc);
10982 		dc_update_planes_and_stream(dm->dc,
10983 					    dummy_updates,
10984 					    status->plane_count,
10985 					    dm_new_crtc_state->stream,
10986 					    &stream_update);
10987 		mutex_unlock(&dm->dc_lock);
10988 		kfree(dummy_updates);
10989 
10990 		drm_connector_update_privacy_screen(new_con_state);
10991 	}
10992 
10993 	/**
10994 	 * Enable interrupts for CRTCs that are newly enabled or went through
10995 	 * a modeset. It was intentionally deferred until after the front end
10996 	 * state was modified to wait until the OTG was on and so the IRQ
10997 	 * handlers didn't access stale or invalid state.
10998 	 */
10999 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11000 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11001 #ifdef CONFIG_DEBUG_FS
11002 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
11003 #endif
11004 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
11005 		if (old_crtc_state->active && !new_crtc_state->active)
11006 			crtc_disable_count++;
11007 
11008 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11009 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11010 
11011 		/* For freesync config update on crtc state and params for irq */
11012 		update_stream_irq_parameters(dm, dm_new_crtc_state);
11013 
11014 #ifdef CONFIG_DEBUG_FS
11015 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11016 		cur_crc_src = acrtc->dm_irq_params.crc_src;
11017 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11018 #endif
11019 
11020 		if (new_crtc_state->active &&
11021 		    (!old_crtc_state->active ||
11022 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11023 			dc_stream_retain(dm_new_crtc_state->stream);
11024 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
11025 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
11026 		}
11027 		/* Handle vrr on->off / off->on transitions */
11028 		amdgpu_dm_handle_vrr_transition(dm_old_crtc_state, dm_new_crtc_state);
11029 
11030 #ifdef CONFIG_DEBUG_FS
11031 		if (new_crtc_state->active &&
11032 		    (!old_crtc_state->active ||
11033 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11034 			/**
11035 			 * Frontend may have changed so reapply the CRC capture
11036 			 * settings for the stream.
11037 			 */
11038 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
11039 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
11040 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
11041 					uint8_t cnt;
11042 
11043 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11044 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
11045 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
11046 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
11047 
11048 							/**
11049 							 * It takes 2 frames for HW to stably generate CRC when
11050 							 * resuming from suspend, so we set skip_frame_cnt 2.
11051 							 */
11052 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
11053 						}
11054 					}
11055 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11056 				}
11057 #endif
11058 				if (amdgpu_dm_crtc_configure_crc_source(
11059 					crtc, dm_new_crtc_state, cur_crc_src))
11060 					drm_dbg_atomic(dev, "Failed to configure crc source");
11061 			}
11062 		}
11063 #endif
11064 	}
11065 
11066 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
11067 		if (new_crtc_state->async_flip)
11068 			wait_for_vblank = false;
11069 
11070 	/* update planes when needed per crtc*/
11071 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
11072 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11073 
11074 		if (dm_new_crtc_state->stream)
11075 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
11076 	}
11077 
11078 	/* Enable writeback */
11079 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11080 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11081 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11082 
11083 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11084 			continue;
11085 
11086 		if (!new_con_state->writeback_job)
11087 			continue;
11088 
11089 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11090 
11091 		if (!new_crtc_state)
11092 			continue;
11093 
11094 		if (acrtc->wb_enabled)
11095 			continue;
11096 
11097 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11098 
11099 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
11100 		acrtc->wb_enabled = true;
11101 	}
11102 
11103 	/* Update audio instances for each connector. */
11104 	amdgpu_dm_commit_audio(dev, state);
11105 
11106 	/* restore the backlight level */
11107 	for (i = 0; i < dm->num_of_edps; i++) {
11108 		if (dm->backlight_dev[i] &&
11109 		    (dm->actual_brightness[i] != dm->brightness[i]))
11110 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11111 	}
11112 
11113 	/*
11114 	 * send vblank event on all events not handled in flip and
11115 	 * mark consumed event for drm_atomic_helper_commit_hw_done
11116 	 */
11117 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11118 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11119 
11120 		if (new_crtc_state->event)
11121 			drm_send_event_locked(dev, &new_crtc_state->event->base);
11122 
11123 		new_crtc_state->event = NULL;
11124 	}
11125 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11126 
11127 	/* Signal HW programming completion */
11128 	drm_atomic_helper_commit_hw_done(state);
11129 
11130 	if (wait_for_vblank)
11131 		drm_atomic_helper_wait_for_flip_done(dev, state);
11132 
11133 	drm_atomic_helper_cleanup_planes(dev, state);
11134 
11135 	/* Don't free the memory if we are hitting this as part of suspend.
11136 	 * This way we don't free any memory during suspend; see
11137 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
11138 	 * non-suspend modeset or when the driver is torn down.
11139 	 */
11140 	if (!adev->in_suspend) {
11141 		/* return the stolen vga memory back to VRAM */
11142 		if (!adev->mman.keep_stolen_vga_memory)
11143 			amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
11144 		amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
11145 	}
11146 
11147 	/*
11148 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
11149 	 * so we can put the GPU into runtime suspend if we're not driving any
11150 	 * displays anymore
11151 	 */
11152 	for (i = 0; i < crtc_disable_count; i++)
11153 		pm_runtime_put_autosuspend(dev->dev);
11154 	pm_runtime_mark_last_busy(dev->dev);
11155 
11156 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
11157 }
11158 
11159 static int dm_force_atomic_commit(struct drm_connector *connector)
11160 {
11161 	int ret = 0;
11162 	struct drm_device *ddev = connector->dev;
11163 	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
11164 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11165 	struct drm_plane *plane = disconnected_acrtc->base.primary;
11166 	struct drm_connector_state *conn_state;
11167 	struct drm_crtc_state *crtc_state;
11168 	struct drm_plane_state *plane_state;
11169 
11170 	if (!state)
11171 		return -ENOMEM;
11172 
11173 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
11174 
11175 	/* Construct an atomic state to restore previous display setting */
11176 
11177 	/*
11178 	 * Attach connectors to drm_atomic_state
11179 	 */
11180 	conn_state = drm_atomic_get_connector_state(state, connector);
11181 
11182 	/* Check for error in getting connector state */
11183 	if (IS_ERR(conn_state)) {
11184 		ret = PTR_ERR(conn_state);
11185 		goto out;
11186 	}
11187 
11188 	/* Attach crtc to drm_atomic_state*/
11189 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
11190 
11191 	/* Check for error in getting crtc state */
11192 	if (IS_ERR(crtc_state)) {
11193 		ret = PTR_ERR(crtc_state);
11194 		goto out;
11195 	}
11196 
11197 	/* force a restore */
11198 	crtc_state->mode_changed = true;
11199 
11200 	/* Attach plane to drm_atomic_state */
11201 	plane_state = drm_atomic_get_plane_state(state, plane);
11202 
11203 	/* Check for error in getting plane state */
11204 	if (IS_ERR(plane_state)) {
11205 		ret = PTR_ERR(plane_state);
11206 		goto out;
11207 	}
11208 
11209 	/* Call commit internally with the state we just constructed */
11210 	ret = drm_atomic_commit(state);
11211 
11212 out:
11213 	drm_atomic_state_put(state);
11214 	if (ret)
11215 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
11216 
11217 	return ret;
11218 }
11219 
11220 /*
11221  * This function handles all cases when set mode does not come upon hotplug.
11222  * This includes when a display is unplugged then plugged back into the
11223  * same port and when running without usermode desktop manager supprot
11224  */
11225 void dm_restore_drm_connector_state(struct drm_device *dev,
11226 				    struct drm_connector *connector)
11227 {
11228 	struct amdgpu_dm_connector *aconnector;
11229 	struct amdgpu_crtc *disconnected_acrtc;
11230 	struct dm_crtc_state *acrtc_state;
11231 
11232 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11233 		return;
11234 
11235 	aconnector = to_amdgpu_dm_connector(connector);
11236 
11237 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
11238 		return;
11239 
11240 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11241 	if (!disconnected_acrtc)
11242 		return;
11243 
11244 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
11245 	if (!acrtc_state->stream)
11246 		return;
11247 
11248 	/*
11249 	 * If the previous sink is not released and different from the current,
11250 	 * we deduce we are in a state where we can not rely on usermode call
11251 	 * to turn on the display, so we do it here
11252 	 */
11253 	if (acrtc_state->stream->sink != aconnector->dc_sink)
11254 		dm_force_atomic_commit(&aconnector->base);
11255 }
11256 
11257 /*
11258  * Grabs all modesetting locks to serialize against any blocking commits,
11259  * Waits for completion of all non blocking commits.
11260  */
11261 static int do_aquire_global_lock(struct drm_device *dev,
11262 				 struct drm_atomic_state *state)
11263 {
11264 	struct drm_crtc *crtc;
11265 	struct drm_crtc_commit *commit;
11266 	long ret;
11267 
11268 	/*
11269 	 * Adding all modeset locks to aquire_ctx will
11270 	 * ensure that when the framework release it the
11271 	 * extra locks we are locking here will get released to
11272 	 */
11273 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
11274 	if (ret)
11275 		return ret;
11276 
11277 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
11278 		spin_lock(&crtc->commit_lock);
11279 		commit = list_first_entry_or_null(&crtc->commit_list,
11280 				struct drm_crtc_commit, commit_entry);
11281 		if (commit)
11282 			drm_crtc_commit_get(commit);
11283 		spin_unlock(&crtc->commit_lock);
11284 
11285 		if (!commit)
11286 			continue;
11287 
11288 		/*
11289 		 * Make sure all pending HW programming completed and
11290 		 * page flips done
11291 		 */
11292 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
11293 
11294 		if (ret > 0)
11295 			ret = wait_for_completion_interruptible_timeout(
11296 					&commit->flip_done, 10*HZ);
11297 
11298 		if (ret == 0)
11299 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
11300 				  crtc->base.id, crtc->name);
11301 
11302 		drm_crtc_commit_put(commit);
11303 	}
11304 
11305 	return ret < 0 ? ret : 0;
11306 }
11307 
11308 static void get_freesync_config_for_crtc(
11309 	struct dm_crtc_state *new_crtc_state,
11310 	struct dm_connector_state *new_con_state)
11311 {
11312 	struct mod_freesync_config config = {0};
11313 	struct amdgpu_dm_connector *aconnector;
11314 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
11315 	int vrefresh = drm_mode_vrefresh(mode);
11316 	bool fs_vid_mode = false;
11317 
11318 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11319 		return;
11320 
11321 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
11322 
11323 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
11324 					vrefresh >= aconnector->min_vfreq &&
11325 					vrefresh <= aconnector->max_vfreq;
11326 
11327 	if (new_crtc_state->vrr_supported) {
11328 		new_crtc_state->stream->ignore_msa_timing_param = true;
11329 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
11330 
11331 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
11332 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
11333 		config.vsif_supported = true;
11334 		config.btr = true;
11335 
11336 		if (fs_vid_mode) {
11337 			config.state = VRR_STATE_ACTIVE_FIXED;
11338 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
11339 			goto out;
11340 		} else if (new_crtc_state->base.vrr_enabled) {
11341 			config.state = VRR_STATE_ACTIVE_VARIABLE;
11342 		} else {
11343 			config.state = VRR_STATE_INACTIVE;
11344 		}
11345 	} else {
11346 		config.state = VRR_STATE_UNSUPPORTED;
11347 	}
11348 out:
11349 	new_crtc_state->freesync_config = config;
11350 }
11351 
11352 static void reset_freesync_config_for_crtc(
11353 	struct dm_crtc_state *new_crtc_state)
11354 {
11355 	new_crtc_state->vrr_supported = false;
11356 
11357 	memset(&new_crtc_state->vrr_infopacket, 0,
11358 	       sizeof(new_crtc_state->vrr_infopacket));
11359 }
11360 
11361 static bool
11362 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
11363 				 struct drm_crtc_state *new_crtc_state)
11364 {
11365 	const struct drm_display_mode *old_mode, *new_mode;
11366 
11367 	if (!old_crtc_state || !new_crtc_state)
11368 		return false;
11369 
11370 	old_mode = &old_crtc_state->mode;
11371 	new_mode = &new_crtc_state->mode;
11372 
11373 	if (old_mode->clock       == new_mode->clock &&
11374 	    old_mode->hdisplay    == new_mode->hdisplay &&
11375 	    old_mode->vdisplay    == new_mode->vdisplay &&
11376 	    old_mode->htotal      == new_mode->htotal &&
11377 	    old_mode->vtotal      != new_mode->vtotal &&
11378 	    old_mode->hsync_start == new_mode->hsync_start &&
11379 	    old_mode->vsync_start != new_mode->vsync_start &&
11380 	    old_mode->hsync_end   == new_mode->hsync_end &&
11381 	    old_mode->vsync_end   != new_mode->vsync_end &&
11382 	    old_mode->hskew       == new_mode->hskew &&
11383 	    old_mode->vscan       == new_mode->vscan &&
11384 	    (old_mode->vsync_end - old_mode->vsync_start) ==
11385 	    (new_mode->vsync_end - new_mode->vsync_start))
11386 		return true;
11387 
11388 	return false;
11389 }
11390 
11391 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
11392 {
11393 	u64 num, den, res;
11394 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
11395 
11396 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
11397 
11398 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
11399 	den = (unsigned long long)new_crtc_state->mode.htotal *
11400 	      (unsigned long long)new_crtc_state->mode.vtotal;
11401 
11402 	res = div_u64(num, den);
11403 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
11404 }
11405 
11406 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
11407 			 struct drm_atomic_state *state,
11408 			 struct drm_crtc *crtc,
11409 			 struct drm_crtc_state *old_crtc_state,
11410 			 struct drm_crtc_state *new_crtc_state,
11411 			 bool enable,
11412 			 bool *lock_and_validation_needed)
11413 {
11414 	struct dm_atomic_state *dm_state = NULL;
11415 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11416 	struct dc_stream_state *new_stream;
11417 	struct amdgpu_device *adev = dm->adev;
11418 	int ret = 0;
11419 
11420 	/*
11421 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
11422 	 * update changed items
11423 	 */
11424 	struct amdgpu_crtc *acrtc = NULL;
11425 	struct drm_connector *connector = NULL;
11426 	struct amdgpu_dm_connector *aconnector = NULL;
11427 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
11428 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
11429 
11430 	new_stream = NULL;
11431 
11432 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11433 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11434 	acrtc = to_amdgpu_crtc(crtc);
11435 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
11436 	if (connector)
11437 		aconnector = to_amdgpu_dm_connector(connector);
11438 
11439 	/* TODO This hack should go away */
11440 	if (connector && enable) {
11441 		/* Make sure fake sink is created in plug-in scenario */
11442 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
11443 									connector);
11444 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
11445 									connector);
11446 
11447 		if (WARN_ON(!drm_new_conn_state)) {
11448 			ret = -EINVAL;
11449 			goto fail;
11450 		}
11451 
11452 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
11453 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
11454 
11455 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11456 			goto skip_modeset;
11457 
11458 		new_stream = create_validate_stream_for_sink(connector,
11459 							     &new_crtc_state->mode,
11460 							     dm_new_conn_state,
11461 							     dm_old_crtc_state->stream);
11462 
11463 		/*
11464 		 * we can have no stream on ACTION_SET if a display
11465 		 * was disconnected during S3, in this case it is not an
11466 		 * error, the OS will be updated after detection, and
11467 		 * will do the right thing on next atomic commit
11468 		 */
11469 
11470 		if (!new_stream) {
11471 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
11472 					__func__, acrtc->base.base.id);
11473 			ret = -ENOMEM;
11474 			goto fail;
11475 		}
11476 
11477 		/*
11478 		 * TODO: Check VSDB bits to decide whether this should
11479 		 * be enabled or not.
11480 		 */
11481 		new_stream->triggered_crtc_reset.enabled =
11482 			dm->force_timing_sync;
11483 
11484 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11485 
11486 		ret = fill_hdr_info_packet(drm_new_conn_state,
11487 					   &new_stream->hdr_static_metadata);
11488 		if (ret)
11489 			goto fail;
11490 
11491 		/*
11492 		 * If we already removed the old stream from the context
11493 		 * (and set the new stream to NULL) then we can't reuse
11494 		 * the old stream even if the stream and scaling are unchanged.
11495 		 * We'll hit the BUG_ON and black screen.
11496 		 *
11497 		 * TODO: Refactor this function to allow this check to work
11498 		 * in all conditions.
11499 		 */
11500 		if (amdgpu_freesync_vid_mode &&
11501 		    dm_new_crtc_state->stream &&
11502 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
11503 			goto skip_modeset;
11504 
11505 		if (dm_new_crtc_state->stream &&
11506 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11507 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
11508 			new_crtc_state->mode_changed = false;
11509 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
11510 					 new_crtc_state->mode_changed);
11511 		}
11512 	}
11513 
11514 	/* mode_changed flag may get updated above, need to check again */
11515 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11516 		goto skip_modeset;
11517 
11518 	drm_dbg_state(state->dev,
11519 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
11520 		acrtc->crtc_id,
11521 		new_crtc_state->enable,
11522 		new_crtc_state->active,
11523 		new_crtc_state->planes_changed,
11524 		new_crtc_state->mode_changed,
11525 		new_crtc_state->active_changed,
11526 		new_crtc_state->connectors_changed);
11527 
11528 	/* Remove stream for any changed/disabled CRTC */
11529 	if (!enable) {
11530 
11531 		if (!dm_old_crtc_state->stream)
11532 			goto skip_modeset;
11533 
11534 		/* Unset freesync video if it was active before */
11535 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
11536 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
11537 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
11538 		}
11539 
11540 		/* Now check if we should set freesync video mode */
11541 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
11542 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11543 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
11544 		    is_timing_unchanged_for_freesync(new_crtc_state,
11545 						     old_crtc_state)) {
11546 			new_crtc_state->mode_changed = false;
11547 			drm_dbg_driver(adev_to_drm(adev),
11548 				"Mode change not required for front porch change, setting mode_changed to %d",
11549 				new_crtc_state->mode_changed);
11550 
11551 			set_freesync_fixed_config(dm_new_crtc_state);
11552 
11553 			goto skip_modeset;
11554 		} else if (amdgpu_freesync_vid_mode && aconnector &&
11555 			   is_freesync_video_mode(&new_crtc_state->mode,
11556 						  aconnector)) {
11557 			struct drm_display_mode *high_mode;
11558 
11559 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
11560 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
11561 				set_freesync_fixed_config(dm_new_crtc_state);
11562 		}
11563 
11564 		ret = dm_atomic_get_state(state, &dm_state);
11565 		if (ret)
11566 			goto fail;
11567 
11568 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
11569 				crtc->base.id);
11570 
11571 		/* i.e. reset mode */
11572 		if (dc_state_remove_stream(
11573 				dm->dc,
11574 				dm_state->context,
11575 				dm_old_crtc_state->stream) != DC_OK) {
11576 			ret = -EINVAL;
11577 			goto fail;
11578 		}
11579 
11580 		dc_stream_release(dm_old_crtc_state->stream);
11581 		dm_new_crtc_state->stream = NULL;
11582 
11583 		reset_freesync_config_for_crtc(dm_new_crtc_state);
11584 
11585 		*lock_and_validation_needed = true;
11586 
11587 	} else {/* Add stream for any updated/enabled CRTC */
11588 		/*
11589 		 * Quick fix to prevent NULL pointer on new_stream when
11590 		 * added MST connectors not found in existing crtc_state in the chained mode
11591 		 * TODO: need to dig out the root cause of that
11592 		 */
11593 		if (!connector)
11594 			goto skip_modeset;
11595 
11596 		if (modereset_required(new_crtc_state))
11597 			goto skip_modeset;
11598 
11599 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
11600 				     dm_old_crtc_state->stream)) {
11601 
11602 			WARN_ON(dm_new_crtc_state->stream);
11603 
11604 			ret = dm_atomic_get_state(state, &dm_state);
11605 			if (ret)
11606 				goto fail;
11607 
11608 			dm_new_crtc_state->stream = new_stream;
11609 
11610 			dc_stream_retain(new_stream);
11611 
11612 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
11613 					 crtc->base.id);
11614 
11615 			if (dc_state_add_stream(
11616 					dm->dc,
11617 					dm_state->context,
11618 					dm_new_crtc_state->stream) != DC_OK) {
11619 				ret = -EINVAL;
11620 				goto fail;
11621 			}
11622 
11623 			*lock_and_validation_needed = true;
11624 		}
11625 	}
11626 
11627 skip_modeset:
11628 	/* Release extra reference */
11629 	if (new_stream)
11630 		dc_stream_release(new_stream);
11631 
11632 	/*
11633 	 * We want to do dc stream updates that do not require a
11634 	 * full modeset below.
11635 	 */
11636 	if (!(enable && connector && new_crtc_state->active))
11637 		return 0;
11638 	/*
11639 	 * Given above conditions, the dc state cannot be NULL because:
11640 	 * 1. We're in the process of enabling CRTCs (just been added
11641 	 *    to the dc context, or already is on the context)
11642 	 * 2. Has a valid connector attached, and
11643 	 * 3. Is currently active and enabled.
11644 	 * => The dc stream state currently exists.
11645 	 */
11646 	BUG_ON(dm_new_crtc_state->stream == NULL);
11647 
11648 	/* Scaling or underscan settings */
11649 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
11650 				drm_atomic_crtc_needs_modeset(new_crtc_state))
11651 		update_stream_scaling_settings(adev_to_drm(adev),
11652 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
11653 
11654 	/* ABM settings */
11655 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11656 
11657 	/*
11658 	 * Color management settings. We also update color properties
11659 	 * when a modeset is needed, to ensure it gets reprogrammed.
11660 	 */
11661 	if (dm_new_crtc_state->base.color_mgmt_changed ||
11662 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11663 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
11664 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
11665 		if (ret)
11666 			goto fail;
11667 	}
11668 
11669 	/* Update Freesync settings. */
11670 	get_freesync_config_for_crtc(dm_new_crtc_state,
11671 				     dm_new_conn_state);
11672 
11673 	return ret;
11674 
11675 fail:
11676 	if (new_stream)
11677 		dc_stream_release(new_stream);
11678 	return ret;
11679 }
11680 
11681 static bool should_reset_plane(struct drm_atomic_state *state,
11682 			       struct drm_plane *plane,
11683 			       struct drm_plane_state *old_plane_state,
11684 			       struct drm_plane_state *new_plane_state)
11685 {
11686 	struct drm_plane *other;
11687 	struct drm_plane_state *old_other_state, *new_other_state;
11688 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11689 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
11690 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
11691 	int i;
11692 
11693 	/*
11694 	 * TODO: Remove this hack for all asics once it proves that the
11695 	 * fast updates works fine on DCN3.2+.
11696 	 */
11697 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
11698 	    state->allow_modeset)
11699 		return true;
11700 
11701 	if (amdgpu_in_reset(adev) && state->allow_modeset)
11702 		return true;
11703 
11704 	/* Exit early if we know that we're adding or removing the plane. */
11705 	if (old_plane_state->crtc != new_plane_state->crtc)
11706 		return true;
11707 
11708 	/* old crtc == new_crtc == NULL, plane not in context. */
11709 	if (!new_plane_state->crtc)
11710 		return false;
11711 
11712 	new_crtc_state =
11713 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
11714 	old_crtc_state =
11715 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
11716 
11717 	if (!new_crtc_state)
11718 		return true;
11719 
11720 	/*
11721 	 * A change in cursor mode means a new dc pipe needs to be acquired or
11722 	 * released from the state
11723 	 */
11724 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
11725 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
11726 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
11727 	    old_dm_crtc_state != NULL &&
11728 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
11729 		return true;
11730 	}
11731 
11732 	/* CRTC Degamma changes currently require us to recreate planes. */
11733 	if (new_crtc_state->color_mgmt_changed)
11734 		return true;
11735 
11736 	/*
11737 	 * On zpos change, planes need to be reordered by removing and re-adding
11738 	 * them one by one to the dc state, in order of descending zpos.
11739 	 *
11740 	 * TODO: We can likely skip bandwidth validation if the only thing that
11741 	 * changed about the plane was it'z z-ordering.
11742 	 */
11743 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
11744 		return true;
11745 
11746 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
11747 		return true;
11748 
11749 	/*
11750 	 * If there are any new primary or overlay planes being added or
11751 	 * removed then the z-order can potentially change. To ensure
11752 	 * correct z-order and pipe acquisition the current DC architecture
11753 	 * requires us to remove and recreate all existing planes.
11754 	 *
11755 	 * TODO: Come up with a more elegant solution for this.
11756 	 */
11757 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
11758 		struct amdgpu_framebuffer *old_afb, *new_afb;
11759 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
11760 
11761 		dm_new_other_state = to_dm_plane_state(new_other_state);
11762 		dm_old_other_state = to_dm_plane_state(old_other_state);
11763 
11764 		if (other->type == DRM_PLANE_TYPE_CURSOR)
11765 			continue;
11766 
11767 		if (old_other_state->crtc != new_plane_state->crtc &&
11768 		    new_other_state->crtc != new_plane_state->crtc)
11769 			continue;
11770 
11771 		if (old_other_state->crtc != new_other_state->crtc)
11772 			return true;
11773 
11774 		/* Src/dst size and scaling updates. */
11775 		if (old_other_state->src_w != new_other_state->src_w ||
11776 		    old_other_state->src_h != new_other_state->src_h ||
11777 		    old_other_state->crtc_w != new_other_state->crtc_w ||
11778 		    old_other_state->crtc_h != new_other_state->crtc_h)
11779 			return true;
11780 
11781 		/* Rotation / mirroring updates. */
11782 		if (old_other_state->rotation != new_other_state->rotation)
11783 			return true;
11784 
11785 		/* Blending updates. */
11786 		if (old_other_state->pixel_blend_mode !=
11787 		    new_other_state->pixel_blend_mode)
11788 			return true;
11789 
11790 		/* Alpha updates. */
11791 		if (old_other_state->alpha != new_other_state->alpha)
11792 			return true;
11793 
11794 		/* Colorspace changes. */
11795 		if (old_other_state->color_range != new_other_state->color_range ||
11796 		    old_other_state->color_encoding != new_other_state->color_encoding)
11797 			return true;
11798 
11799 		/* HDR/Transfer Function changes. */
11800 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
11801 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
11802 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
11803 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
11804 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
11805 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
11806 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
11807 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
11808 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
11809 			return true;
11810 
11811 		/* Framebuffer checks fall at the end. */
11812 		if (!old_other_state->fb || !new_other_state->fb)
11813 			continue;
11814 
11815 		/* Pixel format changes can require bandwidth updates. */
11816 		if (old_other_state->fb->format != new_other_state->fb->format)
11817 			return true;
11818 
11819 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
11820 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
11821 
11822 		/* Tiling and DCC changes also require bandwidth updates. */
11823 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
11824 		    old_afb->base.modifier != new_afb->base.modifier)
11825 			return true;
11826 	}
11827 
11828 	return false;
11829 }
11830 
11831 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
11832 			      struct drm_plane_state *new_plane_state,
11833 			      struct drm_framebuffer *fb)
11834 {
11835 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
11836 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
11837 	unsigned int pitch;
11838 	bool linear;
11839 
11840 	if (fb->width > new_acrtc->max_cursor_width ||
11841 	    fb->height > new_acrtc->max_cursor_height) {
11842 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB size %dx%d\n",
11843 				 new_plane_state->fb->width,
11844 				 new_plane_state->fb->height);
11845 		return -EINVAL;
11846 	}
11847 	if (new_plane_state->src_w != fb->width << 16 ||
11848 	    new_plane_state->src_h != fb->height << 16) {
11849 		drm_dbg_atomic(adev_to_drm(adev), "Cropping not supported for cursor plane\n");
11850 		return -EINVAL;
11851 	}
11852 
11853 	/* Pitch in pixels */
11854 	pitch = fb->pitches[0] / fb->format->cpp[0];
11855 
11856 	if (fb->width != pitch) {
11857 		drm_dbg_atomic(adev_to_drm(adev), "Cursor FB width %d doesn't match pitch %d",
11858 				 fb->width, pitch);
11859 		return -EINVAL;
11860 	}
11861 
11862 	switch (pitch) {
11863 	case 64:
11864 	case 128:
11865 	case 256:
11866 		/* FB pitch is supported by cursor plane */
11867 		break;
11868 	default:
11869 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB pitch %d px\n", pitch);
11870 		return -EINVAL;
11871 	}
11872 
11873 	/* Core DRM takes care of checking FB modifiers, so we only need to
11874 	 * check tiling flags when the FB doesn't have a modifier.
11875 	 */
11876 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
11877 		if (adev->family == AMDGPU_FAMILY_GC_12_0_0) {
11878 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
11879 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
11880 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
11881 		} else {
11882 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
11883 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
11884 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
11885 		}
11886 		if (!linear) {
11887 			drm_dbg_atomic(adev_to_drm(adev), "Cursor FB not linear");
11888 			return -EINVAL;
11889 		}
11890 	}
11891 
11892 	return 0;
11893 }
11894 
11895 /*
11896  * Helper function for checking the cursor in native mode
11897  */
11898 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
11899 					struct drm_plane *plane,
11900 					struct drm_plane_state *new_plane_state,
11901 					bool enable)
11902 {
11903 
11904 	struct amdgpu_crtc *new_acrtc;
11905 	int ret;
11906 
11907 	if (!enable || !new_plane_crtc ||
11908 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
11909 		return 0;
11910 
11911 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
11912 
11913 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
11914 		drm_dbg_atomic(new_plane_crtc->dev, "Cropping not supported for cursor plane\n");
11915 		return -EINVAL;
11916 	}
11917 
11918 	if (new_plane_state->fb) {
11919 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
11920 						new_plane_state->fb);
11921 		if (ret)
11922 			return ret;
11923 	}
11924 
11925 	return 0;
11926 }
11927 
11928 static bool dm_should_update_native_cursor(struct drm_atomic_state *state,
11929 					   struct drm_crtc *old_plane_crtc,
11930 					   struct drm_crtc *new_plane_crtc,
11931 					   bool enable)
11932 {
11933 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11934 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11935 
11936 	if (!enable) {
11937 		if (old_plane_crtc == NULL)
11938 			return true;
11939 
11940 		old_crtc_state = drm_atomic_get_old_crtc_state(
11941 			state, old_plane_crtc);
11942 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11943 
11944 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
11945 	} else {
11946 		if (new_plane_crtc == NULL)
11947 			return true;
11948 
11949 		new_crtc_state = drm_atomic_get_new_crtc_state(
11950 			state, new_plane_crtc);
11951 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11952 
11953 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
11954 	}
11955 }
11956 
11957 static int dm_update_plane_state(struct dc *dc,
11958 				 struct drm_atomic_state *state,
11959 				 struct drm_plane *plane,
11960 				 struct drm_plane_state *old_plane_state,
11961 				 struct drm_plane_state *new_plane_state,
11962 				 bool enable,
11963 				 bool *lock_and_validation_needed,
11964 				 bool *is_top_most_overlay)
11965 {
11966 
11967 	struct dm_atomic_state *dm_state = NULL;
11968 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
11969 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11970 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
11971 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
11972 	bool needs_reset, update_native_cursor;
11973 	int ret = 0;
11974 
11975 
11976 	new_plane_crtc = new_plane_state->crtc;
11977 	old_plane_crtc = old_plane_state->crtc;
11978 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
11979 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
11980 
11981 	update_native_cursor = dm_should_update_native_cursor(state,
11982 							      old_plane_crtc,
11983 							      new_plane_crtc,
11984 							      enable);
11985 
11986 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
11987 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
11988 						    new_plane_state, enable);
11989 		if (ret)
11990 			return ret;
11991 
11992 		return 0;
11993 	}
11994 
11995 	needs_reset = should_reset_plane(state, plane, old_plane_state,
11996 					 new_plane_state);
11997 
11998 	/* Remove any changed/removed planes */
11999 	if (!enable) {
12000 		if (!needs_reset)
12001 			return 0;
12002 
12003 		if (!old_plane_crtc)
12004 			return 0;
12005 
12006 		old_crtc_state = drm_atomic_get_old_crtc_state(
12007 				state, old_plane_crtc);
12008 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12009 
12010 		if (!dm_old_crtc_state->stream)
12011 			return 0;
12012 
12013 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
12014 				plane->base.id, old_plane_crtc->base.id);
12015 
12016 		ret = dm_atomic_get_state(state, &dm_state);
12017 		if (ret)
12018 			return ret;
12019 
12020 		if (!dc_state_remove_plane(
12021 				dc,
12022 				dm_old_crtc_state->stream,
12023 				dm_old_plane_state->dc_state,
12024 				dm_state->context)) {
12025 
12026 			return -EINVAL;
12027 		}
12028 
12029 		if (dm_old_plane_state->dc_state)
12030 			dc_plane_state_release(dm_old_plane_state->dc_state);
12031 
12032 		dm_new_plane_state->dc_state = NULL;
12033 
12034 		*lock_and_validation_needed = true;
12035 
12036 	} else { /* Add new planes */
12037 		struct dc_plane_state *dc_new_plane_state;
12038 
12039 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
12040 			return 0;
12041 
12042 		if (!new_plane_crtc)
12043 			return 0;
12044 
12045 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
12046 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12047 
12048 		if (!dm_new_crtc_state->stream)
12049 			return 0;
12050 
12051 		if (!needs_reset)
12052 			return 0;
12053 
12054 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
12055 		if (ret)
12056 			goto out;
12057 
12058 		WARN_ON(dm_new_plane_state->dc_state);
12059 
12060 		dc_new_plane_state = dc_create_plane_state(dc);
12061 		if (!dc_new_plane_state) {
12062 			ret = -ENOMEM;
12063 			goto out;
12064 		}
12065 
12066 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
12067 				 plane->base.id, new_plane_crtc->base.id);
12068 
12069 		ret = fill_dc_plane_attributes(
12070 			drm_to_adev(new_plane_crtc->dev),
12071 			dc_new_plane_state,
12072 			new_plane_state,
12073 			new_crtc_state);
12074 		if (ret) {
12075 			dc_plane_state_release(dc_new_plane_state);
12076 			goto out;
12077 		}
12078 
12079 		ret = dm_atomic_get_state(state, &dm_state);
12080 		if (ret) {
12081 			dc_plane_state_release(dc_new_plane_state);
12082 			goto out;
12083 		}
12084 
12085 		/*
12086 		 * Any atomic check errors that occur after this will
12087 		 * not need a release. The plane state will be attached
12088 		 * to the stream, and therefore part of the atomic
12089 		 * state. It'll be released when the atomic state is
12090 		 * cleaned.
12091 		 */
12092 		if (!dc_state_add_plane(
12093 				dc,
12094 				dm_new_crtc_state->stream,
12095 				dc_new_plane_state,
12096 				dm_state->context)) {
12097 
12098 			dc_plane_state_release(dc_new_plane_state);
12099 			ret = -EINVAL;
12100 			goto out;
12101 		}
12102 
12103 		dm_new_plane_state->dc_state = dc_new_plane_state;
12104 
12105 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
12106 
12107 		/* Tell DC to do a full surface update every time there
12108 		 * is a plane change. Inefficient, but works for now.
12109 		 */
12110 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
12111 
12112 		*lock_and_validation_needed = true;
12113 	}
12114 
12115 out:
12116 	/* If enabling cursor overlay failed, attempt fallback to native mode */
12117 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
12118 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12119 						    new_plane_state, enable);
12120 		if (ret)
12121 			return ret;
12122 
12123 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
12124 	}
12125 
12126 	return ret;
12127 }
12128 
12129 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
12130 				       int *src_w, int *src_h)
12131 {
12132 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
12133 	case DRM_MODE_ROTATE_90:
12134 	case DRM_MODE_ROTATE_270:
12135 		*src_w = plane_state->src_h >> 16;
12136 		*src_h = plane_state->src_w >> 16;
12137 		break;
12138 	case DRM_MODE_ROTATE_0:
12139 	case DRM_MODE_ROTATE_180:
12140 	default:
12141 		*src_w = plane_state->src_w >> 16;
12142 		*src_h = plane_state->src_h >> 16;
12143 		break;
12144 	}
12145 }
12146 
12147 static void
12148 dm_get_plane_scale(struct drm_plane_state *plane_state,
12149 		   int *out_plane_scale_w, int *out_plane_scale_h)
12150 {
12151 	int plane_src_w, plane_src_h;
12152 
12153 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
12154 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
12155 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
12156 }
12157 
12158 /*
12159  * The normalized_zpos value cannot be used by this iterator directly. It's only
12160  * calculated for enabled planes, potentially causing normalized_zpos collisions
12161  * between enabled/disabled planes in the atomic state. We need a unique value
12162  * so that the iterator will not generate the same object twice, or loop
12163  * indefinitely.
12164  */
12165 static inline struct __drm_planes_state *__get_next_zpos(
12166 	struct drm_atomic_state *state,
12167 	struct __drm_planes_state *prev)
12168 {
12169 	unsigned int highest_zpos = 0, prev_zpos = 256;
12170 	uint32_t highest_id = 0, prev_id = UINT_MAX;
12171 	struct drm_plane_state *new_plane_state;
12172 	struct drm_plane *plane;
12173 	int i, highest_i = -1;
12174 
12175 	if (prev != NULL) {
12176 		prev_zpos = prev->new_state->zpos;
12177 		prev_id = prev->ptr->base.id;
12178 	}
12179 
12180 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
12181 		/* Skip planes with higher zpos than the previously returned */
12182 		if (new_plane_state->zpos > prev_zpos ||
12183 		    (new_plane_state->zpos == prev_zpos &&
12184 		     plane->base.id >= prev_id))
12185 			continue;
12186 
12187 		/* Save the index of the plane with highest zpos */
12188 		if (new_plane_state->zpos > highest_zpos ||
12189 		    (new_plane_state->zpos == highest_zpos &&
12190 		     plane->base.id > highest_id)) {
12191 			highest_zpos = new_plane_state->zpos;
12192 			highest_id = plane->base.id;
12193 			highest_i = i;
12194 		}
12195 	}
12196 
12197 	if (highest_i < 0)
12198 		return NULL;
12199 
12200 	return &state->planes[highest_i];
12201 }
12202 
12203 /*
12204  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
12205  * by descending zpos, as read from the new plane state. This is the same
12206  * ordering as defined by drm_atomic_normalize_zpos().
12207  */
12208 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
12209 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
12210 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
12211 		for_each_if(((plane) = __i->ptr,				\
12212 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
12213 			     (old_plane_state) = __i->old_state,		\
12214 			     (new_plane_state) = __i->new_state, 1))
12215 
12216 static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
12217 {
12218 	struct drm_connector *connector;
12219 	struct drm_connector_state *conn_state, *old_conn_state;
12220 	struct amdgpu_dm_connector *aconnector = NULL;
12221 	int i;
12222 
12223 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
12224 		if (!conn_state->crtc)
12225 			conn_state = old_conn_state;
12226 
12227 		if (conn_state->crtc != crtc)
12228 			continue;
12229 
12230 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
12231 			continue;
12232 
12233 		aconnector = to_amdgpu_dm_connector(connector);
12234 		if (!aconnector->mst_output_port || !aconnector->mst_root)
12235 			aconnector = NULL;
12236 		else
12237 			break;
12238 	}
12239 
12240 	if (!aconnector)
12241 		return 0;
12242 
12243 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
12244 }
12245 
12246 /**
12247  * DOC: Cursor Modes - Native vs Overlay
12248  *
12249  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
12250  * plane. It does not require a dedicated hw plane to enable, but it is
12251  * subjected to the same z-order and scaling as the hw plane. It also has format
12252  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
12253  * hw plane.
12254  *
12255  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
12256  * own scaling and z-pos. It also has no blending restrictions. It lends to a
12257  * cursor behavior more akin to a DRM client's expectations. However, it does
12258  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
12259  * available.
12260  */
12261 
12262 /**
12263  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
12264  * @adev: amdgpu device
12265  * @state: DRM atomic state
12266  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
12267  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
12268  *
12269  * Get whether the cursor should be enabled in native mode, or overlay mode, on
12270  * the dm_crtc_state.
12271  *
12272  * The cursor should be enabled in overlay mode if there exists an underlying
12273  * plane - on which the cursor may be blended - that is either YUV formatted, or
12274  * scaled differently from the cursor.
12275  *
12276  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
12277  * calling this function.
12278  *
12279  * Return: 0 on success, or an error code if getting the cursor plane state
12280  * failed.
12281  */
12282 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
12283 				   struct drm_atomic_state *state,
12284 				   struct dm_crtc_state *dm_crtc_state,
12285 				   enum amdgpu_dm_cursor_mode *cursor_mode)
12286 {
12287 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
12288 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
12289 	struct drm_plane *plane;
12290 	bool consider_mode_change = false;
12291 	bool entire_crtc_covered = false;
12292 	bool cursor_changed = false;
12293 	int underlying_scale_w, underlying_scale_h;
12294 	int cursor_scale_w, cursor_scale_h;
12295 	int i;
12296 
12297 	/* Overlay cursor not supported on HW before DCN
12298 	 * DCN401 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
12299 	 * as previous DCN generations, so enable native mode on DCN401 in addition to DCE
12300 	 */
12301 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0 ||
12302 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1)) {
12303 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12304 		return 0;
12305 	}
12306 
12307 	/* Init cursor_mode to be the same as current */
12308 	*cursor_mode = dm_crtc_state->cursor_mode;
12309 
12310 	/*
12311 	 * Cursor mode can change if a plane's format changes, scale changes, is
12312 	 * enabled/disabled, or z-order changes.
12313 	 */
12314 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
12315 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
12316 
12317 		/* Only care about planes on this CRTC */
12318 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
12319 			continue;
12320 
12321 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
12322 			cursor_changed = true;
12323 
12324 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
12325 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
12326 		    old_plane_state->fb->format != plane_state->fb->format) {
12327 			consider_mode_change = true;
12328 			break;
12329 		}
12330 
12331 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
12332 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
12333 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
12334 			consider_mode_change = true;
12335 			break;
12336 		}
12337 	}
12338 
12339 	if (!consider_mode_change && !crtc_state->zpos_changed)
12340 		return 0;
12341 
12342 	/*
12343 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
12344 	 * no need to set cursor mode. This avoids needlessly locking the cursor
12345 	 * state.
12346 	 */
12347 	if (!cursor_changed &&
12348 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
12349 		return 0;
12350 	}
12351 
12352 	cursor_state = drm_atomic_get_plane_state(state,
12353 						  crtc_state->crtc->cursor);
12354 	if (IS_ERR(cursor_state))
12355 		return PTR_ERR(cursor_state);
12356 
12357 	/* Cursor is disabled */
12358 	if (!cursor_state->fb)
12359 		return 0;
12360 
12361 	/* For all planes in descending z-order (all of which are below cursor
12362 	 * as per zpos definitions), check their scaling and format
12363 	 */
12364 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
12365 
12366 		/* Only care about non-cursor planes on this CRTC */
12367 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
12368 		    plane->type == DRM_PLANE_TYPE_CURSOR)
12369 			continue;
12370 
12371 		/* Underlying plane is YUV format - use overlay cursor */
12372 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
12373 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12374 			return 0;
12375 		}
12376 
12377 		dm_get_plane_scale(plane_state,
12378 				   &underlying_scale_w, &underlying_scale_h);
12379 		dm_get_plane_scale(cursor_state,
12380 				   &cursor_scale_w, &cursor_scale_h);
12381 
12382 		/* Underlying plane has different scale - use overlay cursor */
12383 		if (cursor_scale_w != underlying_scale_w &&
12384 		    cursor_scale_h != underlying_scale_h) {
12385 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12386 			return 0;
12387 		}
12388 
12389 		/* If this plane covers the whole CRTC, no need to check planes underneath */
12390 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
12391 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
12392 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
12393 			entire_crtc_covered = true;
12394 			break;
12395 		}
12396 	}
12397 
12398 	/* If planes do not cover the entire CRTC, use overlay mode to enable
12399 	 * cursor over holes
12400 	 */
12401 	if (entire_crtc_covered)
12402 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12403 	else
12404 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12405 
12406 	return 0;
12407 }
12408 
12409 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
12410 					    struct drm_atomic_state *state,
12411 					    struct drm_crtc_state *crtc_state)
12412 {
12413 	struct drm_plane *plane;
12414 	struct drm_plane_state *new_plane_state, *old_plane_state;
12415 
12416 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
12417 		new_plane_state = drm_atomic_get_plane_state(state, plane);
12418 		old_plane_state = drm_atomic_get_plane_state(state, plane);
12419 
12420 		if (IS_ERR(new_plane_state) || IS_ERR(old_plane_state)) {
12421 			drm_err(dev, "Failed to get plane state for plane %s\n", plane->name);
12422 			return false;
12423 		}
12424 
12425 		if (old_plane_state->fb && new_plane_state->fb &&
12426 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
12427 			return true;
12428 	}
12429 
12430 	return false;
12431 }
12432 
12433 /**
12434  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
12435  *
12436  * @dev: The DRM device
12437  * @state: The atomic state to commit
12438  *
12439  * Validate that the given atomic state is programmable by DC into hardware.
12440  * This involves constructing a &struct dc_state reflecting the new hardware
12441  * state we wish to commit, then querying DC to see if it is programmable. It's
12442  * important not to modify the existing DC state. Otherwise, atomic_check
12443  * may unexpectedly commit hardware changes.
12444  *
12445  * When validating the DC state, it's important that the right locks are
12446  * acquired. For full updates case which removes/adds/updates streams on one
12447  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
12448  * that any such full update commit will wait for completion of any outstanding
12449  * flip using DRMs synchronization events.
12450  *
12451  * Note that DM adds the affected connectors for all CRTCs in state, when that
12452  * might not seem necessary. This is because DC stream creation requires the
12453  * DC sink, which is tied to the DRM connector state. Cleaning this up should
12454  * be possible but non-trivial - a possible TODO item.
12455  *
12456  * Return: -Error code if validation failed.
12457  */
12458 static int amdgpu_dm_atomic_check(struct drm_device *dev,
12459 				  struct drm_atomic_state *state)
12460 {
12461 	struct amdgpu_device *adev = drm_to_adev(dev);
12462 	struct dm_atomic_state *dm_state = NULL;
12463 	struct dc *dc = adev->dm.dc;
12464 	struct drm_connector *connector;
12465 	struct drm_connector_state *old_con_state, *new_con_state;
12466 	struct drm_crtc *crtc;
12467 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12468 	struct drm_plane *plane;
12469 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
12470 	enum dc_status status;
12471 	int ret, i;
12472 	bool lock_and_validation_needed = false;
12473 	bool is_top_most_overlay = true;
12474 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12475 	struct drm_dp_mst_topology_mgr *mgr;
12476 	struct drm_dp_mst_topology_state *mst_state;
12477 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
12478 
12479 	trace_amdgpu_dm_atomic_check_begin(state);
12480 
12481 	ret = drm_atomic_helper_check_modeset(dev, state);
12482 	if (ret) {
12483 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
12484 		goto fail;
12485 	}
12486 
12487 	/* Check connector changes */
12488 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
12489 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
12490 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
12491 
12492 		/* Skip connectors that are disabled or part of modeset already. */
12493 		if (!new_con_state->crtc)
12494 			continue;
12495 
12496 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
12497 		if (IS_ERR(new_crtc_state)) {
12498 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
12499 			ret = PTR_ERR(new_crtc_state);
12500 			goto fail;
12501 		}
12502 
12503 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
12504 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
12505 			new_crtc_state->connectors_changed = true;
12506 	}
12507 
12508 	if (dc_resource_is_dsc_encoding_supported(dc)) {
12509 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12510 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
12511 				ret = add_affected_mst_dsc_crtcs(state, crtc);
12512 				if (ret) {
12513 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
12514 					goto fail;
12515 				}
12516 			}
12517 		}
12518 	}
12519 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12520 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12521 
12522 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
12523 		    !new_crtc_state->color_mgmt_changed &&
12524 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
12525 			dm_old_crtc_state->dsc_force_changed == false)
12526 			continue;
12527 
12528 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
12529 		if (ret) {
12530 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
12531 			goto fail;
12532 		}
12533 
12534 		if (!new_crtc_state->enable)
12535 			continue;
12536 
12537 		ret = drm_atomic_add_affected_connectors(state, crtc);
12538 		if (ret) {
12539 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
12540 			goto fail;
12541 		}
12542 
12543 		ret = drm_atomic_add_affected_planes(state, crtc);
12544 		if (ret) {
12545 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
12546 			goto fail;
12547 		}
12548 
12549 		if (dm_old_crtc_state->dsc_force_changed)
12550 			new_crtc_state->mode_changed = true;
12551 	}
12552 
12553 	/*
12554 	 * Add all primary and overlay planes on the CRTC to the state
12555 	 * whenever a plane is enabled to maintain correct z-ordering
12556 	 * and to enable fast surface updates.
12557 	 */
12558 	drm_for_each_crtc(crtc, dev) {
12559 		bool modified = false;
12560 
12561 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
12562 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12563 				continue;
12564 
12565 			if (new_plane_state->crtc == crtc ||
12566 			    old_plane_state->crtc == crtc) {
12567 				modified = true;
12568 				break;
12569 			}
12570 		}
12571 
12572 		if (!modified)
12573 			continue;
12574 
12575 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
12576 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12577 				continue;
12578 
12579 			new_plane_state =
12580 				drm_atomic_get_plane_state(state, plane);
12581 
12582 			if (IS_ERR(new_plane_state)) {
12583 				ret = PTR_ERR(new_plane_state);
12584 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
12585 				goto fail;
12586 			}
12587 		}
12588 	}
12589 
12590 	/*
12591 	 * DC consults the zpos (layer_index in DC terminology) to determine the
12592 	 * hw plane on which to enable the hw cursor (see
12593 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
12594 	 * atomic state, so call drm helper to normalize zpos.
12595 	 */
12596 	ret = drm_atomic_normalize_zpos(dev, state);
12597 	if (ret) {
12598 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
12599 		goto fail;
12600 	}
12601 
12602 	/*
12603 	 * Determine whether cursors on each CRTC should be enabled in native or
12604 	 * overlay mode.
12605 	 */
12606 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12607 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12608 
12609 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
12610 					      &dm_new_crtc_state->cursor_mode);
12611 		if (ret) {
12612 			drm_dbg(dev, "Failed to determine cursor mode\n");
12613 			goto fail;
12614 		}
12615 
12616 		/*
12617 		 * If overlay cursor is needed, DC cannot go through the
12618 		 * native cursor update path. All enabled planes on the CRTC
12619 		 * need to be added for DC to not disable a plane by mistake
12620 		 */
12621 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
12622 			ret = drm_atomic_add_affected_planes(state, crtc);
12623 			if (ret)
12624 				goto fail;
12625 		}
12626 	}
12627 
12628 	/* Remove exiting planes if they are modified */
12629 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
12630 
12631 		ret = dm_update_plane_state(dc, state, plane,
12632 					    old_plane_state,
12633 					    new_plane_state,
12634 					    false,
12635 					    &lock_and_validation_needed,
12636 					    &is_top_most_overlay);
12637 		if (ret) {
12638 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
12639 			goto fail;
12640 		}
12641 	}
12642 
12643 	/* Disable all crtcs which require disable */
12644 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12645 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
12646 					   old_crtc_state,
12647 					   new_crtc_state,
12648 					   false,
12649 					   &lock_and_validation_needed);
12650 		if (ret) {
12651 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
12652 			goto fail;
12653 		}
12654 	}
12655 
12656 	/* Enable all crtcs which require enable */
12657 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12658 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
12659 					   old_crtc_state,
12660 					   new_crtc_state,
12661 					   true,
12662 					   &lock_and_validation_needed);
12663 		if (ret) {
12664 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
12665 			goto fail;
12666 		}
12667 	}
12668 
12669 	/* Add new/modified planes */
12670 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
12671 		ret = dm_update_plane_state(dc, state, plane,
12672 					    old_plane_state,
12673 					    new_plane_state,
12674 					    true,
12675 					    &lock_and_validation_needed,
12676 					    &is_top_most_overlay);
12677 		if (ret) {
12678 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
12679 			goto fail;
12680 		}
12681 	}
12682 
12683 #if defined(CONFIG_DRM_AMD_DC_FP)
12684 	if (dc_resource_is_dsc_encoding_supported(dc)) {
12685 		ret = pre_validate_dsc(state, &dm_state, vars);
12686 		if (ret != 0)
12687 			goto fail;
12688 	}
12689 #endif
12690 
12691 	/* Run this here since we want to validate the streams we created */
12692 	ret = drm_atomic_helper_check_planes(dev, state);
12693 	if (ret) {
12694 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
12695 		goto fail;
12696 	}
12697 
12698 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12699 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12700 		if (dm_new_crtc_state->mpo_requested)
12701 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
12702 	}
12703 
12704 	/* Check cursor restrictions */
12705 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12706 		enum amdgpu_dm_cursor_mode required_cursor_mode;
12707 		int is_rotated, is_scaled;
12708 
12709 		/* Overlay cusor not subject to native cursor restrictions */
12710 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12711 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
12712 			continue;
12713 
12714 		/* Check if rotation or scaling is enabled on DCN401 */
12715 		if ((drm_plane_mask(crtc->cursor) & new_crtc_state->plane_mask) &&
12716 		    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1)) {
12717 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
12718 
12719 			is_rotated = new_cursor_state &&
12720 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
12721 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
12722 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
12723 
12724 			if (is_rotated || is_scaled) {
12725 				drm_dbg_driver(
12726 					crtc->dev,
12727 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
12728 					crtc->base.id, crtc->name);
12729 				ret = -EINVAL;
12730 				goto fail;
12731 			}
12732 		}
12733 
12734 		/* If HW can only do native cursor, check restrictions again */
12735 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
12736 					      &required_cursor_mode);
12737 		if (ret) {
12738 			drm_dbg_driver(crtc->dev,
12739 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
12740 				       crtc->base.id, crtc->name);
12741 			goto fail;
12742 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
12743 			drm_dbg_driver(crtc->dev,
12744 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling or YUV restrictions\n",
12745 				       crtc->base.id, crtc->name);
12746 			ret = -EINVAL;
12747 			goto fail;
12748 		}
12749 	}
12750 
12751 	if (state->legacy_cursor_update) {
12752 		/*
12753 		 * This is a fast cursor update coming from the plane update
12754 		 * helper, check if it can be done asynchronously for better
12755 		 * performance.
12756 		 */
12757 		state->async_update =
12758 			!drm_atomic_helper_async_check(dev, state);
12759 
12760 		/*
12761 		 * Skip the remaining global validation if this is an async
12762 		 * update. Cursor updates can be done without affecting
12763 		 * state or bandwidth calcs and this avoids the performance
12764 		 * penalty of locking the private state object and
12765 		 * allocating a new dc_state.
12766 		 */
12767 		if (state->async_update)
12768 			return 0;
12769 	}
12770 
12771 	/* Check scaling and underscan changes*/
12772 	/* TODO Removed scaling changes validation due to inability to commit
12773 	 * new stream into context w\o causing full reset. Need to
12774 	 * decide how to handle.
12775 	 */
12776 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
12777 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
12778 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
12779 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
12780 
12781 		/* Skip any modesets/resets */
12782 		if (!acrtc || drm_atomic_crtc_needs_modeset(
12783 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
12784 			continue;
12785 
12786 		/* Skip any thing not scale or underscan changes */
12787 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
12788 			continue;
12789 
12790 		lock_and_validation_needed = true;
12791 	}
12792 
12793 	/* set the slot info for each mst_state based on the link encoding format */
12794 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
12795 		struct amdgpu_dm_connector *aconnector;
12796 		struct drm_connector *connector;
12797 		struct drm_connector_list_iter iter;
12798 		u8 link_coding_cap;
12799 
12800 		drm_connector_list_iter_begin(dev, &iter);
12801 		drm_for_each_connector_iter(connector, &iter) {
12802 			if (connector->index == mst_state->mgr->conn_base_id) {
12803 				aconnector = to_amdgpu_dm_connector(connector);
12804 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
12805 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
12806 
12807 				break;
12808 			}
12809 		}
12810 		drm_connector_list_iter_end(&iter);
12811 	}
12812 
12813 	/**
12814 	 * Streams and planes are reset when there are changes that affect
12815 	 * bandwidth. Anything that affects bandwidth needs to go through
12816 	 * DC global validation to ensure that the configuration can be applied
12817 	 * to hardware.
12818 	 *
12819 	 * We have to currently stall out here in atomic_check for outstanding
12820 	 * commits to finish in this case because our IRQ handlers reference
12821 	 * DRM state directly - we can end up disabling interrupts too early
12822 	 * if we don't.
12823 	 *
12824 	 * TODO: Remove this stall and drop DM state private objects.
12825 	 */
12826 	if (lock_and_validation_needed) {
12827 		ret = dm_atomic_get_state(state, &dm_state);
12828 		if (ret) {
12829 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
12830 			goto fail;
12831 		}
12832 
12833 		ret = do_aquire_global_lock(dev, state);
12834 		if (ret) {
12835 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
12836 			goto fail;
12837 		}
12838 
12839 #if defined(CONFIG_DRM_AMD_DC_FP)
12840 		if (dc_resource_is_dsc_encoding_supported(dc)) {
12841 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
12842 			if (ret) {
12843 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
12844 				ret = -EINVAL;
12845 				goto fail;
12846 			}
12847 		}
12848 #endif
12849 
12850 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
12851 		if (ret) {
12852 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
12853 			goto fail;
12854 		}
12855 
12856 		/*
12857 		 * Perform validation of MST topology in the state:
12858 		 * We need to perform MST atomic check before calling
12859 		 * dc_validate_global_state(), or there is a chance
12860 		 * to get stuck in an infinite loop and hang eventually.
12861 		 */
12862 		ret = drm_dp_mst_atomic_check(state);
12863 		if (ret) {
12864 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
12865 			goto fail;
12866 		}
12867 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
12868 		if (status != DC_OK) {
12869 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
12870 				       dc_status_to_str(status), status);
12871 			ret = -EINVAL;
12872 			goto fail;
12873 		}
12874 	} else {
12875 		/*
12876 		 * The commit is a fast update. Fast updates shouldn't change
12877 		 * the DC context, affect global validation, and can have their
12878 		 * commit work done in parallel with other commits not touching
12879 		 * the same resource. If we have a new DC context as part of
12880 		 * the DM atomic state from validation we need to free it and
12881 		 * retain the existing one instead.
12882 		 *
12883 		 * Furthermore, since the DM atomic state only contains the DC
12884 		 * context and can safely be annulled, we can free the state
12885 		 * and clear the associated private object now to free
12886 		 * some memory and avoid a possible use-after-free later.
12887 		 */
12888 
12889 		for (i = 0; i < state->num_private_objs; i++) {
12890 			struct drm_private_obj *obj = state->private_objs[i].ptr;
12891 
12892 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
12893 				int j = state->num_private_objs-1;
12894 
12895 				dm_atomic_destroy_state(obj,
12896 						state->private_objs[i].state_to_destroy);
12897 
12898 				/* If i is not at the end of the array then the
12899 				 * last element needs to be moved to where i was
12900 				 * before the array can safely be truncated.
12901 				 */
12902 				if (i != j)
12903 					state->private_objs[i] =
12904 						state->private_objs[j];
12905 
12906 				state->private_objs[j].ptr = NULL;
12907 				state->private_objs[j].state_to_destroy = NULL;
12908 				state->private_objs[j].old_state = NULL;
12909 				state->private_objs[j].new_state = NULL;
12910 
12911 				state->num_private_objs = j;
12912 				break;
12913 			}
12914 		}
12915 	}
12916 
12917 	/* Store the overall update type for use later in atomic check. */
12918 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12919 		struct dm_crtc_state *dm_new_crtc_state =
12920 			to_dm_crtc_state(new_crtc_state);
12921 
12922 		/*
12923 		 * Only allow async flips for fast updates that don't change
12924 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
12925 		 */
12926 		if (new_crtc_state->async_flip &&
12927 		    (lock_and_validation_needed ||
12928 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
12929 			drm_dbg_atomic(crtc->dev,
12930 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
12931 				       crtc->base.id, crtc->name);
12932 			ret = -EINVAL;
12933 			goto fail;
12934 		}
12935 
12936 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
12937 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
12938 	}
12939 
12940 	/* Must be success */
12941 	WARN_ON(ret);
12942 
12943 	trace_amdgpu_dm_atomic_check_finish(state, ret);
12944 
12945 	return ret;
12946 
12947 fail:
12948 	if (ret == -EDEADLK)
12949 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
12950 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
12951 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
12952 	else
12953 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
12954 
12955 	trace_amdgpu_dm_atomic_check_finish(state, ret);
12956 
12957 	return ret;
12958 }
12959 
12960 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
12961 		unsigned int offset,
12962 		unsigned int total_length,
12963 		u8 *data,
12964 		unsigned int length,
12965 		struct amdgpu_hdmi_vsdb_info *vsdb)
12966 {
12967 	bool res;
12968 	union dmub_rb_cmd cmd;
12969 	struct dmub_cmd_send_edid_cea *input;
12970 	struct dmub_cmd_edid_cea_output *output;
12971 
12972 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
12973 		return false;
12974 
12975 	memset(&cmd, 0, sizeof(cmd));
12976 
12977 	input = &cmd.edid_cea.data.input;
12978 
12979 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
12980 	cmd.edid_cea.header.sub_type = 0;
12981 	cmd.edid_cea.header.payload_bytes =
12982 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
12983 	input->offset = offset;
12984 	input->length = length;
12985 	input->cea_total_length = total_length;
12986 	memcpy(input->payload, data, length);
12987 
12988 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
12989 	if (!res) {
12990 		drm_err(adev_to_drm(dm->adev), "EDID CEA parser failed\n");
12991 		return false;
12992 	}
12993 
12994 	output = &cmd.edid_cea.data.output;
12995 
12996 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
12997 		if (!output->ack.success) {
12998 			drm_err(adev_to_drm(dm->adev), "EDID CEA ack failed at offset %d\n",
12999 					output->ack.offset);
13000 		}
13001 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
13002 		if (!output->amd_vsdb.vsdb_found)
13003 			return false;
13004 
13005 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
13006 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
13007 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
13008 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
13009 	} else {
13010 		drm_warn(adev_to_drm(dm->adev), "Unknown EDID CEA parser results\n");
13011 		return false;
13012 	}
13013 
13014 	return true;
13015 }
13016 
13017 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
13018 		u8 *edid_ext, int len,
13019 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13020 {
13021 	int i;
13022 
13023 	/* send extension block to DMCU for parsing */
13024 	for (i = 0; i < len; i += 8) {
13025 		bool res;
13026 		int offset;
13027 
13028 		/* send 8 bytes a time */
13029 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
13030 			return false;
13031 
13032 		if (i+8 == len) {
13033 			/* EDID block sent completed, expect result */
13034 			int version, min_rate, max_rate;
13035 
13036 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
13037 			if (res) {
13038 				/* amd vsdb found */
13039 				vsdb_info->freesync_supported = 1;
13040 				vsdb_info->amd_vsdb_version = version;
13041 				vsdb_info->min_refresh_rate_hz = min_rate;
13042 				vsdb_info->max_refresh_rate_hz = max_rate;
13043 				return true;
13044 			}
13045 			/* not amd vsdb */
13046 			return false;
13047 		}
13048 
13049 		/* check for ack*/
13050 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
13051 		if (!res)
13052 			return false;
13053 	}
13054 
13055 	return false;
13056 }
13057 
13058 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
13059 		u8 *edid_ext, int len,
13060 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13061 {
13062 	int i;
13063 
13064 	/* send extension block to DMCU for parsing */
13065 	for (i = 0; i < len; i += 8) {
13066 		/* send 8 bytes a time */
13067 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
13068 			return false;
13069 	}
13070 
13071 	return vsdb_info->freesync_supported;
13072 }
13073 
13074 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
13075 		u8 *edid_ext, int len,
13076 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13077 {
13078 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
13079 	bool ret;
13080 
13081 	mutex_lock(&adev->dm.dc_lock);
13082 	if (adev->dm.dmub_srv)
13083 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
13084 	else
13085 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
13086 	mutex_unlock(&adev->dm.dc_lock);
13087 	return ret;
13088 }
13089 
13090 static void parse_edid_displayid_vrr(struct drm_connector *connector,
13091 				     const struct edid *edid)
13092 {
13093 	u8 *edid_ext = NULL;
13094 	int i;
13095 	int j = 0;
13096 	u16 min_vfreq;
13097 	u16 max_vfreq;
13098 
13099 	if (edid == NULL || edid->extensions == 0)
13100 		return;
13101 
13102 	/* Find DisplayID extension */
13103 	for (i = 0; i < edid->extensions; i++) {
13104 		edid_ext = (void *)(edid + (i + 1));
13105 		if (edid_ext[0] == DISPLAYID_EXT)
13106 			break;
13107 	}
13108 
13109 	if (edid_ext == NULL)
13110 		return;
13111 
13112 	while (j < EDID_LENGTH) {
13113 		/* Get dynamic video timing range from DisplayID if available */
13114 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
13115 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
13116 			min_vfreq = edid_ext[j+9];
13117 			if (edid_ext[j+1] & 7)
13118 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
13119 			else
13120 				max_vfreq = edid_ext[j+10];
13121 
13122 			if (max_vfreq && min_vfreq) {
13123 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
13124 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
13125 
13126 				return;
13127 			}
13128 		}
13129 		j++;
13130 	}
13131 }
13132 
13133 static int parse_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13134 			  const struct edid *edid, struct amdgpu_hdmi_vsdb_info *vsdb_info)
13135 {
13136 	u8 *edid_ext = NULL;
13137 	int i;
13138 	int j = 0;
13139 
13140 	if (edid == NULL || edid->extensions == 0)
13141 		return -ENODEV;
13142 
13143 	/* Find DisplayID extension */
13144 	for (i = 0; i < edid->extensions; i++) {
13145 		edid_ext = (void *)(edid + (i + 1));
13146 		if (edid_ext[0] == DISPLAYID_EXT)
13147 			break;
13148 	}
13149 
13150 	while (j < EDID_LENGTH - sizeof(struct amd_vsdb_block)) {
13151 		struct amd_vsdb_block *amd_vsdb = (struct amd_vsdb_block *)&edid_ext[j];
13152 		unsigned int ieeeId = (amd_vsdb->ieee_id[2] << 16) | (amd_vsdb->ieee_id[1] << 8) | (amd_vsdb->ieee_id[0]);
13153 
13154 		if (ieeeId == HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_IEEE_REGISTRATION_ID &&
13155 				amd_vsdb->version == HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_VERSION_3) {
13156 			u8 panel_type;
13157 			vsdb_info->replay_mode = (amd_vsdb->feature_caps & AMD_VSDB_VERSION_3_FEATURECAP_REPLAYMODE) ? true : false;
13158 			vsdb_info->amd_vsdb_version = HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_VERSION_3;
13159 			drm_dbg_kms(aconnector->base.dev, "Panel supports Replay Mode: %d\n", vsdb_info->replay_mode);
13160 			panel_type = (amd_vsdb->color_space_eotf_support & AMD_VDSB_VERSION_3_PANEL_TYPE_MASK) >> AMD_VDSB_VERSION_3_PANEL_TYPE_SHIFT;
13161 			switch (panel_type) {
13162 			case AMD_VSDB_PANEL_TYPE_OLED:
13163 				aconnector->dc_link->panel_type = PANEL_TYPE_OLED;
13164 				break;
13165 			case AMD_VSDB_PANEL_TYPE_MINILED:
13166 				aconnector->dc_link->panel_type = PANEL_TYPE_MINILED;
13167 				break;
13168 			default:
13169 				aconnector->dc_link->panel_type = PANEL_TYPE_NONE;
13170 				break;
13171 			}
13172 			drm_dbg_kms(aconnector->base.dev, "Panel type: %d\n",
13173 				    aconnector->dc_link->panel_type);
13174 
13175 			return true;
13176 		}
13177 		j++;
13178 	}
13179 
13180 	return false;
13181 }
13182 
13183 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13184 			       const struct edid *edid,
13185 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
13186 {
13187 	u8 *edid_ext = NULL;
13188 	int i;
13189 	bool valid_vsdb_found = false;
13190 
13191 	/*----- drm_find_cea_extension() -----*/
13192 	/* No EDID or EDID extensions */
13193 	if (edid == NULL || edid->extensions == 0)
13194 		return -ENODEV;
13195 
13196 	/* Find CEA extension */
13197 	for (i = 0; i < edid->extensions; i++) {
13198 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
13199 		if (edid_ext[0] == CEA_EXT)
13200 			break;
13201 	}
13202 
13203 	if (i == edid->extensions)
13204 		return -ENODEV;
13205 
13206 	/*----- cea_db_offsets() -----*/
13207 	if (edid_ext[0] != CEA_EXT)
13208 		return -ENODEV;
13209 
13210 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
13211 
13212 	return valid_vsdb_found ? i : -ENODEV;
13213 }
13214 
13215 /**
13216  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
13217  *
13218  * @connector: Connector to query.
13219  * @drm_edid: DRM EDID from monitor
13220  *
13221  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
13222  * track of some of the display information in the internal data struct used by
13223  * amdgpu_dm. This function checks which type of connector we need to set the
13224  * FreeSync parameters.
13225  */
13226 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
13227 				    const struct drm_edid *drm_edid)
13228 {
13229 	int i = 0;
13230 	struct amdgpu_dm_connector *amdgpu_dm_connector =
13231 			to_amdgpu_dm_connector(connector);
13232 	struct dm_connector_state *dm_con_state = NULL;
13233 	struct dc_sink *sink;
13234 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
13235 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
13236 	const struct edid *edid;
13237 	bool freesync_capable = false;
13238 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
13239 
13240 	if (!connector->state) {
13241 		drm_err(adev_to_drm(adev), "%s - Connector has no state", __func__);
13242 		goto update;
13243 	}
13244 
13245 	sink = amdgpu_dm_connector->dc_sink ?
13246 		amdgpu_dm_connector->dc_sink :
13247 		amdgpu_dm_connector->dc_em_sink;
13248 
13249 	drm_edid_connector_update(connector, drm_edid);
13250 
13251 	if (!drm_edid || !sink) {
13252 		dm_con_state = to_dm_connector_state(connector->state);
13253 
13254 		amdgpu_dm_connector->min_vfreq = 0;
13255 		amdgpu_dm_connector->max_vfreq = 0;
13256 		freesync_capable = false;
13257 
13258 		goto update;
13259 	}
13260 
13261 	dm_con_state = to_dm_connector_state(connector->state);
13262 
13263 	if (!adev->dm.freesync_module || !dc_supports_vrr(sink->ctx->dce_version))
13264 		goto update;
13265 
13266 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
13267 
13268 	/* Some eDP panels only have the refresh rate range info in DisplayID */
13269 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
13270 	     connector->display_info.monitor_range.max_vfreq == 0))
13271 		parse_edid_displayid_vrr(connector, edid);
13272 
13273 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
13274 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
13275 		if (amdgpu_dm_connector->dc_link &&
13276 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
13277 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
13278 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
13279 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13280 				freesync_capable = true;
13281 		}
13282 
13283 		parse_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13284 
13285 		if (vsdb_info.replay_mode) {
13286 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
13287 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
13288 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
13289 		}
13290 
13291 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
13292 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13293 		if (i >= 0 && vsdb_info.freesync_supported) {
13294 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13295 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13296 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13297 				freesync_capable = true;
13298 
13299 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13300 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13301 		}
13302 	}
13303 
13304 	if (amdgpu_dm_connector->dc_link)
13305 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
13306 
13307 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
13308 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13309 		if (i >= 0 && vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
13310 
13311 			amdgpu_dm_connector->pack_sdp_v1_3 = true;
13312 			amdgpu_dm_connector->as_type = as_type;
13313 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13314 
13315 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13316 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13317 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13318 				freesync_capable = true;
13319 
13320 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13321 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13322 		}
13323 	}
13324 
13325 update:
13326 	if (dm_con_state)
13327 		dm_con_state->freesync_capable = freesync_capable;
13328 
13329 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
13330 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
13331 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
13332 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
13333 	}
13334 
13335 	if (connector->vrr_capable_property)
13336 		drm_connector_set_vrr_capable_property(connector,
13337 						       freesync_capable);
13338 }
13339 
13340 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
13341 {
13342 	struct amdgpu_device *adev = drm_to_adev(dev);
13343 	struct dc *dc = adev->dm.dc;
13344 	int i;
13345 
13346 	mutex_lock(&adev->dm.dc_lock);
13347 	if (dc->current_state) {
13348 		for (i = 0; i < dc->current_state->stream_count; ++i)
13349 			dc->current_state->streams[i]
13350 				->triggered_crtc_reset.enabled =
13351 				adev->dm.force_timing_sync;
13352 
13353 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
13354 		dc_trigger_sync(dc, dc->current_state);
13355 	}
13356 	mutex_unlock(&adev->dm.dc_lock);
13357 }
13358 
13359 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
13360 {
13361 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
13362 		dc_exit_ips_for_hw_access(dc);
13363 }
13364 
13365 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
13366 		       u32 value, const char *func_name)
13367 {
13368 #ifdef DM_CHECK_ADDR_0
13369 	if (address == 0) {
13370 		drm_err(adev_to_drm(ctx->driver_context),
13371 			"invalid register write. address = 0");
13372 		return;
13373 	}
13374 #endif
13375 
13376 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13377 	cgs_write_register(ctx->cgs_device, address, value);
13378 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
13379 }
13380 
13381 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
13382 			  const char *func_name)
13383 {
13384 	u32 value;
13385 #ifdef DM_CHECK_ADDR_0
13386 	if (address == 0) {
13387 		drm_err(adev_to_drm(ctx->driver_context),
13388 			"invalid register read; address = 0\n");
13389 		return 0;
13390 	}
13391 #endif
13392 
13393 	if (ctx->dmub_srv &&
13394 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
13395 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
13396 		ASSERT(false);
13397 		return 0;
13398 	}
13399 
13400 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13401 
13402 	value = cgs_read_register(ctx->cgs_device, address);
13403 
13404 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
13405 
13406 	return value;
13407 }
13408 
13409 int amdgpu_dm_process_dmub_aux_transfer_sync(
13410 		struct dc_context *ctx,
13411 		unsigned int link_index,
13412 		struct aux_payload *payload,
13413 		enum aux_return_code_type *operation_result)
13414 {
13415 	struct amdgpu_device *adev = ctx->driver_context;
13416 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
13417 	int ret = -1;
13418 
13419 	mutex_lock(&adev->dm.dpia_aux_lock);
13420 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
13421 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
13422 		goto out;
13423 	}
13424 
13425 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13426 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13427 		*operation_result = AUX_RET_ERROR_TIMEOUT;
13428 		goto out;
13429 	}
13430 
13431 	if (p_notify->result != AUX_RET_SUCCESS) {
13432 		/*
13433 		 * Transient states before tunneling is enabled could
13434 		 * lead to this error. We can ignore this for now.
13435 		 */
13436 		if (p_notify->result == AUX_RET_ERROR_PROTOCOL_ERROR) {
13437 			drm_warn(adev_to_drm(adev), "DPIA AUX failed on 0x%x(%d), error %d\n",
13438 					payload->address, payload->length,
13439 					p_notify->result);
13440 		}
13441 		*operation_result = p_notify->result;
13442 		goto out;
13443 	}
13444 
13445 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command & 0xF;
13446 	if (adev->dm.dmub_notify->aux_reply.command & 0xF0)
13447 		/* The reply is stored in the top nibble of the command. */
13448 		payload->reply[0] = (adev->dm.dmub_notify->aux_reply.command >> 4) & 0xF;
13449 
13450 	/*write req may receive a byte indicating partially written number as well*/
13451 	if (p_notify->aux_reply.length)
13452 		memcpy(payload->data, p_notify->aux_reply.data,
13453 				p_notify->aux_reply.length);
13454 
13455 	/* success */
13456 	ret = p_notify->aux_reply.length;
13457 	*operation_result = p_notify->result;
13458 out:
13459 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
13460 	mutex_unlock(&adev->dm.dpia_aux_lock);
13461 	return ret;
13462 }
13463 
13464 static void abort_fused_io(
13465 		struct dc_context *ctx,
13466 		const struct dmub_cmd_fused_request *request
13467 )
13468 {
13469 	union dmub_rb_cmd command = { 0 };
13470 	struct dmub_rb_cmd_fused_io *io = &command.fused_io;
13471 
13472 	io->header.type = DMUB_CMD__FUSED_IO;
13473 	io->header.sub_type = DMUB_CMD__FUSED_IO_ABORT;
13474 	io->header.payload_bytes = sizeof(*io) - sizeof(io->header);
13475 	io->request = *request;
13476 	dm_execute_dmub_cmd(ctx, &command, DM_DMUB_WAIT_TYPE_NO_WAIT);
13477 }
13478 
13479 static bool execute_fused_io(
13480 		struct amdgpu_device *dev,
13481 		struct dc_context *ctx,
13482 		union dmub_rb_cmd *commands,
13483 		uint8_t count,
13484 		uint32_t timeout_us
13485 )
13486 {
13487 	const uint8_t ddc_line = commands[0].fused_io.request.u.aux.ddc_line;
13488 
13489 	if (ddc_line >= ARRAY_SIZE(dev->dm.fused_io))
13490 		return false;
13491 
13492 	struct fused_io_sync *sync = &dev->dm.fused_io[ddc_line];
13493 	struct dmub_rb_cmd_fused_io *first = &commands[0].fused_io;
13494 	const bool result = dm_execute_dmub_cmd_list(ctx, count, commands, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY)
13495 			&& first->header.ret_status
13496 			&& first->request.status == FUSED_REQUEST_STATUS_SUCCESS;
13497 
13498 	if (!result)
13499 		return false;
13500 
13501 	while (wait_for_completion_timeout(&sync->replied, usecs_to_jiffies(timeout_us))) {
13502 		reinit_completion(&sync->replied);
13503 
13504 		struct dmub_cmd_fused_request *reply = (struct dmub_cmd_fused_request *) sync->reply_data;
13505 
13506 		static_assert(sizeof(*reply) <= sizeof(sync->reply_data), "Size mismatch");
13507 
13508 		if (reply->identifier == first->request.identifier) {
13509 			first->request = *reply;
13510 			return true;
13511 		}
13512 	}
13513 
13514 	reinit_completion(&sync->replied);
13515 	first->request.status = FUSED_REQUEST_STATUS_TIMEOUT;
13516 	abort_fused_io(ctx, &first->request);
13517 	return false;
13518 }
13519 
13520 bool amdgpu_dm_execute_fused_io(
13521 		struct amdgpu_device *dev,
13522 		struct dc_link *link,
13523 		union dmub_rb_cmd *commands,
13524 		uint8_t count,
13525 		uint32_t timeout_us)
13526 {
13527 	struct amdgpu_display_manager *dm = &dev->dm;
13528 
13529 	mutex_lock(&dm->dpia_aux_lock);
13530 
13531 	const bool result = execute_fused_io(dev, link->ctx, commands, count, timeout_us);
13532 
13533 	mutex_unlock(&dm->dpia_aux_lock);
13534 	return result;
13535 }
13536 
13537 int amdgpu_dm_process_dmub_set_config_sync(
13538 		struct dc_context *ctx,
13539 		unsigned int link_index,
13540 		struct set_config_cmd_payload *payload,
13541 		enum set_config_status *operation_result)
13542 {
13543 	struct amdgpu_device *adev = ctx->driver_context;
13544 	bool is_cmd_complete;
13545 	int ret;
13546 
13547 	mutex_lock(&adev->dm.dpia_aux_lock);
13548 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
13549 			link_index, payload, adev->dm.dmub_notify);
13550 
13551 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13552 		ret = 0;
13553 		*operation_result = adev->dm.dmub_notify->sc_status;
13554 	} else {
13555 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13556 		ret = -1;
13557 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
13558 	}
13559 
13560 	if (!is_cmd_complete)
13561 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
13562 	mutex_unlock(&adev->dm.dpia_aux_lock);
13563 	return ret;
13564 }
13565 
13566 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
13567 {
13568 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
13569 }
13570 
13571 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)
13572 {
13573 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
13574 }
13575 
13576 void dm_acpi_process_phy_transition_interlock(
13577 	const struct dc_context *ctx,
13578 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
13579 {
13580 	// Not yet implemented
13581 }
13582