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