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