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