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