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