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