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