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