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