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