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