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