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