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