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