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