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