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