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