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