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