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