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