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