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