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