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