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