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