xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision 0b39cb143d214fac7e30696ac1c53fad563fbb1a)
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.gfxversion = DcGfxVersion9;
8036 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
8037 	dc_plane_state->rotation = ROTATION_ANGLE_0;
8038 	dc_plane_state->is_tiling_rotated = false;
8039 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
8040 
8041 	dc_result = dc_validate_stream(dc, stream);
8042 	if (dc_result == DC_OK)
8043 		dc_result = dc_validate_plane(dc, dc_plane_state);
8044 
8045 	if (dc_result == DC_OK)
8046 		dc_result = dc_state_add_stream(dc, dc_state, stream);
8047 
8048 	if (dc_result == DC_OK && !dc_state_add_plane(
8049 						dc,
8050 						stream,
8051 						dc_plane_state,
8052 						dc_state))
8053 		dc_result = DC_FAIL_ATTACH_SURFACES;
8054 
8055 	if (dc_result == DC_OK)
8056 		dc_result = dc_validate_global_state(dc, dc_state, DC_VALIDATE_MODE_ONLY);
8057 
8058 cleanup:
8059 	if (dc_state)
8060 		dc_state_release(dc_state);
8061 
8062 	if (dc_plane_state)
8063 		dc_plane_state_release(dc_plane_state);
8064 
8065 	return dc_result;
8066 }
8067 
8068 struct dc_stream_state *
8069 create_validate_stream_for_sink(struct drm_connector *connector,
8070 				const struct drm_display_mode *drm_mode,
8071 				const struct dm_connector_state *dm_state,
8072 				const struct dc_stream_state *old_stream)
8073 {
8074 	struct amdgpu_dm_connector *aconnector = NULL;
8075 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8076 	struct dc_stream_state *stream;
8077 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
8078 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
8079 	enum dc_status dc_result = DC_OK;
8080 	uint8_t bpc_limit = 6;
8081 
8082 	if (!dm_state)
8083 		return NULL;
8084 
8085 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
8086 		aconnector = to_amdgpu_dm_connector(connector);
8087 
8088 	if (aconnector &&
8089 	    (aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
8090 	     aconnector->dc_link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER))
8091 		bpc_limit = 8;
8092 
8093 	do {
8094 		drm_dbg_kms(connector->dev, "Trying with %d bpc\n", requested_bpc);
8095 		stream = create_stream_for_sink(connector, drm_mode,
8096 						dm_state, old_stream,
8097 						requested_bpc);
8098 		if (stream == NULL) {
8099 			drm_err(adev_to_drm(adev), "Failed to create stream for sink!\n");
8100 			break;
8101 		}
8102 
8103 		dc_result = dc_validate_stream(adev->dm.dc, stream);
8104 
8105 		if (!aconnector) /* writeback connector */
8106 			return stream;
8107 
8108 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
8109 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
8110 
8111 		if (dc_result == DC_OK)
8112 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
8113 
8114 		if (dc_result != DC_OK) {
8115 			drm_dbg_kms(connector->dev, "Pruned mode %d x %d (clk %d) %s %s -- %s\n",
8116 				      drm_mode->hdisplay,
8117 				      drm_mode->vdisplay,
8118 				      drm_mode->clock,
8119 				      dc_pixel_encoding_to_str(stream->timing.pixel_encoding),
8120 				      dc_color_depth_to_str(stream->timing.display_color_depth),
8121 				      dc_status_to_str(dc_result));
8122 
8123 			dc_stream_release(stream);
8124 			stream = NULL;
8125 			requested_bpc -= 2; /* lower bpc to retry validation */
8126 		}
8127 
8128 	} while (stream == NULL && requested_bpc >= bpc_limit);
8129 
8130 	switch (dc_result) {
8131 	/*
8132 	 * If we failed to validate DP bandwidth stream with the requested RGB color depth,
8133 	 * we try to fallback and configure in order:
8134 	 * YUV422 (8bpc, 6bpc)
8135 	 * YUV420 (8bpc, 6bpc)
8136 	 */
8137 	case DC_FAIL_ENC_VALIDATE:
8138 	case DC_EXCEED_DONGLE_CAP:
8139 	case DC_NO_DP_LINK_BANDWIDTH:
8140 		/* recursively entered twice and already tried both YUV422 and YUV420 */
8141 		if (aconnector->force_yuv422_output && aconnector->force_yuv420_output)
8142 			break;
8143 		/* first failure; try YUV422 */
8144 		if (!aconnector->force_yuv422_output) {
8145 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV422\n",
8146 				    __func__, __LINE__, dc_result);
8147 			aconnector->force_yuv422_output = true;
8148 		/* recursively entered and YUV422 failed, try YUV420 */
8149 		} else if (!aconnector->force_yuv420_output) {
8150 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV420\n",
8151 				    __func__, __LINE__, dc_result);
8152 			aconnector->force_yuv420_output = true;
8153 		}
8154 		stream = create_validate_stream_for_sink(connector, drm_mode,
8155 							 dm_state, old_stream);
8156 		aconnector->force_yuv422_output = false;
8157 		aconnector->force_yuv420_output = false;
8158 		break;
8159 	case DC_OK:
8160 		break;
8161 	default:
8162 		drm_dbg_kms(connector->dev, "%s:%d Unhandled validation failure %d\n",
8163 			    __func__, __LINE__, dc_result);
8164 		break;
8165 	}
8166 
8167 	return stream;
8168 }
8169 
8170 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
8171 				   const struct drm_display_mode *mode)
8172 {
8173 	int result = MODE_ERROR;
8174 	struct dc_sink *dc_sink;
8175 	struct drm_display_mode *test_mode;
8176 	/* TODO: Unhardcode stream count */
8177 	struct dc_stream_state *stream;
8178 	/* we always have an amdgpu_dm_connector here since we got
8179 	 * here via the amdgpu_dm_connector_helper_funcs
8180 	 */
8181 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8182 
8183 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
8184 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
8185 		return result;
8186 
8187 	/*
8188 	 * Only run this the first time mode_valid is called to initilialize
8189 	 * EDID mgmt
8190 	 */
8191 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
8192 		!aconnector->dc_em_sink)
8193 		handle_edid_mgmt(aconnector);
8194 
8195 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
8196 
8197 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
8198 				aconnector->base.force != DRM_FORCE_ON) {
8199 		drm_err(connector->dev, "dc_sink is NULL!\n");
8200 		goto fail;
8201 	}
8202 
8203 	test_mode = drm_mode_duplicate(connector->dev, mode);
8204 	if (!test_mode)
8205 		goto fail;
8206 
8207 	drm_mode_set_crtcinfo(test_mode, 0);
8208 
8209 	stream = create_validate_stream_for_sink(connector, test_mode,
8210 						 to_dm_connector_state(connector->state),
8211 						 NULL);
8212 	drm_mode_destroy(connector->dev, test_mode);
8213 	if (stream) {
8214 		dc_stream_release(stream);
8215 		result = MODE_OK;
8216 	}
8217 
8218 fail:
8219 	/* TODO: error handling*/
8220 	return result;
8221 }
8222 
8223 static int fill_hdr_info_packet(const struct drm_connector_state *state,
8224 				struct dc_info_packet *out)
8225 {
8226 	struct hdmi_drm_infoframe frame;
8227 	unsigned char buf[30]; /* 26 + 4 */
8228 	ssize_t len;
8229 	int ret, i;
8230 
8231 	memset(out, 0, sizeof(*out));
8232 
8233 	if (!state->hdr_output_metadata)
8234 		return 0;
8235 
8236 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
8237 	if (ret)
8238 		return ret;
8239 
8240 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
8241 	if (len < 0)
8242 		return (int)len;
8243 
8244 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
8245 	if (len != 30)
8246 		return -EINVAL;
8247 
8248 	/* Prepare the infopacket for DC. */
8249 	switch (state->connector->connector_type) {
8250 	case DRM_MODE_CONNECTOR_HDMIA:
8251 		out->hb0 = 0x87; /* type */
8252 		out->hb1 = 0x01; /* version */
8253 		out->hb2 = 0x1A; /* length */
8254 		out->sb[0] = buf[3]; /* checksum */
8255 		i = 1;
8256 		break;
8257 
8258 	case DRM_MODE_CONNECTOR_DisplayPort:
8259 	case DRM_MODE_CONNECTOR_eDP:
8260 		out->hb0 = 0x00; /* sdp id, zero */
8261 		out->hb1 = 0x87; /* type */
8262 		out->hb2 = 0x1D; /* payload len - 1 */
8263 		out->hb3 = (0x13 << 2); /* sdp version */
8264 		out->sb[0] = 0x01; /* version */
8265 		out->sb[1] = 0x1A; /* length */
8266 		i = 2;
8267 		break;
8268 
8269 	default:
8270 		return -EINVAL;
8271 	}
8272 
8273 	memcpy(&out->sb[i], &buf[4], 26);
8274 	out->valid = true;
8275 
8276 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
8277 		       sizeof(out->sb), false);
8278 
8279 	return 0;
8280 }
8281 
8282 static int
8283 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
8284 				 struct drm_atomic_state *state)
8285 {
8286 	struct drm_connector_state *new_con_state =
8287 		drm_atomic_get_new_connector_state(state, conn);
8288 	struct drm_connector_state *old_con_state =
8289 		drm_atomic_get_old_connector_state(state, conn);
8290 	struct drm_crtc *crtc = new_con_state->crtc;
8291 	struct drm_crtc_state *new_crtc_state;
8292 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
8293 	int ret;
8294 
8295 	if (WARN_ON(unlikely(!old_con_state || !new_con_state)))
8296 		return -EINVAL;
8297 
8298 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
8299 
8300 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
8301 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
8302 		if (ret < 0)
8303 			return ret;
8304 	}
8305 
8306 	if (!crtc)
8307 		return 0;
8308 
8309 	if (new_con_state->privacy_screen_sw_state != old_con_state->privacy_screen_sw_state) {
8310 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8311 		if (IS_ERR(new_crtc_state))
8312 			return PTR_ERR(new_crtc_state);
8313 
8314 		new_crtc_state->mode_changed = true;
8315 	}
8316 
8317 	if (new_con_state->colorspace != old_con_state->colorspace) {
8318 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8319 		if (IS_ERR(new_crtc_state))
8320 			return PTR_ERR(new_crtc_state);
8321 
8322 		new_crtc_state->mode_changed = true;
8323 	}
8324 
8325 	if (new_con_state->content_type != old_con_state->content_type) {
8326 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8327 		if (IS_ERR(new_crtc_state))
8328 			return PTR_ERR(new_crtc_state);
8329 
8330 		new_crtc_state->mode_changed = true;
8331 	}
8332 
8333 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
8334 		struct dc_info_packet hdr_infopacket;
8335 
8336 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
8337 		if (ret)
8338 			return ret;
8339 
8340 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8341 		if (IS_ERR(new_crtc_state))
8342 			return PTR_ERR(new_crtc_state);
8343 
8344 		/*
8345 		 * DC considers the stream backends changed if the
8346 		 * static metadata changes. Forcing the modeset also
8347 		 * gives a simple way for userspace to switch from
8348 		 * 8bpc to 10bpc when setting the metadata to enter
8349 		 * or exit HDR.
8350 		 *
8351 		 * Changing the static metadata after it's been
8352 		 * set is permissible, however. So only force a
8353 		 * modeset if we're entering or exiting HDR.
8354 		 */
8355 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
8356 			!old_con_state->hdr_output_metadata ||
8357 			!new_con_state->hdr_output_metadata;
8358 	}
8359 
8360 	return 0;
8361 }
8362 
8363 static const struct drm_connector_helper_funcs
8364 amdgpu_dm_connector_helper_funcs = {
8365 	/*
8366 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
8367 	 * modes will be filtered by drm_mode_validate_size(), and those modes
8368 	 * are missing after user start lightdm. So we need to renew modes list.
8369 	 * in get_modes call back, not just return the modes count
8370 	 */
8371 	.get_modes = get_modes,
8372 	.mode_valid = amdgpu_dm_connector_mode_valid,
8373 	.atomic_check = amdgpu_dm_connector_atomic_check,
8374 };
8375 
8376 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
8377 {
8378 
8379 }
8380 
8381 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
8382 {
8383 	switch (display_color_depth) {
8384 	case COLOR_DEPTH_666:
8385 		return 6;
8386 	case COLOR_DEPTH_888:
8387 		return 8;
8388 	case COLOR_DEPTH_101010:
8389 		return 10;
8390 	case COLOR_DEPTH_121212:
8391 		return 12;
8392 	case COLOR_DEPTH_141414:
8393 		return 14;
8394 	case COLOR_DEPTH_161616:
8395 		return 16;
8396 	default:
8397 		break;
8398 	}
8399 	return 0;
8400 }
8401 
8402 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
8403 					  struct drm_crtc_state *crtc_state,
8404 					  struct drm_connector_state *conn_state)
8405 {
8406 	struct drm_atomic_state *state = crtc_state->state;
8407 	struct drm_connector *connector = conn_state->connector;
8408 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8409 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
8410 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
8411 	struct drm_dp_mst_topology_mgr *mst_mgr;
8412 	struct drm_dp_mst_port *mst_port;
8413 	struct drm_dp_mst_topology_state *mst_state;
8414 	enum dc_color_depth color_depth;
8415 	int clock, bpp = 0;
8416 	bool is_y420 = false;
8417 
8418 	if ((connector->connector_type == DRM_MODE_CONNECTOR_eDP) ||
8419 	    (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)) {
8420 		struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8421 		struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8422 		enum drm_mode_status result;
8423 
8424 		result = drm_crtc_helper_mode_valid_fixed(encoder->crtc, adjusted_mode, native_mode);
8425 		if (result != MODE_OK && dm_new_connector_state->scaling == RMX_OFF) {
8426 			drm_dbg_driver(encoder->dev,
8427 				       "mode %dx%d@%dHz is not native, enabling scaling\n",
8428 				       adjusted_mode->hdisplay, adjusted_mode->vdisplay,
8429 				       drm_mode_vrefresh(adjusted_mode));
8430 			dm_new_connector_state->scaling = RMX_ASPECT;
8431 		}
8432 		return 0;
8433 	}
8434 
8435 	if (!aconnector->mst_output_port)
8436 		return 0;
8437 
8438 	mst_port = aconnector->mst_output_port;
8439 	mst_mgr = &aconnector->mst_root->mst_mgr;
8440 
8441 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
8442 		return 0;
8443 
8444 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
8445 	if (IS_ERR(mst_state))
8446 		return PTR_ERR(mst_state);
8447 
8448 	mst_state->pbn_div.full = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
8449 
8450 	if (!state->duplicated) {
8451 		int max_bpc = conn_state->max_requested_bpc;
8452 
8453 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
8454 			  aconnector->force_yuv420_output;
8455 		color_depth = convert_color_depth_from_display_info(connector,
8456 								    is_y420,
8457 								    max_bpc);
8458 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
8459 		clock = adjusted_mode->clock;
8460 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
8461 	}
8462 
8463 	dm_new_connector_state->vcpi_slots =
8464 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
8465 					      dm_new_connector_state->pbn);
8466 	if (dm_new_connector_state->vcpi_slots < 0) {
8467 		drm_dbg_atomic(connector->dev, "failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
8468 		return dm_new_connector_state->vcpi_slots;
8469 	}
8470 	return 0;
8471 }
8472 
8473 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
8474 	.disable = dm_encoder_helper_disable,
8475 	.atomic_check = dm_encoder_helper_atomic_check
8476 };
8477 
8478 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state *state,
8479 					    struct dc_state *dc_state,
8480 					    struct dsc_mst_fairness_vars *vars)
8481 {
8482 	struct dc_stream_state *stream = NULL;
8483 	struct drm_connector *connector;
8484 	struct drm_connector_state *new_con_state;
8485 	struct amdgpu_dm_connector *aconnector;
8486 	struct dm_connector_state *dm_conn_state;
8487 	int i, j, ret;
8488 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
8489 
8490 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8491 
8492 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
8493 			continue;
8494 
8495 		aconnector = to_amdgpu_dm_connector(connector);
8496 
8497 		if (!aconnector->mst_output_port)
8498 			continue;
8499 
8500 		if (!new_con_state || !new_con_state->crtc)
8501 			continue;
8502 
8503 		dm_conn_state = to_dm_connector_state(new_con_state);
8504 
8505 		for (j = 0; j < dc_state->stream_count; j++) {
8506 			stream = dc_state->streams[j];
8507 			if (!stream)
8508 				continue;
8509 
8510 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
8511 				break;
8512 
8513 			stream = NULL;
8514 		}
8515 
8516 		if (!stream)
8517 			continue;
8518 
8519 		pbn_div = dm_mst_get_pbn_divider(stream->link);
8520 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
8521 		for (j = 0; j < dc_state->stream_count; j++) {
8522 			if (vars[j].aconnector == aconnector) {
8523 				pbn = vars[j].pbn;
8524 				break;
8525 			}
8526 		}
8527 
8528 		if (j == dc_state->stream_count || pbn_div == 0)
8529 			continue;
8530 
8531 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
8532 
8533 		if (stream->timing.flags.DSC != 1) {
8534 			dm_conn_state->pbn = pbn;
8535 			dm_conn_state->vcpi_slots = slot_num;
8536 
8537 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
8538 							   dm_conn_state->pbn, false);
8539 			if (ret < 0)
8540 				return ret;
8541 
8542 			continue;
8543 		}
8544 
8545 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
8546 		if (vcpi < 0)
8547 			return vcpi;
8548 
8549 		dm_conn_state->pbn = pbn;
8550 		dm_conn_state->vcpi_slots = vcpi;
8551 	}
8552 	return 0;
8553 }
8554 
8555 static int to_drm_connector_type(enum signal_type st, uint32_t connector_id)
8556 {
8557 	switch (st) {
8558 	case SIGNAL_TYPE_HDMI_TYPE_A:
8559 		return DRM_MODE_CONNECTOR_HDMIA;
8560 	case SIGNAL_TYPE_EDP:
8561 		return DRM_MODE_CONNECTOR_eDP;
8562 	case SIGNAL_TYPE_LVDS:
8563 		return DRM_MODE_CONNECTOR_LVDS;
8564 	case SIGNAL_TYPE_RGB:
8565 		return DRM_MODE_CONNECTOR_VGA;
8566 	case SIGNAL_TYPE_DISPLAY_PORT:
8567 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
8568 		return DRM_MODE_CONNECTOR_DisplayPort;
8569 	case SIGNAL_TYPE_DVI_DUAL_LINK:
8570 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
8571 		if (connector_id == CONNECTOR_ID_SINGLE_LINK_DVII ||
8572 			connector_id == CONNECTOR_ID_DUAL_LINK_DVII)
8573 			return DRM_MODE_CONNECTOR_DVII;
8574 
8575 		return DRM_MODE_CONNECTOR_DVID;
8576 	case SIGNAL_TYPE_VIRTUAL:
8577 		return DRM_MODE_CONNECTOR_VIRTUAL;
8578 
8579 	default:
8580 		return DRM_MODE_CONNECTOR_Unknown;
8581 	}
8582 }
8583 
8584 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
8585 {
8586 	struct drm_encoder *encoder;
8587 
8588 	/* There is only one encoder per connector */
8589 	drm_connector_for_each_possible_encoder(connector, encoder)
8590 		return encoder;
8591 
8592 	return NULL;
8593 }
8594 
8595 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
8596 {
8597 	struct drm_encoder *encoder;
8598 	struct amdgpu_encoder *amdgpu_encoder;
8599 
8600 	encoder = amdgpu_dm_connector_to_encoder(connector);
8601 
8602 	if (encoder == NULL)
8603 		return;
8604 
8605 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8606 
8607 	amdgpu_encoder->native_mode.clock = 0;
8608 
8609 	if (!list_empty(&connector->probed_modes)) {
8610 		struct drm_display_mode *preferred_mode = NULL;
8611 
8612 		list_for_each_entry(preferred_mode,
8613 				    &connector->probed_modes,
8614 				    head) {
8615 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
8616 				amdgpu_encoder->native_mode = *preferred_mode;
8617 
8618 			break;
8619 		}
8620 
8621 	}
8622 }
8623 
8624 static struct drm_display_mode *
8625 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
8626 			     const char *name,
8627 			     int hdisplay, int vdisplay)
8628 {
8629 	struct drm_device *dev = encoder->dev;
8630 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8631 	struct drm_display_mode *mode = NULL;
8632 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8633 
8634 	mode = drm_mode_duplicate(dev, native_mode);
8635 
8636 	if (mode == NULL)
8637 		return NULL;
8638 
8639 	mode->hdisplay = hdisplay;
8640 	mode->vdisplay = vdisplay;
8641 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8642 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
8643 
8644 	return mode;
8645 
8646 }
8647 
8648 static const struct amdgpu_dm_mode_size {
8649 	char name[DRM_DISPLAY_MODE_LEN];
8650 	int w;
8651 	int h;
8652 } common_modes[] = {
8653 	{  "640x480",  640,  480},
8654 	{  "800x600",  800,  600},
8655 	{ "1024x768", 1024,  768},
8656 	{ "1280x720", 1280,  720},
8657 	{ "1280x800", 1280,  800},
8658 	{"1280x1024", 1280, 1024},
8659 	{ "1440x900", 1440,  900},
8660 	{"1680x1050", 1680, 1050},
8661 	{"1600x1200", 1600, 1200},
8662 	{"1920x1080", 1920, 1080},
8663 	{"1920x1200", 1920, 1200}
8664 };
8665 
8666 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
8667 						 struct drm_connector *connector)
8668 {
8669 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8670 	struct drm_display_mode *mode = NULL;
8671 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8672 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8673 				to_amdgpu_dm_connector(connector);
8674 	int i;
8675 	int n;
8676 
8677 	if ((connector->connector_type != DRM_MODE_CONNECTOR_eDP) &&
8678 	    (connector->connector_type != DRM_MODE_CONNECTOR_LVDS))
8679 		return;
8680 
8681 	n = ARRAY_SIZE(common_modes);
8682 
8683 	for (i = 0; i < n; i++) {
8684 		struct drm_display_mode *curmode = NULL;
8685 		bool mode_existed = false;
8686 
8687 		if (common_modes[i].w > native_mode->hdisplay ||
8688 		    common_modes[i].h > native_mode->vdisplay ||
8689 		   (common_modes[i].w == native_mode->hdisplay &&
8690 		    common_modes[i].h == native_mode->vdisplay))
8691 			continue;
8692 
8693 		list_for_each_entry(curmode, &connector->probed_modes, head) {
8694 			if (common_modes[i].w == curmode->hdisplay &&
8695 			    common_modes[i].h == curmode->vdisplay) {
8696 				mode_existed = true;
8697 				break;
8698 			}
8699 		}
8700 
8701 		if (mode_existed)
8702 			continue;
8703 
8704 		mode = amdgpu_dm_create_common_mode(encoder,
8705 				common_modes[i].name, common_modes[i].w,
8706 				common_modes[i].h);
8707 		if (!mode)
8708 			continue;
8709 
8710 		drm_mode_probed_add(connector, mode);
8711 		amdgpu_dm_connector->num_modes++;
8712 	}
8713 }
8714 
8715 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
8716 {
8717 	struct drm_encoder *encoder;
8718 	struct amdgpu_encoder *amdgpu_encoder;
8719 	const struct drm_display_mode *native_mode;
8720 
8721 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
8722 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
8723 		return;
8724 
8725 	mutex_lock(&connector->dev->mode_config.mutex);
8726 	amdgpu_dm_connector_get_modes(connector);
8727 	mutex_unlock(&connector->dev->mode_config.mutex);
8728 
8729 	encoder = amdgpu_dm_connector_to_encoder(connector);
8730 	if (!encoder)
8731 		return;
8732 
8733 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8734 
8735 	native_mode = &amdgpu_encoder->native_mode;
8736 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
8737 		return;
8738 
8739 	drm_connector_set_panel_orientation_with_quirk(connector,
8740 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
8741 						       native_mode->hdisplay,
8742 						       native_mode->vdisplay);
8743 }
8744 
8745 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
8746 					      const struct drm_edid *drm_edid)
8747 {
8748 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8749 			to_amdgpu_dm_connector(connector);
8750 
8751 	if (drm_edid) {
8752 		/* empty probed_modes */
8753 		INIT_LIST_HEAD(&connector->probed_modes);
8754 		amdgpu_dm_connector->num_modes =
8755 				drm_edid_connector_add_modes(connector);
8756 
8757 		/* sorting the probed modes before calling function
8758 		 * amdgpu_dm_get_native_mode() since EDID can have
8759 		 * more than one preferred mode. The modes that are
8760 		 * later in the probed mode list could be of higher
8761 		 * and preferred resolution. For example, 3840x2160
8762 		 * resolution in base EDID preferred timing and 4096x2160
8763 		 * preferred resolution in DID extension block later.
8764 		 */
8765 		drm_mode_sort(&connector->probed_modes);
8766 		amdgpu_dm_get_native_mode(connector);
8767 
8768 		/* Freesync capabilities are reset by calling
8769 		 * drm_edid_connector_add_modes() and need to be
8770 		 * restored here.
8771 		 */
8772 		amdgpu_dm_update_freesync_caps(connector, drm_edid);
8773 	} else {
8774 		amdgpu_dm_connector->num_modes = 0;
8775 	}
8776 }
8777 
8778 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
8779 			      struct drm_display_mode *mode)
8780 {
8781 	struct drm_display_mode *m;
8782 
8783 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
8784 		if (drm_mode_equal(m, mode))
8785 			return true;
8786 	}
8787 
8788 	return false;
8789 }
8790 
8791 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
8792 {
8793 	const struct drm_display_mode *m;
8794 	struct drm_display_mode *new_mode;
8795 	uint i;
8796 	u32 new_modes_count = 0;
8797 
8798 	/* Standard FPS values
8799 	 *
8800 	 * 23.976       - TV/NTSC
8801 	 * 24           - Cinema
8802 	 * 25           - TV/PAL
8803 	 * 29.97        - TV/NTSC
8804 	 * 30           - TV/NTSC
8805 	 * 48           - Cinema HFR
8806 	 * 50           - TV/PAL
8807 	 * 60           - Commonly used
8808 	 * 48,72,96,120 - Multiples of 24
8809 	 */
8810 	static const u32 common_rates[] = {
8811 		23976, 24000, 25000, 29970, 30000,
8812 		48000, 50000, 60000, 72000, 96000, 120000
8813 	};
8814 
8815 	/*
8816 	 * Find mode with highest refresh rate with the same resolution
8817 	 * as the preferred mode. Some monitors report a preferred mode
8818 	 * with lower resolution than the highest refresh rate supported.
8819 	 */
8820 
8821 	m = get_highest_refresh_rate_mode(aconnector, true);
8822 	if (!m)
8823 		return 0;
8824 
8825 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
8826 		u64 target_vtotal, target_vtotal_diff;
8827 		u64 num, den;
8828 
8829 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
8830 			continue;
8831 
8832 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
8833 		    common_rates[i] > aconnector->max_vfreq * 1000)
8834 			continue;
8835 
8836 		num = (unsigned long long)m->clock * 1000 * 1000;
8837 		den = common_rates[i] * (unsigned long long)m->htotal;
8838 		target_vtotal = div_u64(num, den);
8839 		target_vtotal_diff = target_vtotal - m->vtotal;
8840 
8841 		/* Check for illegal modes */
8842 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
8843 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
8844 		    m->vtotal + target_vtotal_diff < m->vsync_end)
8845 			continue;
8846 
8847 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
8848 		if (!new_mode)
8849 			goto out;
8850 
8851 		new_mode->vtotal += (u16)target_vtotal_diff;
8852 		new_mode->vsync_start += (u16)target_vtotal_diff;
8853 		new_mode->vsync_end += (u16)target_vtotal_diff;
8854 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8855 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
8856 
8857 		if (!is_duplicate_mode(aconnector, new_mode)) {
8858 			drm_mode_probed_add(&aconnector->base, new_mode);
8859 			new_modes_count += 1;
8860 		} else
8861 			drm_mode_destroy(aconnector->base.dev, new_mode);
8862 	}
8863  out:
8864 	return new_modes_count;
8865 }
8866 
8867 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
8868 						   const struct drm_edid *drm_edid)
8869 {
8870 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8871 		to_amdgpu_dm_connector(connector);
8872 
8873 	if (!(amdgpu_freesync_vid_mode && drm_edid))
8874 		return;
8875 
8876 	if (!amdgpu_dm_connector->dc_sink || !amdgpu_dm_connector->dc_link)
8877 		return;
8878 
8879 	if (!dc_supports_vrr(amdgpu_dm_connector->dc_sink->ctx->dce_version))
8880 		return;
8881 
8882 	if (dc_connector_supports_analog(amdgpu_dm_connector->dc_link->link_id.id) &&
8883 	    amdgpu_dm_connector->dc_sink->edid_caps.analog)
8884 		return;
8885 
8886 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
8887 		amdgpu_dm_connector->num_modes +=
8888 			add_fs_modes(amdgpu_dm_connector);
8889 }
8890 
8891 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
8892 {
8893 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8894 			to_amdgpu_dm_connector(connector);
8895 	struct dc_link *dc_link = amdgpu_dm_connector->dc_link;
8896 	struct drm_encoder *encoder;
8897 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
8898 	struct dc_link_settings *verified_link_cap = &dc_link->verified_link_cap;
8899 	const struct dc *dc = dc_link->dc;
8900 
8901 	encoder = amdgpu_dm_connector_to_encoder(connector);
8902 
8903 	if (!drm_edid) {
8904 		amdgpu_dm_connector->num_modes =
8905 				drm_add_modes_noedid(connector, 640, 480);
8906 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
8907 			amdgpu_dm_connector->num_modes +=
8908 				drm_add_modes_noedid(connector, 1920, 1080);
8909 
8910 		if (amdgpu_dm_connector->dc_sink &&
8911 		    amdgpu_dm_connector->dc_sink->edid_caps.analog &&
8912 		    dc_connector_supports_analog(dc_link->link_id.id)) {
8913 			/* Analog monitor connected by DAC load detection.
8914 			 * Add common modes. It will be up to the user to select one that works.
8915 			 */
8916 			for (int i = 0; i < ARRAY_SIZE(common_modes); i++)
8917 				amdgpu_dm_connector->num_modes += drm_add_modes_noedid(
8918 					connector, common_modes[i].w, common_modes[i].h);
8919 		}
8920 	} else {
8921 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
8922 		if (encoder)
8923 			amdgpu_dm_connector_add_common_modes(encoder, connector);
8924 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
8925 	}
8926 	amdgpu_dm_fbc_init(connector);
8927 
8928 	return amdgpu_dm_connector->num_modes;
8929 }
8930 
8931 static const u32 supported_colorspaces =
8932 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
8933 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
8934 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
8935 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
8936 
8937 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
8938 				     struct amdgpu_dm_connector *aconnector,
8939 				     int connector_type,
8940 				     struct dc_link *link,
8941 				     int link_index)
8942 {
8943 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
8944 
8945 	/*
8946 	 * Some of the properties below require access to state, like bpc.
8947 	 * Allocate some default initial connector state with our reset helper.
8948 	 */
8949 	if (aconnector->base.funcs->reset)
8950 		aconnector->base.funcs->reset(&aconnector->base);
8951 
8952 	aconnector->connector_id = link_index;
8953 	aconnector->bl_idx = -1;
8954 	aconnector->dc_link = link;
8955 	aconnector->base.interlace_allowed = false;
8956 	aconnector->base.doublescan_allowed = false;
8957 	aconnector->base.stereo_allowed = false;
8958 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
8959 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
8960 	aconnector->audio_inst = -1;
8961 	aconnector->pack_sdp_v1_3 = false;
8962 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
8963 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
8964 	mutex_init(&aconnector->hpd_lock);
8965 	mutex_init(&aconnector->handle_mst_msg_ready);
8966 
8967 	/*
8968 	 * If HDMI HPD debounce delay is set, use the minimum between selected
8969 	 * value and AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS
8970 	 */
8971 	if (amdgpu_hdmi_hpd_debounce_delay_ms) {
8972 		aconnector->hdmi_hpd_debounce_delay_ms = min(amdgpu_hdmi_hpd_debounce_delay_ms,
8973 							     AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS);
8974 		INIT_DELAYED_WORK(&aconnector->hdmi_hpd_debounce_work, hdmi_hpd_debounce_work);
8975 		aconnector->hdmi_prev_sink = NULL;
8976 	} else {
8977 		aconnector->hdmi_hpd_debounce_delay_ms = 0;
8978 	}
8979 
8980 	/*
8981 	 * configure support HPD hot plug connector_>polled default value is 0
8982 	 * which means HPD hot plug not supported
8983 	 */
8984 	switch (connector_type) {
8985 	case DRM_MODE_CONNECTOR_HDMIA:
8986 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
8987 		aconnector->base.ycbcr_420_allowed =
8988 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
8989 		break;
8990 	case DRM_MODE_CONNECTOR_DisplayPort:
8991 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
8992 		link->link_enc = link_enc_cfg_get_link_enc(link);
8993 		ASSERT(link->link_enc);
8994 		if (link->link_enc)
8995 			aconnector->base.ycbcr_420_allowed =
8996 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
8997 		break;
8998 	case DRM_MODE_CONNECTOR_DVID:
8999 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9000 		break;
9001 	case DRM_MODE_CONNECTOR_DVII:
9002 	case DRM_MODE_CONNECTOR_VGA:
9003 		aconnector->base.polled =
9004 			DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT;
9005 		break;
9006 	default:
9007 		break;
9008 	}
9009 
9010 	drm_object_attach_property(&aconnector->base.base,
9011 				dm->ddev->mode_config.scaling_mode_property,
9012 				DRM_MODE_SCALE_NONE);
9013 
9014 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA
9015 		|| (connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root))
9016 		drm_connector_attach_broadcast_rgb_property(&aconnector->base);
9017 
9018 	drm_object_attach_property(&aconnector->base.base,
9019 				adev->mode_info.underscan_property,
9020 				UNDERSCAN_OFF);
9021 	drm_object_attach_property(&aconnector->base.base,
9022 				adev->mode_info.underscan_hborder_property,
9023 				0);
9024 	drm_object_attach_property(&aconnector->base.base,
9025 				adev->mode_info.underscan_vborder_property,
9026 				0);
9027 
9028 	if (!aconnector->mst_root)
9029 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
9030 
9031 	aconnector->base.state->max_bpc = 16;
9032 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
9033 
9034 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9035 		/* Content Type is currently only implemented for HDMI. */
9036 		drm_connector_attach_content_type_property(&aconnector->base);
9037 	}
9038 
9039 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9040 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
9041 			drm_connector_attach_colorspace_property(&aconnector->base);
9042 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
9043 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
9044 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
9045 			drm_connector_attach_colorspace_property(&aconnector->base);
9046 	}
9047 
9048 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9049 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
9050 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
9051 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
9052 
9053 		if (!aconnector->mst_root)
9054 			drm_connector_attach_vrr_capable_property(&aconnector->base);
9055 
9056 		if (adev->dm.hdcp_workqueue)
9057 			drm_connector_attach_content_protection_property(&aconnector->base, true);
9058 	}
9059 
9060 	if (connector_type == DRM_MODE_CONNECTOR_eDP) {
9061 		struct drm_privacy_screen *privacy_screen;
9062 
9063 		privacy_screen = drm_privacy_screen_get(adev_to_drm(adev)->dev, NULL);
9064 		if (!IS_ERR(privacy_screen)) {
9065 			drm_connector_attach_privacy_screen_provider(&aconnector->base,
9066 								     privacy_screen);
9067 		} else if (PTR_ERR(privacy_screen) != -ENODEV) {
9068 			drm_warn(adev_to_drm(adev), "Error getting privacy-screen\n");
9069 		}
9070 	}
9071 }
9072 
9073 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
9074 			      struct i2c_msg *msgs, int num)
9075 {
9076 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
9077 	struct ddc_service *ddc_service = i2c->ddc_service;
9078 	struct i2c_command cmd;
9079 	int i;
9080 	int result = -EIO;
9081 
9082 	if (!ddc_service->ddc_pin)
9083 		return result;
9084 
9085 	cmd.payloads = kcalloc(num, sizeof(struct i2c_payload), GFP_KERNEL);
9086 
9087 	if (!cmd.payloads)
9088 		return result;
9089 
9090 	cmd.number_of_payloads = num;
9091 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
9092 	cmd.speed = 100;
9093 
9094 	for (i = 0; i < num; i++) {
9095 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
9096 		cmd.payloads[i].address = msgs[i].addr;
9097 		cmd.payloads[i].length = msgs[i].len;
9098 		cmd.payloads[i].data = msgs[i].buf;
9099 	}
9100 
9101 	if (i2c->oem) {
9102 		if (dc_submit_i2c_oem(
9103 			    ddc_service->ctx->dc,
9104 			    &cmd))
9105 			result = num;
9106 	} else {
9107 		if (dc_submit_i2c(
9108 			    ddc_service->ctx->dc,
9109 			    ddc_service->link->link_index,
9110 			    &cmd))
9111 			result = num;
9112 	}
9113 
9114 	kfree(cmd.payloads);
9115 	return result;
9116 }
9117 
9118 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
9119 {
9120 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
9121 }
9122 
9123 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
9124 	.master_xfer = amdgpu_dm_i2c_xfer,
9125 	.functionality = amdgpu_dm_i2c_func,
9126 };
9127 
9128 static struct amdgpu_i2c_adapter *
9129 create_i2c(struct ddc_service *ddc_service, bool oem)
9130 {
9131 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
9132 	struct amdgpu_i2c_adapter *i2c;
9133 
9134 	i2c = kzalloc(sizeof(struct amdgpu_i2c_adapter), GFP_KERNEL);
9135 	if (!i2c)
9136 		return NULL;
9137 	i2c->base.owner = THIS_MODULE;
9138 	i2c->base.dev.parent = &adev->pdev->dev;
9139 	i2c->base.algo = &amdgpu_dm_i2c_algo;
9140 	if (oem)
9141 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c OEM bus");
9142 	else
9143 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d",
9144 			 ddc_service->link->link_index);
9145 	i2c_set_adapdata(&i2c->base, i2c);
9146 	i2c->ddc_service = ddc_service;
9147 	i2c->oem = oem;
9148 
9149 	return i2c;
9150 }
9151 
9152 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
9153 {
9154 	struct cec_connector_info conn_info;
9155 	struct drm_device *ddev = aconnector->base.dev;
9156 	struct device *hdmi_dev = ddev->dev;
9157 
9158 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
9159 		drm_info(ddev, "HDMI-CEC feature masked\n");
9160 		return -EINVAL;
9161 	}
9162 
9163 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
9164 	aconnector->notifier =
9165 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
9166 	if (!aconnector->notifier) {
9167 		drm_err(ddev, "Failed to create cec notifier\n");
9168 		return -ENOMEM;
9169 	}
9170 
9171 	return 0;
9172 }
9173 
9174 /*
9175  * Note: this function assumes that dc_link_detect() was called for the
9176  * dc_link which will be represented by this aconnector.
9177  */
9178 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
9179 				    struct amdgpu_dm_connector *aconnector,
9180 				    u32 link_index,
9181 				    struct amdgpu_encoder *aencoder)
9182 {
9183 	int res = 0;
9184 	int connector_type;
9185 	struct dc *dc = dm->dc;
9186 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
9187 	struct amdgpu_i2c_adapter *i2c;
9188 
9189 	/* Not needed for writeback connector */
9190 	link->priv = aconnector;
9191 
9192 
9193 	i2c = create_i2c(link->ddc, false);
9194 	if (!i2c) {
9195 		drm_err(adev_to_drm(dm->adev), "Failed to create i2c adapter data\n");
9196 		return -ENOMEM;
9197 	}
9198 
9199 	aconnector->i2c = i2c;
9200 	res = devm_i2c_add_adapter(dm->adev->dev, &i2c->base);
9201 
9202 	if (res) {
9203 		drm_err(adev_to_drm(dm->adev), "Failed to register hw i2c %d\n", link->link_index);
9204 		goto out_free;
9205 	}
9206 
9207 	connector_type = to_drm_connector_type(link->connector_signal, link->link_id.id);
9208 
9209 	res = drm_connector_init_with_ddc(
9210 			dm->ddev,
9211 			&aconnector->base,
9212 			&amdgpu_dm_connector_funcs,
9213 			connector_type,
9214 			&i2c->base);
9215 
9216 	if (res) {
9217 		drm_err(adev_to_drm(dm->adev), "connector_init failed\n");
9218 		aconnector->connector_id = -1;
9219 		goto out_free;
9220 	}
9221 
9222 	drm_connector_helper_add(
9223 			&aconnector->base,
9224 			&amdgpu_dm_connector_helper_funcs);
9225 
9226 	amdgpu_dm_connector_init_helper(
9227 		dm,
9228 		aconnector,
9229 		connector_type,
9230 		link,
9231 		link_index);
9232 
9233 	drm_connector_attach_encoder(
9234 		&aconnector->base, &aencoder->base);
9235 
9236 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9237 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
9238 		amdgpu_dm_initialize_hdmi_connector(aconnector);
9239 
9240 	if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
9241 		|| connector_type == DRM_MODE_CONNECTOR_eDP)
9242 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
9243 
9244 out_free:
9245 	if (res) {
9246 		kfree(i2c);
9247 		aconnector->i2c = NULL;
9248 	}
9249 	return res;
9250 }
9251 
9252 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
9253 {
9254 	switch (adev->mode_info.num_crtc) {
9255 	case 1:
9256 		return 0x1;
9257 	case 2:
9258 		return 0x3;
9259 	case 3:
9260 		return 0x7;
9261 	case 4:
9262 		return 0xf;
9263 	case 5:
9264 		return 0x1f;
9265 	case 6:
9266 	default:
9267 		return 0x3f;
9268 	}
9269 }
9270 
9271 static int amdgpu_dm_encoder_init(struct drm_device *dev,
9272 				  struct amdgpu_encoder *aencoder,
9273 				  uint32_t link_index)
9274 {
9275 	struct amdgpu_device *adev = drm_to_adev(dev);
9276 
9277 	int res = drm_encoder_init(dev,
9278 				   &aencoder->base,
9279 				   &amdgpu_dm_encoder_funcs,
9280 				   DRM_MODE_ENCODER_TMDS,
9281 				   NULL);
9282 
9283 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
9284 
9285 	if (!res)
9286 		aencoder->encoder_id = link_index;
9287 	else
9288 		aencoder->encoder_id = -1;
9289 
9290 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
9291 
9292 	return res;
9293 }
9294 
9295 static void manage_dm_interrupts(struct amdgpu_device *adev,
9296 				 struct amdgpu_crtc *acrtc,
9297 				 struct dm_crtc_state *acrtc_state)
9298 {	/*
9299 	 * We cannot be sure that the frontend index maps to the same
9300 	 * backend index - some even map to more than one.
9301 	 * So we have to go through the CRTC to find the right IRQ.
9302 	 */
9303 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
9304 			adev,
9305 			acrtc->crtc_id);
9306 	struct drm_device *dev = adev_to_drm(adev);
9307 
9308 	struct drm_vblank_crtc_config config = {0};
9309 	struct dc_crtc_timing *timing;
9310 	int offdelay;
9311 
9312 	if (acrtc_state) {
9313 		timing = &acrtc_state->stream->timing;
9314 
9315 		/*
9316 		 * Depending on when the HW latching event of double-buffered
9317 		 * registers happen relative to the PSR SDP deadline, and how
9318 		 * bad the Panel clock has drifted since the last ALPM off
9319 		 * event, there can be up to 3 frames of delay between sending
9320 		 * the PSR exit cmd to DMUB fw, and when the panel starts
9321 		 * displaying live frames.
9322 		 *
9323 		 * We can set:
9324 		 *
9325 		 * 20/100 * offdelay_ms = 3_frames_ms
9326 		 * => offdelay_ms = 5 * 3_frames_ms
9327 		 *
9328 		 * This ensures that `3_frames_ms` will only be experienced as a
9329 		 * 20% delay on top how long the display has been static, and
9330 		 * thus make the delay less perceivable.
9331 		 */
9332 		if (acrtc_state->stream->link->psr_settings.psr_version <
9333 		    DC_PSR_VERSION_UNSUPPORTED) {
9334 			offdelay = DIV64_U64_ROUND_UP((u64)5 * 3 * 10 *
9335 						      timing->v_total *
9336 						      timing->h_total,
9337 						      timing->pix_clk_100hz);
9338 			config.offdelay_ms = offdelay ?: 30;
9339 		} else if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
9340 			   IP_VERSION(3, 5, 0) ||
9341 			   !(adev->flags & AMD_IS_APU)) {
9342 			/*
9343 			 * Older HW and DGPU have issues with instant off;
9344 			 * use a 2 frame offdelay.
9345 			 */
9346 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
9347 						      timing->v_total *
9348 						      timing->h_total,
9349 						      timing->pix_clk_100hz);
9350 
9351 			config.offdelay_ms = offdelay ?: 30;
9352 		} else {
9353 			/* offdelay_ms = 0 will never disable vblank */
9354 			config.offdelay_ms = 1;
9355 			config.disable_immediate = true;
9356 		}
9357 
9358 		drm_crtc_vblank_on_config(&acrtc->base,
9359 					  &config);
9360 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_get.*/
9361 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9362 		case IP_VERSION(3, 0, 0):
9363 		case IP_VERSION(3, 0, 2):
9364 		case IP_VERSION(3, 0, 3):
9365 		case IP_VERSION(3, 2, 0):
9366 			if (amdgpu_irq_get(adev, &adev->pageflip_irq, irq_type))
9367 				drm_err(dev, "DM_IRQ: Cannot get pageflip irq!\n");
9368 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9369 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
9370 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
9371 #endif
9372 		}
9373 
9374 	} else {
9375 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
9376 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9377 		case IP_VERSION(3, 0, 0):
9378 		case IP_VERSION(3, 0, 2):
9379 		case IP_VERSION(3, 0, 3):
9380 		case IP_VERSION(3, 2, 0):
9381 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9382 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
9383 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
9384 #endif
9385 			if (amdgpu_irq_put(adev, &adev->pageflip_irq, irq_type))
9386 				drm_err(dev, "DM_IRQ: Cannot put pageflip irq!\n");
9387 		}
9388 
9389 		drm_crtc_vblank_off(&acrtc->base);
9390 	}
9391 }
9392 
9393 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
9394 				      struct amdgpu_crtc *acrtc)
9395 {
9396 	int irq_type =
9397 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
9398 
9399 	/**
9400 	 * This reads the current state for the IRQ and force reapplies
9401 	 * the setting to hardware.
9402 	 */
9403 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
9404 }
9405 
9406 static bool
9407 is_scaling_state_different(const struct dm_connector_state *dm_state,
9408 			   const struct dm_connector_state *old_dm_state)
9409 {
9410 	if (dm_state->scaling != old_dm_state->scaling)
9411 		return true;
9412 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
9413 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
9414 			return true;
9415 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
9416 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
9417 			return true;
9418 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
9419 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
9420 		return true;
9421 	return false;
9422 }
9423 
9424 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
9425 					    struct drm_crtc_state *old_crtc_state,
9426 					    struct drm_connector_state *new_conn_state,
9427 					    struct drm_connector_state *old_conn_state,
9428 					    const struct drm_connector *connector,
9429 					    struct hdcp_workqueue *hdcp_w)
9430 {
9431 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
9432 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
9433 
9434 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
9435 		connector->index, connector->status, connector->dpms);
9436 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
9437 		old_conn_state->content_protection, new_conn_state->content_protection);
9438 
9439 	if (old_crtc_state)
9440 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9441 		old_crtc_state->enable,
9442 		old_crtc_state->active,
9443 		old_crtc_state->mode_changed,
9444 		old_crtc_state->active_changed,
9445 		old_crtc_state->connectors_changed);
9446 
9447 	if (new_crtc_state)
9448 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9449 		new_crtc_state->enable,
9450 		new_crtc_state->active,
9451 		new_crtc_state->mode_changed,
9452 		new_crtc_state->active_changed,
9453 		new_crtc_state->connectors_changed);
9454 
9455 	/* hdcp content type change */
9456 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
9457 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
9458 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9459 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
9460 		return true;
9461 	}
9462 
9463 	/* CP is being re enabled, ignore this */
9464 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
9465 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9466 		if (new_crtc_state && new_crtc_state->mode_changed) {
9467 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9468 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
9469 			return true;
9470 		}
9471 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
9472 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
9473 		return false;
9474 	}
9475 
9476 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
9477 	 *
9478 	 * Handles:	UNDESIRED -> ENABLED
9479 	 */
9480 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
9481 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
9482 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9483 
9484 	/* Stream removed and re-enabled
9485 	 *
9486 	 * Can sometimes overlap with the HPD case,
9487 	 * thus set update_hdcp to false to avoid
9488 	 * setting HDCP multiple times.
9489 	 *
9490 	 * Handles:	DESIRED -> DESIRED (Special case)
9491 	 */
9492 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
9493 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
9494 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9495 		dm_con_state->update_hdcp = false;
9496 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
9497 			__func__);
9498 		return true;
9499 	}
9500 
9501 	/* Hot-plug, headless s3, dpms
9502 	 *
9503 	 * Only start HDCP if the display is connected/enabled.
9504 	 * update_hdcp flag will be set to false until the next
9505 	 * HPD comes in.
9506 	 *
9507 	 * Handles:	DESIRED -> DESIRED (Special case)
9508 	 */
9509 	if (dm_con_state->update_hdcp &&
9510 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
9511 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
9512 		dm_con_state->update_hdcp = false;
9513 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
9514 			__func__);
9515 		return true;
9516 	}
9517 
9518 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
9519 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9520 			if (new_crtc_state && new_crtc_state->mode_changed) {
9521 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
9522 					__func__);
9523 				return true;
9524 			}
9525 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
9526 				__func__);
9527 			return false;
9528 		}
9529 
9530 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
9531 		return false;
9532 	}
9533 
9534 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9535 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
9536 			__func__);
9537 		return true;
9538 	}
9539 
9540 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
9541 	return false;
9542 }
9543 
9544 static void remove_stream(struct amdgpu_device *adev,
9545 			  struct amdgpu_crtc *acrtc,
9546 			  struct dc_stream_state *stream)
9547 {
9548 	/* this is the update mode case */
9549 
9550 	acrtc->otg_inst = -1;
9551 	acrtc->enabled = false;
9552 }
9553 
9554 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
9555 {
9556 
9557 	assert_spin_locked(&acrtc->base.dev->event_lock);
9558 	WARN_ON(acrtc->event);
9559 
9560 	acrtc->event = acrtc->base.state->event;
9561 
9562 	/* Set the flip status */
9563 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
9564 
9565 	/* Mark this event as consumed */
9566 	acrtc->base.state->event = NULL;
9567 
9568 	drm_dbg_state(acrtc->base.dev,
9569 		      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
9570 		      acrtc->crtc_id);
9571 }
9572 
9573 static void update_freesync_state_on_stream(
9574 	struct amdgpu_display_manager *dm,
9575 	struct dm_crtc_state *new_crtc_state,
9576 	struct dc_stream_state *new_stream,
9577 	struct dc_plane_state *surface,
9578 	u32 flip_timestamp_in_us)
9579 {
9580 	struct mod_vrr_params vrr_params;
9581 	struct dc_info_packet vrr_infopacket = {0};
9582 	struct amdgpu_device *adev = dm->adev;
9583 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9584 	unsigned long flags;
9585 	bool pack_sdp_v1_3 = false;
9586 	struct amdgpu_dm_connector *aconn;
9587 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
9588 
9589 	if (!new_stream)
9590 		return;
9591 
9592 	/*
9593 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9594 	 * For now it's sufficient to just guard against these conditions.
9595 	 */
9596 
9597 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9598 		return;
9599 
9600 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9601 	vrr_params = acrtc->dm_irq_params.vrr_params;
9602 
9603 	if (surface) {
9604 		mod_freesync_handle_preflip(
9605 			dm->freesync_module,
9606 			surface,
9607 			new_stream,
9608 			flip_timestamp_in_us,
9609 			&vrr_params);
9610 
9611 		if (adev->family < AMDGPU_FAMILY_AI &&
9612 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
9613 			mod_freesync_handle_v_update(dm->freesync_module,
9614 						     new_stream, &vrr_params);
9615 
9616 			/* Need to call this before the frame ends. */
9617 			dc_stream_adjust_vmin_vmax(dm->dc,
9618 						   new_crtc_state->stream,
9619 						   &vrr_params.adjust);
9620 		}
9621 	}
9622 
9623 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
9624 
9625 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
9626 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
9627 
9628 		if (aconn->vsdb_info.amd_vsdb_version == 1)
9629 			packet_type = PACKET_TYPE_FS_V1;
9630 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
9631 			packet_type = PACKET_TYPE_FS_V2;
9632 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
9633 			packet_type = PACKET_TYPE_FS_V3;
9634 
9635 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
9636 					&new_stream->adaptive_sync_infopacket);
9637 	}
9638 
9639 	mod_freesync_build_vrr_infopacket(
9640 		dm->freesync_module,
9641 		new_stream,
9642 		&vrr_params,
9643 		packet_type,
9644 		TRANSFER_FUNC_UNKNOWN,
9645 		&vrr_infopacket,
9646 		pack_sdp_v1_3);
9647 
9648 	new_crtc_state->freesync_vrr_info_changed |=
9649 		(memcmp(&new_crtc_state->vrr_infopacket,
9650 			&vrr_infopacket,
9651 			sizeof(vrr_infopacket)) != 0);
9652 
9653 	acrtc->dm_irq_params.vrr_params = vrr_params;
9654 	new_crtc_state->vrr_infopacket = vrr_infopacket;
9655 
9656 	new_stream->vrr_infopacket = vrr_infopacket;
9657 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
9658 
9659 	if (new_crtc_state->freesync_vrr_info_changed)
9660 		drm_dbg_kms(adev_to_drm(adev), "VRR packet update: crtc=%u enabled=%d state=%d",
9661 			      new_crtc_state->base.crtc->base.id,
9662 			      (int)new_crtc_state->base.vrr_enabled,
9663 			      (int)vrr_params.state);
9664 
9665 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9666 }
9667 
9668 static void update_stream_irq_parameters(
9669 	struct amdgpu_display_manager *dm,
9670 	struct dm_crtc_state *new_crtc_state)
9671 {
9672 	struct dc_stream_state *new_stream = new_crtc_state->stream;
9673 	struct mod_vrr_params vrr_params;
9674 	struct mod_freesync_config config = new_crtc_state->freesync_config;
9675 	struct amdgpu_device *adev = dm->adev;
9676 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9677 	unsigned long flags;
9678 
9679 	if (!new_stream)
9680 		return;
9681 
9682 	/*
9683 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9684 	 * For now it's sufficient to just guard against these conditions.
9685 	 */
9686 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9687 		return;
9688 
9689 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9690 	vrr_params = acrtc->dm_irq_params.vrr_params;
9691 
9692 	if (new_crtc_state->vrr_supported &&
9693 	    config.min_refresh_in_uhz &&
9694 	    config.max_refresh_in_uhz) {
9695 		/*
9696 		 * if freesync compatible mode was set, config.state will be set
9697 		 * in atomic check
9698 		 */
9699 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
9700 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
9701 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
9702 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
9703 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
9704 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
9705 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
9706 		} else {
9707 			config.state = new_crtc_state->base.vrr_enabled ?
9708 						     VRR_STATE_ACTIVE_VARIABLE :
9709 						     VRR_STATE_INACTIVE;
9710 		}
9711 	} else {
9712 		config.state = VRR_STATE_UNSUPPORTED;
9713 	}
9714 
9715 	mod_freesync_build_vrr_params(dm->freesync_module,
9716 				      new_stream,
9717 				      &config, &vrr_params);
9718 
9719 	new_crtc_state->freesync_config = config;
9720 	/* Copy state for access from DM IRQ handler */
9721 	acrtc->dm_irq_params.freesync_config = config;
9722 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
9723 	acrtc->dm_irq_params.vrr_params = vrr_params;
9724 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9725 }
9726 
9727 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
9728 					    struct dm_crtc_state *new_state)
9729 {
9730 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
9731 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
9732 
9733 	if (!old_vrr_active && new_vrr_active) {
9734 		/* Transition VRR inactive -> active:
9735 		 * While VRR is active, we must not disable vblank irq, as a
9736 		 * reenable after disable would compute bogus vblank/pflip
9737 		 * timestamps if it likely happened inside display front-porch.
9738 		 *
9739 		 * We also need vupdate irq for the actual core vblank handling
9740 		 * at end of vblank.
9741 		 */
9742 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
9743 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
9744 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR off->on: Get vblank ref\n",
9745 				 __func__, new_state->base.crtc->base.id);
9746 	} else if (old_vrr_active && !new_vrr_active) {
9747 		/* Transition VRR active -> inactive:
9748 		 * Allow vblank irq disable again for fixed refresh rate.
9749 		 */
9750 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
9751 		drm_crtc_vblank_put(new_state->base.crtc);
9752 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR on->off: Drop vblank ref\n",
9753 				 __func__, new_state->base.crtc->base.id);
9754 	}
9755 }
9756 
9757 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
9758 {
9759 	struct drm_plane *plane;
9760 	struct drm_plane_state *old_plane_state;
9761 	int i;
9762 
9763 	/*
9764 	 * TODO: Make this per-stream so we don't issue redundant updates for
9765 	 * commits with multiple streams.
9766 	 */
9767 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
9768 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
9769 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
9770 }
9771 
9772 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
9773 {
9774 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
9775 
9776 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
9777 }
9778 
9779 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
9780 				    struct drm_plane_state *old_plane_state,
9781 				    struct dc_stream_update *update)
9782 {
9783 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
9784 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
9785 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
9786 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
9787 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
9788 	uint64_t address = afb ? afb->address : 0;
9789 	struct dc_cursor_position position = {0};
9790 	struct dc_cursor_attributes attributes;
9791 	int ret;
9792 
9793 	if (!plane->state->fb && !old_plane_state->fb)
9794 		return;
9795 
9796 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
9797 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
9798 		       plane->state->crtc_h);
9799 
9800 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
9801 	if (ret)
9802 		return;
9803 
9804 	if (!position.enable) {
9805 		/* turn off cursor */
9806 		if (crtc_state && crtc_state->stream) {
9807 			dc_stream_set_cursor_position(crtc_state->stream,
9808 						      &position);
9809 			update->cursor_position = &crtc_state->stream->cursor_position;
9810 		}
9811 		return;
9812 	}
9813 
9814 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
9815 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
9816 
9817 	memset(&attributes, 0, sizeof(attributes));
9818 	attributes.address.high_part = upper_32_bits(address);
9819 	attributes.address.low_part  = lower_32_bits(address);
9820 	attributes.width             = plane->state->crtc_w;
9821 	attributes.height            = plane->state->crtc_h;
9822 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
9823 	attributes.rotation_angle    = 0;
9824 	attributes.attribute_flags.value = 0;
9825 
9826 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
9827 	 * legacy gamma setup.
9828 	 */
9829 	if (crtc_state->cm_is_degamma_srgb &&
9830 	    adev->dm.dc->caps.color.dpp.gamma_corr)
9831 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
9832 
9833 	if (afb)
9834 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
9835 
9836 	if (crtc_state->stream) {
9837 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
9838 						     &attributes))
9839 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
9840 
9841 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
9842 
9843 		if (!dc_stream_set_cursor_position(crtc_state->stream,
9844 						   &position))
9845 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
9846 
9847 		update->cursor_position = &crtc_state->stream->cursor_position;
9848 	}
9849 }
9850 
9851 static void amdgpu_dm_enable_self_refresh(struct amdgpu_crtc *acrtc_attach,
9852 					  const struct dm_crtc_state *acrtc_state,
9853 					  const u64 current_ts)
9854 {
9855 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
9856 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
9857 	struct amdgpu_dm_connector *aconn =
9858 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
9859 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
9860 
9861 	if (acrtc_state->update_type > UPDATE_TYPE_FAST) {
9862 		if (pr->config.replay_supported && !pr->replay_feature_enabled)
9863 			amdgpu_dm_link_setup_replay(acrtc_state->stream->link, aconn);
9864 		else if (psr->psr_version != DC_PSR_VERSION_UNSUPPORTED &&
9865 			     !psr->psr_feature_enabled)
9866 			if (!aconn->disallow_edp_enter_psr)
9867 				amdgpu_dm_link_setup_psr(acrtc_state->stream);
9868 	}
9869 
9870 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
9871 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
9872 	    (psr->psr_feature_enabled || pr->config.replay_supported)) {
9873 		if (aconn->sr_skip_count > 0)
9874 			aconn->sr_skip_count--;
9875 
9876 		/* Allow SR when skip count is 0. */
9877 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
9878 
9879 		/*
9880 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
9881 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
9882 		 * can be enabled immediately once OS demonstrates an
9883 		 * adequate number of fast atomic commits to notify KMD
9884 		 * of update events. See `vblank_control_worker()`.
9885 		 */
9886 		if (!vrr_active &&
9887 		    acrtc_attach->dm_irq_params.allow_sr_entry &&
9888 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
9889 		    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
9890 #endif
9891 		    (current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
9892 			if (pr->replay_feature_enabled && !pr->replay_allow_active)
9893 				amdgpu_dm_replay_enable(acrtc_state->stream, true);
9894 			if (psr->psr_version == DC_PSR_VERSION_SU_1 &&
9895 			    !psr->psr_allow_active && !aconn->disallow_edp_enter_psr)
9896 				amdgpu_dm_psr_enable(acrtc_state->stream);
9897 		}
9898 	} else {
9899 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
9900 	}
9901 }
9902 
9903 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
9904 				    struct drm_device *dev,
9905 				    struct amdgpu_display_manager *dm,
9906 				    struct drm_crtc *pcrtc,
9907 				    bool wait_for_vblank)
9908 {
9909 	u32 i;
9910 	u64 timestamp_ns = ktime_get_ns();
9911 	struct drm_plane *plane;
9912 	struct drm_plane_state *old_plane_state, *new_plane_state;
9913 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
9914 	struct drm_crtc_state *new_pcrtc_state =
9915 			drm_atomic_get_new_crtc_state(state, pcrtc);
9916 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
9917 	struct dm_crtc_state *dm_old_crtc_state =
9918 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
9919 	int planes_count = 0, vpos, hpos;
9920 	unsigned long flags;
9921 	u32 target_vblank, last_flip_vblank;
9922 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
9923 	bool cursor_update = false;
9924 	bool pflip_present = false;
9925 	bool dirty_rects_changed = false;
9926 	bool updated_planes_and_streams = false;
9927 	struct {
9928 		struct dc_surface_update surface_updates[MAX_SURFACES];
9929 		struct dc_plane_info plane_infos[MAX_SURFACES];
9930 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
9931 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
9932 		struct dc_stream_update stream_update;
9933 	} *bundle;
9934 
9935 	bundle = kzalloc(sizeof(*bundle), GFP_KERNEL);
9936 
9937 	if (!bundle) {
9938 		drm_err(dev, "Failed to allocate update bundle\n");
9939 		goto cleanup;
9940 	}
9941 
9942 	/*
9943 	 * Disable the cursor first if we're disabling all the planes.
9944 	 * It'll remain on the screen after the planes are re-enabled
9945 	 * if we don't.
9946 	 *
9947 	 * If the cursor is transitioning from native to overlay mode, the
9948 	 * native cursor needs to be disabled first.
9949 	 */
9950 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
9951 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
9952 		struct dc_cursor_position cursor_position = {0};
9953 
9954 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
9955 						   &cursor_position))
9956 			drm_err(dev, "DC failed to disable native cursor\n");
9957 
9958 		bundle->stream_update.cursor_position =
9959 				&acrtc_state->stream->cursor_position;
9960 	}
9961 
9962 	if (acrtc_state->active_planes == 0 &&
9963 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
9964 		amdgpu_dm_commit_cursors(state);
9965 
9966 	/* update planes when needed */
9967 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
9968 		struct drm_crtc *crtc = new_plane_state->crtc;
9969 		struct drm_crtc_state *new_crtc_state;
9970 		struct drm_framebuffer *fb = new_plane_state->fb;
9971 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
9972 		bool plane_needs_flip;
9973 		struct dc_plane_state *dc_plane;
9974 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
9975 
9976 		/* Cursor plane is handled after stream updates */
9977 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
9978 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
9979 			if ((fb && crtc == pcrtc) ||
9980 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
9981 				cursor_update = true;
9982 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
9983 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
9984 			}
9985 
9986 			continue;
9987 		}
9988 
9989 		if (!fb || !crtc || pcrtc != crtc)
9990 			continue;
9991 
9992 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
9993 		if (!new_crtc_state->active)
9994 			continue;
9995 
9996 		dc_plane = dm_new_plane_state->dc_state;
9997 		if (!dc_plane)
9998 			continue;
9999 
10000 		bundle->surface_updates[planes_count].surface = dc_plane;
10001 		if (new_pcrtc_state->color_mgmt_changed) {
10002 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
10003 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
10004 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
10005 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
10006 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
10007 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
10008 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
10009 		}
10010 
10011 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
10012 				     &bundle->scaling_infos[planes_count]);
10013 
10014 		bundle->surface_updates[planes_count].scaling_info =
10015 			&bundle->scaling_infos[planes_count];
10016 
10017 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
10018 
10019 		pflip_present = pflip_present || plane_needs_flip;
10020 
10021 		if (!plane_needs_flip) {
10022 			planes_count += 1;
10023 			continue;
10024 		}
10025 
10026 		fill_dc_plane_info_and_addr(
10027 			dm->adev, new_plane_state,
10028 			afb->tiling_flags,
10029 			&bundle->plane_infos[planes_count],
10030 			&bundle->flip_addrs[planes_count].address,
10031 			afb->tmz_surface);
10032 
10033 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
10034 				 new_plane_state->plane->index,
10035 				 bundle->plane_infos[planes_count].dcc.enable);
10036 
10037 		bundle->surface_updates[planes_count].plane_info =
10038 			&bundle->plane_infos[planes_count];
10039 
10040 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
10041 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
10042 			fill_dc_dirty_rects(plane, old_plane_state,
10043 					    new_plane_state, new_crtc_state,
10044 					    &bundle->flip_addrs[planes_count],
10045 					    acrtc_state->stream->link->psr_settings.psr_version ==
10046 					    DC_PSR_VERSION_SU_1,
10047 					    &dirty_rects_changed);
10048 
10049 			/*
10050 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
10051 			 * and enabled it again after dirty regions are stable to avoid video glitch.
10052 			 * PSR-SU will be enabled in vblank_control_worker() if user pause the video
10053 			 * during the PSR-SU was disabled.
10054 			 */
10055 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
10056 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
10057 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
10058 			    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
10059 #endif
10060 			    dirty_rects_changed) {
10061 				mutex_lock(&dm->dc_lock);
10062 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
10063 				timestamp_ns;
10064 				if (acrtc_state->stream->link->psr_settings.psr_allow_active)
10065 					amdgpu_dm_psr_disable(acrtc_state->stream, true);
10066 				mutex_unlock(&dm->dc_lock);
10067 			}
10068 		}
10069 
10070 		/*
10071 		 * Only allow immediate flips for fast updates that don't
10072 		 * change memory domain, FB pitch, DCC state, rotation or
10073 		 * mirroring.
10074 		 *
10075 		 * dm_crtc_helper_atomic_check() only accepts async flips with
10076 		 * fast updates.
10077 		 */
10078 		if (crtc->state->async_flip &&
10079 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
10080 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
10081 			drm_warn_once(state->dev,
10082 				      "[PLANE:%d:%s] async flip with non-fast update\n",
10083 				      plane->base.id, plane->name);
10084 
10085 		bundle->flip_addrs[planes_count].flip_immediate =
10086 			crtc->state->async_flip &&
10087 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
10088 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
10089 
10090 		timestamp_ns = ktime_get_ns();
10091 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
10092 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
10093 		bundle->surface_updates[planes_count].surface = dc_plane;
10094 
10095 		if (!bundle->surface_updates[planes_count].surface) {
10096 			drm_err(dev, "No surface for CRTC: id=%d\n",
10097 					acrtc_attach->crtc_id);
10098 			continue;
10099 		}
10100 
10101 		if (plane == pcrtc->primary)
10102 			update_freesync_state_on_stream(
10103 				dm,
10104 				acrtc_state,
10105 				acrtc_state->stream,
10106 				dc_plane,
10107 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
10108 
10109 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
10110 				 __func__,
10111 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
10112 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
10113 
10114 		planes_count += 1;
10115 
10116 	}
10117 
10118 	if (pflip_present) {
10119 		if (!vrr_active) {
10120 			/* Use old throttling in non-vrr fixed refresh rate mode
10121 			 * to keep flip scheduling based on target vblank counts
10122 			 * working in a backwards compatible way, e.g., for
10123 			 * clients using the GLX_OML_sync_control extension or
10124 			 * DRI3/Present extension with defined target_msc.
10125 			 */
10126 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
10127 		} else {
10128 			/* For variable refresh rate mode only:
10129 			 * Get vblank of last completed flip to avoid > 1 vrr
10130 			 * flips per video frame by use of throttling, but allow
10131 			 * flip programming anywhere in the possibly large
10132 			 * variable vrr vblank interval for fine-grained flip
10133 			 * timing control and more opportunity to avoid stutter
10134 			 * on late submission of flips.
10135 			 */
10136 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10137 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
10138 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10139 		}
10140 
10141 		target_vblank = last_flip_vblank + wait_for_vblank;
10142 
10143 		/*
10144 		 * Wait until we're out of the vertical blank period before the one
10145 		 * targeted by the flip
10146 		 */
10147 		while ((acrtc_attach->enabled &&
10148 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
10149 							    0, &vpos, &hpos, NULL,
10150 							    NULL, &pcrtc->hwmode)
10151 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
10152 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
10153 			(int)(target_vblank -
10154 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
10155 			usleep_range(1000, 1100);
10156 		}
10157 
10158 		/**
10159 		 * Prepare the flip event for the pageflip interrupt to handle.
10160 		 *
10161 		 * This only works in the case where we've already turned on the
10162 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
10163 		 * from 0 -> n planes we have to skip a hardware generated event
10164 		 * and rely on sending it from software.
10165 		 */
10166 		if (acrtc_attach->base.state->event &&
10167 		    acrtc_state->active_planes > 0) {
10168 			drm_crtc_vblank_get(pcrtc);
10169 
10170 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10171 
10172 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
10173 			prepare_flip_isr(acrtc_attach);
10174 
10175 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10176 		}
10177 
10178 		if (acrtc_state->stream) {
10179 			if (acrtc_state->freesync_vrr_info_changed)
10180 				bundle->stream_update.vrr_infopacket =
10181 					&acrtc_state->stream->vrr_infopacket;
10182 		}
10183 	} else if (cursor_update && acrtc_state->active_planes > 0) {
10184 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10185 		if (acrtc_attach->base.state->event) {
10186 			drm_crtc_vblank_get(pcrtc);
10187 			acrtc_attach->event = acrtc_attach->base.state->event;
10188 			acrtc_attach->base.state->event = NULL;
10189 		}
10190 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10191 	}
10192 
10193 	/* Update the planes if changed or disable if we don't have any. */
10194 	if ((planes_count || acrtc_state->active_planes == 0) &&
10195 		acrtc_state->stream) {
10196 		/*
10197 		 * If PSR or idle optimizations are enabled then flush out
10198 		 * any pending work before hardware programming.
10199 		 */
10200 		if (dm->vblank_control_workqueue)
10201 			flush_workqueue(dm->vblank_control_workqueue);
10202 
10203 		bundle->stream_update.stream = acrtc_state->stream;
10204 		if (new_pcrtc_state->mode_changed) {
10205 			bundle->stream_update.src = acrtc_state->stream->src;
10206 			bundle->stream_update.dst = acrtc_state->stream->dst;
10207 		}
10208 
10209 		if (new_pcrtc_state->color_mgmt_changed) {
10210 			/*
10211 			 * TODO: This isn't fully correct since we've actually
10212 			 * already modified the stream in place.
10213 			 */
10214 			bundle->stream_update.gamut_remap =
10215 				&acrtc_state->stream->gamut_remap_matrix;
10216 			bundle->stream_update.output_csc_transform =
10217 				&acrtc_state->stream->csc_color_matrix;
10218 			bundle->stream_update.out_transfer_func =
10219 				&acrtc_state->stream->out_transfer_func;
10220 			bundle->stream_update.lut3d_func =
10221 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
10222 			bundle->stream_update.func_shaper =
10223 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
10224 		}
10225 
10226 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
10227 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
10228 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
10229 
10230 		mutex_lock(&dm->dc_lock);
10231 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) || vrr_active) {
10232 			if (acrtc_state->stream->link->replay_settings.replay_allow_active)
10233 				amdgpu_dm_replay_disable(acrtc_state->stream);
10234 			if (acrtc_state->stream->link->psr_settings.psr_allow_active)
10235 				amdgpu_dm_psr_disable(acrtc_state->stream, true);
10236 		}
10237 		mutex_unlock(&dm->dc_lock);
10238 
10239 		/*
10240 		 * If FreeSync state on the stream has changed then we need to
10241 		 * re-adjust the min/max bounds now that DC doesn't handle this
10242 		 * as part of commit.
10243 		 */
10244 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
10245 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10246 			dc_stream_adjust_vmin_vmax(
10247 				dm->dc, acrtc_state->stream,
10248 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
10249 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10250 		}
10251 		mutex_lock(&dm->dc_lock);
10252 		update_planes_and_stream_adapter(dm->dc,
10253 					 acrtc_state->update_type,
10254 					 planes_count,
10255 					 acrtc_state->stream,
10256 					 &bundle->stream_update,
10257 					 bundle->surface_updates);
10258 		updated_planes_and_streams = true;
10259 
10260 		/**
10261 		 * Enable or disable the interrupts on the backend.
10262 		 *
10263 		 * Most pipes are put into power gating when unused.
10264 		 *
10265 		 * When power gating is enabled on a pipe we lose the
10266 		 * interrupt enablement state when power gating is disabled.
10267 		 *
10268 		 * So we need to update the IRQ control state in hardware
10269 		 * whenever the pipe turns on (since it could be previously
10270 		 * power gated) or off (since some pipes can't be power gated
10271 		 * on some ASICs).
10272 		 */
10273 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
10274 			dm_update_pflip_irq_state(drm_to_adev(dev),
10275 						  acrtc_attach);
10276 
10277 		amdgpu_dm_enable_self_refresh(acrtc_attach, acrtc_state, timestamp_ns);
10278 		mutex_unlock(&dm->dc_lock);
10279 	}
10280 
10281 	/*
10282 	 * Update cursor state *after* programming all the planes.
10283 	 * This avoids redundant programming in the case where we're going
10284 	 * to be disabling a single plane - those pipes are being disabled.
10285 	 */
10286 	if (acrtc_state->active_planes &&
10287 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
10288 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10289 		amdgpu_dm_commit_cursors(state);
10290 
10291 cleanup:
10292 	kfree(bundle);
10293 }
10294 
10295 static void amdgpu_dm_commit_audio(struct drm_device *dev,
10296 				   struct drm_atomic_state *state)
10297 {
10298 	struct amdgpu_device *adev = drm_to_adev(dev);
10299 	struct amdgpu_dm_connector *aconnector;
10300 	struct drm_connector *connector;
10301 	struct drm_connector_state *old_con_state, *new_con_state;
10302 	struct drm_crtc_state *new_crtc_state;
10303 	struct dm_crtc_state *new_dm_crtc_state;
10304 	const struct dc_stream_status *status;
10305 	int i, inst;
10306 
10307 	/* Notify device removals. */
10308 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10309 		if (old_con_state->crtc != new_con_state->crtc) {
10310 			/* CRTC changes require notification. */
10311 			goto notify;
10312 		}
10313 
10314 		if (!new_con_state->crtc)
10315 			continue;
10316 
10317 		new_crtc_state = drm_atomic_get_new_crtc_state(
10318 			state, new_con_state->crtc);
10319 
10320 		if (!new_crtc_state)
10321 			continue;
10322 
10323 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10324 			continue;
10325 
10326 notify:
10327 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10328 			continue;
10329 
10330 		aconnector = to_amdgpu_dm_connector(connector);
10331 
10332 		mutex_lock(&adev->dm.audio_lock);
10333 		inst = aconnector->audio_inst;
10334 		aconnector->audio_inst = -1;
10335 		mutex_unlock(&adev->dm.audio_lock);
10336 
10337 		amdgpu_dm_audio_eld_notify(adev, inst);
10338 	}
10339 
10340 	/* Notify audio device additions. */
10341 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10342 		if (!new_con_state->crtc)
10343 			continue;
10344 
10345 		new_crtc_state = drm_atomic_get_new_crtc_state(
10346 			state, new_con_state->crtc);
10347 
10348 		if (!new_crtc_state)
10349 			continue;
10350 
10351 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10352 			continue;
10353 
10354 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
10355 		if (!new_dm_crtc_state->stream)
10356 			continue;
10357 
10358 		status = dc_stream_get_status(new_dm_crtc_state->stream);
10359 		if (!status)
10360 			continue;
10361 
10362 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10363 			continue;
10364 
10365 		aconnector = to_amdgpu_dm_connector(connector);
10366 
10367 		mutex_lock(&adev->dm.audio_lock);
10368 		inst = status->audio_inst;
10369 		aconnector->audio_inst = inst;
10370 		mutex_unlock(&adev->dm.audio_lock);
10371 
10372 		amdgpu_dm_audio_eld_notify(adev, inst);
10373 	}
10374 }
10375 
10376 /*
10377  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
10378  * @crtc_state: the DRM CRTC state
10379  * @stream_state: the DC stream state.
10380  *
10381  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
10382  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
10383  */
10384 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
10385 						struct dc_stream_state *stream_state)
10386 {
10387 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
10388 }
10389 
10390 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
10391 			      struct dm_crtc_state *crtc_state)
10392 {
10393 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
10394 }
10395 
10396 static void amdgpu_dm_commit_streams(struct drm_atomic_state *state,
10397 					struct dc_state *dc_state)
10398 {
10399 	struct drm_device *dev = state->dev;
10400 	struct amdgpu_device *adev = drm_to_adev(dev);
10401 	struct amdgpu_display_manager *dm = &adev->dm;
10402 	struct drm_crtc *crtc;
10403 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10404 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10405 	struct drm_connector_state *old_con_state;
10406 	struct drm_connector *connector;
10407 	bool mode_set_reset_required = false;
10408 	u32 i;
10409 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
10410 	bool set_backlight_level = false;
10411 
10412 	/* Disable writeback */
10413 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
10414 		struct dm_connector_state *dm_old_con_state;
10415 		struct amdgpu_crtc *acrtc;
10416 
10417 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
10418 			continue;
10419 
10420 		old_crtc_state = NULL;
10421 
10422 		dm_old_con_state = to_dm_connector_state(old_con_state);
10423 		if (!dm_old_con_state->base.crtc)
10424 			continue;
10425 
10426 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
10427 		if (acrtc)
10428 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10429 
10430 		if (!acrtc || !acrtc->wb_enabled)
10431 			continue;
10432 
10433 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10434 
10435 		dm_clear_writeback(dm, dm_old_crtc_state);
10436 		acrtc->wb_enabled = false;
10437 	}
10438 
10439 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
10440 				      new_crtc_state, i) {
10441 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10442 
10443 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10444 
10445 		if (old_crtc_state->active &&
10446 		    (!new_crtc_state->active ||
10447 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10448 			manage_dm_interrupts(adev, acrtc, NULL);
10449 			dc_stream_release(dm_old_crtc_state->stream);
10450 		}
10451 	}
10452 
10453 	drm_atomic_helper_calc_timestamping_constants(state);
10454 
10455 	/* update changed items */
10456 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10457 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10458 
10459 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10460 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10461 
10462 		drm_dbg_state(state->dev,
10463 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
10464 			acrtc->crtc_id,
10465 			new_crtc_state->enable,
10466 			new_crtc_state->active,
10467 			new_crtc_state->planes_changed,
10468 			new_crtc_state->mode_changed,
10469 			new_crtc_state->active_changed,
10470 			new_crtc_state->connectors_changed);
10471 
10472 		/* Disable cursor if disabling crtc */
10473 		if (old_crtc_state->active && !new_crtc_state->active) {
10474 			struct dc_cursor_position position;
10475 
10476 			memset(&position, 0, sizeof(position));
10477 			mutex_lock(&dm->dc_lock);
10478 			dc_exit_ips_for_hw_access(dm->dc);
10479 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
10480 			mutex_unlock(&dm->dc_lock);
10481 		}
10482 
10483 		/* Copy all transient state flags into dc state */
10484 		if (dm_new_crtc_state->stream) {
10485 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
10486 							    dm_new_crtc_state->stream);
10487 		}
10488 
10489 		/* handles headless hotplug case, updating new_state and
10490 		 * aconnector as needed
10491 		 */
10492 
10493 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
10494 
10495 			drm_dbg_atomic(dev,
10496 				       "Atomic commit: SET crtc id %d: [%p]\n",
10497 				       acrtc->crtc_id, acrtc);
10498 
10499 			if (!dm_new_crtc_state->stream) {
10500 				/*
10501 				 * this could happen because of issues with
10502 				 * userspace notifications delivery.
10503 				 * In this case userspace tries to set mode on
10504 				 * display which is disconnected in fact.
10505 				 * dc_sink is NULL in this case on aconnector.
10506 				 * We expect reset mode will come soon.
10507 				 *
10508 				 * This can also happen when unplug is done
10509 				 * during resume sequence ended
10510 				 *
10511 				 * In this case, we want to pretend we still
10512 				 * have a sink to keep the pipe running so that
10513 				 * hw state is consistent with the sw state
10514 				 */
10515 				drm_dbg_atomic(dev,
10516 					       "Failed to create new stream for crtc %d\n",
10517 						acrtc->base.base.id);
10518 				continue;
10519 			}
10520 
10521 			if (dm_old_crtc_state->stream)
10522 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10523 
10524 			pm_runtime_get_noresume(dev->dev);
10525 
10526 			acrtc->enabled = true;
10527 			acrtc->hw_mode = new_crtc_state->mode;
10528 			crtc->hwmode = new_crtc_state->mode;
10529 			mode_set_reset_required = true;
10530 			set_backlight_level = true;
10531 		} else if (modereset_required(new_crtc_state)) {
10532 			drm_dbg_atomic(dev,
10533 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
10534 				       acrtc->crtc_id, acrtc);
10535 			/* i.e. reset mode */
10536 			if (dm_old_crtc_state->stream)
10537 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10538 
10539 			mode_set_reset_required = true;
10540 		}
10541 	} /* for_each_crtc_in_state() */
10542 
10543 	/* if there mode set or reset, disable eDP PSR, Replay */
10544 	if (mode_set_reset_required) {
10545 		if (dm->vblank_control_workqueue)
10546 			flush_workqueue(dm->vblank_control_workqueue);
10547 
10548 		amdgpu_dm_replay_disable_all(dm);
10549 		amdgpu_dm_psr_disable_all(dm);
10550 	}
10551 
10552 	dm_enable_per_frame_crtc_master_sync(dc_state);
10553 	mutex_lock(&dm->dc_lock);
10554 	dc_exit_ips_for_hw_access(dm->dc);
10555 	WARN_ON(!dc_commit_streams(dm->dc, &params));
10556 
10557 	/* Allow idle optimization when vblank count is 0 for display off */
10558 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
10559 		dc_allow_idle_optimizations(dm->dc, true);
10560 	mutex_unlock(&dm->dc_lock);
10561 
10562 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10563 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10564 
10565 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10566 
10567 		if (dm_new_crtc_state->stream != NULL) {
10568 			const struct dc_stream_status *status =
10569 					dc_stream_get_status(dm_new_crtc_state->stream);
10570 
10571 			if (!status)
10572 				status = dc_state_get_stream_status(dc_state,
10573 									 dm_new_crtc_state->stream);
10574 			if (!status)
10575 				drm_err(dev,
10576 					"got no status for stream %p on acrtc%p\n",
10577 					dm_new_crtc_state->stream, acrtc);
10578 			else
10579 				acrtc->otg_inst = status->primary_otg_inst;
10580 		}
10581 	}
10582 
10583 	/* During boot up and resume the DC layer will reset the panel brightness
10584 	 * to fix a flicker issue.
10585 	 * It will cause the dm->actual_brightness is not the current panel brightness
10586 	 * level. (the dm->brightness is the correct panel level)
10587 	 * So we set the backlight level with dm->brightness value after set mode
10588 	 */
10589 	if (set_backlight_level) {
10590 		for (i = 0; i < dm->num_of_edps; i++) {
10591 			if (dm->backlight_dev[i])
10592 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
10593 		}
10594 	}
10595 }
10596 
10597 static void dm_set_writeback(struct amdgpu_display_manager *dm,
10598 			      struct dm_crtc_state *crtc_state,
10599 			      struct drm_connector *connector,
10600 			      struct drm_connector_state *new_con_state)
10601 {
10602 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
10603 	struct amdgpu_device *adev = dm->adev;
10604 	struct amdgpu_crtc *acrtc;
10605 	struct dc_writeback_info *wb_info;
10606 	struct pipe_ctx *pipe = NULL;
10607 	struct amdgpu_framebuffer *afb;
10608 	int i = 0;
10609 
10610 	wb_info = kzalloc(sizeof(*wb_info), GFP_KERNEL);
10611 	if (!wb_info) {
10612 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
10613 		return;
10614 	}
10615 
10616 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
10617 	if (!acrtc) {
10618 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
10619 		kfree(wb_info);
10620 		return;
10621 	}
10622 
10623 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
10624 	if (!afb) {
10625 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
10626 		kfree(wb_info);
10627 		return;
10628 	}
10629 
10630 	for (i = 0; i < MAX_PIPES; i++) {
10631 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
10632 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
10633 			break;
10634 		}
10635 	}
10636 
10637 	/* fill in wb_info */
10638 	wb_info->wb_enabled = true;
10639 
10640 	wb_info->dwb_pipe_inst = 0;
10641 	wb_info->dwb_params.dwbscl_black_color = 0;
10642 	wb_info->dwb_params.hdr_mult = 0x1F000;
10643 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
10644 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
10645 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
10646 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
10647 
10648 	/* width & height from crtc */
10649 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
10650 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
10651 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
10652 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
10653 
10654 	wb_info->dwb_params.cnv_params.crop_en = false;
10655 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
10656 
10657 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
10658 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
10659 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
10660 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
10661 
10662 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
10663 
10664 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
10665 
10666 	wb_info->dwb_params.scaler_taps.h_taps = 1;
10667 	wb_info->dwb_params.scaler_taps.v_taps = 1;
10668 	wb_info->dwb_params.scaler_taps.h_taps_c = 1;
10669 	wb_info->dwb_params.scaler_taps.v_taps_c = 1;
10670 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
10671 
10672 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
10673 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
10674 
10675 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
10676 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
10677 		wb_info->mcif_buf_params.chroma_address[i] = 0;
10678 	}
10679 
10680 	wb_info->mcif_buf_params.p_vmid = 1;
10681 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
10682 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
10683 		wb_info->mcif_warmup_params.region_size =
10684 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
10685 	}
10686 	wb_info->mcif_warmup_params.p_vmid = 1;
10687 	wb_info->writeback_source_plane = pipe->plane_state;
10688 
10689 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
10690 
10691 	acrtc->wb_pending = true;
10692 	acrtc->wb_conn = wb_conn;
10693 	drm_writeback_queue_job(wb_conn, new_con_state);
10694 }
10695 
10696 static void amdgpu_dm_update_hdcp(struct drm_atomic_state *state)
10697 {
10698 	struct drm_connector_state *old_con_state, *new_con_state;
10699 	struct drm_device *dev = state->dev;
10700 	struct drm_connector *connector;
10701 	struct amdgpu_device *adev = drm_to_adev(dev);
10702 	int i;
10703 
10704 	if (!adev->dm.hdcp_workqueue)
10705 		return;
10706 
10707 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10708 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10709 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10710 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10711 		struct dm_crtc_state *dm_new_crtc_state;
10712 		struct amdgpu_dm_connector *aconnector;
10713 
10714 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10715 			continue;
10716 
10717 		aconnector = to_amdgpu_dm_connector(connector);
10718 
10719 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
10720 
10721 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
10722 			connector->index, connector->status, connector->dpms);
10723 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
10724 			old_con_state->content_protection, new_con_state->content_protection);
10725 
10726 		if (aconnector->dc_sink) {
10727 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
10728 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
10729 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
10730 				aconnector->dc_sink->edid_caps.display_name);
10731 			}
10732 		}
10733 
10734 		new_crtc_state = NULL;
10735 		old_crtc_state = NULL;
10736 
10737 		if (acrtc) {
10738 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
10739 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10740 		}
10741 
10742 		if (old_crtc_state)
10743 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
10744 			old_crtc_state->enable,
10745 			old_crtc_state->active,
10746 			old_crtc_state->mode_changed,
10747 			old_crtc_state->active_changed,
10748 			old_crtc_state->connectors_changed);
10749 
10750 		if (new_crtc_state)
10751 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
10752 			new_crtc_state->enable,
10753 			new_crtc_state->active,
10754 			new_crtc_state->mode_changed,
10755 			new_crtc_state->active_changed,
10756 			new_crtc_state->connectors_changed);
10757 
10758 
10759 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10760 
10761 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
10762 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
10763 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
10764 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
10765 			dm_new_con_state->update_hdcp = true;
10766 			continue;
10767 		}
10768 
10769 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
10770 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
10771 			/* when display is unplugged from mst hub, connctor will
10772 			 * be destroyed within dm_dp_mst_connector_destroy. connector
10773 			 * hdcp perperties, like type, undesired, desired, enabled,
10774 			 * will be lost. So, save hdcp properties into hdcp_work within
10775 			 * amdgpu_dm_atomic_commit_tail. if the same display is
10776 			 * plugged back with same display index, its hdcp properties
10777 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
10778 			 */
10779 
10780 			bool enable_encryption = false;
10781 
10782 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
10783 				enable_encryption = true;
10784 
10785 			if (aconnector->dc_link && aconnector->dc_sink &&
10786 				aconnector->dc_link->type == dc_connection_mst_branch) {
10787 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
10788 				struct hdcp_workqueue *hdcp_w =
10789 					&hdcp_work[aconnector->dc_link->link_index];
10790 
10791 				hdcp_w->hdcp_content_type[connector->index] =
10792 					new_con_state->hdcp_content_type;
10793 				hdcp_w->content_protection[connector->index] =
10794 					new_con_state->content_protection;
10795 			}
10796 
10797 			if (new_crtc_state && new_crtc_state->mode_changed &&
10798 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
10799 				enable_encryption = true;
10800 
10801 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
10802 
10803 			if (aconnector->dc_link)
10804 				hdcp_update_display(
10805 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
10806 					new_con_state->hdcp_content_type, enable_encryption);
10807 		}
10808 	}
10809 }
10810 
10811 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_state *state)
10812 {
10813 	struct drm_crtc *crtc;
10814 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10815 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10816 	int i, ret;
10817 
10818 	ret = drm_dp_mst_atomic_setup_commit(state);
10819 	if (ret)
10820 		return ret;
10821 
10822 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10823 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10824 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10825 		/*
10826 		 * Color management settings. We also update color properties
10827 		 * when a modeset is needed, to ensure it gets reprogrammed.
10828 		 */
10829 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
10830 		    (dm_new_crtc_state->base.color_mgmt_changed ||
10831 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
10832 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10833 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
10834 			if (ret) {
10835 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
10836 				return ret;
10837 			}
10838 		}
10839 	}
10840 
10841 	return 0;
10842 }
10843 
10844 /**
10845  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
10846  * @state: The atomic state to commit
10847  *
10848  * This will tell DC to commit the constructed DC state from atomic_check,
10849  * programming the hardware. Any failures here implies a hardware failure, since
10850  * atomic check should have filtered anything non-kosher.
10851  */
10852 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
10853 {
10854 	struct drm_device *dev = state->dev;
10855 	struct amdgpu_device *adev = drm_to_adev(dev);
10856 	struct amdgpu_display_manager *dm = &adev->dm;
10857 	struct dm_atomic_state *dm_state;
10858 	struct dc_state *dc_state = NULL;
10859 	u32 i, j;
10860 	struct drm_crtc *crtc;
10861 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10862 	unsigned long flags;
10863 	bool wait_for_vblank = true;
10864 	struct drm_connector *connector;
10865 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
10866 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10867 	int crtc_disable_count = 0;
10868 
10869 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
10870 
10871 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
10872 	drm_dp_mst_atomic_wait_for_dependencies(state);
10873 
10874 	dm_state = dm_atomic_get_new_state(state);
10875 	if (dm_state && dm_state->context) {
10876 		dc_state = dm_state->context;
10877 		amdgpu_dm_commit_streams(state, dc_state);
10878 	}
10879 
10880 	amdgpu_dm_update_hdcp(state);
10881 
10882 	/* Handle connector state changes */
10883 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10884 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10885 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
10886 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10887 		struct dc_surface_update *dummy_updates;
10888 		struct dc_stream_update stream_update;
10889 		struct dc_info_packet hdr_packet;
10890 		struct dc_stream_status *status = NULL;
10891 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
10892 
10893 		memset(&stream_update, 0, sizeof(stream_update));
10894 
10895 		if (acrtc) {
10896 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
10897 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10898 		}
10899 
10900 		/* Skip any modesets/resets */
10901 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
10902 			continue;
10903 
10904 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10905 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10906 
10907 		scaling_changed = is_scaling_state_different(dm_new_con_state,
10908 							     dm_old_con_state);
10909 
10910 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
10911 			(dm_old_crtc_state->stream->output_color_space !=
10912 				get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
10913 			output_color_space_changed = true;
10914 
10915 		abm_changed = dm_new_crtc_state->abm_level !=
10916 			      dm_old_crtc_state->abm_level;
10917 
10918 		hdr_changed =
10919 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
10920 
10921 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
10922 			continue;
10923 
10924 		stream_update.stream = dm_new_crtc_state->stream;
10925 		if (scaling_changed) {
10926 			update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
10927 					dm_new_con_state, dm_new_crtc_state->stream);
10928 
10929 			stream_update.src = dm_new_crtc_state->stream->src;
10930 			stream_update.dst = dm_new_crtc_state->stream->dst;
10931 		}
10932 
10933 		if (output_color_space_changed) {
10934 			dm_new_crtc_state->stream->output_color_space
10935 				= get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
10936 
10937 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
10938 		}
10939 
10940 		if (abm_changed) {
10941 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
10942 
10943 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
10944 		}
10945 
10946 		if (hdr_changed) {
10947 			fill_hdr_info_packet(new_con_state, &hdr_packet);
10948 			stream_update.hdr_static_metadata = &hdr_packet;
10949 		}
10950 
10951 		status = dc_stream_get_status(dm_new_crtc_state->stream);
10952 
10953 		if (WARN_ON(!status))
10954 			continue;
10955 
10956 		WARN_ON(!status->plane_count);
10957 
10958 		/*
10959 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
10960 		 * Here we create an empty update on each plane.
10961 		 * To fix this, DC should permit updating only stream properties.
10962 		 */
10963 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
10964 		if (!dummy_updates) {
10965 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
10966 			continue;
10967 		}
10968 		for (j = 0; j < status->plane_count; j++)
10969 			dummy_updates[j].surface = status->plane_states[0];
10970 
10971 		sort(dummy_updates, status->plane_count,
10972 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
10973 
10974 		mutex_lock(&dm->dc_lock);
10975 		dc_exit_ips_for_hw_access(dm->dc);
10976 		dc_update_planes_and_stream(dm->dc,
10977 					    dummy_updates,
10978 					    status->plane_count,
10979 					    dm_new_crtc_state->stream,
10980 					    &stream_update);
10981 		mutex_unlock(&dm->dc_lock);
10982 		kfree(dummy_updates);
10983 
10984 		drm_connector_update_privacy_screen(new_con_state);
10985 	}
10986 
10987 	/**
10988 	 * Enable interrupts for CRTCs that are newly enabled or went through
10989 	 * a modeset. It was intentionally deferred until after the front end
10990 	 * state was modified to wait until the OTG was on and so the IRQ
10991 	 * handlers didn't access stale or invalid state.
10992 	 */
10993 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10994 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10995 #ifdef CONFIG_DEBUG_FS
10996 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
10997 #endif
10998 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
10999 		if (old_crtc_state->active && !new_crtc_state->active)
11000 			crtc_disable_count++;
11001 
11002 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11003 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11004 
11005 		/* For freesync config update on crtc state and params for irq */
11006 		update_stream_irq_parameters(dm, dm_new_crtc_state);
11007 
11008 #ifdef CONFIG_DEBUG_FS
11009 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11010 		cur_crc_src = acrtc->dm_irq_params.crc_src;
11011 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11012 #endif
11013 
11014 		if (new_crtc_state->active &&
11015 		    (!old_crtc_state->active ||
11016 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11017 			dc_stream_retain(dm_new_crtc_state->stream);
11018 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
11019 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
11020 		}
11021 		/* Handle vrr on->off / off->on transitions */
11022 		amdgpu_dm_handle_vrr_transition(dm_old_crtc_state, dm_new_crtc_state);
11023 
11024 #ifdef CONFIG_DEBUG_FS
11025 		if (new_crtc_state->active &&
11026 		    (!old_crtc_state->active ||
11027 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11028 			/**
11029 			 * Frontend may have changed so reapply the CRC capture
11030 			 * settings for the stream.
11031 			 */
11032 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
11033 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
11034 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
11035 					uint8_t cnt;
11036 
11037 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11038 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
11039 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
11040 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
11041 
11042 							/**
11043 							 * It takes 2 frames for HW to stably generate CRC when
11044 							 * resuming from suspend, so we set skip_frame_cnt 2.
11045 							 */
11046 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
11047 						}
11048 					}
11049 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11050 				}
11051 #endif
11052 				if (amdgpu_dm_crtc_configure_crc_source(
11053 					crtc, dm_new_crtc_state, cur_crc_src))
11054 					drm_dbg_atomic(dev, "Failed to configure crc source");
11055 			}
11056 		}
11057 #endif
11058 	}
11059 
11060 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
11061 		if (new_crtc_state->async_flip)
11062 			wait_for_vblank = false;
11063 
11064 	/* update planes when needed per crtc*/
11065 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
11066 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11067 
11068 		if (dm_new_crtc_state->stream)
11069 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
11070 	}
11071 
11072 	/* Enable writeback */
11073 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11074 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11075 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11076 
11077 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11078 			continue;
11079 
11080 		if (!new_con_state->writeback_job)
11081 			continue;
11082 
11083 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11084 
11085 		if (!new_crtc_state)
11086 			continue;
11087 
11088 		if (acrtc->wb_enabled)
11089 			continue;
11090 
11091 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11092 
11093 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
11094 		acrtc->wb_enabled = true;
11095 	}
11096 
11097 	/* Update audio instances for each connector. */
11098 	amdgpu_dm_commit_audio(dev, state);
11099 
11100 	/* restore the backlight level */
11101 	for (i = 0; i < dm->num_of_edps; i++) {
11102 		if (dm->backlight_dev[i] &&
11103 		    (dm->actual_brightness[i] != dm->brightness[i]))
11104 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11105 	}
11106 
11107 	/*
11108 	 * send vblank event on all events not handled in flip and
11109 	 * mark consumed event for drm_atomic_helper_commit_hw_done
11110 	 */
11111 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11112 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11113 
11114 		if (new_crtc_state->event)
11115 			drm_send_event_locked(dev, &new_crtc_state->event->base);
11116 
11117 		new_crtc_state->event = NULL;
11118 	}
11119 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11120 
11121 	/* Signal HW programming completion */
11122 	drm_atomic_helper_commit_hw_done(state);
11123 
11124 	if (wait_for_vblank)
11125 		drm_atomic_helper_wait_for_flip_done(dev, state);
11126 
11127 	drm_atomic_helper_cleanup_planes(dev, state);
11128 
11129 	/* Don't free the memory if we are hitting this as part of suspend.
11130 	 * This way we don't free any memory during suspend; see
11131 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
11132 	 * non-suspend modeset or when the driver is torn down.
11133 	 */
11134 	if (!adev->in_suspend) {
11135 		/* return the stolen vga memory back to VRAM */
11136 		if (!adev->mman.keep_stolen_vga_memory)
11137 			amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
11138 		amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
11139 	}
11140 
11141 	/*
11142 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
11143 	 * so we can put the GPU into runtime suspend if we're not driving any
11144 	 * displays anymore
11145 	 */
11146 	for (i = 0; i < crtc_disable_count; i++)
11147 		pm_runtime_put_autosuspend(dev->dev);
11148 	pm_runtime_mark_last_busy(dev->dev);
11149 
11150 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
11151 }
11152 
11153 static int dm_force_atomic_commit(struct drm_connector *connector)
11154 {
11155 	int ret = 0;
11156 	struct drm_device *ddev = connector->dev;
11157 	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
11158 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11159 	struct drm_plane *plane = disconnected_acrtc->base.primary;
11160 	struct drm_connector_state *conn_state;
11161 	struct drm_crtc_state *crtc_state;
11162 	struct drm_plane_state *plane_state;
11163 
11164 	if (!state)
11165 		return -ENOMEM;
11166 
11167 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
11168 
11169 	/* Construct an atomic state to restore previous display setting */
11170 
11171 	/*
11172 	 * Attach connectors to drm_atomic_state
11173 	 */
11174 	conn_state = drm_atomic_get_connector_state(state, connector);
11175 
11176 	/* Check for error in getting connector state */
11177 	if (IS_ERR(conn_state)) {
11178 		ret = PTR_ERR(conn_state);
11179 		goto out;
11180 	}
11181 
11182 	/* Attach crtc to drm_atomic_state*/
11183 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
11184 
11185 	/* Check for error in getting crtc state */
11186 	if (IS_ERR(crtc_state)) {
11187 		ret = PTR_ERR(crtc_state);
11188 		goto out;
11189 	}
11190 
11191 	/* force a restore */
11192 	crtc_state->mode_changed = true;
11193 
11194 	/* Attach plane to drm_atomic_state */
11195 	plane_state = drm_atomic_get_plane_state(state, plane);
11196 
11197 	/* Check for error in getting plane state */
11198 	if (IS_ERR(plane_state)) {
11199 		ret = PTR_ERR(plane_state);
11200 		goto out;
11201 	}
11202 
11203 	/* Call commit internally with the state we just constructed */
11204 	ret = drm_atomic_commit(state);
11205 
11206 out:
11207 	drm_atomic_state_put(state);
11208 	if (ret)
11209 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
11210 
11211 	return ret;
11212 }
11213 
11214 /*
11215  * This function handles all cases when set mode does not come upon hotplug.
11216  * This includes when a display is unplugged then plugged back into the
11217  * same port and when running without usermode desktop manager supprot
11218  */
11219 void dm_restore_drm_connector_state(struct drm_device *dev,
11220 				    struct drm_connector *connector)
11221 {
11222 	struct amdgpu_dm_connector *aconnector;
11223 	struct amdgpu_crtc *disconnected_acrtc;
11224 	struct dm_crtc_state *acrtc_state;
11225 
11226 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11227 		return;
11228 
11229 	aconnector = to_amdgpu_dm_connector(connector);
11230 
11231 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
11232 		return;
11233 
11234 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11235 	if (!disconnected_acrtc)
11236 		return;
11237 
11238 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
11239 	if (!acrtc_state->stream)
11240 		return;
11241 
11242 	/*
11243 	 * If the previous sink is not released and different from the current,
11244 	 * we deduce we are in a state where we can not rely on usermode call
11245 	 * to turn on the display, so we do it here
11246 	 */
11247 	if (acrtc_state->stream->sink != aconnector->dc_sink)
11248 		dm_force_atomic_commit(&aconnector->base);
11249 }
11250 
11251 /*
11252  * Grabs all modesetting locks to serialize against any blocking commits,
11253  * Waits for completion of all non blocking commits.
11254  */
11255 static int do_aquire_global_lock(struct drm_device *dev,
11256 				 struct drm_atomic_state *state)
11257 {
11258 	struct drm_crtc *crtc;
11259 	struct drm_crtc_commit *commit;
11260 	long ret;
11261 
11262 	/*
11263 	 * Adding all modeset locks to aquire_ctx will
11264 	 * ensure that when the framework release it the
11265 	 * extra locks we are locking here will get released to
11266 	 */
11267 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
11268 	if (ret)
11269 		return ret;
11270 
11271 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
11272 		spin_lock(&crtc->commit_lock);
11273 		commit = list_first_entry_or_null(&crtc->commit_list,
11274 				struct drm_crtc_commit, commit_entry);
11275 		if (commit)
11276 			drm_crtc_commit_get(commit);
11277 		spin_unlock(&crtc->commit_lock);
11278 
11279 		if (!commit)
11280 			continue;
11281 
11282 		/*
11283 		 * Make sure all pending HW programming completed and
11284 		 * page flips done
11285 		 */
11286 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
11287 
11288 		if (ret > 0)
11289 			ret = wait_for_completion_interruptible_timeout(
11290 					&commit->flip_done, 10*HZ);
11291 
11292 		if (ret == 0)
11293 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
11294 				  crtc->base.id, crtc->name);
11295 
11296 		drm_crtc_commit_put(commit);
11297 	}
11298 
11299 	return ret < 0 ? ret : 0;
11300 }
11301 
11302 static void get_freesync_config_for_crtc(
11303 	struct dm_crtc_state *new_crtc_state,
11304 	struct dm_connector_state *new_con_state)
11305 {
11306 	struct mod_freesync_config config = {0};
11307 	struct amdgpu_dm_connector *aconnector;
11308 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
11309 	int vrefresh = drm_mode_vrefresh(mode);
11310 	bool fs_vid_mode = false;
11311 
11312 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11313 		return;
11314 
11315 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
11316 
11317 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
11318 					vrefresh >= aconnector->min_vfreq &&
11319 					vrefresh <= aconnector->max_vfreq;
11320 
11321 	if (new_crtc_state->vrr_supported) {
11322 		new_crtc_state->stream->ignore_msa_timing_param = true;
11323 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
11324 
11325 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
11326 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
11327 		config.vsif_supported = true;
11328 		config.btr = true;
11329 
11330 		if (fs_vid_mode) {
11331 			config.state = VRR_STATE_ACTIVE_FIXED;
11332 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
11333 			goto out;
11334 		} else if (new_crtc_state->base.vrr_enabled) {
11335 			config.state = VRR_STATE_ACTIVE_VARIABLE;
11336 		} else {
11337 			config.state = VRR_STATE_INACTIVE;
11338 		}
11339 	} else {
11340 		config.state = VRR_STATE_UNSUPPORTED;
11341 	}
11342 out:
11343 	new_crtc_state->freesync_config = config;
11344 }
11345 
11346 static void reset_freesync_config_for_crtc(
11347 	struct dm_crtc_state *new_crtc_state)
11348 {
11349 	new_crtc_state->vrr_supported = false;
11350 
11351 	memset(&new_crtc_state->vrr_infopacket, 0,
11352 	       sizeof(new_crtc_state->vrr_infopacket));
11353 }
11354 
11355 static bool
11356 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
11357 				 struct drm_crtc_state *new_crtc_state)
11358 {
11359 	const struct drm_display_mode *old_mode, *new_mode;
11360 
11361 	if (!old_crtc_state || !new_crtc_state)
11362 		return false;
11363 
11364 	old_mode = &old_crtc_state->mode;
11365 	new_mode = &new_crtc_state->mode;
11366 
11367 	if (old_mode->clock       == new_mode->clock &&
11368 	    old_mode->hdisplay    == new_mode->hdisplay &&
11369 	    old_mode->vdisplay    == new_mode->vdisplay &&
11370 	    old_mode->htotal      == new_mode->htotal &&
11371 	    old_mode->vtotal      != new_mode->vtotal &&
11372 	    old_mode->hsync_start == new_mode->hsync_start &&
11373 	    old_mode->vsync_start != new_mode->vsync_start &&
11374 	    old_mode->hsync_end   == new_mode->hsync_end &&
11375 	    old_mode->vsync_end   != new_mode->vsync_end &&
11376 	    old_mode->hskew       == new_mode->hskew &&
11377 	    old_mode->vscan       == new_mode->vscan &&
11378 	    (old_mode->vsync_end - old_mode->vsync_start) ==
11379 	    (new_mode->vsync_end - new_mode->vsync_start))
11380 		return true;
11381 
11382 	return false;
11383 }
11384 
11385 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
11386 {
11387 	u64 num, den, res;
11388 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
11389 
11390 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
11391 
11392 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
11393 	den = (unsigned long long)new_crtc_state->mode.htotal *
11394 	      (unsigned long long)new_crtc_state->mode.vtotal;
11395 
11396 	res = div_u64(num, den);
11397 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
11398 }
11399 
11400 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
11401 			 struct drm_atomic_state *state,
11402 			 struct drm_crtc *crtc,
11403 			 struct drm_crtc_state *old_crtc_state,
11404 			 struct drm_crtc_state *new_crtc_state,
11405 			 bool enable,
11406 			 bool *lock_and_validation_needed)
11407 {
11408 	struct dm_atomic_state *dm_state = NULL;
11409 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11410 	struct dc_stream_state *new_stream;
11411 	struct amdgpu_device *adev = dm->adev;
11412 	int ret = 0;
11413 
11414 	/*
11415 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
11416 	 * update changed items
11417 	 */
11418 	struct amdgpu_crtc *acrtc = NULL;
11419 	struct drm_connector *connector = NULL;
11420 	struct amdgpu_dm_connector *aconnector = NULL;
11421 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
11422 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
11423 
11424 	new_stream = NULL;
11425 
11426 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11427 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11428 	acrtc = to_amdgpu_crtc(crtc);
11429 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
11430 	if (connector)
11431 		aconnector = to_amdgpu_dm_connector(connector);
11432 
11433 	/* TODO This hack should go away */
11434 	if (connector && enable) {
11435 		/* Make sure fake sink is created in plug-in scenario */
11436 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
11437 									connector);
11438 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
11439 									connector);
11440 
11441 		if (WARN_ON(!drm_new_conn_state)) {
11442 			ret = -EINVAL;
11443 			goto fail;
11444 		}
11445 
11446 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
11447 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
11448 
11449 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11450 			goto skip_modeset;
11451 
11452 		new_stream = create_validate_stream_for_sink(connector,
11453 							     &new_crtc_state->mode,
11454 							     dm_new_conn_state,
11455 							     dm_old_crtc_state->stream);
11456 
11457 		/*
11458 		 * we can have no stream on ACTION_SET if a display
11459 		 * was disconnected during S3, in this case it is not an
11460 		 * error, the OS will be updated after detection, and
11461 		 * will do the right thing on next atomic commit
11462 		 */
11463 
11464 		if (!new_stream) {
11465 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
11466 					__func__, acrtc->base.base.id);
11467 			ret = -ENOMEM;
11468 			goto fail;
11469 		}
11470 
11471 		/*
11472 		 * TODO: Check VSDB bits to decide whether this should
11473 		 * be enabled or not.
11474 		 */
11475 		new_stream->triggered_crtc_reset.enabled =
11476 			dm->force_timing_sync;
11477 
11478 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11479 
11480 		ret = fill_hdr_info_packet(drm_new_conn_state,
11481 					   &new_stream->hdr_static_metadata);
11482 		if (ret)
11483 			goto fail;
11484 
11485 		/*
11486 		 * If we already removed the old stream from the context
11487 		 * (and set the new stream to NULL) then we can't reuse
11488 		 * the old stream even if the stream and scaling are unchanged.
11489 		 * We'll hit the BUG_ON and black screen.
11490 		 *
11491 		 * TODO: Refactor this function to allow this check to work
11492 		 * in all conditions.
11493 		 */
11494 		if (amdgpu_freesync_vid_mode &&
11495 		    dm_new_crtc_state->stream &&
11496 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
11497 			goto skip_modeset;
11498 
11499 		if (dm_new_crtc_state->stream &&
11500 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11501 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
11502 			new_crtc_state->mode_changed = false;
11503 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
11504 					 new_crtc_state->mode_changed);
11505 		}
11506 	}
11507 
11508 	/* mode_changed flag may get updated above, need to check again */
11509 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11510 		goto skip_modeset;
11511 
11512 	drm_dbg_state(state->dev,
11513 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
11514 		acrtc->crtc_id,
11515 		new_crtc_state->enable,
11516 		new_crtc_state->active,
11517 		new_crtc_state->planes_changed,
11518 		new_crtc_state->mode_changed,
11519 		new_crtc_state->active_changed,
11520 		new_crtc_state->connectors_changed);
11521 
11522 	/* Remove stream for any changed/disabled CRTC */
11523 	if (!enable) {
11524 
11525 		if (!dm_old_crtc_state->stream)
11526 			goto skip_modeset;
11527 
11528 		/* Unset freesync video if it was active before */
11529 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
11530 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
11531 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
11532 		}
11533 
11534 		/* Now check if we should set freesync video mode */
11535 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
11536 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11537 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
11538 		    is_timing_unchanged_for_freesync(new_crtc_state,
11539 						     old_crtc_state)) {
11540 			new_crtc_state->mode_changed = false;
11541 			drm_dbg_driver(adev_to_drm(adev),
11542 				"Mode change not required for front porch change, setting mode_changed to %d",
11543 				new_crtc_state->mode_changed);
11544 
11545 			set_freesync_fixed_config(dm_new_crtc_state);
11546 
11547 			goto skip_modeset;
11548 		} else if (amdgpu_freesync_vid_mode && aconnector &&
11549 			   is_freesync_video_mode(&new_crtc_state->mode,
11550 						  aconnector)) {
11551 			struct drm_display_mode *high_mode;
11552 
11553 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
11554 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
11555 				set_freesync_fixed_config(dm_new_crtc_state);
11556 		}
11557 
11558 		ret = dm_atomic_get_state(state, &dm_state);
11559 		if (ret)
11560 			goto fail;
11561 
11562 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
11563 				crtc->base.id);
11564 
11565 		/* i.e. reset mode */
11566 		if (dc_state_remove_stream(
11567 				dm->dc,
11568 				dm_state->context,
11569 				dm_old_crtc_state->stream) != DC_OK) {
11570 			ret = -EINVAL;
11571 			goto fail;
11572 		}
11573 
11574 		dc_stream_release(dm_old_crtc_state->stream);
11575 		dm_new_crtc_state->stream = NULL;
11576 
11577 		reset_freesync_config_for_crtc(dm_new_crtc_state);
11578 
11579 		*lock_and_validation_needed = true;
11580 
11581 	} else {/* Add stream for any updated/enabled CRTC */
11582 		/*
11583 		 * Quick fix to prevent NULL pointer on new_stream when
11584 		 * added MST connectors not found in existing crtc_state in the chained mode
11585 		 * TODO: need to dig out the root cause of that
11586 		 */
11587 		if (!connector)
11588 			goto skip_modeset;
11589 
11590 		if (modereset_required(new_crtc_state))
11591 			goto skip_modeset;
11592 
11593 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
11594 				     dm_old_crtc_state->stream)) {
11595 
11596 			WARN_ON(dm_new_crtc_state->stream);
11597 
11598 			ret = dm_atomic_get_state(state, &dm_state);
11599 			if (ret)
11600 				goto fail;
11601 
11602 			dm_new_crtc_state->stream = new_stream;
11603 
11604 			dc_stream_retain(new_stream);
11605 
11606 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
11607 					 crtc->base.id);
11608 
11609 			if (dc_state_add_stream(
11610 					dm->dc,
11611 					dm_state->context,
11612 					dm_new_crtc_state->stream) != DC_OK) {
11613 				ret = -EINVAL;
11614 				goto fail;
11615 			}
11616 
11617 			*lock_and_validation_needed = true;
11618 		}
11619 	}
11620 
11621 skip_modeset:
11622 	/* Release extra reference */
11623 	if (new_stream)
11624 		dc_stream_release(new_stream);
11625 
11626 	/*
11627 	 * We want to do dc stream updates that do not require a
11628 	 * full modeset below.
11629 	 */
11630 	if (!(enable && connector && new_crtc_state->active))
11631 		return 0;
11632 	/*
11633 	 * Given above conditions, the dc state cannot be NULL because:
11634 	 * 1. We're in the process of enabling CRTCs (just been added
11635 	 *    to the dc context, or already is on the context)
11636 	 * 2. Has a valid connector attached, and
11637 	 * 3. Is currently active and enabled.
11638 	 * => The dc stream state currently exists.
11639 	 */
11640 	BUG_ON(dm_new_crtc_state->stream == NULL);
11641 
11642 	/* Scaling or underscan settings */
11643 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
11644 				drm_atomic_crtc_needs_modeset(new_crtc_state))
11645 		update_stream_scaling_settings(adev_to_drm(adev),
11646 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
11647 
11648 	/* ABM settings */
11649 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11650 
11651 	/*
11652 	 * Color management settings. We also update color properties
11653 	 * when a modeset is needed, to ensure it gets reprogrammed.
11654 	 */
11655 	if (dm_new_crtc_state->base.color_mgmt_changed ||
11656 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11657 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
11658 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
11659 		if (ret)
11660 			goto fail;
11661 	}
11662 
11663 	/* Update Freesync settings. */
11664 	get_freesync_config_for_crtc(dm_new_crtc_state,
11665 				     dm_new_conn_state);
11666 
11667 	return ret;
11668 
11669 fail:
11670 	if (new_stream)
11671 		dc_stream_release(new_stream);
11672 	return ret;
11673 }
11674 
11675 static bool should_reset_plane(struct drm_atomic_state *state,
11676 			       struct drm_plane *plane,
11677 			       struct drm_plane_state *old_plane_state,
11678 			       struct drm_plane_state *new_plane_state)
11679 {
11680 	struct drm_plane *other;
11681 	struct drm_plane_state *old_other_state, *new_other_state;
11682 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11683 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
11684 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
11685 	struct drm_connector_state *new_con_state;
11686 	struct drm_connector *connector;
11687 	int i;
11688 
11689 	/*
11690 	 * TODO: Remove this hack for all asics once it proves that the
11691 	 * fast updates works fine on DCN3.2+.
11692 	 */
11693 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
11694 	    state->allow_modeset)
11695 		return true;
11696 
11697 	/* Check for writeback commit */
11698 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11699 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11700 			continue;
11701 
11702 		if (new_con_state->writeback_job)
11703 			return true;
11704 	}
11705 
11706 	if (amdgpu_in_reset(adev) && state->allow_modeset)
11707 		return true;
11708 
11709 	/* Exit early if we know that we're adding or removing the plane. */
11710 	if (old_plane_state->crtc != new_plane_state->crtc)
11711 		return true;
11712 
11713 	/* old crtc == new_crtc == NULL, plane not in context. */
11714 	if (!new_plane_state->crtc)
11715 		return false;
11716 
11717 	new_crtc_state =
11718 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
11719 	old_crtc_state =
11720 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
11721 
11722 	if (!new_crtc_state)
11723 		return true;
11724 
11725 	/*
11726 	 * A change in cursor mode means a new dc pipe needs to be acquired or
11727 	 * released from the state
11728 	 */
11729 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
11730 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
11731 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
11732 	    old_dm_crtc_state != NULL &&
11733 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
11734 		return true;
11735 	}
11736 
11737 	/* CRTC Degamma changes currently require us to recreate planes. */
11738 	if (new_crtc_state->color_mgmt_changed)
11739 		return true;
11740 
11741 	/*
11742 	 * On zpos change, planes need to be reordered by removing and re-adding
11743 	 * them one by one to the dc state, in order of descending zpos.
11744 	 *
11745 	 * TODO: We can likely skip bandwidth validation if the only thing that
11746 	 * changed about the plane was it'z z-ordering.
11747 	 */
11748 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
11749 		return true;
11750 
11751 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
11752 		return true;
11753 
11754 	/*
11755 	 * If there are any new primary or overlay planes being added or
11756 	 * removed then the z-order can potentially change. To ensure
11757 	 * correct z-order and pipe acquisition the current DC architecture
11758 	 * requires us to remove and recreate all existing planes.
11759 	 *
11760 	 * TODO: Come up with a more elegant solution for this.
11761 	 */
11762 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
11763 		struct amdgpu_framebuffer *old_afb, *new_afb;
11764 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
11765 
11766 		dm_new_other_state = to_dm_plane_state(new_other_state);
11767 		dm_old_other_state = to_dm_plane_state(old_other_state);
11768 
11769 		if (other->type == DRM_PLANE_TYPE_CURSOR)
11770 			continue;
11771 
11772 		if (old_other_state->crtc != new_plane_state->crtc &&
11773 		    new_other_state->crtc != new_plane_state->crtc)
11774 			continue;
11775 
11776 		if (old_other_state->crtc != new_other_state->crtc)
11777 			return true;
11778 
11779 		/* Src/dst size and scaling updates. */
11780 		if (old_other_state->src_w != new_other_state->src_w ||
11781 		    old_other_state->src_h != new_other_state->src_h ||
11782 		    old_other_state->crtc_w != new_other_state->crtc_w ||
11783 		    old_other_state->crtc_h != new_other_state->crtc_h)
11784 			return true;
11785 
11786 		/* Rotation / mirroring updates. */
11787 		if (old_other_state->rotation != new_other_state->rotation)
11788 			return true;
11789 
11790 		/* Blending updates. */
11791 		if (old_other_state->pixel_blend_mode !=
11792 		    new_other_state->pixel_blend_mode)
11793 			return true;
11794 
11795 		/* Alpha updates. */
11796 		if (old_other_state->alpha != new_other_state->alpha)
11797 			return true;
11798 
11799 		/* Colorspace changes. */
11800 		if (old_other_state->color_range != new_other_state->color_range ||
11801 		    old_other_state->color_encoding != new_other_state->color_encoding)
11802 			return true;
11803 
11804 		/* HDR/Transfer Function changes. */
11805 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
11806 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
11807 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
11808 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
11809 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
11810 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
11811 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
11812 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
11813 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
11814 			return true;
11815 
11816 		/* Framebuffer checks fall at the end. */
11817 		if (!old_other_state->fb || !new_other_state->fb)
11818 			continue;
11819 
11820 		/* Pixel format changes can require bandwidth updates. */
11821 		if (old_other_state->fb->format != new_other_state->fb->format)
11822 			return true;
11823 
11824 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
11825 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
11826 
11827 		/* Tiling and DCC changes also require bandwidth updates. */
11828 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
11829 		    old_afb->base.modifier != new_afb->base.modifier)
11830 			return true;
11831 	}
11832 
11833 	return false;
11834 }
11835 
11836 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
11837 			      struct drm_plane_state *new_plane_state,
11838 			      struct drm_framebuffer *fb)
11839 {
11840 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
11841 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
11842 	unsigned int pitch;
11843 	bool linear;
11844 
11845 	if (fb->width > new_acrtc->max_cursor_width ||
11846 	    fb->height > new_acrtc->max_cursor_height) {
11847 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB size %dx%d\n",
11848 				 new_plane_state->fb->width,
11849 				 new_plane_state->fb->height);
11850 		return -EINVAL;
11851 	}
11852 	if (new_plane_state->src_w != fb->width << 16 ||
11853 	    new_plane_state->src_h != fb->height << 16) {
11854 		drm_dbg_atomic(adev_to_drm(adev), "Cropping not supported for cursor plane\n");
11855 		return -EINVAL;
11856 	}
11857 
11858 	/* Pitch in pixels */
11859 	pitch = fb->pitches[0] / fb->format->cpp[0];
11860 
11861 	if (fb->width != pitch) {
11862 		drm_dbg_atomic(adev_to_drm(adev), "Cursor FB width %d doesn't match pitch %d",
11863 				 fb->width, pitch);
11864 		return -EINVAL;
11865 	}
11866 
11867 	switch (pitch) {
11868 	case 64:
11869 	case 128:
11870 	case 256:
11871 		/* FB pitch is supported by cursor plane */
11872 		break;
11873 	default:
11874 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB pitch %d px\n", pitch);
11875 		return -EINVAL;
11876 	}
11877 
11878 	/* Core DRM takes care of checking FB modifiers, so we only need to
11879 	 * check tiling flags when the FB doesn't have a modifier.
11880 	 */
11881 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
11882 		if (adev->family == AMDGPU_FAMILY_GC_12_0_0) {
11883 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
11884 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
11885 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
11886 		} else {
11887 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
11888 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
11889 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
11890 		}
11891 		if (!linear) {
11892 			drm_dbg_atomic(adev_to_drm(adev), "Cursor FB not linear");
11893 			return -EINVAL;
11894 		}
11895 	}
11896 
11897 	return 0;
11898 }
11899 
11900 /*
11901  * Helper function for checking the cursor in native mode
11902  */
11903 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
11904 					struct drm_plane *plane,
11905 					struct drm_plane_state *new_plane_state,
11906 					bool enable)
11907 {
11908 
11909 	struct amdgpu_crtc *new_acrtc;
11910 	int ret;
11911 
11912 	if (!enable || !new_plane_crtc ||
11913 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
11914 		return 0;
11915 
11916 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
11917 
11918 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
11919 		drm_dbg_atomic(new_plane_crtc->dev, "Cropping not supported for cursor plane\n");
11920 		return -EINVAL;
11921 	}
11922 
11923 	if (new_plane_state->fb) {
11924 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
11925 						new_plane_state->fb);
11926 		if (ret)
11927 			return ret;
11928 	}
11929 
11930 	return 0;
11931 }
11932 
11933 static bool dm_should_update_native_cursor(struct drm_atomic_state *state,
11934 					   struct drm_crtc *old_plane_crtc,
11935 					   struct drm_crtc *new_plane_crtc,
11936 					   bool enable)
11937 {
11938 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11939 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11940 
11941 	if (!enable) {
11942 		if (old_plane_crtc == NULL)
11943 			return true;
11944 
11945 		old_crtc_state = drm_atomic_get_old_crtc_state(
11946 			state, old_plane_crtc);
11947 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11948 
11949 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
11950 	} else {
11951 		if (new_plane_crtc == NULL)
11952 			return true;
11953 
11954 		new_crtc_state = drm_atomic_get_new_crtc_state(
11955 			state, new_plane_crtc);
11956 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11957 
11958 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
11959 	}
11960 }
11961 
11962 static int dm_update_plane_state(struct dc *dc,
11963 				 struct drm_atomic_state *state,
11964 				 struct drm_plane *plane,
11965 				 struct drm_plane_state *old_plane_state,
11966 				 struct drm_plane_state *new_plane_state,
11967 				 bool enable,
11968 				 bool *lock_and_validation_needed,
11969 				 bool *is_top_most_overlay)
11970 {
11971 
11972 	struct dm_atomic_state *dm_state = NULL;
11973 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
11974 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11975 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
11976 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
11977 	bool needs_reset, update_native_cursor;
11978 	int ret = 0;
11979 
11980 
11981 	new_plane_crtc = new_plane_state->crtc;
11982 	old_plane_crtc = old_plane_state->crtc;
11983 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
11984 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
11985 
11986 	update_native_cursor = dm_should_update_native_cursor(state,
11987 							      old_plane_crtc,
11988 							      new_plane_crtc,
11989 							      enable);
11990 
11991 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
11992 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
11993 						    new_plane_state, enable);
11994 		if (ret)
11995 			return ret;
11996 
11997 		return 0;
11998 	}
11999 
12000 	needs_reset = should_reset_plane(state, plane, old_plane_state,
12001 					 new_plane_state);
12002 
12003 	/* Remove any changed/removed planes */
12004 	if (!enable) {
12005 		if (!needs_reset)
12006 			return 0;
12007 
12008 		if (!old_plane_crtc)
12009 			return 0;
12010 
12011 		old_crtc_state = drm_atomic_get_old_crtc_state(
12012 				state, old_plane_crtc);
12013 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12014 
12015 		if (!dm_old_crtc_state->stream)
12016 			return 0;
12017 
12018 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
12019 				plane->base.id, old_plane_crtc->base.id);
12020 
12021 		ret = dm_atomic_get_state(state, &dm_state);
12022 		if (ret)
12023 			return ret;
12024 
12025 		if (!dc_state_remove_plane(
12026 				dc,
12027 				dm_old_crtc_state->stream,
12028 				dm_old_plane_state->dc_state,
12029 				dm_state->context)) {
12030 
12031 			return -EINVAL;
12032 		}
12033 
12034 		if (dm_old_plane_state->dc_state)
12035 			dc_plane_state_release(dm_old_plane_state->dc_state);
12036 
12037 		dm_new_plane_state->dc_state = NULL;
12038 
12039 		*lock_and_validation_needed = true;
12040 
12041 	} else { /* Add new planes */
12042 		struct dc_plane_state *dc_new_plane_state;
12043 
12044 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
12045 			return 0;
12046 
12047 		if (!new_plane_crtc)
12048 			return 0;
12049 
12050 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
12051 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12052 
12053 		if (!dm_new_crtc_state->stream)
12054 			return 0;
12055 
12056 		if (!needs_reset)
12057 			return 0;
12058 
12059 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
12060 		if (ret)
12061 			goto out;
12062 
12063 		WARN_ON(dm_new_plane_state->dc_state);
12064 
12065 		dc_new_plane_state = dc_create_plane_state(dc);
12066 		if (!dc_new_plane_state) {
12067 			ret = -ENOMEM;
12068 			goto out;
12069 		}
12070 
12071 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
12072 				 plane->base.id, new_plane_crtc->base.id);
12073 
12074 		ret = fill_dc_plane_attributes(
12075 			drm_to_adev(new_plane_crtc->dev),
12076 			dc_new_plane_state,
12077 			new_plane_state,
12078 			new_crtc_state);
12079 		if (ret) {
12080 			dc_plane_state_release(dc_new_plane_state);
12081 			goto out;
12082 		}
12083 
12084 		ret = dm_atomic_get_state(state, &dm_state);
12085 		if (ret) {
12086 			dc_plane_state_release(dc_new_plane_state);
12087 			goto out;
12088 		}
12089 
12090 		/*
12091 		 * Any atomic check errors that occur after this will
12092 		 * not need a release. The plane state will be attached
12093 		 * to the stream, and therefore part of the atomic
12094 		 * state. It'll be released when the atomic state is
12095 		 * cleaned.
12096 		 */
12097 		if (!dc_state_add_plane(
12098 				dc,
12099 				dm_new_crtc_state->stream,
12100 				dc_new_plane_state,
12101 				dm_state->context)) {
12102 
12103 			dc_plane_state_release(dc_new_plane_state);
12104 			ret = -EINVAL;
12105 			goto out;
12106 		}
12107 
12108 		dm_new_plane_state->dc_state = dc_new_plane_state;
12109 
12110 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
12111 
12112 		/* Tell DC to do a full surface update every time there
12113 		 * is a plane change. Inefficient, but works for now.
12114 		 */
12115 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
12116 
12117 		*lock_and_validation_needed = true;
12118 	}
12119 
12120 out:
12121 	/* If enabling cursor overlay failed, attempt fallback to native mode */
12122 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
12123 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12124 						    new_plane_state, enable);
12125 		if (ret)
12126 			return ret;
12127 
12128 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
12129 	}
12130 
12131 	return ret;
12132 }
12133 
12134 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
12135 				       int *src_w, int *src_h)
12136 {
12137 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
12138 	case DRM_MODE_ROTATE_90:
12139 	case DRM_MODE_ROTATE_270:
12140 		*src_w = plane_state->src_h >> 16;
12141 		*src_h = plane_state->src_w >> 16;
12142 		break;
12143 	case DRM_MODE_ROTATE_0:
12144 	case DRM_MODE_ROTATE_180:
12145 	default:
12146 		*src_w = plane_state->src_w >> 16;
12147 		*src_h = plane_state->src_h >> 16;
12148 		break;
12149 	}
12150 }
12151 
12152 static void
12153 dm_get_plane_scale(struct drm_plane_state *plane_state,
12154 		   int *out_plane_scale_w, int *out_plane_scale_h)
12155 {
12156 	int plane_src_w, plane_src_h;
12157 
12158 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
12159 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
12160 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
12161 }
12162 
12163 /*
12164  * The normalized_zpos value cannot be used by this iterator directly. It's only
12165  * calculated for enabled planes, potentially causing normalized_zpos collisions
12166  * between enabled/disabled planes in the atomic state. We need a unique value
12167  * so that the iterator will not generate the same object twice, or loop
12168  * indefinitely.
12169  */
12170 static inline struct __drm_planes_state *__get_next_zpos(
12171 	struct drm_atomic_state *state,
12172 	struct __drm_planes_state *prev)
12173 {
12174 	unsigned int highest_zpos = 0, prev_zpos = 256;
12175 	uint32_t highest_id = 0, prev_id = UINT_MAX;
12176 	struct drm_plane_state *new_plane_state;
12177 	struct drm_plane *plane;
12178 	int i, highest_i = -1;
12179 
12180 	if (prev != NULL) {
12181 		prev_zpos = prev->new_state->zpos;
12182 		prev_id = prev->ptr->base.id;
12183 	}
12184 
12185 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
12186 		/* Skip planes with higher zpos than the previously returned */
12187 		if (new_plane_state->zpos > prev_zpos ||
12188 		    (new_plane_state->zpos == prev_zpos &&
12189 		     plane->base.id >= prev_id))
12190 			continue;
12191 
12192 		/* Save the index of the plane with highest zpos */
12193 		if (new_plane_state->zpos > highest_zpos ||
12194 		    (new_plane_state->zpos == highest_zpos &&
12195 		     plane->base.id > highest_id)) {
12196 			highest_zpos = new_plane_state->zpos;
12197 			highest_id = plane->base.id;
12198 			highest_i = i;
12199 		}
12200 	}
12201 
12202 	if (highest_i < 0)
12203 		return NULL;
12204 
12205 	return &state->planes[highest_i];
12206 }
12207 
12208 /*
12209  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
12210  * by descending zpos, as read from the new plane state. This is the same
12211  * ordering as defined by drm_atomic_normalize_zpos().
12212  */
12213 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
12214 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
12215 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
12216 		for_each_if(((plane) = __i->ptr,				\
12217 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
12218 			     (old_plane_state) = __i->old_state,		\
12219 			     (new_plane_state) = __i->new_state, 1))
12220 
12221 static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
12222 {
12223 	struct drm_connector *connector;
12224 	struct drm_connector_state *conn_state, *old_conn_state;
12225 	struct amdgpu_dm_connector *aconnector = NULL;
12226 	int i;
12227 
12228 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
12229 		if (!conn_state->crtc)
12230 			conn_state = old_conn_state;
12231 
12232 		if (conn_state->crtc != crtc)
12233 			continue;
12234 
12235 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
12236 			continue;
12237 
12238 		aconnector = to_amdgpu_dm_connector(connector);
12239 		if (!aconnector->mst_output_port || !aconnector->mst_root)
12240 			aconnector = NULL;
12241 		else
12242 			break;
12243 	}
12244 
12245 	if (!aconnector)
12246 		return 0;
12247 
12248 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
12249 }
12250 
12251 /**
12252  * DOC: Cursor Modes - Native vs Overlay
12253  *
12254  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
12255  * plane. It does not require a dedicated hw plane to enable, but it is
12256  * subjected to the same z-order and scaling as the hw plane. It also has format
12257  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
12258  * hw plane.
12259  *
12260  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
12261  * own scaling and z-pos. It also has no blending restrictions. It lends to a
12262  * cursor behavior more akin to a DRM client's expectations. However, it does
12263  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
12264  * available.
12265  */
12266 
12267 /**
12268  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
12269  * @adev: amdgpu device
12270  * @state: DRM atomic state
12271  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
12272  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
12273  *
12274  * Get whether the cursor should be enabled in native mode, or overlay mode, on
12275  * the dm_crtc_state.
12276  *
12277  * The cursor should be enabled in overlay mode if there exists an underlying
12278  * plane - on which the cursor may be blended - that is either YUV formatted, or
12279  * scaled differently from the cursor.
12280  *
12281  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
12282  * calling this function.
12283  *
12284  * Return: 0 on success, or an error code if getting the cursor plane state
12285  * failed.
12286  */
12287 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
12288 				   struct drm_atomic_state *state,
12289 				   struct dm_crtc_state *dm_crtc_state,
12290 				   enum amdgpu_dm_cursor_mode *cursor_mode)
12291 {
12292 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
12293 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
12294 	struct drm_plane *plane;
12295 	bool consider_mode_change = false;
12296 	bool entire_crtc_covered = false;
12297 	bool cursor_changed = false;
12298 	int underlying_scale_w, underlying_scale_h;
12299 	int cursor_scale_w, cursor_scale_h;
12300 	int i;
12301 
12302 	/* Overlay cursor not supported on HW before DCN
12303 	 * DCN401 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
12304 	 * as previous DCN generations, so enable native mode on DCN401 in addition to DCE
12305 	 */
12306 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0 ||
12307 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1)) {
12308 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12309 		return 0;
12310 	}
12311 
12312 	/* Init cursor_mode to be the same as current */
12313 	*cursor_mode = dm_crtc_state->cursor_mode;
12314 
12315 	/*
12316 	 * Cursor mode can change if a plane's format changes, scale changes, is
12317 	 * enabled/disabled, or z-order changes.
12318 	 */
12319 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
12320 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
12321 
12322 		/* Only care about planes on this CRTC */
12323 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
12324 			continue;
12325 
12326 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
12327 			cursor_changed = true;
12328 
12329 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
12330 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
12331 		    old_plane_state->fb->format != plane_state->fb->format) {
12332 			consider_mode_change = true;
12333 			break;
12334 		}
12335 
12336 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
12337 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
12338 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
12339 			consider_mode_change = true;
12340 			break;
12341 		}
12342 	}
12343 
12344 	if (!consider_mode_change && !crtc_state->zpos_changed)
12345 		return 0;
12346 
12347 	/*
12348 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
12349 	 * no need to set cursor mode. This avoids needlessly locking the cursor
12350 	 * state.
12351 	 */
12352 	if (!cursor_changed &&
12353 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
12354 		return 0;
12355 	}
12356 
12357 	cursor_state = drm_atomic_get_plane_state(state,
12358 						  crtc_state->crtc->cursor);
12359 	if (IS_ERR(cursor_state))
12360 		return PTR_ERR(cursor_state);
12361 
12362 	/* Cursor is disabled */
12363 	if (!cursor_state->fb)
12364 		return 0;
12365 
12366 	/* For all planes in descending z-order (all of which are below cursor
12367 	 * as per zpos definitions), check their scaling and format
12368 	 */
12369 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
12370 
12371 		/* Only care about non-cursor planes on this CRTC */
12372 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
12373 		    plane->type == DRM_PLANE_TYPE_CURSOR)
12374 			continue;
12375 
12376 		/* Underlying plane is YUV format - use overlay cursor */
12377 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
12378 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12379 			return 0;
12380 		}
12381 
12382 		dm_get_plane_scale(plane_state,
12383 				   &underlying_scale_w, &underlying_scale_h);
12384 		dm_get_plane_scale(cursor_state,
12385 				   &cursor_scale_w, &cursor_scale_h);
12386 
12387 		/* Underlying plane has different scale - use overlay cursor */
12388 		if (cursor_scale_w != underlying_scale_w &&
12389 		    cursor_scale_h != underlying_scale_h) {
12390 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12391 			return 0;
12392 		}
12393 
12394 		/* If this plane covers the whole CRTC, no need to check planes underneath */
12395 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
12396 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
12397 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
12398 			entire_crtc_covered = true;
12399 			break;
12400 		}
12401 	}
12402 
12403 	/* If planes do not cover the entire CRTC, use overlay mode to enable
12404 	 * cursor over holes
12405 	 */
12406 	if (entire_crtc_covered)
12407 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12408 	else
12409 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12410 
12411 	return 0;
12412 }
12413 
12414 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
12415 					    struct drm_atomic_state *state,
12416 					    struct drm_crtc_state *crtc_state)
12417 {
12418 	struct drm_plane *plane;
12419 	struct drm_plane_state *new_plane_state, *old_plane_state;
12420 
12421 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
12422 		new_plane_state = drm_atomic_get_plane_state(state, plane);
12423 		old_plane_state = drm_atomic_get_plane_state(state, plane);
12424 
12425 		if (IS_ERR(new_plane_state) || IS_ERR(old_plane_state)) {
12426 			drm_err(dev, "Failed to get plane state for plane %s\n", plane->name);
12427 			return false;
12428 		}
12429 
12430 		if (old_plane_state->fb && new_plane_state->fb &&
12431 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
12432 			return true;
12433 	}
12434 
12435 	return false;
12436 }
12437 
12438 /**
12439  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
12440  *
12441  * @dev: The DRM device
12442  * @state: The atomic state to commit
12443  *
12444  * Validate that the given atomic state is programmable by DC into hardware.
12445  * This involves constructing a &struct dc_state reflecting the new hardware
12446  * state we wish to commit, then querying DC to see if it is programmable. It's
12447  * important not to modify the existing DC state. Otherwise, atomic_check
12448  * may unexpectedly commit hardware changes.
12449  *
12450  * When validating the DC state, it's important that the right locks are
12451  * acquired. For full updates case which removes/adds/updates streams on one
12452  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
12453  * that any such full update commit will wait for completion of any outstanding
12454  * flip using DRMs synchronization events.
12455  *
12456  * Note that DM adds the affected connectors for all CRTCs in state, when that
12457  * might not seem necessary. This is because DC stream creation requires the
12458  * DC sink, which is tied to the DRM connector state. Cleaning this up should
12459  * be possible but non-trivial - a possible TODO item.
12460  *
12461  * Return: -Error code if validation failed.
12462  */
12463 static int amdgpu_dm_atomic_check(struct drm_device *dev,
12464 				  struct drm_atomic_state *state)
12465 {
12466 	struct amdgpu_device *adev = drm_to_adev(dev);
12467 	struct dm_atomic_state *dm_state = NULL;
12468 	struct dc *dc = adev->dm.dc;
12469 	struct drm_connector *connector;
12470 	struct drm_connector_state *old_con_state, *new_con_state;
12471 	struct drm_crtc *crtc;
12472 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12473 	struct drm_plane *plane;
12474 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
12475 	enum dc_status status;
12476 	int ret, i;
12477 	bool lock_and_validation_needed = false;
12478 	bool is_top_most_overlay = true;
12479 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12480 	struct drm_dp_mst_topology_mgr *mgr;
12481 	struct drm_dp_mst_topology_state *mst_state;
12482 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
12483 
12484 	trace_amdgpu_dm_atomic_check_begin(state);
12485 
12486 	ret = drm_atomic_helper_check_modeset(dev, state);
12487 	if (ret) {
12488 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
12489 		goto fail;
12490 	}
12491 
12492 	/* Check connector changes */
12493 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
12494 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
12495 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
12496 
12497 		/* Skip connectors that are disabled or part of modeset already. */
12498 		if (!new_con_state->crtc)
12499 			continue;
12500 
12501 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
12502 		if (IS_ERR(new_crtc_state)) {
12503 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
12504 			ret = PTR_ERR(new_crtc_state);
12505 			goto fail;
12506 		}
12507 
12508 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
12509 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
12510 			new_crtc_state->connectors_changed = true;
12511 	}
12512 
12513 	if (dc_resource_is_dsc_encoding_supported(dc)) {
12514 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12515 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
12516 				ret = add_affected_mst_dsc_crtcs(state, crtc);
12517 				if (ret) {
12518 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
12519 					goto fail;
12520 				}
12521 			}
12522 		}
12523 	}
12524 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12525 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12526 
12527 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
12528 		    !new_crtc_state->color_mgmt_changed &&
12529 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
12530 			dm_old_crtc_state->dsc_force_changed == false)
12531 			continue;
12532 
12533 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
12534 		if (ret) {
12535 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
12536 			goto fail;
12537 		}
12538 
12539 		if (!new_crtc_state->enable)
12540 			continue;
12541 
12542 		ret = drm_atomic_add_affected_connectors(state, crtc);
12543 		if (ret) {
12544 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
12545 			goto fail;
12546 		}
12547 
12548 		ret = drm_atomic_add_affected_planes(state, crtc);
12549 		if (ret) {
12550 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
12551 			goto fail;
12552 		}
12553 
12554 		if (dm_old_crtc_state->dsc_force_changed)
12555 			new_crtc_state->mode_changed = true;
12556 	}
12557 
12558 	/*
12559 	 * Add all primary and overlay planes on the CRTC to the state
12560 	 * whenever a plane is enabled to maintain correct z-ordering
12561 	 * and to enable fast surface updates.
12562 	 */
12563 	drm_for_each_crtc(crtc, dev) {
12564 		bool modified = false;
12565 
12566 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
12567 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12568 				continue;
12569 
12570 			if (new_plane_state->crtc == crtc ||
12571 			    old_plane_state->crtc == crtc) {
12572 				modified = true;
12573 				break;
12574 			}
12575 		}
12576 
12577 		if (!modified)
12578 			continue;
12579 
12580 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
12581 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12582 				continue;
12583 
12584 			new_plane_state =
12585 				drm_atomic_get_plane_state(state, plane);
12586 
12587 			if (IS_ERR(new_plane_state)) {
12588 				ret = PTR_ERR(new_plane_state);
12589 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
12590 				goto fail;
12591 			}
12592 		}
12593 	}
12594 
12595 	/*
12596 	 * DC consults the zpos (layer_index in DC terminology) to determine the
12597 	 * hw plane on which to enable the hw cursor (see
12598 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
12599 	 * atomic state, so call drm helper to normalize zpos.
12600 	 */
12601 	ret = drm_atomic_normalize_zpos(dev, state);
12602 	if (ret) {
12603 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
12604 		goto fail;
12605 	}
12606 
12607 	/*
12608 	 * Determine whether cursors on each CRTC should be enabled in native or
12609 	 * overlay mode.
12610 	 */
12611 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12612 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12613 
12614 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
12615 					      &dm_new_crtc_state->cursor_mode);
12616 		if (ret) {
12617 			drm_dbg(dev, "Failed to determine cursor mode\n");
12618 			goto fail;
12619 		}
12620 
12621 		/*
12622 		 * If overlay cursor is needed, DC cannot go through the
12623 		 * native cursor update path. All enabled planes on the CRTC
12624 		 * need to be added for DC to not disable a plane by mistake
12625 		 */
12626 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
12627 			ret = drm_atomic_add_affected_planes(state, crtc);
12628 			if (ret)
12629 				goto fail;
12630 		}
12631 	}
12632 
12633 	/* Remove exiting planes if they are modified */
12634 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
12635 
12636 		ret = dm_update_plane_state(dc, state, plane,
12637 					    old_plane_state,
12638 					    new_plane_state,
12639 					    false,
12640 					    &lock_and_validation_needed,
12641 					    &is_top_most_overlay);
12642 		if (ret) {
12643 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
12644 			goto fail;
12645 		}
12646 	}
12647 
12648 	/* Disable all crtcs which require disable */
12649 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12650 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
12651 					   old_crtc_state,
12652 					   new_crtc_state,
12653 					   false,
12654 					   &lock_and_validation_needed);
12655 		if (ret) {
12656 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
12657 			goto fail;
12658 		}
12659 	}
12660 
12661 	/* Enable all crtcs which require enable */
12662 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12663 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
12664 					   old_crtc_state,
12665 					   new_crtc_state,
12666 					   true,
12667 					   &lock_and_validation_needed);
12668 		if (ret) {
12669 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
12670 			goto fail;
12671 		}
12672 	}
12673 
12674 	/* Add new/modified planes */
12675 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
12676 		ret = dm_update_plane_state(dc, state, plane,
12677 					    old_plane_state,
12678 					    new_plane_state,
12679 					    true,
12680 					    &lock_and_validation_needed,
12681 					    &is_top_most_overlay);
12682 		if (ret) {
12683 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
12684 			goto fail;
12685 		}
12686 	}
12687 
12688 #if defined(CONFIG_DRM_AMD_DC_FP)
12689 	if (dc_resource_is_dsc_encoding_supported(dc)) {
12690 		ret = pre_validate_dsc(state, &dm_state, vars);
12691 		if (ret != 0)
12692 			goto fail;
12693 	}
12694 #endif
12695 
12696 	/* Run this here since we want to validate the streams we created */
12697 	ret = drm_atomic_helper_check_planes(dev, state);
12698 	if (ret) {
12699 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
12700 		goto fail;
12701 	}
12702 
12703 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12704 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12705 		if (dm_new_crtc_state->mpo_requested)
12706 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
12707 	}
12708 
12709 	/* Check cursor restrictions */
12710 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12711 		enum amdgpu_dm_cursor_mode required_cursor_mode;
12712 		int is_rotated, is_scaled;
12713 
12714 		/* Overlay cusor not subject to native cursor restrictions */
12715 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12716 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
12717 			continue;
12718 
12719 		/* Check if rotation or scaling is enabled on DCN401 */
12720 		if ((drm_plane_mask(crtc->cursor) & new_crtc_state->plane_mask) &&
12721 		    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1)) {
12722 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
12723 
12724 			is_rotated = new_cursor_state &&
12725 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
12726 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
12727 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
12728 
12729 			if (is_rotated || is_scaled) {
12730 				drm_dbg_driver(
12731 					crtc->dev,
12732 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
12733 					crtc->base.id, crtc->name);
12734 				ret = -EINVAL;
12735 				goto fail;
12736 			}
12737 		}
12738 
12739 		/* If HW can only do native cursor, check restrictions again */
12740 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
12741 					      &required_cursor_mode);
12742 		if (ret) {
12743 			drm_dbg_driver(crtc->dev,
12744 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
12745 				       crtc->base.id, crtc->name);
12746 			goto fail;
12747 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
12748 			drm_dbg_driver(crtc->dev,
12749 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling or YUV restrictions\n",
12750 				       crtc->base.id, crtc->name);
12751 			ret = -EINVAL;
12752 			goto fail;
12753 		}
12754 	}
12755 
12756 	if (state->legacy_cursor_update) {
12757 		/*
12758 		 * This is a fast cursor update coming from the plane update
12759 		 * helper, check if it can be done asynchronously for better
12760 		 * performance.
12761 		 */
12762 		state->async_update =
12763 			!drm_atomic_helper_async_check(dev, state);
12764 
12765 		/*
12766 		 * Skip the remaining global validation if this is an async
12767 		 * update. Cursor updates can be done without affecting
12768 		 * state or bandwidth calcs and this avoids the performance
12769 		 * penalty of locking the private state object and
12770 		 * allocating a new dc_state.
12771 		 */
12772 		if (state->async_update)
12773 			return 0;
12774 	}
12775 
12776 	/* Check scaling and underscan changes*/
12777 	/* TODO Removed scaling changes validation due to inability to commit
12778 	 * new stream into context w\o causing full reset. Need to
12779 	 * decide how to handle.
12780 	 */
12781 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
12782 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
12783 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
12784 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
12785 
12786 		/* Skip any modesets/resets */
12787 		if (!acrtc || drm_atomic_crtc_needs_modeset(
12788 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
12789 			continue;
12790 
12791 		/* Skip any thing not scale or underscan changes */
12792 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
12793 			continue;
12794 
12795 		lock_and_validation_needed = true;
12796 	}
12797 
12798 	/* set the slot info for each mst_state based on the link encoding format */
12799 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
12800 		struct amdgpu_dm_connector *aconnector;
12801 		struct drm_connector *connector;
12802 		struct drm_connector_list_iter iter;
12803 		u8 link_coding_cap;
12804 
12805 		drm_connector_list_iter_begin(dev, &iter);
12806 		drm_for_each_connector_iter(connector, &iter) {
12807 			if (connector->index == mst_state->mgr->conn_base_id) {
12808 				aconnector = to_amdgpu_dm_connector(connector);
12809 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
12810 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
12811 
12812 				break;
12813 			}
12814 		}
12815 		drm_connector_list_iter_end(&iter);
12816 	}
12817 
12818 	/**
12819 	 * Streams and planes are reset when there are changes that affect
12820 	 * bandwidth. Anything that affects bandwidth needs to go through
12821 	 * DC global validation to ensure that the configuration can be applied
12822 	 * to hardware.
12823 	 *
12824 	 * We have to currently stall out here in atomic_check for outstanding
12825 	 * commits to finish in this case because our IRQ handlers reference
12826 	 * DRM state directly - we can end up disabling interrupts too early
12827 	 * if we don't.
12828 	 *
12829 	 * TODO: Remove this stall and drop DM state private objects.
12830 	 */
12831 	if (lock_and_validation_needed) {
12832 		ret = dm_atomic_get_state(state, &dm_state);
12833 		if (ret) {
12834 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
12835 			goto fail;
12836 		}
12837 
12838 		ret = do_aquire_global_lock(dev, state);
12839 		if (ret) {
12840 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
12841 			goto fail;
12842 		}
12843 
12844 #if defined(CONFIG_DRM_AMD_DC_FP)
12845 		if (dc_resource_is_dsc_encoding_supported(dc)) {
12846 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
12847 			if (ret) {
12848 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
12849 				ret = -EINVAL;
12850 				goto fail;
12851 			}
12852 		}
12853 #endif
12854 
12855 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
12856 		if (ret) {
12857 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
12858 			goto fail;
12859 		}
12860 
12861 		/*
12862 		 * Perform validation of MST topology in the state:
12863 		 * We need to perform MST atomic check before calling
12864 		 * dc_validate_global_state(), or there is a chance
12865 		 * to get stuck in an infinite loop and hang eventually.
12866 		 */
12867 		ret = drm_dp_mst_atomic_check(state);
12868 		if (ret) {
12869 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
12870 			goto fail;
12871 		}
12872 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
12873 		if (status != DC_OK) {
12874 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
12875 				       dc_status_to_str(status), status);
12876 			ret = -EINVAL;
12877 			goto fail;
12878 		}
12879 	} else {
12880 		/*
12881 		 * The commit is a fast update. Fast updates shouldn't change
12882 		 * the DC context, affect global validation, and can have their
12883 		 * commit work done in parallel with other commits not touching
12884 		 * the same resource. If we have a new DC context as part of
12885 		 * the DM atomic state from validation we need to free it and
12886 		 * retain the existing one instead.
12887 		 *
12888 		 * Furthermore, since the DM atomic state only contains the DC
12889 		 * context and can safely be annulled, we can free the state
12890 		 * and clear the associated private object now to free
12891 		 * some memory and avoid a possible use-after-free later.
12892 		 */
12893 
12894 		for (i = 0; i < state->num_private_objs; i++) {
12895 			struct drm_private_obj *obj = state->private_objs[i].ptr;
12896 
12897 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
12898 				int j = state->num_private_objs-1;
12899 
12900 				dm_atomic_destroy_state(obj,
12901 						state->private_objs[i].state_to_destroy);
12902 
12903 				/* If i is not at the end of the array then the
12904 				 * last element needs to be moved to where i was
12905 				 * before the array can safely be truncated.
12906 				 */
12907 				if (i != j)
12908 					state->private_objs[i] =
12909 						state->private_objs[j];
12910 
12911 				state->private_objs[j].ptr = NULL;
12912 				state->private_objs[j].state_to_destroy = NULL;
12913 				state->private_objs[j].old_state = NULL;
12914 				state->private_objs[j].new_state = NULL;
12915 
12916 				state->num_private_objs = j;
12917 				break;
12918 			}
12919 		}
12920 	}
12921 
12922 	/* Store the overall update type for use later in atomic check. */
12923 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12924 		struct dm_crtc_state *dm_new_crtc_state =
12925 			to_dm_crtc_state(new_crtc_state);
12926 
12927 		/*
12928 		 * Only allow async flips for fast updates that don't change
12929 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
12930 		 */
12931 		if (new_crtc_state->async_flip &&
12932 		    (lock_and_validation_needed ||
12933 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
12934 			drm_dbg_atomic(crtc->dev,
12935 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
12936 				       crtc->base.id, crtc->name);
12937 			ret = -EINVAL;
12938 			goto fail;
12939 		}
12940 
12941 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
12942 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
12943 	}
12944 
12945 	/* Must be success */
12946 	WARN_ON(ret);
12947 
12948 	trace_amdgpu_dm_atomic_check_finish(state, ret);
12949 
12950 	return ret;
12951 
12952 fail:
12953 	if (ret == -EDEADLK)
12954 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
12955 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
12956 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
12957 	else
12958 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
12959 
12960 	trace_amdgpu_dm_atomic_check_finish(state, ret);
12961 
12962 	return ret;
12963 }
12964 
12965 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
12966 		unsigned int offset,
12967 		unsigned int total_length,
12968 		u8 *data,
12969 		unsigned int length,
12970 		struct amdgpu_hdmi_vsdb_info *vsdb)
12971 {
12972 	bool res;
12973 	union dmub_rb_cmd cmd;
12974 	struct dmub_cmd_send_edid_cea *input;
12975 	struct dmub_cmd_edid_cea_output *output;
12976 
12977 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
12978 		return false;
12979 
12980 	memset(&cmd, 0, sizeof(cmd));
12981 
12982 	input = &cmd.edid_cea.data.input;
12983 
12984 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
12985 	cmd.edid_cea.header.sub_type = 0;
12986 	cmd.edid_cea.header.payload_bytes =
12987 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
12988 	input->offset = offset;
12989 	input->length = length;
12990 	input->cea_total_length = total_length;
12991 	memcpy(input->payload, data, length);
12992 
12993 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
12994 	if (!res) {
12995 		drm_err(adev_to_drm(dm->adev), "EDID CEA parser failed\n");
12996 		return false;
12997 	}
12998 
12999 	output = &cmd.edid_cea.data.output;
13000 
13001 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
13002 		if (!output->ack.success) {
13003 			drm_err(adev_to_drm(dm->adev), "EDID CEA ack failed at offset %d\n",
13004 					output->ack.offset);
13005 		}
13006 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
13007 		if (!output->amd_vsdb.vsdb_found)
13008 			return false;
13009 
13010 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
13011 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
13012 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
13013 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
13014 	} else {
13015 		drm_warn(adev_to_drm(dm->adev), "Unknown EDID CEA parser results\n");
13016 		return false;
13017 	}
13018 
13019 	return true;
13020 }
13021 
13022 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
13023 		u8 *edid_ext, int len,
13024 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13025 {
13026 	int i;
13027 
13028 	/* send extension block to DMCU for parsing */
13029 	for (i = 0; i < len; i += 8) {
13030 		bool res;
13031 		int offset;
13032 
13033 		/* send 8 bytes a time */
13034 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
13035 			return false;
13036 
13037 		if (i+8 == len) {
13038 			/* EDID block sent completed, expect result */
13039 			int version, min_rate, max_rate;
13040 
13041 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
13042 			if (res) {
13043 				/* amd vsdb found */
13044 				vsdb_info->freesync_supported = 1;
13045 				vsdb_info->amd_vsdb_version = version;
13046 				vsdb_info->min_refresh_rate_hz = min_rate;
13047 				vsdb_info->max_refresh_rate_hz = max_rate;
13048 				return true;
13049 			}
13050 			/* not amd vsdb */
13051 			return false;
13052 		}
13053 
13054 		/* check for ack*/
13055 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
13056 		if (!res)
13057 			return false;
13058 	}
13059 
13060 	return false;
13061 }
13062 
13063 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
13064 		u8 *edid_ext, int len,
13065 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13066 {
13067 	int i;
13068 
13069 	/* send extension block to DMCU for parsing */
13070 	for (i = 0; i < len; i += 8) {
13071 		/* send 8 bytes a time */
13072 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
13073 			return false;
13074 	}
13075 
13076 	return vsdb_info->freesync_supported;
13077 }
13078 
13079 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
13080 		u8 *edid_ext, int len,
13081 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13082 {
13083 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
13084 	bool ret;
13085 
13086 	mutex_lock(&adev->dm.dc_lock);
13087 	if (adev->dm.dmub_srv)
13088 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
13089 	else
13090 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
13091 	mutex_unlock(&adev->dm.dc_lock);
13092 	return ret;
13093 }
13094 
13095 static void parse_edid_displayid_vrr(struct drm_connector *connector,
13096 				     const struct edid *edid)
13097 {
13098 	u8 *edid_ext = NULL;
13099 	int i;
13100 	int j = 0;
13101 	u16 min_vfreq;
13102 	u16 max_vfreq;
13103 
13104 	if (edid == NULL || edid->extensions == 0)
13105 		return;
13106 
13107 	/* Find DisplayID extension */
13108 	for (i = 0; i < edid->extensions; i++) {
13109 		edid_ext = (void *)(edid + (i + 1));
13110 		if (edid_ext[0] == DISPLAYID_EXT)
13111 			break;
13112 	}
13113 
13114 	if (edid_ext == NULL)
13115 		return;
13116 
13117 	while (j < EDID_LENGTH) {
13118 		/* Get dynamic video timing range from DisplayID if available */
13119 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
13120 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
13121 			min_vfreq = edid_ext[j+9];
13122 			if (edid_ext[j+1] & 7)
13123 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
13124 			else
13125 				max_vfreq = edid_ext[j+10];
13126 
13127 			if (max_vfreq && min_vfreq) {
13128 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
13129 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
13130 
13131 				return;
13132 			}
13133 		}
13134 		j++;
13135 	}
13136 }
13137 
13138 static int parse_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13139 			  const struct edid *edid, struct amdgpu_hdmi_vsdb_info *vsdb_info)
13140 {
13141 	u8 *edid_ext = NULL;
13142 	int i;
13143 	int j = 0;
13144 
13145 	if (edid == NULL || edid->extensions == 0)
13146 		return -ENODEV;
13147 
13148 	/* Find DisplayID extension */
13149 	for (i = 0; i < edid->extensions; i++) {
13150 		edid_ext = (void *)(edid + (i + 1));
13151 		if (edid_ext[0] == DISPLAYID_EXT)
13152 			break;
13153 	}
13154 
13155 	while (j < EDID_LENGTH - sizeof(struct amd_vsdb_block)) {
13156 		struct amd_vsdb_block *amd_vsdb = (struct amd_vsdb_block *)&edid_ext[j];
13157 		unsigned int ieeeId = (amd_vsdb->ieee_id[2] << 16) | (amd_vsdb->ieee_id[1] << 8) | (amd_vsdb->ieee_id[0]);
13158 
13159 		if (ieeeId == HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_IEEE_REGISTRATION_ID &&
13160 				amd_vsdb->version == HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_VERSION_3) {
13161 			u8 panel_type;
13162 			vsdb_info->replay_mode = (amd_vsdb->feature_caps & AMD_VSDB_VERSION_3_FEATURECAP_REPLAYMODE) ? true : false;
13163 			vsdb_info->amd_vsdb_version = HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_VERSION_3;
13164 			drm_dbg_kms(aconnector->base.dev, "Panel supports Replay Mode: %d\n", vsdb_info->replay_mode);
13165 			panel_type = (amd_vsdb->color_space_eotf_support & AMD_VDSB_VERSION_3_PANEL_TYPE_MASK) >> AMD_VDSB_VERSION_3_PANEL_TYPE_SHIFT;
13166 			switch (panel_type) {
13167 			case AMD_VSDB_PANEL_TYPE_OLED:
13168 				aconnector->dc_link->panel_type = PANEL_TYPE_OLED;
13169 				break;
13170 			case AMD_VSDB_PANEL_TYPE_MINILED:
13171 				aconnector->dc_link->panel_type = PANEL_TYPE_MINILED;
13172 				break;
13173 			default:
13174 				aconnector->dc_link->panel_type = PANEL_TYPE_NONE;
13175 				break;
13176 			}
13177 			drm_dbg_kms(aconnector->base.dev, "Panel type: %d\n",
13178 				    aconnector->dc_link->panel_type);
13179 
13180 			return true;
13181 		}
13182 		j++;
13183 	}
13184 
13185 	return false;
13186 }
13187 
13188 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13189 			       const struct edid *edid,
13190 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
13191 {
13192 	u8 *edid_ext = NULL;
13193 	int i;
13194 	bool valid_vsdb_found = false;
13195 
13196 	/*----- drm_find_cea_extension() -----*/
13197 	/* No EDID or EDID extensions */
13198 	if (edid == NULL || edid->extensions == 0)
13199 		return -ENODEV;
13200 
13201 	/* Find CEA extension */
13202 	for (i = 0; i < edid->extensions; i++) {
13203 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
13204 		if (edid_ext[0] == CEA_EXT)
13205 			break;
13206 	}
13207 
13208 	if (i == edid->extensions)
13209 		return -ENODEV;
13210 
13211 	/*----- cea_db_offsets() -----*/
13212 	if (edid_ext[0] != CEA_EXT)
13213 		return -ENODEV;
13214 
13215 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
13216 
13217 	return valid_vsdb_found ? i : -ENODEV;
13218 }
13219 
13220 /**
13221  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
13222  *
13223  * @connector: Connector to query.
13224  * @drm_edid: DRM EDID from monitor
13225  *
13226  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
13227  * track of some of the display information in the internal data struct used by
13228  * amdgpu_dm. This function checks which type of connector we need to set the
13229  * FreeSync parameters.
13230  */
13231 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
13232 				    const struct drm_edid *drm_edid)
13233 {
13234 	int i = 0;
13235 	struct amdgpu_dm_connector *amdgpu_dm_connector =
13236 			to_amdgpu_dm_connector(connector);
13237 	struct dm_connector_state *dm_con_state = NULL;
13238 	struct dc_sink *sink;
13239 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
13240 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
13241 	const struct edid *edid;
13242 	bool freesync_capable = false;
13243 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
13244 
13245 	if (!connector->state) {
13246 		drm_err(adev_to_drm(adev), "%s - Connector has no state", __func__);
13247 		goto update;
13248 	}
13249 
13250 	sink = amdgpu_dm_connector->dc_sink ?
13251 		amdgpu_dm_connector->dc_sink :
13252 		amdgpu_dm_connector->dc_em_sink;
13253 
13254 	drm_edid_connector_update(connector, drm_edid);
13255 
13256 	if (!drm_edid || !sink) {
13257 		dm_con_state = to_dm_connector_state(connector->state);
13258 
13259 		amdgpu_dm_connector->min_vfreq = 0;
13260 		amdgpu_dm_connector->max_vfreq = 0;
13261 		freesync_capable = false;
13262 
13263 		goto update;
13264 	}
13265 
13266 	dm_con_state = to_dm_connector_state(connector->state);
13267 
13268 	if (!adev->dm.freesync_module || !dc_supports_vrr(sink->ctx->dce_version))
13269 		goto update;
13270 
13271 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
13272 
13273 	/* Some eDP panels only have the refresh rate range info in DisplayID */
13274 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
13275 	     connector->display_info.monitor_range.max_vfreq == 0))
13276 		parse_edid_displayid_vrr(connector, edid);
13277 
13278 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
13279 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
13280 		if (amdgpu_dm_connector->dc_link &&
13281 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
13282 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
13283 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
13284 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13285 				freesync_capable = true;
13286 		}
13287 
13288 		parse_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13289 
13290 		if (vsdb_info.replay_mode) {
13291 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
13292 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
13293 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
13294 		}
13295 
13296 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
13297 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13298 		if (i >= 0 && vsdb_info.freesync_supported) {
13299 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13300 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13301 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13302 				freesync_capable = true;
13303 
13304 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13305 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13306 		}
13307 	}
13308 
13309 	if (amdgpu_dm_connector->dc_link)
13310 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
13311 
13312 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
13313 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13314 		if (i >= 0 && vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
13315 
13316 			amdgpu_dm_connector->pack_sdp_v1_3 = true;
13317 			amdgpu_dm_connector->as_type = as_type;
13318 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13319 
13320 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13321 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13322 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13323 				freesync_capable = true;
13324 
13325 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13326 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13327 		}
13328 	}
13329 
13330 update:
13331 	if (dm_con_state)
13332 		dm_con_state->freesync_capable = freesync_capable;
13333 
13334 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
13335 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
13336 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
13337 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
13338 	}
13339 
13340 	if (connector->vrr_capable_property)
13341 		drm_connector_set_vrr_capable_property(connector,
13342 						       freesync_capable);
13343 }
13344 
13345 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
13346 {
13347 	struct amdgpu_device *adev = drm_to_adev(dev);
13348 	struct dc *dc = adev->dm.dc;
13349 	int i;
13350 
13351 	mutex_lock(&adev->dm.dc_lock);
13352 	if (dc->current_state) {
13353 		for (i = 0; i < dc->current_state->stream_count; ++i)
13354 			dc->current_state->streams[i]
13355 				->triggered_crtc_reset.enabled =
13356 				adev->dm.force_timing_sync;
13357 
13358 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
13359 		dc_trigger_sync(dc, dc->current_state);
13360 	}
13361 	mutex_unlock(&adev->dm.dc_lock);
13362 }
13363 
13364 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
13365 {
13366 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
13367 		dc_exit_ips_for_hw_access(dc);
13368 }
13369 
13370 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
13371 		       u32 value, const char *func_name)
13372 {
13373 #ifdef DM_CHECK_ADDR_0
13374 	if (address == 0) {
13375 		drm_err(adev_to_drm(ctx->driver_context),
13376 			"invalid register write. address = 0");
13377 		return;
13378 	}
13379 #endif
13380 
13381 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13382 	cgs_write_register(ctx->cgs_device, address, value);
13383 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
13384 }
13385 
13386 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
13387 			  const char *func_name)
13388 {
13389 	u32 value;
13390 #ifdef DM_CHECK_ADDR_0
13391 	if (address == 0) {
13392 		drm_err(adev_to_drm(ctx->driver_context),
13393 			"invalid register read; address = 0\n");
13394 		return 0;
13395 	}
13396 #endif
13397 
13398 	if (ctx->dmub_srv &&
13399 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
13400 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
13401 		ASSERT(false);
13402 		return 0;
13403 	}
13404 
13405 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13406 
13407 	value = cgs_read_register(ctx->cgs_device, address);
13408 
13409 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
13410 
13411 	return value;
13412 }
13413 
13414 int amdgpu_dm_process_dmub_aux_transfer_sync(
13415 		struct dc_context *ctx,
13416 		unsigned int link_index,
13417 		struct aux_payload *payload,
13418 		enum aux_return_code_type *operation_result)
13419 {
13420 	struct amdgpu_device *adev = ctx->driver_context;
13421 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
13422 	int ret = -1;
13423 
13424 	mutex_lock(&adev->dm.dpia_aux_lock);
13425 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
13426 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
13427 		goto out;
13428 	}
13429 
13430 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13431 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13432 		*operation_result = AUX_RET_ERROR_TIMEOUT;
13433 		goto out;
13434 	}
13435 
13436 	if (p_notify->result != AUX_RET_SUCCESS) {
13437 		/*
13438 		 * Transient states before tunneling is enabled could
13439 		 * lead to this error. We can ignore this for now.
13440 		 */
13441 		if (p_notify->result == AUX_RET_ERROR_PROTOCOL_ERROR) {
13442 			drm_warn(adev_to_drm(adev), "DPIA AUX failed on 0x%x(%d), error %d\n",
13443 					payload->address, payload->length,
13444 					p_notify->result);
13445 		}
13446 		*operation_result = p_notify->result;
13447 		goto out;
13448 	}
13449 
13450 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command & 0xF;
13451 	if (adev->dm.dmub_notify->aux_reply.command & 0xF0)
13452 		/* The reply is stored in the top nibble of the command. */
13453 		payload->reply[0] = (adev->dm.dmub_notify->aux_reply.command >> 4) & 0xF;
13454 
13455 	/*write req may receive a byte indicating partially written number as well*/
13456 	if (p_notify->aux_reply.length)
13457 		memcpy(payload->data, p_notify->aux_reply.data,
13458 				p_notify->aux_reply.length);
13459 
13460 	/* success */
13461 	ret = p_notify->aux_reply.length;
13462 	*operation_result = p_notify->result;
13463 out:
13464 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
13465 	mutex_unlock(&adev->dm.dpia_aux_lock);
13466 	return ret;
13467 }
13468 
13469 static void abort_fused_io(
13470 		struct dc_context *ctx,
13471 		const struct dmub_cmd_fused_request *request
13472 )
13473 {
13474 	union dmub_rb_cmd command = { 0 };
13475 	struct dmub_rb_cmd_fused_io *io = &command.fused_io;
13476 
13477 	io->header.type = DMUB_CMD__FUSED_IO;
13478 	io->header.sub_type = DMUB_CMD__FUSED_IO_ABORT;
13479 	io->header.payload_bytes = sizeof(*io) - sizeof(io->header);
13480 	io->request = *request;
13481 	dm_execute_dmub_cmd(ctx, &command, DM_DMUB_WAIT_TYPE_NO_WAIT);
13482 }
13483 
13484 static bool execute_fused_io(
13485 		struct amdgpu_device *dev,
13486 		struct dc_context *ctx,
13487 		union dmub_rb_cmd *commands,
13488 		uint8_t count,
13489 		uint32_t timeout_us
13490 )
13491 {
13492 	const uint8_t ddc_line = commands[0].fused_io.request.u.aux.ddc_line;
13493 
13494 	if (ddc_line >= ARRAY_SIZE(dev->dm.fused_io))
13495 		return false;
13496 
13497 	struct fused_io_sync *sync = &dev->dm.fused_io[ddc_line];
13498 	struct dmub_rb_cmd_fused_io *first = &commands[0].fused_io;
13499 	const bool result = dm_execute_dmub_cmd_list(ctx, count, commands, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY)
13500 			&& first->header.ret_status
13501 			&& first->request.status == FUSED_REQUEST_STATUS_SUCCESS;
13502 
13503 	if (!result)
13504 		return false;
13505 
13506 	while (wait_for_completion_timeout(&sync->replied, usecs_to_jiffies(timeout_us))) {
13507 		reinit_completion(&sync->replied);
13508 
13509 		struct dmub_cmd_fused_request *reply = (struct dmub_cmd_fused_request *) sync->reply_data;
13510 
13511 		static_assert(sizeof(*reply) <= sizeof(sync->reply_data), "Size mismatch");
13512 
13513 		if (reply->identifier == first->request.identifier) {
13514 			first->request = *reply;
13515 			return true;
13516 		}
13517 	}
13518 
13519 	reinit_completion(&sync->replied);
13520 	first->request.status = FUSED_REQUEST_STATUS_TIMEOUT;
13521 	abort_fused_io(ctx, &first->request);
13522 	return false;
13523 }
13524 
13525 bool amdgpu_dm_execute_fused_io(
13526 		struct amdgpu_device *dev,
13527 		struct dc_link *link,
13528 		union dmub_rb_cmd *commands,
13529 		uint8_t count,
13530 		uint32_t timeout_us)
13531 {
13532 	struct amdgpu_display_manager *dm = &dev->dm;
13533 
13534 	mutex_lock(&dm->dpia_aux_lock);
13535 
13536 	const bool result = execute_fused_io(dev, link->ctx, commands, count, timeout_us);
13537 
13538 	mutex_unlock(&dm->dpia_aux_lock);
13539 	return result;
13540 }
13541 
13542 int amdgpu_dm_process_dmub_set_config_sync(
13543 		struct dc_context *ctx,
13544 		unsigned int link_index,
13545 		struct set_config_cmd_payload *payload,
13546 		enum set_config_status *operation_result)
13547 {
13548 	struct amdgpu_device *adev = ctx->driver_context;
13549 	bool is_cmd_complete;
13550 	int ret;
13551 
13552 	mutex_lock(&adev->dm.dpia_aux_lock);
13553 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
13554 			link_index, payload, adev->dm.dmub_notify);
13555 
13556 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13557 		ret = 0;
13558 		*operation_result = adev->dm.dmub_notify->sc_status;
13559 	} else {
13560 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13561 		ret = -1;
13562 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
13563 	}
13564 
13565 	if (!is_cmd_complete)
13566 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
13567 	mutex_unlock(&adev->dm.dpia_aux_lock);
13568 	return ret;
13569 }
13570 
13571 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
13572 {
13573 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
13574 }
13575 
13576 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)
13577 {
13578 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
13579 }
13580 
13581 void dm_acpi_process_phy_transition_interlock(
13582 	const struct dc_context *ctx,
13583 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
13584 {
13585 	// Not yet implemented
13586 }
13587