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