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