xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision 92c4c9fdc838d3b41a996bb700ea64b9e78fc7ea)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright 2015-2026 Advanced Micro Devices, Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  * Authors: AMD
24  *
25  */
26 
27 /* The caprices of the preprocessor require that this be declared right here */
28 #define CREATE_TRACE_POINTS
29 
30 #include "dm_services_types.h"
31 #include "dc.h"
32 #include "link_enc_cfg.h"
33 #include "dc/inc/core_types.h"
34 #include "dal_asic_id.h"
35 #include "dmub/dmub_srv.h"
36 #include "dc/inc/hw/dmcu.h"
37 #include "dc/inc/hw/abm.h"
38 #include "dc/dc_dmub_srv.h"
39 #include "dc/dc_edid_parser.h"
40 #include "dc/dc_stat.h"
41 #include "dc/dc_state.h"
42 #include "amdgpu_dm_trace.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 "amdgpu.h"
49 #include "amdgpu_display.h"
50 #include "amdgpu_ucode.h"
51 #include "atom.h"
52 #include "amdgpu_dm.h"
53 #include "amdgpu_dm_plane.h"
54 #include "amdgpu_dm_crtc.h"
55 #include "amdgpu_dm_hdcp.h"
56 #include <drm/display/drm_hdcp_helper.h>
57 #include "amdgpu_dm_wb.h"
58 #include "amdgpu_atombios.h"
59 
60 #include "amd_shared.h"
61 #include "amdgpu_dm_irq.h"
62 #include "dm_helpers.h"
63 #include "amdgpu_dm_mst_types.h"
64 #if defined(CONFIG_DEBUG_FS)
65 #include "amdgpu_dm_debugfs.h"
66 #endif
67 #include "amdgpu_dm_psr.h"
68 #include "amdgpu_dm_replay.h"
69 
70 #include "ivsrcid/ivsrcid_vislands30.h"
71 
72 #include <linux/backlight.h>
73 #include <linux/module.h>
74 #include <linux/moduleparam.h>
75 #include <linux/types.h>
76 #include <linux/pm_runtime.h>
77 #include <linux/pci.h>
78 #include <linux/power_supply.h>
79 #include <linux/firmware.h>
80 #include <linux/component.h>
81 #include <linux/sort.h>
82 
83 #include <drm/drm_privacy_screen_consumer.h>
84 #include <drm/display/drm_dp_mst_helper.h>
85 #include <drm/display/drm_hdmi_helper.h>
86 #include <drm/drm_atomic.h>
87 #include <drm/drm_atomic_uapi.h>
88 #include <drm/drm_atomic_helper.h>
89 #include <drm/drm_blend.h>
90 #include <drm/drm_fixed.h>
91 #include <drm/drm_fourcc.h>
92 #include <drm/drm_edid.h>
93 #include <drm/drm_eld.h>
94 #include <drm/drm_mode.h>
95 #include <drm/drm_utils.h>
96 #include <drm/drm_vblank.h>
97 #include <drm/drm_audio_component.h>
98 #include <drm/drm_colorop.h>
99 #include <drm/drm_gem_atomic_helper.h>
100 
101 #include <media/cec-notifier.h>
102 #include <acpi/video.h>
103 
104 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
105 
106 #include "modules/inc/mod_freesync.h"
107 #include "modules/power/power_helpers.h"
108 
109 static_assert(AMDGPU_DMUB_NOTIFICATION_MAX == DMUB_NOTIFICATION_MAX, "AMDGPU_DMUB_NOTIFICATION_MAX mismatch");
110 
111 #define FIRMWARE_RENOIR_DMUB "amdgpu/renoir_dmcub.bin"
112 MODULE_FIRMWARE(FIRMWARE_RENOIR_DMUB);
113 #define FIRMWARE_SIENNA_CICHLID_DMUB "amdgpu/sienna_cichlid_dmcub.bin"
114 MODULE_FIRMWARE(FIRMWARE_SIENNA_CICHLID_DMUB);
115 #define FIRMWARE_NAVY_FLOUNDER_DMUB "amdgpu/navy_flounder_dmcub.bin"
116 MODULE_FIRMWARE(FIRMWARE_NAVY_FLOUNDER_DMUB);
117 #define FIRMWARE_GREEN_SARDINE_DMUB "amdgpu/green_sardine_dmcub.bin"
118 MODULE_FIRMWARE(FIRMWARE_GREEN_SARDINE_DMUB);
119 #define FIRMWARE_VANGOGH_DMUB "amdgpu/vangogh_dmcub.bin"
120 MODULE_FIRMWARE(FIRMWARE_VANGOGH_DMUB);
121 #define FIRMWARE_DIMGREY_CAVEFISH_DMUB "amdgpu/dimgrey_cavefish_dmcub.bin"
122 MODULE_FIRMWARE(FIRMWARE_DIMGREY_CAVEFISH_DMUB);
123 #define FIRMWARE_BEIGE_GOBY_DMUB "amdgpu/beige_goby_dmcub.bin"
124 MODULE_FIRMWARE(FIRMWARE_BEIGE_GOBY_DMUB);
125 #define FIRMWARE_YELLOW_CARP_DMUB "amdgpu/yellow_carp_dmcub.bin"
126 MODULE_FIRMWARE(FIRMWARE_YELLOW_CARP_DMUB);
127 #define FIRMWARE_DCN_314_DMUB "amdgpu/dcn_3_1_4_dmcub.bin"
128 MODULE_FIRMWARE(FIRMWARE_DCN_314_DMUB);
129 #define FIRMWARE_DCN_315_DMUB "amdgpu/dcn_3_1_5_dmcub.bin"
130 MODULE_FIRMWARE(FIRMWARE_DCN_315_DMUB);
131 #define FIRMWARE_DCN316_DMUB "amdgpu/dcn_3_1_6_dmcub.bin"
132 MODULE_FIRMWARE(FIRMWARE_DCN316_DMUB);
133 
134 #define FIRMWARE_DCN_V3_2_0_DMCUB "amdgpu/dcn_3_2_0_dmcub.bin"
135 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_0_DMCUB);
136 #define FIRMWARE_DCN_V3_2_1_DMCUB "amdgpu/dcn_3_2_1_dmcub.bin"
137 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_1_DMCUB);
138 
139 #define FIRMWARE_RAVEN_DMCU		"amdgpu/raven_dmcu.bin"
140 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
141 
142 #define FIRMWARE_NAVI12_DMCU            "amdgpu/navi12_dmcu.bin"
143 MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
144 
145 #define FIRMWARE_DCN_35_DMUB "amdgpu/dcn_3_5_dmcub.bin"
146 MODULE_FIRMWARE(FIRMWARE_DCN_35_DMUB);
147 
148 #define FIRMWARE_DCN_351_DMUB "amdgpu/dcn_3_5_1_dmcub.bin"
149 MODULE_FIRMWARE(FIRMWARE_DCN_351_DMUB);
150 
151 #define FIRMWARE_DCN_36_DMUB "amdgpu/dcn_3_6_dmcub.bin"
152 MODULE_FIRMWARE(FIRMWARE_DCN_36_DMUB);
153 
154 #define FIRMWARE_DCN_401_DMUB "amdgpu/dcn_4_0_1_dmcub.bin"
155 MODULE_FIRMWARE(FIRMWARE_DCN_401_DMUB);
156 
157 #define FIRMWARE_DCN_42_DMUB "amdgpu/dcn_4_2_dmcub.bin"
158 MODULE_FIRMWARE(FIRMWARE_DCN_42_DMUB);
159 
160 /**
161  * DOC: overview
162  *
163  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
164  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
165  * requests into DC requests, and DC responses into DRM responses.
166  *
167  * The root control structure is &struct amdgpu_display_manager.
168  */
169 
170 /* basic init/fini API */
171 static int amdgpu_dm_init(struct amdgpu_device *adev);
172 static void amdgpu_dm_fini(struct amdgpu_device *adev);
173 static bool is_freesync_video_mode(const struct drm_display_mode *mode, struct amdgpu_dm_connector *aconnector);
174 static void reset_freesync_config_for_crtc(struct dm_crtc_state *new_crtc_state);
175 static struct amdgpu_i2c_adapter *
176 create_i2c(struct ddc_service *ddc_service, bool oem);
177 
get_subconnector_type(struct dc_link * link)178 static enum drm_mode_subconnector get_subconnector_type(struct dc_link *link)
179 {
180 	switch (link->dpcd_caps.dongle_type) {
181 	case DISPLAY_DONGLE_NONE:
182 		return DRM_MODE_SUBCONNECTOR_Native;
183 	case DISPLAY_DONGLE_DP_VGA_CONVERTER:
184 		return DRM_MODE_SUBCONNECTOR_VGA;
185 	case DISPLAY_DONGLE_DP_DVI_CONVERTER:
186 	case DISPLAY_DONGLE_DP_DVI_DONGLE:
187 		return DRM_MODE_SUBCONNECTOR_DVID;
188 	case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
189 	case DISPLAY_DONGLE_DP_HDMI_DONGLE:
190 		return DRM_MODE_SUBCONNECTOR_HDMIA;
191 	case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
192 	default:
193 		return DRM_MODE_SUBCONNECTOR_Unknown;
194 	}
195 }
196 
update_subconnector_property(struct amdgpu_dm_connector * aconnector)197 static void update_subconnector_property(struct amdgpu_dm_connector *aconnector)
198 {
199 	struct dc_link *link = aconnector->dc_link;
200 	struct drm_connector *connector = &aconnector->base;
201 	enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
202 
203 	if (connector->connector_type != DRM_MODE_CONNECTOR_DisplayPort)
204 		return;
205 
206 	if (aconnector->dc_sink)
207 		subconnector = get_subconnector_type(link);
208 
209 	drm_object_property_set_value(&connector->base,
210 			connector->dev->mode_config.dp_subconnector_property,
211 			subconnector);
212 }
213 
214 /*
215  * initializes drm_device display related structures, based on the information
216  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
217  * drm_encoder, drm_mode_config
218  *
219  * Returns 0 on success
220  */
221 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
222 /* removes and deallocates the drm structures, created by the above function */
223 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
224 
225 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
226 				    struct amdgpu_dm_connector *amdgpu_dm_connector,
227 				    u32 link_index,
228 				    struct amdgpu_encoder *amdgpu_encoder);
229 static int amdgpu_dm_encoder_init(struct drm_device *dev,
230 				  struct amdgpu_encoder *aencoder,
231 				  uint32_t link_index);
232 
233 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
234 
235 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_state *state);
236 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
237 
238 static int amdgpu_dm_atomic_check(struct drm_device *dev,
239 				  struct drm_atomic_state *state);
240 
241 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector);
242 static void handle_hpd_rx_irq(void *param);
243 
244 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
245 					 int bl_idx,
246 					 u32 user_brightness);
247 
248 static bool
249 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
250 				 struct drm_crtc_state *new_crtc_state);
251 /*
252  * dm_vblank_get_counter
253  *
254  * @brief
255  * Get counter for number of vertical blanks
256  *
257  * @param
258  * struct amdgpu_device *adev - [in] desired amdgpu device
259  * int disp_idx - [in] which CRTC to get the counter from
260  *
261  * @return
262  * Counter for vertical blanks
263  */
dm_vblank_get_counter(struct amdgpu_device * adev,int crtc)264 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
265 {
266 	struct amdgpu_crtc *acrtc = NULL;
267 
268 	if (crtc >= adev->mode_info.num_crtc)
269 		return 0;
270 
271 	acrtc = adev->mode_info.crtcs[crtc];
272 
273 	if (!acrtc->dm_irq_params.stream) {
274 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
275 			  crtc);
276 		return 0;
277 	}
278 
279 	return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
280 }
281 
dm_crtc_get_scanoutpos(struct amdgpu_device * adev,int crtc,u32 * vbl,u32 * position)282 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
283 				  u32 *vbl, u32 *position)
284 {
285 	u32 v_blank_start = 0, v_blank_end = 0, h_position = 0, v_position = 0;
286 	struct amdgpu_crtc *acrtc = NULL;
287 	struct dc *dc = adev->dm.dc;
288 
289 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
290 		return -EINVAL;
291 
292 	acrtc = adev->mode_info.crtcs[crtc];
293 
294 	if (!acrtc->dm_irq_params.stream) {
295 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
296 			  crtc);
297 		return 0;
298 	}
299 
300 	if (dc && dc->caps.ips_support && dc->idle_optimizations_allowed)
301 		dc_allow_idle_optimizations(dc, false);
302 
303 	/*
304 	 * TODO rework base driver to use values directly.
305 	 * for now parse it back into reg-format
306 	 */
307 	dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
308 				 &v_blank_start,
309 				 &v_blank_end,
310 				 &h_position,
311 				 &v_position);
312 
313 	*position = v_position | (h_position << 16);
314 	*vbl = v_blank_start | (v_blank_end << 16);
315 
316 	return 0;
317 }
318 
dm_is_idle(struct amdgpu_ip_block * ip_block)319 static bool dm_is_idle(struct amdgpu_ip_block *ip_block)
320 {
321 	/* XXX todo */
322 	return true;
323 }
324 
dm_wait_for_idle(struct amdgpu_ip_block * ip_block)325 static int dm_wait_for_idle(struct amdgpu_ip_block *ip_block)
326 {
327 	/* XXX todo */
328 	return 0;
329 }
330 
dm_check_soft_reset(struct amdgpu_ip_block * ip_block)331 static bool dm_check_soft_reset(struct amdgpu_ip_block *ip_block)
332 {
333 	return false;
334 }
335 
dm_soft_reset(struct amdgpu_ip_block * ip_block)336 static int dm_soft_reset(struct amdgpu_ip_block *ip_block)
337 {
338 	/* XXX todo */
339 	return 0;
340 }
341 
342 static struct amdgpu_crtc *
get_crtc_by_otg_inst(struct amdgpu_device * adev,int otg_inst)343 get_crtc_by_otg_inst(struct amdgpu_device *adev,
344 		     int otg_inst)
345 {
346 	struct drm_device *dev = adev_to_drm(adev);
347 	struct drm_crtc *crtc;
348 	struct amdgpu_crtc *amdgpu_crtc;
349 
350 	if (WARN_ON(otg_inst == -1))
351 		return adev->mode_info.crtcs[0];
352 
353 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
354 		amdgpu_crtc = to_amdgpu_crtc(crtc);
355 
356 		if (amdgpu_crtc->otg_inst == otg_inst)
357 			return amdgpu_crtc;
358 	}
359 
360 	return NULL;
361 }
362 
is_dc_timing_adjust_needed(struct dm_crtc_state * old_state,struct dm_crtc_state * new_state)363 static inline bool is_dc_timing_adjust_needed(struct dm_crtc_state *old_state,
364 					      struct dm_crtc_state *new_state)
365 {
366 	if (new_state->stream->adjust.timing_adjust_pending)
367 		return true;
368 	if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
369 		return true;
370 	else if (amdgpu_dm_crtc_vrr_active(old_state) != amdgpu_dm_crtc_vrr_active(new_state))
371 		return true;
372 	else
373 		return false;
374 }
375 
376 /*
377  * DC will program planes with their z-order determined by their ordering
378  * in the dc_surface_updates array. This comparator is used to sort them
379  * by descending zpos.
380  */
dm_plane_layer_index_cmp(const void * a,const void * b)381 static int dm_plane_layer_index_cmp(const void *a, const void *b)
382 {
383 	const struct dc_surface_update *sa = (struct dc_surface_update *)a;
384 	const struct dc_surface_update *sb = (struct dc_surface_update *)b;
385 
386 	/* Sort by descending dc_plane layer_index (i.e. normalized_zpos) */
387 	return sb->surface->layer_index - sa->surface->layer_index;
388 }
389 
390 /**
391  * update_planes_and_stream_adapter() - Send planes to be updated in DC
392  *
393  * DC has a generic way to update planes and stream via
394  * dc_update_planes_and_stream function; however, DM might need some
395  * adjustments and preparation before calling it. This function is a wrapper
396  * for the dc_update_planes_and_stream that does any required configuration
397  * before passing control to DC.
398  *
399  * @dc: Display Core control structure
400  * @update_type: specify whether it is FULL/MEDIUM/FAST update
401  * @planes_count: planes count to update
402  * @stream: stream state
403  * @stream_update: stream update
404  * @array_of_surface_update: dc surface update pointer
405  *
406  */
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)407 static inline bool update_planes_and_stream_adapter(struct dc *dc,
408 						    int update_type,
409 						    int planes_count,
410 						    struct dc_stream_state *stream,
411 						    struct dc_stream_update *stream_update,
412 						    struct dc_surface_update *array_of_surface_update)
413 {
414 	sort(array_of_surface_update, planes_count,
415 	     sizeof(*array_of_surface_update), dm_plane_layer_index_cmp, NULL);
416 
417 	/*
418 	 * Previous frame finished and HW is ready for optimization.
419 	 */
420 	dc_post_update_surfaces_to_stream(dc);
421 
422 	return dc_update_planes_and_stream(dc,
423 					   array_of_surface_update,
424 					   planes_count,
425 					   stream,
426 					   stream_update);
427 }
428 
429 /**
430  * dm_pflip_high_irq() - Handle pageflip interrupt
431  * @interrupt_params: ignored
432  *
433  * Handles the pageflip interrupt by notifying all interested parties
434  * that the pageflip has been completed.
435  */
dm_pflip_high_irq(void * interrupt_params)436 static void dm_pflip_high_irq(void *interrupt_params)
437 {
438 	struct amdgpu_crtc *amdgpu_crtc;
439 	struct common_irq_params *irq_params = interrupt_params;
440 	struct amdgpu_device *adev = irq_params->adev;
441 	struct drm_device *dev = adev_to_drm(adev);
442 	unsigned long flags;
443 	struct drm_pending_vblank_event *e;
444 	u32 vpos, hpos, v_blank_start, v_blank_end;
445 	bool vrr_active;
446 
447 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
448 
449 	/* IRQ could occur when in initial stage */
450 	/* TODO work and BO cleanup */
451 	if (amdgpu_crtc == NULL) {
452 		drm_dbg_state(dev, "CRTC is null, returning.\n");
453 		return;
454 	}
455 
456 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
457 
458 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED) {
459 		drm_dbg_state(dev,
460 			      "amdgpu_crtc->pflip_status = %d != AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p]\n",
461 			      amdgpu_crtc->pflip_status, AMDGPU_FLIP_SUBMITTED,
462 			      amdgpu_crtc->crtc_id, amdgpu_crtc);
463 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
464 		return;
465 	}
466 
467 	/* page flip completed. */
468 	e = amdgpu_crtc->event;
469 	amdgpu_crtc->event = NULL;
470 
471 	WARN_ON(!e);
472 
473 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(amdgpu_crtc);
474 
475 	/* Fixed refresh rate, or VRR scanout position outside front-porch? */
476 	if (!vrr_active ||
477 	    !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
478 				      &v_blank_end, &hpos, &vpos) ||
479 	    (vpos < v_blank_start)) {
480 		/* Update to correct count and vblank timestamp if racing with
481 		 * vblank irq. This also updates to the correct vblank timestamp
482 		 * even in VRR mode, as scanout is past the front-porch atm.
483 		 */
484 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
485 
486 		/* Wake up userspace by sending the pageflip event with proper
487 		 * count and timestamp of vblank of flip completion.
488 		 */
489 		if (e) {
490 			drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
491 
492 			/* Event sent, so done with vblank for this flip */
493 			drm_crtc_vblank_put(&amdgpu_crtc->base);
494 		}
495 	} else if (e) {
496 		/* VRR active and inside front-porch: vblank count and
497 		 * timestamp for pageflip event will only be up to date after
498 		 * drm_crtc_handle_vblank() has been executed from late vblank
499 		 * irq handler after start of back-porch (vline 0). We queue the
500 		 * pageflip event for send-out by drm_crtc_handle_vblank() with
501 		 * updated timestamp and count, once it runs after us.
502 		 *
503 		 * We need to open-code this instead of using the helper
504 		 * drm_crtc_arm_vblank_event(), as that helper would
505 		 * call drm_crtc_accurate_vblank_count(), which we must
506 		 * not call in VRR mode while we are in front-porch!
507 		 */
508 
509 		/* sequence will be replaced by real count during send-out. */
510 		e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
511 		e->pipe = amdgpu_crtc->crtc_id;
512 
513 		list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
514 		e = NULL;
515 	}
516 
517 	/* Keep track of vblank of this flip for flip throttling. We use the
518 	 * cooked hw counter, as that one incremented at start of this vblank
519 	 * of pageflip completion, so last_flip_vblank is the forbidden count
520 	 * for queueing new pageflips if vsync + VRR is enabled.
521 	 */
522 	amdgpu_crtc->dm_irq_params.last_flip_vblank =
523 		amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
524 
525 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
526 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
527 
528 	drm_dbg_state(dev,
529 		      "crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
530 		      amdgpu_crtc->crtc_id, amdgpu_crtc, vrr_active, (int)!e);
531 }
532 
dm_handle_vmin_vmax_update(struct work_struct * offload_work)533 static void dm_handle_vmin_vmax_update(struct work_struct *offload_work)
534 {
535 	struct vupdate_offload_work *work = container_of(offload_work, struct vupdate_offload_work, work);
536 	struct amdgpu_device *adev = work->adev;
537 	struct dc_stream_state *stream = work->stream;
538 	struct dc_crtc_timing_adjust *adjust = work->adjust;
539 
540 	mutex_lock(&adev->dm.dc_lock);
541 	dc_stream_adjust_vmin_vmax(adev->dm.dc, stream, adjust);
542 	mutex_unlock(&adev->dm.dc_lock);
543 
544 	dc_stream_release(stream);
545 	kfree(work->adjust);
546 	kfree(work);
547 }
548 
schedule_dc_vmin_vmax(struct amdgpu_device * adev,struct dc_stream_state * stream,struct dc_crtc_timing_adjust * adjust)549 static void schedule_dc_vmin_vmax(struct amdgpu_device *adev,
550 	struct dc_stream_state *stream,
551 	struct dc_crtc_timing_adjust *adjust)
552 {
553 	struct vupdate_offload_work *offload_work = kzalloc_obj(*offload_work,
554 								GFP_NOWAIT);
555 	if (!offload_work) {
556 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate vupdate_offload_work\n");
557 		return;
558 	}
559 
560 	struct dc_crtc_timing_adjust *adjust_copy = kzalloc_obj(*adjust_copy,
561 								GFP_NOWAIT);
562 	if (!adjust_copy) {
563 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate adjust_copy\n");
564 		kfree(offload_work);
565 		return;
566 	}
567 
568 	dc_stream_retain(stream);
569 	memcpy(adjust_copy, adjust, sizeof(*adjust_copy));
570 
571 	INIT_WORK(&offload_work->work, dm_handle_vmin_vmax_update);
572 	offload_work->adev = adev;
573 	offload_work->stream = stream;
574 	offload_work->adjust = adjust_copy;
575 
576 	queue_work(system_percpu_wq, &offload_work->work);
577 }
578 
dm_vupdate_high_irq(void * interrupt_params)579 static void dm_vupdate_high_irq(void *interrupt_params)
580 {
581 	struct common_irq_params *irq_params = interrupt_params;
582 	struct amdgpu_device *adev = irq_params->adev;
583 	struct amdgpu_crtc *acrtc;
584 	struct drm_device *drm_dev;
585 	struct drm_vblank_crtc *vblank;
586 	ktime_t frame_duration_ns, previous_timestamp;
587 	unsigned long flags;
588 	int vrr_active;
589 
590 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
591 
592 	if (acrtc) {
593 		vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
594 		drm_dev = acrtc->base.dev;
595 		vblank = drm_crtc_vblank_crtc(&acrtc->base);
596 		previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
597 		frame_duration_ns = vblank->time - previous_timestamp;
598 
599 		if (frame_duration_ns > 0) {
600 			trace_amdgpu_refresh_rate_track(acrtc->base.index,
601 						frame_duration_ns,
602 						ktime_divns(NSEC_PER_SEC, frame_duration_ns));
603 			atomic64_set(&irq_params->previous_timestamp, vblank->time);
604 		}
605 
606 		drm_dbg_vbl(drm_dev,
607 			    "crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
608 			    vrr_active);
609 
610 		/* Core vblank handling is done here after end of front-porch in
611 		 * vrr mode, as vblank timestamping will give valid results
612 		 * while now done after front-porch. This will also deliver
613 		 * page-flip completion events that have been queued to us
614 		 * if a pageflip happened inside front-porch.
615 		 */
616 		if (vrr_active && acrtc->dm_irq_params.stream) {
617 			bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
618 			bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
619 			bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state
620 				== VRR_STATE_ACTIVE_VARIABLE;
621 
622 			amdgpu_dm_crtc_handle_vblank(acrtc);
623 
624 			/* BTR processing for pre-DCE12 ASICs */
625 			if (adev->family < AMDGPU_FAMILY_AI) {
626 				spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
627 				mod_freesync_handle_v_update(
628 				    adev->dm.freesync_module,
629 				    acrtc->dm_irq_params.stream,
630 				    &acrtc->dm_irq_params.vrr_params);
631 
632 				if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
633 					schedule_dc_vmin_vmax(adev,
634 						acrtc->dm_irq_params.stream,
635 						&acrtc->dm_irq_params.vrr_params.adjust);
636 				}
637 				spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
638 			}
639 		}
640 	}
641 }
642 
643 /**
644  * dm_crtc_high_irq() - Handles CRTC interrupt
645  * @interrupt_params: used for determining the CRTC instance
646  *
647  * Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
648  * event handler.
649  */
dm_crtc_high_irq(void * interrupt_params)650 static void dm_crtc_high_irq(void *interrupt_params)
651 {
652 	struct common_irq_params *irq_params = interrupt_params;
653 	struct amdgpu_device *adev = irq_params->adev;
654 	struct drm_writeback_job *job;
655 	struct amdgpu_crtc *acrtc;
656 	unsigned long flags;
657 	int vrr_active;
658 
659 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
660 	if (!acrtc)
661 		return;
662 
663 	if (acrtc->wb_conn) {
664 		spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
665 
666 		if (acrtc->wb_pending) {
667 			job = list_first_entry_or_null(&acrtc->wb_conn->job_queue,
668 						       struct drm_writeback_job,
669 						       list_entry);
670 			acrtc->wb_pending = false;
671 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
672 
673 			if (job) {
674 				unsigned int v_total, refresh_hz;
675 				struct dc_stream_state *stream = acrtc->dm_irq_params.stream;
676 
677 				v_total = stream->adjust.v_total_max ?
678 					  stream->adjust.v_total_max : stream->timing.v_total;
679 				refresh_hz = div_u64((uint64_t) stream->timing.pix_clk_100hz *
680 					     100LL, (v_total * stream->timing.h_total));
681 				mdelay(1000 / refresh_hz);
682 
683 				drm_writeback_signal_completion(acrtc->wb_conn, 0);
684 				dc_stream_fc_disable_writeback(adev->dm.dc,
685 							       acrtc->dm_irq_params.stream, 0);
686 			}
687 		} else
688 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
689 	}
690 
691 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
692 
693 	drm_dbg_vbl(adev_to_drm(adev),
694 		    "crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
695 		    vrr_active, acrtc->dm_irq_params.active_planes);
696 
697 	/**
698 	 * Core vblank handling at start of front-porch is only possible
699 	 * in non-vrr mode, as only there vblank timestamping will give
700 	 * valid results while done in front-porch. Otherwise defer it
701 	 * to dm_vupdate_high_irq after end of front-porch.
702 	 */
703 	if (!vrr_active)
704 		amdgpu_dm_crtc_handle_vblank(acrtc);
705 
706 	/**
707 	 * Following stuff must happen at start of vblank, for crc
708 	 * computation and below-the-range btr support in vrr mode.
709 	 */
710 	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
711 
712 	/* BTR updates need to happen before VUPDATE on Vega and above. */
713 	if (adev->family < AMDGPU_FAMILY_AI)
714 		return;
715 
716 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
717 
718 	if (acrtc->dm_irq_params.stream &&
719 		acrtc->dm_irq_params.vrr_params.supported) {
720 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
721 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
722 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state == VRR_STATE_ACTIVE_VARIABLE;
723 
724 		mod_freesync_handle_v_update(adev->dm.freesync_module,
725 					     acrtc->dm_irq_params.stream,
726 					     &acrtc->dm_irq_params.vrr_params);
727 
728 		/* update vmin_vmax only if freesync is enabled, or only if PSR and REPLAY are disabled */
729 		if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
730 			schedule_dc_vmin_vmax(adev, acrtc->dm_irq_params.stream,
731 					&acrtc->dm_irq_params.vrr_params.adjust);
732 		}
733 	}
734 
735 	/*
736 	 * If there aren't any active_planes then DCH HUBP may be clock-gated.
737 	 * In that case, pageflip completion interrupts won't fire and pageflip
738 	 * completion events won't get delivered. Prevent this by sending
739 	 * pending pageflip events from here if a flip is still pending.
740 	 *
741 	 * If any planes are enabled, use dm_pflip_high_irq() instead, to
742 	 * avoid race conditions between flip programming and completion,
743 	 * which could cause too early flip completion events.
744 	 */
745 	if (adev->family >= AMDGPU_FAMILY_RV &&
746 	    acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
747 	    acrtc->dm_irq_params.active_planes == 0) {
748 		if (acrtc->event) {
749 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
750 			acrtc->event = NULL;
751 			drm_crtc_vblank_put(&acrtc->base);
752 		}
753 		acrtc->pflip_status = AMDGPU_FLIP_NONE;
754 	}
755 
756 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
757 }
758 
759 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
760 /**
761  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
762  * DCN generation ASICs
763  * @interrupt_params: interrupt parameters
764  *
765  * Used to set crc window/read out crc value at vertical line 0 position
766  */
dm_dcn_vertical_interrupt0_high_irq(void * interrupt_params)767 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
768 {
769 	struct common_irq_params *irq_params = interrupt_params;
770 	struct amdgpu_device *adev = irq_params->adev;
771 	struct amdgpu_crtc *acrtc;
772 
773 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
774 
775 	if (!acrtc)
776 		return;
777 
778 	amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
779 }
780 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
781 
782 /**
783  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
784  * @adev: amdgpu_device pointer
785  * @notify: dmub notification structure
786  *
787  * Dmub AUX or SET_CONFIG command completion processing callback
788  * Copies dmub notification to DM which is to be read by AUX command.
789  * issuing thread and also signals the event to wake up the thread.
790  */
dmub_aux_setconfig_callback(struct amdgpu_device * adev,struct dmub_notification * notify)791 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
792 					struct dmub_notification *notify)
793 {
794 	if (adev->dm.dmub_notify)
795 		memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
796 	if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
797 		complete(&adev->dm.dmub_aux_transfer_done);
798 }
799 
dmub_aux_fused_io_callback(struct amdgpu_device * adev,struct dmub_notification * notify)800 static void dmub_aux_fused_io_callback(struct amdgpu_device *adev,
801 					struct dmub_notification *notify)
802 {
803 	if (!adev || !notify) {
804 		ASSERT(false);
805 		return;
806 	}
807 
808 	const struct dmub_cmd_fused_request *req = &notify->fused_request;
809 	const uint8_t ddc_line = req->u.aux.ddc_line;
810 
811 	if (ddc_line >= ARRAY_SIZE(adev->dm.fused_io)) {
812 		ASSERT(false);
813 		return;
814 	}
815 
816 	struct fused_io_sync *sync = &adev->dm.fused_io[ddc_line];
817 
818 	static_assert(sizeof(*req) <= sizeof(sync->reply_data), "Size mismatch");
819 	memcpy(sync->reply_data, req, sizeof(*req));
820 	complete(&sync->replied);
821 }
822 
823 /**
824  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
825  * @adev: amdgpu_device pointer
826  * @notify: dmub notification structure
827  *
828  * Dmub Hpd interrupt processing callback. Gets displayindex through the
829  * ink index and calls helper to do the processing.
830  */
dmub_hpd_callback(struct amdgpu_device * adev,struct dmub_notification * notify)831 static void dmub_hpd_callback(struct amdgpu_device *adev,
832 			      struct dmub_notification *notify)
833 {
834 	struct amdgpu_dm_connector *aconnector;
835 	struct amdgpu_dm_connector *hpd_aconnector = NULL;
836 	struct drm_connector *connector;
837 	struct drm_connector_list_iter iter;
838 	struct dc_link *link;
839 	u8 link_index = 0;
840 	struct drm_device *dev;
841 
842 	if (adev == NULL)
843 		return;
844 
845 	if (notify == NULL) {
846 		drm_err(adev_to_drm(adev), "DMUB HPD callback notification was NULL");
847 		return;
848 	}
849 
850 	if (notify->link_index > adev->dm.dc->link_count) {
851 		drm_err(adev_to_drm(adev), "DMUB HPD index (%u)is abnormal", notify->link_index);
852 		return;
853 	}
854 
855 	/* Skip DMUB HPD IRQ in suspend/resume. We will probe them later. */
856 	if (notify->type == DMUB_NOTIFICATION_HPD && adev->in_suspend) {
857 		drm_info(adev_to_drm(adev), "Skip DMUB HPD IRQ callback in suspend/resume\n");
858 		return;
859 	}
860 
861 	link_index = notify->link_index;
862 	link = adev->dm.dc->links[link_index];
863 	dev = adev->dm.ddev;
864 
865 	drm_connector_list_iter_begin(dev, &iter);
866 	drm_for_each_connector_iter(connector, &iter) {
867 
868 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
869 			continue;
870 
871 		aconnector = to_amdgpu_dm_connector(connector);
872 		if (link && aconnector->dc_link == link) {
873 			if (notify->type == DMUB_NOTIFICATION_HPD)
874 				drm_info(adev_to_drm(adev), "DMUB HPD IRQ callback: link_index=%u\n", link_index);
875 			else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
876 				drm_info(adev_to_drm(adev), "DMUB HPD RX IRQ callback: link_index=%u\n", link_index);
877 			else
878 				drm_warn(adev_to_drm(adev), "DMUB Unknown HPD callback type %d, link_index=%u\n",
879 						notify->type, link_index);
880 
881 			hpd_aconnector = aconnector;
882 			break;
883 		}
884 	}
885 	drm_connector_list_iter_end(&iter);
886 
887 	if (hpd_aconnector) {
888 		if (notify->type == DMUB_NOTIFICATION_HPD) {
889 			if (hpd_aconnector->dc_link->hpd_status == (notify->hpd_status == DP_HPD_PLUG))
890 				drm_warn(adev_to_drm(adev), "DMUB reported hpd status unchanged. link_index=%u\n", link_index);
891 			handle_hpd_irq_helper(hpd_aconnector);
892 		} else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ) {
893 			handle_hpd_rx_irq(hpd_aconnector);
894 		}
895 	}
896 }
897 
898 /**
899  * dmub_hpd_sense_callback - DMUB HPD sense processing callback.
900  * @adev: amdgpu_device pointer
901  * @notify: dmub notification structure
902  *
903  * HPD sense changes can occur during low power states and need to be
904  * notified from firmware to driver.
905  */
dmub_hpd_sense_callback(struct amdgpu_device * adev,struct dmub_notification * notify)906 static void dmub_hpd_sense_callback(struct amdgpu_device *adev,
907 			      struct dmub_notification *notify)
908 {
909 	drm_dbg_driver(adev_to_drm(adev), "DMUB HPD SENSE callback.\n");
910 }
911 
912 /**
913  * register_dmub_notify_callback - Sets callback for DMUB notify
914  * @adev: amdgpu_device pointer
915  * @type: Type of dmub notification
916  * @callback: Dmub interrupt callback function
917  * @dmub_int_thread_offload: offload indicator
918  *
919  * API to register a dmub callback handler for a dmub notification
920  * Also sets indicator whether callback processing to be offloaded.
921  * to dmub interrupt handling thread
922  * Return: true if successfully registered, false if there is existing registration
923  */
register_dmub_notify_callback(struct amdgpu_device * adev,enum dmub_notification_type type,dmub_notify_interrupt_callback_t callback,bool dmub_int_thread_offload)924 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
925 					  enum dmub_notification_type type,
926 					  dmub_notify_interrupt_callback_t callback,
927 					  bool dmub_int_thread_offload)
928 {
929 	if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
930 		adev->dm.dmub_callback[type] = callback;
931 		adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
932 	} else
933 		return false;
934 
935 	return true;
936 }
937 
dm_handle_hpd_work(struct work_struct * work)938 static void dm_handle_hpd_work(struct work_struct *work)
939 {
940 	struct dmub_hpd_work *dmub_hpd_wrk;
941 
942 	dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
943 
944 	if (!dmub_hpd_wrk->dmub_notify) {
945 		drm_err(adev_to_drm(dmub_hpd_wrk->adev), "dmub_hpd_wrk dmub_notify is NULL");
946 		return;
947 	}
948 
949 	if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
950 		dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
951 		dmub_hpd_wrk->dmub_notify);
952 	}
953 
954 	kfree(dmub_hpd_wrk->dmub_notify);
955 	kfree(dmub_hpd_wrk);
956 
957 }
958 
dmub_notification_type_str(enum dmub_notification_type e)959 static const char *dmub_notification_type_str(enum dmub_notification_type e)
960 {
961 	switch (e) {
962 	case DMUB_NOTIFICATION_NO_DATA:
963 		return "NO_DATA";
964 	case DMUB_NOTIFICATION_AUX_REPLY:
965 		return "AUX_REPLY";
966 	case DMUB_NOTIFICATION_HPD:
967 		return "HPD";
968 	case DMUB_NOTIFICATION_HPD_IRQ:
969 		return "HPD_IRQ";
970 	case DMUB_NOTIFICATION_SET_CONFIG_REPLY:
971 		return "SET_CONFIG_REPLY";
972 	case DMUB_NOTIFICATION_DPIA_NOTIFICATION:
973 		return "DPIA_NOTIFICATION";
974 	case DMUB_NOTIFICATION_HPD_SENSE_NOTIFY:
975 		return "HPD_SENSE_NOTIFY";
976 	case DMUB_NOTIFICATION_FUSED_IO:
977 		return "FUSED_IO";
978 	default:
979 		return "<unknown>";
980 	}
981 }
982 
983 #define DMUB_TRACE_MAX_READ 64
984 /**
985  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
986  * @interrupt_params: used for determining the Outbox instance
987  *
988  * Handles the Outbox Interrupt
989  * event handler.
990  */
dm_dmub_outbox1_low_irq(void * interrupt_params)991 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
992 {
993 	struct dmub_notification notify = {0};
994 	struct common_irq_params *irq_params = interrupt_params;
995 	struct amdgpu_device *adev = irq_params->adev;
996 	struct amdgpu_display_manager *dm = &adev->dm;
997 	struct dmcub_trace_buf_entry entry = { 0 };
998 	u32 count = 0;
999 	struct dmub_hpd_work *dmub_hpd_wrk;
1000 
1001 	do {
1002 		if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
1003 			trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
1004 							entry.param0, entry.param1);
1005 
1006 			drm_dbg_driver(adev_to_drm(adev), "trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
1007 				 entry.trace_code, entry.tick_count, entry.param0, entry.param1);
1008 		} else
1009 			break;
1010 
1011 		count++;
1012 
1013 	} while (count <= DMUB_TRACE_MAX_READ);
1014 
1015 	if (count > DMUB_TRACE_MAX_READ)
1016 		drm_dbg_driver(adev_to_drm(adev), "Warning : count > DMUB_TRACE_MAX_READ");
1017 
1018 	if (dc_enable_dmub_notifications(adev->dm.dc) &&
1019 		irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
1020 
1021 		do {
1022 			dc_stat_get_dmub_notification(adev->dm.dc, &notify);
1023 			if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
1024 				drm_err(adev_to_drm(adev), "DM: notify type %d invalid!", notify.type);
1025 				continue;
1026 			}
1027 			if (!dm->dmub_callback[notify.type]) {
1028 				drm_warn(adev_to_drm(adev), "DMUB notification skipped due to no handler: type=%s\n",
1029 					dmub_notification_type_str(notify.type));
1030 				continue;
1031 			}
1032 			if (dm->dmub_thread_offload[notify.type] == true) {
1033 				dmub_hpd_wrk = kzalloc_obj(*dmub_hpd_wrk,
1034 							   GFP_ATOMIC);
1035 				if (!dmub_hpd_wrk) {
1036 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk");
1037 					return;
1038 				}
1039 				dmub_hpd_wrk->dmub_notify = kmemdup(&notify, sizeof(struct dmub_notification),
1040 								    GFP_ATOMIC);
1041 				if (!dmub_hpd_wrk->dmub_notify) {
1042 					kfree(dmub_hpd_wrk);
1043 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk->dmub_notify");
1044 					return;
1045 				}
1046 				INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
1047 				dmub_hpd_wrk->adev = adev;
1048 				queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
1049 			} else {
1050 				dm->dmub_callback[notify.type](adev, &notify);
1051 			}
1052 		} while (notify.pending_notification);
1053 	}
1054 }
1055 
dm_set_clockgating_state(struct amdgpu_ip_block * ip_block,enum amd_clockgating_state state)1056 static int dm_set_clockgating_state(struct amdgpu_ip_block *ip_block,
1057 		  enum amd_clockgating_state state)
1058 {
1059 	return 0;
1060 }
1061 
dm_set_powergating_state(struct amdgpu_ip_block * ip_block,enum amd_powergating_state state)1062 static int dm_set_powergating_state(struct amdgpu_ip_block *ip_block,
1063 		  enum amd_powergating_state state)
1064 {
1065 	return 0;
1066 }
1067 
1068 /* Prototypes of private functions */
1069 static int dm_early_init(struct amdgpu_ip_block *ip_block);
1070 
1071 /* Allocate memory for FBC compressed data  */
amdgpu_dm_fbc_init(struct drm_connector * connector)1072 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
1073 {
1074 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
1075 	struct dm_compressor_info *compressor = &adev->dm.compressor;
1076 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
1077 	struct drm_display_mode *mode;
1078 	unsigned long max_size = 0;
1079 
1080 	if (adev->dm.dc->fbc_compressor == NULL)
1081 		return;
1082 
1083 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
1084 		return;
1085 
1086 	if (compressor->bo_ptr)
1087 		return;
1088 
1089 
1090 	list_for_each_entry(mode, &connector->modes, head) {
1091 		if (max_size < (unsigned long) mode->htotal * mode->vtotal)
1092 			max_size = (unsigned long) mode->htotal * mode->vtotal;
1093 	}
1094 
1095 	if (max_size) {
1096 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
1097 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
1098 			    &compressor->gpu_addr, &compressor->cpu_addr);
1099 
1100 		if (r)
1101 			drm_err(adev_to_drm(adev), "DM: Failed to initialize FBC\n");
1102 		else {
1103 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
1104 			drm_info(adev_to_drm(adev), "DM: FBC alloc %lu\n", max_size*4);
1105 		}
1106 
1107 	}
1108 
1109 }
1110 
amdgpu_dm_audio_component_get_eld(struct device * kdev,int port,int pipe,bool * enabled,unsigned char * buf,int max_bytes)1111 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
1112 					  int pipe, bool *enabled,
1113 					  unsigned char *buf, int max_bytes)
1114 {
1115 	struct drm_device *dev = dev_get_drvdata(kdev);
1116 	struct amdgpu_device *adev = drm_to_adev(dev);
1117 	struct drm_connector *connector;
1118 	struct drm_connector_list_iter conn_iter;
1119 	struct amdgpu_dm_connector *aconnector;
1120 	int ret = 0;
1121 
1122 	*enabled = false;
1123 
1124 	mutex_lock(&adev->dm.audio_lock);
1125 
1126 	drm_connector_list_iter_begin(dev, &conn_iter);
1127 	drm_for_each_connector_iter(connector, &conn_iter) {
1128 
1129 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1130 			continue;
1131 
1132 		aconnector = to_amdgpu_dm_connector(connector);
1133 		if (aconnector->audio_inst != port)
1134 			continue;
1135 
1136 		*enabled = true;
1137 		mutex_lock(&connector->eld_mutex);
1138 		ret = drm_eld_size(connector->eld);
1139 		memcpy(buf, connector->eld, min(max_bytes, ret));
1140 		mutex_unlock(&connector->eld_mutex);
1141 
1142 		break;
1143 	}
1144 	drm_connector_list_iter_end(&conn_iter);
1145 
1146 	mutex_unlock(&adev->dm.audio_lock);
1147 
1148 	drm_dbg_kms(adev_to_drm(adev), "Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
1149 
1150 	return ret;
1151 }
1152 
1153 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
1154 	.get_eld = amdgpu_dm_audio_component_get_eld,
1155 };
1156 
amdgpu_dm_audio_component_bind(struct device * kdev,struct device * hda_kdev,void * data)1157 static int amdgpu_dm_audio_component_bind(struct device *kdev,
1158 				       struct device *hda_kdev, void *data)
1159 {
1160 	struct drm_device *dev = dev_get_drvdata(kdev);
1161 	struct amdgpu_device *adev = drm_to_adev(dev);
1162 	struct drm_audio_component *acomp = data;
1163 
1164 	acomp->ops = &amdgpu_dm_audio_component_ops;
1165 	acomp->dev = kdev;
1166 	adev->dm.audio_component = acomp;
1167 
1168 	return 0;
1169 }
1170 
amdgpu_dm_audio_component_unbind(struct device * kdev,struct device * hda_kdev,void * data)1171 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
1172 					  struct device *hda_kdev, void *data)
1173 {
1174 	struct amdgpu_device *adev = drm_to_adev(dev_get_drvdata(kdev));
1175 	struct drm_audio_component *acomp = data;
1176 
1177 	acomp->ops = NULL;
1178 	acomp->dev = NULL;
1179 	adev->dm.audio_component = NULL;
1180 }
1181 
1182 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
1183 	.bind	= amdgpu_dm_audio_component_bind,
1184 	.unbind	= amdgpu_dm_audio_component_unbind,
1185 };
1186 
amdgpu_dm_audio_init(struct amdgpu_device * adev)1187 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
1188 {
1189 	int i, ret;
1190 
1191 	if (!amdgpu_audio)
1192 		return 0;
1193 
1194 	adev->mode_info.audio.enabled = true;
1195 
1196 	adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
1197 
1198 	for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
1199 		adev->mode_info.audio.pin[i].channels = -1;
1200 		adev->mode_info.audio.pin[i].rate = -1;
1201 		adev->mode_info.audio.pin[i].bits_per_sample = -1;
1202 		adev->mode_info.audio.pin[i].status_bits = 0;
1203 		adev->mode_info.audio.pin[i].category_code = 0;
1204 		adev->mode_info.audio.pin[i].connected = false;
1205 		adev->mode_info.audio.pin[i].id =
1206 			adev->dm.dc->res_pool->audios[i]->inst;
1207 		adev->mode_info.audio.pin[i].offset = 0;
1208 	}
1209 
1210 	ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1211 	if (ret < 0)
1212 		return ret;
1213 
1214 	adev->dm.audio_registered = true;
1215 
1216 	return 0;
1217 }
1218 
amdgpu_dm_audio_fini(struct amdgpu_device * adev)1219 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
1220 {
1221 	if (!amdgpu_audio)
1222 		return;
1223 
1224 	if (!adev->mode_info.audio.enabled)
1225 		return;
1226 
1227 	if (adev->dm.audio_registered) {
1228 		component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1229 		adev->dm.audio_registered = false;
1230 	}
1231 
1232 	/* TODO: Disable audio? */
1233 
1234 	adev->mode_info.audio.enabled = false;
1235 }
1236 
amdgpu_dm_audio_eld_notify(struct amdgpu_device * adev,int pin)1237 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
1238 {
1239 	struct drm_audio_component *acomp = adev->dm.audio_component;
1240 
1241 	if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
1242 		drm_dbg_kms(adev_to_drm(adev), "Notify ELD: %d\n", pin);
1243 
1244 		acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1245 						 pin, -1);
1246 	}
1247 }
1248 
dm_dmub_hw_init(struct amdgpu_device * adev)1249 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1250 {
1251 	const struct dmcub_firmware_header_v1_0 *hdr;
1252 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1253 	struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1254 	const struct firmware *dmub_fw = adev->dm.dmub_fw;
1255 	struct dc *dc = adev->dm.dc;
1256 	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1257 	struct abm *abm = adev->dm.dc->res_pool->abm;
1258 	struct dc_context *ctx = adev->dm.dc->ctx;
1259 	struct dmub_srv_hw_params hw_params;
1260 	enum dmub_status status;
1261 	const unsigned char *fw_inst_const, *fw_bss_data;
1262 	u32 i, fw_inst_const_size, fw_bss_data_size;
1263 	bool has_hw_support;
1264 
1265 	if (!dmub_srv)
1266 		/* DMUB isn't supported on the ASIC. */
1267 		return 0;
1268 
1269 	if (!fb_info) {
1270 		drm_err(adev_to_drm(adev), "No framebuffer info for DMUB service.\n");
1271 		return -EINVAL;
1272 	}
1273 
1274 	if (!dmub_fw) {
1275 		/* Firmware required for DMUB support. */
1276 		drm_err(adev_to_drm(adev), "No firmware provided for DMUB.\n");
1277 		return -EINVAL;
1278 	}
1279 
1280 	/* initialize register offsets for ASICs with runtime initialization available */
1281 	if (dmub_srv->hw_funcs.init_reg_offsets)
1282 		dmub_srv->hw_funcs.init_reg_offsets(dmub_srv, ctx);
1283 
1284 	status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1285 	if (status != DMUB_STATUS_OK) {
1286 		drm_err(adev_to_drm(adev), "Error checking HW support for DMUB: %d\n", status);
1287 		return -EINVAL;
1288 	}
1289 
1290 	if (!has_hw_support) {
1291 		drm_info(adev_to_drm(adev), "DMUB unsupported on ASIC\n");
1292 		return 0;
1293 	}
1294 
1295 	/* Reset DMCUB if it was previously running - before we overwrite its memory. */
1296 	status = dmub_srv_hw_reset(dmub_srv);
1297 	if (status != DMUB_STATUS_OK)
1298 		drm_warn(adev_to_drm(adev), "Error resetting DMUB HW: %d\n", status);
1299 
1300 	hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1301 
1302 	fw_inst_const = dmub_fw->data +
1303 			le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1304 			PSP_HEADER_BYTES_256;
1305 
1306 	fw_bss_data = dmub_fw->data +
1307 		      le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1308 		      le32_to_cpu(hdr->inst_const_bytes);
1309 
1310 	/* Copy firmware and bios info into FB memory. */
1311 	fw_inst_const_size = adev->dm.fw_inst_size;
1312 
1313 	fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1314 
1315 	/* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1316 	 * amdgpu_ucode_init_single_fw will load dmub firmware
1317 	 * fw_inst_const part to cw0; otherwise, the firmware back door load
1318 	 * will be done by dm_dmub_hw_init
1319 	 */
1320 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1321 		memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1322 				fw_inst_const_size);
1323 	}
1324 
1325 	if (fw_bss_data_size)
1326 		memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1327 		       fw_bss_data, fw_bss_data_size);
1328 
1329 	/* Copy firmware bios info into FB memory. */
1330 	memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1331 	       adev->bios_size);
1332 
1333 	/* Reset regions that need to be reset. */
1334 	memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1335 	fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1336 
1337 	memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1338 	       fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1339 
1340 	memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1341 	       fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1342 
1343 	memset(fb_info->fb[DMUB_WINDOW_SHARED_STATE].cpu_addr, 0,
1344 	       fb_info->fb[DMUB_WINDOW_SHARED_STATE].size);
1345 
1346 	/* Initialize hardware. */
1347 	memset(&hw_params, 0, sizeof(hw_params));
1348 	hw_params.soc_fb_info.fb_base = adev->gmc.fb_start;
1349 	hw_params.soc_fb_info.fb_offset = adev->vm_manager.vram_base_offset;
1350 
1351 	/* backdoor load firmware and trigger dmub running */
1352 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1353 		hw_params.load_inst_const = true;
1354 
1355 	if (dmcu)
1356 		hw_params.psp_version = dmcu->psp_version;
1357 
1358 	for (i = 0; i < fb_info->num_fb; ++i)
1359 		hw_params.fb[i] = &fb_info->fb[i];
1360 
1361 	/* Enable usb4 dpia in the FW APU */
1362 	if (dc->caps.is_apu &&
1363 		dc->res_pool->usb4_dpia_count != 0 &&
1364 		!dc->debug.dpia_debug.bits.disable_dpia) {
1365 		hw_params.dpia_supported = true;
1366 		hw_params.disable_dpia = dc->debug.dpia_debug.bits.disable_dpia;
1367 		hw_params.dpia_hpd_int_enable_supported = false;
1368 		hw_params.enable_non_transparent_setconfig = dc->config.consolidated_dpia_dp_lt;
1369 		hw_params.disable_dpia_bw_allocation = !dc->config.usb4_bw_alloc_support;
1370 	}
1371 
1372 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1373 	case IP_VERSION(3, 5, 0):
1374 	case IP_VERSION(3, 5, 1):
1375 	case IP_VERSION(3, 6, 0):
1376 	case IP_VERSION(4, 2, 0):
1377 		hw_params.ips_sequential_ono = adev->external_rev_id > 0x10;
1378 		hw_params.lower_hbr3_phy_ssc = true;
1379 		break;
1380 	default:
1381 		break;
1382 	}
1383 
1384 	status = dmub_srv_hw_init(dmub_srv, &hw_params);
1385 	if (status != DMUB_STATUS_OK) {
1386 		drm_err(adev_to_drm(adev), "Error initializing DMUB HW: %d\n", status);
1387 		return -EINVAL;
1388 	}
1389 
1390 	/* Wait for firmware load to finish. */
1391 	status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1392 	if (status != DMUB_STATUS_OK)
1393 		drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1394 
1395 	/* Init DMCU and ABM if available. */
1396 	if (dmcu && abm) {
1397 		dmcu->funcs->dmcu_init(dmcu);
1398 		abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1399 	}
1400 
1401 	if (!adev->dm.dc->ctx->dmub_srv)
1402 		adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1403 	if (!adev->dm.dc->ctx->dmub_srv) {
1404 		drm_err(adev_to_drm(adev), "Couldn't allocate DC DMUB server!\n");
1405 		return -ENOMEM;
1406 	}
1407 
1408 	drm_info(adev_to_drm(adev), "DMUB hardware initialized: version=0x%08X\n",
1409 		 adev->dm.dmcub_fw_version);
1410 
1411 	/* Keeping sanity checks off if
1412 	 * DCN31 >= 4.0.59.0
1413 	 * DCN314 >= 8.0.16.0
1414 	 * Otherwise, turn on sanity checks
1415 	 */
1416 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1417 	case IP_VERSION(3, 1, 2):
1418 	case IP_VERSION(3, 1, 3):
1419 		if (adev->dm.dmcub_fw_version &&
1420 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1421 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(4, 0, 59))
1422 				adev->dm.dc->debug.sanity_checks = true;
1423 		break;
1424 	case IP_VERSION(3, 1, 4):
1425 		if (adev->dm.dmcub_fw_version &&
1426 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1427 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(8, 0, 16))
1428 				adev->dm.dc->debug.sanity_checks = true;
1429 		break;
1430 	default:
1431 		break;
1432 	}
1433 
1434 	return 0;
1435 }
1436 
dm_dmub_hw_resume(struct amdgpu_device * adev)1437 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1438 {
1439 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1440 	enum dmub_status status;
1441 	bool init;
1442 	int r;
1443 
1444 	if (!dmub_srv) {
1445 		/* DMUB isn't supported on the ASIC. */
1446 		return;
1447 	}
1448 
1449 	status = dmub_srv_is_hw_init(dmub_srv, &init);
1450 	if (status != DMUB_STATUS_OK)
1451 		drm_warn(adev_to_drm(adev), "DMUB hardware init check failed: %d\n", status);
1452 
1453 	if (status == DMUB_STATUS_OK && init) {
1454 		/* Wait for firmware load to finish. */
1455 		status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1456 		if (status != DMUB_STATUS_OK)
1457 			drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1458 	} else {
1459 		/* Perform the full hardware initialization. */
1460 		r = dm_dmub_hw_init(adev);
1461 		if (r)
1462 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
1463 	}
1464 }
1465 
mmhub_read_system_context(struct amdgpu_device * adev,struct dc_phy_addr_space_config * pa_config)1466 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1467 {
1468 	u64 pt_base;
1469 	u32 logical_addr_low;
1470 	u32 logical_addr_high;
1471 	u32 agp_base, agp_bot, agp_top;
1472 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1473 
1474 	memset(pa_config, 0, sizeof(*pa_config));
1475 
1476 	agp_base = 0;
1477 	agp_bot = adev->gmc.agp_start >> 24;
1478 	agp_top = adev->gmc.agp_end >> 24;
1479 
1480 	/* AGP aperture is disabled */
1481 	if (agp_bot > agp_top) {
1482 		logical_addr_low = adev->gmc.fb_start >> 18;
1483 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1484 				       AMD_APU_IS_RENOIR |
1485 				       AMD_APU_IS_GREEN_SARDINE))
1486 			/*
1487 			 * Raven2 has a HW issue that it is unable to use the vram which
1488 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1489 			 * workaround that increase system aperture high address (add 1)
1490 			 * to get rid of the VM fault and hardware hang.
1491 			 */
1492 			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
1493 		else
1494 			logical_addr_high = adev->gmc.fb_end >> 18;
1495 	} else {
1496 		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1497 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1498 				       AMD_APU_IS_RENOIR |
1499 				       AMD_APU_IS_GREEN_SARDINE))
1500 			/*
1501 			 * Raven2 has a HW issue that it is unable to use the vram which
1502 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1503 			 * workaround that increase system aperture high address (add 1)
1504 			 * to get rid of the VM fault and hardware hang.
1505 			 */
1506 			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1507 		else
1508 			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1509 	}
1510 
1511 	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1512 
1513 	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
1514 						   AMDGPU_GPU_PAGE_SHIFT);
1515 	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
1516 						  AMDGPU_GPU_PAGE_SHIFT);
1517 	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
1518 						 AMDGPU_GPU_PAGE_SHIFT);
1519 	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
1520 						AMDGPU_GPU_PAGE_SHIFT);
1521 	page_table_base.high_part = upper_32_bits(pt_base);
1522 	page_table_base.low_part = lower_32_bits(pt_base);
1523 
1524 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1525 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1526 
1527 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
1528 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1529 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1530 
1531 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1532 	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
1533 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1534 
1535 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1536 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1537 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1538 
1539 	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
1540 
1541 }
1542 
force_connector_state(struct amdgpu_dm_connector * aconnector,enum drm_connector_force force_state)1543 static void force_connector_state(
1544 	struct amdgpu_dm_connector *aconnector,
1545 	enum drm_connector_force force_state)
1546 {
1547 	struct drm_connector *connector = &aconnector->base;
1548 
1549 	mutex_lock(&connector->dev->mode_config.mutex);
1550 	aconnector->base.force = force_state;
1551 	mutex_unlock(&connector->dev->mode_config.mutex);
1552 
1553 	mutex_lock(&aconnector->hpd_lock);
1554 	drm_kms_helper_connector_hotplug_event(connector);
1555 	mutex_unlock(&aconnector->hpd_lock);
1556 }
1557 
dm_handle_hpd_rx_offload_work(struct work_struct * work)1558 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1559 {
1560 	struct hpd_rx_irq_offload_work *offload_work;
1561 	struct amdgpu_dm_connector *aconnector;
1562 	struct dc_link *dc_link;
1563 	struct amdgpu_device *adev;
1564 	enum dc_connection_type new_connection_type = dc_connection_none;
1565 	unsigned long flags;
1566 	union test_response test_response;
1567 
1568 	memset(&test_response, 0, sizeof(test_response));
1569 
1570 	offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1571 	aconnector = offload_work->offload_wq->aconnector;
1572 	adev = offload_work->adev;
1573 
1574 	if (!aconnector) {
1575 		drm_err(adev_to_drm(adev), "Can't retrieve aconnector in hpd_rx_irq_offload_work");
1576 		goto skip;
1577 	}
1578 
1579 	dc_link = aconnector->dc_link;
1580 
1581 	mutex_lock(&aconnector->hpd_lock);
1582 	if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
1583 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
1584 	mutex_unlock(&aconnector->hpd_lock);
1585 
1586 	if (new_connection_type == dc_connection_none)
1587 		goto skip;
1588 
1589 	if (amdgpu_in_reset(adev))
1590 		goto skip;
1591 
1592 	if (offload_work->data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
1593 		offload_work->data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
1594 		dm_handle_mst_sideband_msg_ready_event(&aconnector->mst_mgr, DOWN_OR_UP_MSG_RDY_EVENT);
1595 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1596 		offload_work->offload_wq->is_handling_mst_msg_rdy_event = false;
1597 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1598 		goto skip;
1599 	}
1600 
1601 	mutex_lock(&adev->dm.dc_lock);
1602 	if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
1603 		dc_link_dp_handle_automated_test(dc_link);
1604 
1605 		if (aconnector->timing_changed) {
1606 			/* force connector disconnect and reconnect */
1607 			force_connector_state(aconnector, DRM_FORCE_OFF);
1608 			msleep(100);
1609 			force_connector_state(aconnector, DRM_FORCE_UNSPECIFIED);
1610 		}
1611 
1612 		test_response.bits.ACK = 1;
1613 
1614 		core_link_write_dpcd(
1615 		dc_link,
1616 		DP_TEST_RESPONSE,
1617 		&test_response.raw,
1618 		sizeof(test_response));
1619 	} else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1620 			dc_link_check_link_loss_status(dc_link, &offload_work->data) &&
1621 			dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1622 		/* offload_work->data is from handle_hpd_rx_irq->
1623 		 * schedule_hpd_rx_offload_work.this is defer handle
1624 		 * for hpd short pulse. upon here, link status may be
1625 		 * changed, need get latest link status from dpcd
1626 		 * registers. if link status is good, skip run link
1627 		 * training again.
1628 		 */
1629 		union hpd_irq_data irq_data;
1630 
1631 		memset(&irq_data, 0, sizeof(irq_data));
1632 
1633 		/* before dc_link_dp_handle_link_loss, allow new link lost handle
1634 		 * request be added to work queue if link lost at end of dc_link_
1635 		 * dp_handle_link_loss
1636 		 */
1637 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1638 		offload_work->offload_wq->is_handling_link_loss = false;
1639 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1640 
1641 		if ((dc_link_dp_read_hpd_rx_irq_data(dc_link, &irq_data) == DC_OK) &&
1642 			dc_link_check_link_loss_status(dc_link, &irq_data))
1643 			dc_link_dp_handle_link_loss(dc_link);
1644 	}
1645 	mutex_unlock(&adev->dm.dc_lock);
1646 
1647 skip:
1648 	kfree(offload_work);
1649 
1650 }
1651 
hpd_rx_irq_create_workqueue(struct amdgpu_device * adev)1652 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct amdgpu_device *adev)
1653 {
1654 	struct dc *dc = adev->dm.dc;
1655 	int max_caps = dc->caps.max_links;
1656 	int i = 0;
1657 	struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1658 
1659 	hpd_rx_offload_wq = kzalloc_objs(*hpd_rx_offload_wq, max_caps);
1660 
1661 	if (!hpd_rx_offload_wq)
1662 		return NULL;
1663 
1664 
1665 	for (i = 0; i < max_caps; i++) {
1666 		hpd_rx_offload_wq[i].wq =
1667 				    create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1668 
1669 		if (hpd_rx_offload_wq[i].wq == NULL) {
1670 			drm_err(adev_to_drm(adev), "create amdgpu_dm_hpd_rx_offload_wq fail!");
1671 			goto out_err;
1672 		}
1673 
1674 		spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
1675 	}
1676 
1677 	return hpd_rx_offload_wq;
1678 
1679 out_err:
1680 	for (i = 0; i < max_caps; i++) {
1681 		if (hpd_rx_offload_wq[i].wq)
1682 			destroy_workqueue(hpd_rx_offload_wq[i].wq);
1683 	}
1684 	kfree(hpd_rx_offload_wq);
1685 	return NULL;
1686 }
1687 
1688 struct amdgpu_stutter_quirk {
1689 	u16 chip_vendor;
1690 	u16 chip_device;
1691 	u16 subsys_vendor;
1692 	u16 subsys_device;
1693 	u8 revision;
1694 };
1695 
1696 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1697 	/* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1698 	{ 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1699 	{ 0, 0, 0, 0, 0 },
1700 };
1701 
dm_should_disable_stutter(struct pci_dev * pdev)1702 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1703 {
1704 	const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1705 
1706 	while (p && p->chip_device != 0) {
1707 		if (pdev->vendor == p->chip_vendor &&
1708 		    pdev->device == p->chip_device &&
1709 		    pdev->subsystem_vendor == p->subsys_vendor &&
1710 		    pdev->subsystem_device == p->subsys_device &&
1711 		    pdev->revision == p->revision) {
1712 			return true;
1713 		}
1714 		++p;
1715 	}
1716 	return false;
1717 }
1718 
1719 
1720 void*
dm_allocate_gpu_mem(struct amdgpu_device * adev,enum dc_gpu_mem_alloc_type type,size_t size,long long * addr)1721 dm_allocate_gpu_mem(
1722 		struct amdgpu_device *adev,
1723 		enum dc_gpu_mem_alloc_type type,
1724 		size_t size,
1725 		long long *addr)
1726 {
1727 	struct dal_allocation *da;
1728 	u32 domain = (type == DC_MEM_ALLOC_TYPE_GART) ?
1729 		AMDGPU_GEM_DOMAIN_GTT : AMDGPU_GEM_DOMAIN_VRAM;
1730 	int ret;
1731 
1732 	da = kzalloc_obj(struct dal_allocation);
1733 	if (!da)
1734 		return NULL;
1735 
1736 	ret = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
1737 				      domain, &da->bo,
1738 				      &da->gpu_addr, &da->cpu_ptr);
1739 
1740 	*addr = da->gpu_addr;
1741 
1742 	if (ret) {
1743 		kfree(da);
1744 		return NULL;
1745 	}
1746 
1747 	/* add da to list in dm */
1748 	list_add(&da->list, &adev->dm.da_list);
1749 
1750 	return da->cpu_ptr;
1751 }
1752 
1753 void
dm_free_gpu_mem(struct amdgpu_device * adev,enum dc_gpu_mem_alloc_type type,void * pvMem)1754 dm_free_gpu_mem(
1755 		struct amdgpu_device *adev,
1756 		enum dc_gpu_mem_alloc_type type,
1757 		void *pvMem)
1758 {
1759 	struct dal_allocation *da;
1760 
1761 	/* walk the da list in DM */
1762 	list_for_each_entry(da, &adev->dm.da_list, list) {
1763 		if (pvMem == da->cpu_ptr) {
1764 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
1765 			list_del(&da->list);
1766 			kfree(da);
1767 			break;
1768 		}
1769 	}
1770 
1771 }
1772 
1773 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)1774 dm_dmub_send_vbios_gpint_command(struct amdgpu_device *adev,
1775 				 enum dmub_gpint_command command_code,
1776 				 uint16_t param,
1777 				 uint32_t timeout_us)
1778 {
1779 	union dmub_gpint_data_register reg, test;
1780 	uint32_t i;
1781 
1782 	/* Assume that VBIOS DMUB is ready to take commands */
1783 
1784 	reg.bits.status = 1;
1785 	reg.bits.command_code = command_code;
1786 	reg.bits.param = param;
1787 
1788 	cgs_write_register(adev->dm.cgs_device, 0x34c0 + 0x01f8, reg.all);
1789 
1790 	for (i = 0; i < timeout_us; ++i) {
1791 		udelay(1);
1792 
1793 		/* Check if our GPINT got acked */
1794 		reg.bits.status = 0;
1795 		test = (union dmub_gpint_data_register)
1796 			cgs_read_register(adev->dm.cgs_device, 0x34c0 + 0x01f8);
1797 
1798 		if (test.all == reg.all)
1799 			return DMUB_STATUS_OK;
1800 	}
1801 
1802 	return DMUB_STATUS_TIMEOUT;
1803 }
1804 
dm_dmub_get_vbios_bounding_box(struct amdgpu_device * adev)1805 static void *dm_dmub_get_vbios_bounding_box(struct amdgpu_device *adev)
1806 {
1807 	void *bb;
1808 	long long addr;
1809 	unsigned int bb_size;
1810 	int i = 0;
1811 	uint16_t chunk;
1812 	enum dmub_gpint_command send_addrs[] = {
1813 		DMUB_GPINT__SET_BB_ADDR_WORD0,
1814 		DMUB_GPINT__SET_BB_ADDR_WORD1,
1815 		DMUB_GPINT__SET_BB_ADDR_WORD2,
1816 		DMUB_GPINT__SET_BB_ADDR_WORD3,
1817 	};
1818 	enum dmub_status ret;
1819 
1820 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1821 	case IP_VERSION(4, 0, 1):
1822 		bb_size = sizeof(struct dml2_soc_bb);
1823 		break;
1824 	case IP_VERSION(4, 2, 0):
1825 		bb_size = sizeof(struct dml2_soc_bb);
1826 		break;
1827 	default:
1828 		return NULL;
1829 	}
1830 
1831 	bb =  dm_allocate_gpu_mem(adev,
1832 				  DC_MEM_ALLOC_TYPE_GART,
1833 				  bb_size,
1834 				  &addr);
1835 	if (!bb)
1836 		return NULL;
1837 
1838 	for (i = 0; i < 4; i++) {
1839 		/* Extract 16-bit chunk */
1840 		chunk = ((uint64_t) addr >> (i * 16)) & 0xFFFF;
1841 		/* Send the chunk */
1842 		ret = dm_dmub_send_vbios_gpint_command(adev, send_addrs[i], chunk, 30000);
1843 		if (ret != DMUB_STATUS_OK)
1844 			goto free_bb;
1845 	}
1846 
1847 	/* Now ask DMUB to copy the bb */
1848 	ret = dm_dmub_send_vbios_gpint_command(adev, DMUB_GPINT__BB_COPY, 1, 200000);
1849 	if (ret != DMUB_STATUS_OK)
1850 		goto free_bb;
1851 
1852 	return bb;
1853 
1854 free_bb:
1855 	dm_free_gpu_mem(adev, DC_MEM_ALLOC_TYPE_GART, (void *) bb);
1856 	return NULL;
1857 
1858 }
1859 
dm_get_default_ips_mode(struct amdgpu_device * adev)1860 static enum dmub_ips_disable_type dm_get_default_ips_mode(
1861 	struct amdgpu_device *adev)
1862 {
1863 	enum dmub_ips_disable_type ret = DMUB_IPS_ENABLE;
1864 
1865 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1866 	case IP_VERSION(3, 5, 0):
1867 	case IP_VERSION(3, 6, 0):
1868 	case IP_VERSION(3, 5, 1):
1869 		ret =  DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
1870 		break;
1871 	case IP_VERSION(4, 2, 0):
1872 		ret =  DMUB_IPS_DISABLE_ALL;
1873 		break;
1874 	default:
1875 		/* ASICs older than DCN35 do not have IPSs */
1876 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 5, 0))
1877 			ret = DMUB_IPS_DISABLE_ALL;
1878 		break;
1879 	}
1880 
1881 	return ret;
1882 }
1883 
amdgpu_dm_init(struct amdgpu_device * adev)1884 static int amdgpu_dm_init(struct amdgpu_device *adev)
1885 {
1886 	struct dc_init_data init_data;
1887 	struct dc_callback_init init_params;
1888 	int r;
1889 
1890 	adev->dm.ddev = adev_to_drm(adev);
1891 	adev->dm.adev = adev;
1892 
1893 	/* Zero all the fields */
1894 	memset(&init_data, 0, sizeof(init_data));
1895 	memset(&init_params, 0, sizeof(init_params));
1896 
1897 	mutex_init(&adev->dm.dpia_aux_lock);
1898 	mutex_init(&adev->dm.dc_lock);
1899 	mutex_init(&adev->dm.audio_lock);
1900 
1901 	if (amdgpu_dm_irq_init(adev)) {
1902 		drm_err(adev_to_drm(adev), "failed to initialize DM IRQ support.\n");
1903 		goto error;
1904 	}
1905 
1906 	init_data.asic_id.chip_family = adev->family;
1907 
1908 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
1909 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
1910 	init_data.asic_id.chip_id = adev->pdev->device;
1911 
1912 	init_data.asic_id.vram_width = adev->gmc.vram_width;
1913 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
1914 	init_data.asic_id.atombios_base_address =
1915 		adev->mode_info.atom_context->bios;
1916 
1917 	init_data.driver = adev;
1918 
1919 	/* cgs_device was created in dm_sw_init() */
1920 	init_data.cgs_device = adev->dm.cgs_device;
1921 
1922 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
1923 
1924 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1925 	case IP_VERSION(2, 1, 0):
1926 		switch (adev->dm.dmcub_fw_version) {
1927 		case 0: /* development */
1928 		case 0x1: /* linux-firmware.git hash 6d9f399 */
1929 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
1930 			init_data.flags.disable_dmcu = false;
1931 			break;
1932 		default:
1933 			init_data.flags.disable_dmcu = true;
1934 		}
1935 		break;
1936 	case IP_VERSION(2, 0, 3):
1937 		init_data.flags.disable_dmcu = true;
1938 		break;
1939 	default:
1940 		break;
1941 	}
1942 
1943 	/* APU support S/G display by default except:
1944 	 * ASICs before Carrizo,
1945 	 * RAVEN1 (Users reported stability issue)
1946 	 */
1947 
1948 	if (adev->asic_type < CHIP_CARRIZO) {
1949 		init_data.flags.gpu_vm_support = false;
1950 	} else if (adev->asic_type == CHIP_RAVEN) {
1951 		if (adev->apu_flags & AMD_APU_IS_RAVEN)
1952 			init_data.flags.gpu_vm_support = false;
1953 		else
1954 			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
1955 	} else {
1956 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(2, 0, 3))
1957 			init_data.flags.gpu_vm_support = (amdgpu_sg_display == 1);
1958 		else
1959 			init_data.flags.gpu_vm_support =
1960 				(amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
1961 	}
1962 
1963 	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
1964 
1965 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
1966 		init_data.flags.fbc_support = true;
1967 
1968 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
1969 		init_data.flags.multi_mon_pp_mclk_switch = true;
1970 
1971 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
1972 		init_data.flags.disable_fractional_pwm = true;
1973 
1974 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
1975 		init_data.flags.edp_no_power_sequencing = true;
1976 
1977 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
1978 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
1979 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
1980 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
1981 
1982 	init_data.flags.seamless_boot_edp_requested = false;
1983 
1984 	if (amdgpu_device_seamless_boot_supported(adev)) {
1985 		init_data.flags.seamless_boot_edp_requested = true;
1986 		init_data.flags.allow_seamless_boot_optimization = true;
1987 		drm_dbg(adev->dm.ddev, "Seamless boot requested\n");
1988 	}
1989 
1990 	init_data.flags.enable_mipi_converter_optimization = true;
1991 
1992 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
1993 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
1994 	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
1995 
1996 	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
1997 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
1998 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS_DYNAMIC)
1999 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_DYNAMIC;
2000 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS2_DYNAMIC)
2001 		init_data.flags.disable_ips = DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
2002 	else if (amdgpu_dc_debug_mask & DC_FORCE_IPS_ENABLE)
2003 		init_data.flags.disable_ips = DMUB_IPS_ENABLE;
2004 	else
2005 		init_data.flags.disable_ips = dm_get_default_ips_mode(adev);
2006 
2007 	init_data.flags.disable_ips_in_vpb = 0;
2008 
2009 	/* DCN35 and above supports dynamic DTBCLK switch */
2010 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 5, 0))
2011 		init_data.flags.allow_0_dtb_clk = true;
2012 
2013 	/* Enable DWB for tested platforms only */
2014 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
2015 		init_data.num_virtual_links = 1;
2016 
2017 	/* DCN42 and above dpia switch to unified link training path */
2018 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 2, 0)) {
2019 		init_data.flags.consolidated_dpia_dp_lt = true;
2020 		init_data.flags.enable_dpia_pre_training = true;
2021 		init_data.flags.unify_link_enc_assignment = true;
2022 		init_data.flags.usb4_bw_alloc_support = true;
2023 	}
2024 	retrieve_dmi_info(&adev->dm);
2025 	if (adev->dm.edp0_on_dp1_quirk)
2026 		init_data.flags.support_edp0_on_dp1 = true;
2027 
2028 	if (adev->dm.bb_from_dmub)
2029 		init_data.bb_from_dmub = adev->dm.bb_from_dmub;
2030 	else
2031 		init_data.bb_from_dmub = NULL;
2032 
2033 	/* Display Core create. */
2034 	adev->dm.dc = dc_create(&init_data);
2035 
2036 	if (adev->dm.dc) {
2037 		drm_info(adev_to_drm(adev), "Display Core v%s initialized on %s\n", DC_VER,
2038 			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
2039 	} else {
2040 		drm_info(adev_to_drm(adev), "Display Core failed to initialize with v%s!\n", DC_VER);
2041 		goto error;
2042 	}
2043 
2044 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
2045 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
2046 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
2047 	}
2048 
2049 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2050 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2051 	if (dm_should_disable_stutter(adev->pdev))
2052 		adev->dm.dc->debug.disable_stutter = true;
2053 
2054 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
2055 		adev->dm.dc->debug.disable_stutter = true;
2056 
2057 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
2058 		adev->dm.dc->debug.disable_dsc = true;
2059 
2060 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
2061 		adev->dm.dc->debug.disable_clock_gate = true;
2062 
2063 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
2064 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
2065 
2066 	if (amdgpu_dc_debug_mask & DC_DISABLE_SUBVP_FAMS) {
2067 		adev->dm.dc->debug.force_disable_subvp = true;
2068 		adev->dm.dc->debug.fams2_config.bits.enable = false;
2069 	}
2070 
2071 	if (amdgpu_dc_debug_mask & DC_ENABLE_DML2) {
2072 		adev->dm.dc->debug.using_dml2 = true;
2073 		adev->dm.dc->debug.using_dml21 = true;
2074 	}
2075 
2076 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_FORCE_FW_ENABLE)
2077 		adev->dm.dc->debug.hdcp_lc_force_fw_enable = true;
2078 
2079 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_ENABLE_SW_FALLBACK)
2080 		adev->dm.dc->debug.hdcp_lc_enable_sw_fallback = true;
2081 
2082 	if (amdgpu_dc_debug_mask & DC_SKIP_DETECTION_LT)
2083 		adev->dm.dc->debug.skip_detection_link_training = true;
2084 
2085 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
2086 
2087 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
2088 	adev->dm.dc->debug.ignore_cable_id = true;
2089 
2090 	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
2091 		drm_info(adev_to_drm(adev), "DP-HDMI FRL PCON supported\n");
2092 
2093 	r = dm_dmub_hw_init(adev);
2094 	if (r) {
2095 		drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
2096 		goto error;
2097 	}
2098 
2099 	dc_hardware_init(adev->dm.dc);
2100 
2101 	adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev);
2102 	if (!adev->dm.hpd_rx_offload_wq) {
2103 		drm_err(adev_to_drm(adev), "failed to create hpd rx offload workqueue.\n");
2104 		goto error;
2105 	}
2106 
2107 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
2108 		struct dc_phy_addr_space_config pa_config;
2109 
2110 		mmhub_read_system_context(adev, &pa_config);
2111 
2112 		// Call the DC init_memory func
2113 		dc_setup_system_context(adev->dm.dc, &pa_config);
2114 	}
2115 
2116 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
2117 	if (!adev->dm.freesync_module) {
2118 		drm_err(adev_to_drm(adev),
2119 		"failed to initialize freesync_module.\n");
2120 	} else
2121 		drm_dbg_driver(adev_to_drm(adev), "freesync_module init done %p.\n",
2122 				adev->dm.freesync_module);
2123 
2124 	amdgpu_dm_init_color_mod();
2125 
2126 	if (adev->dm.dc->caps.max_links > 0) {
2127 		adev->dm.vblank_control_workqueue =
2128 			create_singlethread_workqueue("dm_vblank_control_workqueue");
2129 		if (!adev->dm.vblank_control_workqueue)
2130 			drm_err(adev_to_drm(adev), "failed to initialize vblank_workqueue.\n");
2131 	}
2132 
2133 	if (adev->dm.dc->caps.ips_support &&
2134 	    adev->dm.dc->config.disable_ips != DMUB_IPS_DISABLE_ALL)
2135 		adev->dm.idle_workqueue = idle_create_workqueue(adev);
2136 
2137 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
2138 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
2139 
2140 		if (!adev->dm.hdcp_workqueue)
2141 			drm_err(adev_to_drm(adev), "failed to initialize hdcp_workqueue.\n");
2142 		else
2143 			drm_dbg_driver(adev_to_drm(adev),
2144 				       "hdcp_workqueue init done %p.\n",
2145 				       adev->dm.hdcp_workqueue);
2146 
2147 		dc_init_callbacks(adev->dm.dc, &init_params);
2148 	}
2149 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2150 		init_completion(&adev->dm.dmub_aux_transfer_done);
2151 		adev->dm.dmub_notify = kzalloc_obj(struct dmub_notification);
2152 		if (!adev->dm.dmub_notify) {
2153 			drm_info(adev_to_drm(adev), "fail to allocate adev->dm.dmub_notify");
2154 			goto error;
2155 		}
2156 
2157 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
2158 		if (!adev->dm.delayed_hpd_wq) {
2159 			drm_err(adev_to_drm(adev), "failed to create hpd offload workqueue.\n");
2160 			goto error;
2161 		}
2162 
2163 		amdgpu_dm_outbox_init(adev);
2164 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
2165 			dmub_aux_setconfig_callback, false)) {
2166 			drm_err(adev_to_drm(adev), "fail to register dmub aux callback");
2167 			goto error;
2168 		}
2169 
2170 		for (size_t i = 0; i < ARRAY_SIZE(adev->dm.fused_io); i++)
2171 			init_completion(&adev->dm.fused_io[i].replied);
2172 
2173 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_FUSED_IO,
2174 			dmub_aux_fused_io_callback, false)) {
2175 			drm_err(adev_to_drm(adev), "fail to register dmub fused io callback");
2176 			goto error;
2177 		}
2178 		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
2179 		 * It is expected that DMUB will resend any pending notifications at this point. Note
2180 		 * that hpd and hpd_irq handler registration are deferred to register_hpd_handlers() to
2181 		 * align legacy interface initialization sequence. Connection status will be proactivly
2182 		 * detected once in the amdgpu_dm_initialize_drm_device.
2183 		 */
2184 		dc_enable_dmub_outbox(adev->dm.dc);
2185 
2186 		/* DPIA trace goes to dmesg logs only if outbox is enabled */
2187 		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
2188 			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
2189 	}
2190 
2191 	if (amdgpu_dm_initialize_drm_device(adev)) {
2192 		drm_err(adev_to_drm(adev),
2193 		"failed to initialize sw for display support.\n");
2194 		goto error;
2195 	}
2196 
2197 	/* create fake encoders for MST */
2198 	dm_dp_create_fake_mst_encoders(adev);
2199 
2200 	/* TODO: Add_display_info? */
2201 
2202 	/* TODO use dynamic cursor width */
2203 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
2204 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
2205 
2206 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
2207 		drm_err(adev_to_drm(adev),
2208 		"failed to initialize vblank for display support.\n");
2209 		goto error;
2210 	}
2211 
2212 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2213 	amdgpu_dm_crtc_secure_display_create_contexts(adev);
2214 	if (!adev->dm.secure_display_ctx.crtc_ctx)
2215 		drm_err(adev_to_drm(adev), "failed to initialize secure display contexts.\n");
2216 
2217 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))
2218 		adev->dm.secure_display_ctx.support_mul_roi = true;
2219 
2220 #endif
2221 
2222 	drm_dbg_driver(adev_to_drm(adev), "KMS initialized.\n");
2223 
2224 	return 0;
2225 error:
2226 	amdgpu_dm_fini(adev);
2227 
2228 	return -EINVAL;
2229 }
2230 
amdgpu_dm_early_fini(struct amdgpu_ip_block * ip_block)2231 static int amdgpu_dm_early_fini(struct amdgpu_ip_block *ip_block)
2232 {
2233 	struct amdgpu_device *adev = ip_block->adev;
2234 
2235 	amdgpu_dm_audio_fini(adev);
2236 
2237 	return 0;
2238 }
2239 
amdgpu_dm_fini(struct amdgpu_device * adev)2240 static void amdgpu_dm_fini(struct amdgpu_device *adev)
2241 {
2242 	int i;
2243 
2244 	if (adev->dm.vblank_control_workqueue) {
2245 		destroy_workqueue(adev->dm.vblank_control_workqueue);
2246 		adev->dm.vblank_control_workqueue = NULL;
2247 	}
2248 
2249 	if (adev->dm.idle_workqueue) {
2250 		if (adev->dm.idle_workqueue->running) {
2251 			adev->dm.idle_workqueue->enable = false;
2252 			flush_work(&adev->dm.idle_workqueue->work);
2253 		}
2254 
2255 		kfree(adev->dm.idle_workqueue);
2256 		adev->dm.idle_workqueue = NULL;
2257 	}
2258 
2259 	/* Disable ISM before dc_destroy() invalidates dm->dc */
2260 	scoped_guard(mutex, &adev->dm.dc_lock)
2261 		amdgpu_dm_ism_disable(&adev->dm);
2262 
2263 	amdgpu_dm_destroy_drm_device(&adev->dm);
2264 
2265 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2266 	if (adev->dm.secure_display_ctx.crtc_ctx) {
2267 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
2268 			if (adev->dm.secure_display_ctx.crtc_ctx[i].crtc) {
2269 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].notify_ta_work);
2270 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].forward_roi_work);
2271 			}
2272 		}
2273 		kfree(adev->dm.secure_display_ctx.crtc_ctx);
2274 		adev->dm.secure_display_ctx.crtc_ctx = NULL;
2275 	}
2276 #endif
2277 	if (adev->dm.hdcp_workqueue) {
2278 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
2279 		adev->dm.hdcp_workqueue = NULL;
2280 	}
2281 
2282 	if (adev->dm.dc) {
2283 		dc_deinit_callbacks(adev->dm.dc);
2284 		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
2285 		if (dc_enable_dmub_notifications(adev->dm.dc)) {
2286 			kfree(adev->dm.dmub_notify);
2287 			adev->dm.dmub_notify = NULL;
2288 			destroy_workqueue(adev->dm.delayed_hpd_wq);
2289 			adev->dm.delayed_hpd_wq = NULL;
2290 		}
2291 	}
2292 
2293 	if (adev->dm.dmub_bo)
2294 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
2295 				      &adev->dm.dmub_bo_gpu_addr,
2296 				      &adev->dm.dmub_bo_cpu_addr);
2297 
2298 	if (adev->dm.boot_time_crc_info.bo_ptr)
2299 		amdgpu_bo_free_kernel(&adev->dm.boot_time_crc_info.bo_ptr,
2300 					&adev->dm.boot_time_crc_info.gpu_addr,
2301 					&adev->dm.boot_time_crc_info.cpu_addr);
2302 
2303 	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
2304 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
2305 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
2306 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
2307 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
2308 			}
2309 		}
2310 
2311 		kfree(adev->dm.hpd_rx_offload_wq);
2312 		adev->dm.hpd_rx_offload_wq = NULL;
2313 	}
2314 
2315 	/* DC Destroy TODO: Replace destroy DAL */
2316 	if (adev->dm.dc)
2317 		dc_destroy(&adev->dm.dc);
2318 	/*
2319 	 * TODO: pageflip, vlank interrupt
2320 	 *
2321 	 * amdgpu_dm_irq_fini(adev);
2322 	 */
2323 
2324 	if (adev->dm.cgs_device) {
2325 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
2326 		adev->dm.cgs_device = NULL;
2327 	}
2328 	if (adev->dm.freesync_module) {
2329 		mod_freesync_destroy(adev->dm.freesync_module);
2330 		adev->dm.freesync_module = NULL;
2331 	}
2332 
2333 	mutex_destroy(&adev->dm.audio_lock);
2334 	mutex_destroy(&adev->dm.dc_lock);
2335 	mutex_destroy(&adev->dm.dpia_aux_lock);
2336 }
2337 
load_dmcu_fw(struct amdgpu_device * adev)2338 static int load_dmcu_fw(struct amdgpu_device *adev)
2339 {
2340 	const char *fw_name_dmcu = NULL;
2341 	int r;
2342 	const struct dmcu_firmware_header_v1_0 *hdr;
2343 
2344 	switch (adev->asic_type) {
2345 #if defined(CONFIG_DRM_AMD_DC_SI)
2346 	case CHIP_TAHITI:
2347 	case CHIP_PITCAIRN:
2348 	case CHIP_VERDE:
2349 	case CHIP_OLAND:
2350 #endif
2351 	case CHIP_BONAIRE:
2352 	case CHIP_HAWAII:
2353 	case CHIP_KAVERI:
2354 	case CHIP_KABINI:
2355 	case CHIP_MULLINS:
2356 	case CHIP_TONGA:
2357 	case CHIP_FIJI:
2358 	case CHIP_CARRIZO:
2359 	case CHIP_STONEY:
2360 	case CHIP_POLARIS11:
2361 	case CHIP_POLARIS10:
2362 	case CHIP_POLARIS12:
2363 	case CHIP_VEGAM:
2364 	case CHIP_VEGA10:
2365 	case CHIP_VEGA12:
2366 	case CHIP_VEGA20:
2367 		return 0;
2368 	case CHIP_NAVI12:
2369 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
2370 		break;
2371 	case CHIP_RAVEN:
2372 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
2373 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2374 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
2375 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2376 		else
2377 			return 0;
2378 		break;
2379 	default:
2380 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2381 		case IP_VERSION(2, 0, 2):
2382 		case IP_VERSION(2, 0, 3):
2383 		case IP_VERSION(2, 0, 0):
2384 		case IP_VERSION(2, 1, 0):
2385 		case IP_VERSION(3, 0, 0):
2386 		case IP_VERSION(3, 0, 2):
2387 		case IP_VERSION(3, 0, 3):
2388 		case IP_VERSION(3, 0, 1):
2389 		case IP_VERSION(3, 1, 2):
2390 		case IP_VERSION(3, 1, 3):
2391 		case IP_VERSION(3, 1, 4):
2392 		case IP_VERSION(3, 1, 5):
2393 		case IP_VERSION(3, 1, 6):
2394 		case IP_VERSION(3, 2, 0):
2395 		case IP_VERSION(3, 2, 1):
2396 		case IP_VERSION(3, 5, 0):
2397 		case IP_VERSION(3, 5, 1):
2398 		case IP_VERSION(3, 6, 0):
2399 		case IP_VERSION(4, 0, 1):
2400 		case IP_VERSION(4, 2, 0):
2401 			return 0;
2402 		default:
2403 			break;
2404 		}
2405 		drm_err(adev_to_drm(adev), "Unsupported ASIC type: 0x%X\n", adev->asic_type);
2406 		return -EINVAL;
2407 	}
2408 
2409 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
2410 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not supported on direct or SMU loading\n");
2411 		return 0;
2412 	}
2413 
2414 	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, AMDGPU_UCODE_REQUIRED,
2415 				 "%s", fw_name_dmcu);
2416 	if (r == -ENODEV) {
2417 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
2418 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not found\n");
2419 		adev->dm.fw_dmcu = NULL;
2420 		return 0;
2421 	}
2422 	if (r) {
2423 		drm_err(adev_to_drm(adev), "amdgpu_dm: Can't validate firmware \"%s\"\n",
2424 			fw_name_dmcu);
2425 		amdgpu_ucode_release(&adev->dm.fw_dmcu);
2426 		return r;
2427 	}
2428 
2429 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
2430 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
2431 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
2432 	adev->firmware.fw_size +=
2433 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2434 
2435 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
2436 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
2437 	adev->firmware.fw_size +=
2438 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2439 
2440 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
2441 
2442 	drm_dbg_kms(adev_to_drm(adev), "PSP loading DMCU firmware\n");
2443 
2444 	return 0;
2445 }
2446 
amdgpu_dm_dmub_reg_read(void * ctx,uint32_t address)2447 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
2448 {
2449 	struct amdgpu_device *adev = ctx;
2450 
2451 	return dm_read_reg(adev->dm.dc->ctx, address);
2452 }
2453 
amdgpu_dm_dmub_reg_write(void * ctx,uint32_t address,uint32_t value)2454 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
2455 				     uint32_t value)
2456 {
2457 	struct amdgpu_device *adev = ctx;
2458 
2459 	return dm_write_reg(adev->dm.dc->ctx, address, value);
2460 }
2461 
dm_dmub_sw_init(struct amdgpu_device * adev)2462 static int dm_dmub_sw_init(struct amdgpu_device *adev)
2463 {
2464 	struct dmub_srv_create_params create_params;
2465 	struct dmub_srv_fw_meta_info_params fw_meta_info_params;
2466 	struct dmub_srv_region_params region_params;
2467 	struct dmub_srv_region_info region_info;
2468 	struct dmub_srv_memory_params memory_params;
2469 	struct dmub_fw_meta_info fw_info;
2470 	struct dmub_srv_fb_info *fb_info;
2471 	struct dmub_srv *dmub_srv;
2472 	const struct dmcub_firmware_header_v1_0 *hdr;
2473 	enum dmub_asic dmub_asic;
2474 	enum dmub_status status;
2475 	static enum dmub_window_memory_type window_memory_type[DMUB_WINDOW_TOTAL] = {
2476 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_0_INST_CONST
2477 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_1_STACK
2478 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_2_BSS_DATA
2479 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_3_VBIOS
2480 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_4_MAILBOX
2481 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_5_TRACEBUFF
2482 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_6_FW_STATE
2483 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_7_SCRATCH_MEM
2484 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_IB_MEM
2485 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_SHARED_STATE
2486 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_LSDMA_BUFFER
2487 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_CURSOR_OFFLOAD
2488 	};
2489 	int r;
2490 
2491 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2492 	case IP_VERSION(2, 1, 0):
2493 		dmub_asic = DMUB_ASIC_DCN21;
2494 		break;
2495 	case IP_VERSION(3, 0, 0):
2496 		dmub_asic = DMUB_ASIC_DCN30;
2497 		break;
2498 	case IP_VERSION(3, 0, 1):
2499 		dmub_asic = DMUB_ASIC_DCN301;
2500 		break;
2501 	case IP_VERSION(3, 0, 2):
2502 		dmub_asic = DMUB_ASIC_DCN302;
2503 		break;
2504 	case IP_VERSION(3, 0, 3):
2505 		dmub_asic = DMUB_ASIC_DCN303;
2506 		break;
2507 	case IP_VERSION(3, 1, 2):
2508 	case IP_VERSION(3, 1, 3):
2509 		dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
2510 		break;
2511 	case IP_VERSION(3, 1, 4):
2512 		dmub_asic = DMUB_ASIC_DCN314;
2513 		break;
2514 	case IP_VERSION(3, 1, 5):
2515 		dmub_asic = DMUB_ASIC_DCN315;
2516 		break;
2517 	case IP_VERSION(3, 1, 6):
2518 		dmub_asic = DMUB_ASIC_DCN316;
2519 		break;
2520 	case IP_VERSION(3, 2, 0):
2521 		dmub_asic = DMUB_ASIC_DCN32;
2522 		break;
2523 	case IP_VERSION(3, 2, 1):
2524 		dmub_asic = DMUB_ASIC_DCN321;
2525 		break;
2526 	case IP_VERSION(3, 5, 0):
2527 	case IP_VERSION(3, 5, 1):
2528 		dmub_asic = DMUB_ASIC_DCN35;
2529 		break;
2530 	case IP_VERSION(3, 6, 0):
2531 		dmub_asic = DMUB_ASIC_DCN36;
2532 		break;
2533 	case IP_VERSION(4, 0, 1):
2534 		dmub_asic = DMUB_ASIC_DCN401;
2535 		break;
2536 	case IP_VERSION(4, 2, 0):
2537 		dmub_asic = DMUB_ASIC_DCN42;
2538 		break;
2539 	default:
2540 		/* ASIC doesn't support DMUB. */
2541 		return 0;
2542 	}
2543 
2544 	hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
2545 	adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
2546 
2547 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
2548 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
2549 			AMDGPU_UCODE_ID_DMCUB;
2550 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
2551 			adev->dm.dmub_fw;
2552 		adev->firmware.fw_size +=
2553 			ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
2554 
2555 		drm_info(adev_to_drm(adev), "Loading DMUB firmware via PSP: version=0x%08X\n",
2556 			 adev->dm.dmcub_fw_version);
2557 	}
2558 
2559 
2560 	adev->dm.dmub_srv = kzalloc_obj(*adev->dm.dmub_srv);
2561 	dmub_srv = adev->dm.dmub_srv;
2562 
2563 	if (!dmub_srv) {
2564 		drm_err(adev_to_drm(adev), "Failed to allocate DMUB service!\n");
2565 		return -ENOMEM;
2566 	}
2567 
2568 	memset(&create_params, 0, sizeof(create_params));
2569 	create_params.user_ctx = adev;
2570 	create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2571 	create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2572 	create_params.asic = dmub_asic;
2573 
2574 	/* Create the DMUB service. */
2575 	status = dmub_srv_create(dmub_srv, &create_params);
2576 	if (status != DMUB_STATUS_OK) {
2577 		drm_err(adev_to_drm(adev), "Error creating DMUB service: %d\n", status);
2578 		return -EINVAL;
2579 	}
2580 
2581 	/* Extract the FW meta info. */
2582 	memset(&fw_meta_info_params, 0, sizeof(fw_meta_info_params));
2583 
2584 	fw_meta_info_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2585 					      PSP_HEADER_BYTES_256;
2586 	fw_meta_info_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2587 	fw_meta_info_params.fw_inst_const = adev->dm.dmub_fw->data +
2588 					    le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2589 					    PSP_HEADER_BYTES_256;
2590 	fw_meta_info_params.fw_bss_data = fw_meta_info_params.bss_data_size ? adev->dm.dmub_fw->data +
2591 					  le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2592 					  le32_to_cpu(hdr->inst_const_bytes) : NULL;
2593 	fw_meta_info_params.custom_psp_footer_size = 0;
2594 
2595 	status = dmub_srv_get_fw_meta_info_from_raw_fw(&fw_meta_info_params, &fw_info);
2596 	if (status != DMUB_STATUS_OK) {
2597 		/* Skip returning early, just log the error. */
2598 		drm_err(adev_to_drm(adev), "Error getting DMUB FW meta info: %d\n", status);
2599 		// return -EINVAL;
2600 	}
2601 
2602 	/* Calculate the size of all the regions for the DMUB service. */
2603 	memset(&region_params, 0, sizeof(region_params));
2604 
2605 	region_params.inst_const_size = fw_meta_info_params.inst_const_size;
2606 	region_params.bss_data_size = fw_meta_info_params.bss_data_size;
2607 	region_params.vbios_size = adev->bios_size;
2608 	region_params.fw_bss_data = fw_meta_info_params.fw_bss_data;
2609 	region_params.fw_inst_const = fw_meta_info_params.fw_inst_const;
2610 	region_params.window_memory_type = window_memory_type;
2611 	region_params.fw_info = (status == DMUB_STATUS_OK) ? &fw_info : NULL;
2612 
2613 	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2614 					   &region_info);
2615 
2616 	if (status != DMUB_STATUS_OK) {
2617 		drm_err(adev_to_drm(adev), "Error calculating DMUB region info: %d\n", status);
2618 		return -EINVAL;
2619 	}
2620 
2621 	/*
2622 	 * Allocate a framebuffer based on the total size of all the regions.
2623 	 * TODO: Move this into GART.
2624 	 */
2625 	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2626 				    AMDGPU_GEM_DOMAIN_VRAM |
2627 				    AMDGPU_GEM_DOMAIN_GTT,
2628 				    &adev->dm.dmub_bo,
2629 				    &adev->dm.dmub_bo_gpu_addr,
2630 				    &adev->dm.dmub_bo_cpu_addr);
2631 	if (r)
2632 		return r;
2633 
2634 	/* Rebase the regions on the framebuffer address. */
2635 	memset(&memory_params, 0, sizeof(memory_params));
2636 	memory_params.cpu_fb_addr = adev->dm.dmub_bo_cpu_addr;
2637 	memory_params.gpu_fb_addr = adev->dm.dmub_bo_gpu_addr;
2638 	memory_params.region_info = &region_info;
2639 	memory_params.window_memory_type = window_memory_type;
2640 
2641 	adev->dm.dmub_fb_info = kzalloc_obj(*adev->dm.dmub_fb_info);
2642 	fb_info = adev->dm.dmub_fb_info;
2643 
2644 	if (!fb_info) {
2645 		drm_err(adev_to_drm(adev),
2646 			"Failed to allocate framebuffer info for DMUB service!\n");
2647 		return -ENOMEM;
2648 	}
2649 
2650 	status = dmub_srv_calc_mem_info(dmub_srv, &memory_params, fb_info);
2651 	if (status != DMUB_STATUS_OK) {
2652 		drm_err(adev_to_drm(adev), "Error calculating DMUB FB info: %d\n", status);
2653 		return -EINVAL;
2654 	}
2655 
2656 	adev->dm.bb_from_dmub = dm_dmub_get_vbios_bounding_box(adev);
2657 	adev->dm.fw_inst_size = fw_meta_info_params.inst_const_size;
2658 
2659 	return 0;
2660 }
2661 
dm_sw_init(struct amdgpu_ip_block * ip_block)2662 static int dm_sw_init(struct amdgpu_ip_block *ip_block)
2663 {
2664 	struct amdgpu_device *adev = ip_block->adev;
2665 	int r;
2666 
2667 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
2668 
2669 	if (!adev->dm.cgs_device) {
2670 		drm_err(adev_to_drm(adev), "failed to create cgs device.\n");
2671 		return -EINVAL;
2672 	}
2673 
2674 	/* Moved from dm init since we need to use allocations for storing bounding box data */
2675 	INIT_LIST_HEAD(&adev->dm.da_list);
2676 
2677 	r = dm_dmub_sw_init(adev);
2678 	if (r)
2679 		return r;
2680 
2681 	return load_dmcu_fw(adev);
2682 }
2683 
dm_sw_fini(struct amdgpu_ip_block * ip_block)2684 static int dm_sw_fini(struct amdgpu_ip_block *ip_block)
2685 {
2686 	struct amdgpu_device *adev = ip_block->adev;
2687 	struct dal_allocation *da;
2688 
2689 	list_for_each_entry(da, &adev->dm.da_list, list) {
2690 		if (adev->dm.bb_from_dmub == (void *) da->cpu_ptr) {
2691 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
2692 			list_del(&da->list);
2693 			kfree(da);
2694 			adev->dm.bb_from_dmub = NULL;
2695 			break;
2696 		}
2697 	}
2698 
2699 
2700 	kfree(adev->dm.dmub_fb_info);
2701 	adev->dm.dmub_fb_info = NULL;
2702 
2703 	if (adev->dm.dmub_srv) {
2704 		dmub_srv_destroy(adev->dm.dmub_srv);
2705 		kfree(adev->dm.dmub_srv);
2706 		adev->dm.dmub_srv = NULL;
2707 	}
2708 
2709 	amdgpu_ucode_release(&adev->dm.dmub_fw);
2710 	amdgpu_ucode_release(&adev->dm.fw_dmcu);
2711 
2712 	return 0;
2713 }
2714 
detect_mst_link_for_all_connectors(struct drm_device * dev)2715 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2716 {
2717 	struct amdgpu_dm_connector *aconnector;
2718 	struct drm_connector *connector;
2719 	struct drm_connector_list_iter iter;
2720 	int ret = 0;
2721 
2722 	drm_connector_list_iter_begin(dev, &iter);
2723 	drm_for_each_connector_iter(connector, &iter) {
2724 
2725 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2726 			continue;
2727 
2728 		aconnector = to_amdgpu_dm_connector(connector);
2729 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
2730 		    aconnector->mst_mgr.aux) {
2731 			drm_dbg_kms(dev, "DM_MST: starting TM on aconnector: %p [id: %d]\n",
2732 					 aconnector,
2733 					 aconnector->base.base.id);
2734 
2735 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2736 			if (ret < 0) {
2737 				drm_err(dev, "DM_MST: Failed to start MST\n");
2738 				aconnector->dc_link->type =
2739 					dc_connection_single;
2740 				ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2741 								     aconnector->dc_link);
2742 				break;
2743 			}
2744 		}
2745 	}
2746 	drm_connector_list_iter_end(&iter);
2747 
2748 	return ret;
2749 }
2750 
amdgpu_dm_boot_time_crc_init(struct amdgpu_device * adev)2751 static void amdgpu_dm_boot_time_crc_init(struct amdgpu_device *adev)
2752 {
2753 	struct dm_boot_time_crc_info *bootcrc_info = NULL;
2754 	struct dmub_srv *dmub = NULL;
2755 	union dmub_fw_boot_options option = {0};
2756 	int ret = 0;
2757 	const uint32_t fb_size = 3 * 1024 * 1024;	/* 3MB for DCC pattern */
2758 
2759 	if (!adev || !adev->dm.dc || !adev->dm.dc->ctx ||
2760 		!adev->dm.dc->ctx->dmub_srv) {
2761 		return;
2762 	}
2763 
2764 	dmub = adev->dm.dc->ctx->dmub_srv->dmub;
2765 	bootcrc_info = &adev->dm.boot_time_crc_info;
2766 
2767 	if (!dmub || !dmub->hw_funcs.get_fw_boot_option) {
2768 		drm_dbg(adev_to_drm(adev), "failed to init boot time crc buffer\n");
2769 		return;
2770 	}
2771 
2772 	option = dmub->hw_funcs.get_fw_boot_option(dmub);
2773 
2774 	/* Return if boot time CRC is not enabled */
2775 	if (option.bits.bootcrc_en_at_S0i3 == 0)
2776 		return;
2777 
2778 	/* Create a buffer for boot time CRC */
2779 	ret = amdgpu_bo_create_kernel(adev, fb_size, PAGE_SIZE,
2780 		AMDGPU_GEM_DOMAIN_VRAM | AMDGPU_GEM_DOMAIN_GTT,
2781 		&bootcrc_info->bo_ptr,
2782 		&bootcrc_info->gpu_addr,
2783 		&bootcrc_info->cpu_addr);
2784 
2785 	if (ret) {
2786 		drm_dbg(adev_to_drm(adev), "failed to create boot time crc buffer\n");
2787 	} else {
2788 		bootcrc_info->size = fb_size;
2789 
2790 		drm_dbg(adev_to_drm(adev), "boot time crc buffer created addr 0x%llx, size %u\n",
2791 			bootcrc_info->gpu_addr, bootcrc_info->size);
2792 
2793 		/* Send the buffer info to DMUB */
2794 		dc_dmub_srv_boot_time_crc_init(adev->dm.dc,
2795 			bootcrc_info->gpu_addr, bootcrc_info->size);
2796 	}
2797 }
2798 
dm_late_init(struct amdgpu_ip_block * ip_block)2799 static int dm_late_init(struct amdgpu_ip_block *ip_block)
2800 {
2801 	struct amdgpu_device *adev = ip_block->adev;
2802 
2803 	struct dmcu_iram_parameters params;
2804 	unsigned int linear_lut[16];
2805 	int i;
2806 	struct dmcu *dmcu = NULL;
2807 
2808 	dmcu = adev->dm.dc->res_pool->dmcu;
2809 
2810 	/* Init the boot time CRC (skip in resume) */
2811 	if ((adev->in_suspend == 0) &&
2812 		(amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(3, 6, 0)))
2813 		amdgpu_dm_boot_time_crc_init(adev);
2814 
2815 	for (i = 0; i < 16; i++)
2816 		linear_lut[i] = 0xFFFF * i / 15;
2817 
2818 	params.set = 0;
2819 	params.backlight_ramping_override = false;
2820 	params.backlight_ramping_start = 0xCCCC;
2821 	params.backlight_ramping_reduction = 0xCCCCCCCC;
2822 	params.backlight_lut_array_size = 16;
2823 	params.backlight_lut_array = linear_lut;
2824 
2825 	/* Min backlight level after ABM reduction,  Don't allow below 1%
2826 	 * 0xFFFF x 0.01 = 0x28F
2827 	 */
2828 	params.min_abm_backlight = 0x28F;
2829 	/* In the case where abm is implemented on dmcub,
2830 	 * dmcu object will be null.
2831 	 * ABM 2.4 and up are implemented on dmcub.
2832 	 */
2833 	if (dmcu) {
2834 		if (!dmcu_load_iram(dmcu, params))
2835 			return -EINVAL;
2836 	} else if (adev->dm.dc->ctx->dmub_srv) {
2837 		struct dc_link *edp_links[MAX_NUM_EDP];
2838 		int edp_num;
2839 
2840 		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
2841 		for (i = 0; i < edp_num; i++) {
2842 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
2843 				return -EINVAL;
2844 		}
2845 	}
2846 
2847 	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
2848 }
2849 
resume_mst_branch_status(struct drm_dp_mst_topology_mgr * mgr)2850 static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
2851 {
2852 	u8 buf[UUID_SIZE];
2853 	guid_t guid;
2854 	int ret;
2855 
2856 	mutex_lock(&mgr->lock);
2857 	if (!mgr->mst_primary)
2858 		goto out_fail;
2859 
2860 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
2861 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2862 		goto out_fail;
2863 	}
2864 
2865 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
2866 				 DP_MST_EN |
2867 				 DP_UP_REQ_EN |
2868 				 DP_UPSTREAM_IS_SRC);
2869 	if (ret < 0) {
2870 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
2871 		goto out_fail;
2872 	}
2873 
2874 	/* Some hubs forget their guids after they resume */
2875 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, buf, sizeof(buf));
2876 	if (ret != sizeof(buf)) {
2877 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2878 		goto out_fail;
2879 	}
2880 
2881 	import_guid(&guid, buf);
2882 
2883 	if (guid_is_null(&guid)) {
2884 		guid_gen(&guid);
2885 		export_guid(buf, &guid);
2886 
2887 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, buf, sizeof(buf));
2888 
2889 		if (ret != sizeof(buf)) {
2890 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
2891 			goto out_fail;
2892 		}
2893 	}
2894 
2895 	guid_copy(&mgr->mst_primary->guid, &guid);
2896 
2897 out_fail:
2898 	mutex_unlock(&mgr->lock);
2899 }
2900 
hdmi_cec_unset_edid(struct amdgpu_dm_connector * aconnector)2901 void hdmi_cec_unset_edid(struct amdgpu_dm_connector *aconnector)
2902 {
2903 	struct cec_notifier *n = aconnector->notifier;
2904 
2905 	if (!n)
2906 		return;
2907 
2908 	cec_notifier_phys_addr_invalidate(n);
2909 }
2910 
hdmi_cec_set_edid(struct amdgpu_dm_connector * aconnector)2911 void hdmi_cec_set_edid(struct amdgpu_dm_connector *aconnector)
2912 {
2913 	struct drm_connector *connector = &aconnector->base;
2914 	struct cec_notifier *n = aconnector->notifier;
2915 
2916 	if (!n)
2917 		return;
2918 
2919 	cec_notifier_set_phys_addr(n,
2920 				   connector->display_info.source_physical_address);
2921 }
2922 
s3_handle_hdmi_cec(struct drm_device * ddev,bool suspend)2923 static void s3_handle_hdmi_cec(struct drm_device *ddev, bool suspend)
2924 {
2925 	struct amdgpu_dm_connector *aconnector;
2926 	struct drm_connector *connector;
2927 	struct drm_connector_list_iter conn_iter;
2928 
2929 	drm_connector_list_iter_begin(ddev, &conn_iter);
2930 	drm_for_each_connector_iter(connector, &conn_iter) {
2931 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2932 			continue;
2933 
2934 		aconnector = to_amdgpu_dm_connector(connector);
2935 		if (suspend)
2936 			hdmi_cec_unset_edid(aconnector);
2937 		else
2938 			hdmi_cec_set_edid(aconnector);
2939 	}
2940 	drm_connector_list_iter_end(&conn_iter);
2941 }
2942 
s3_handle_mst(struct drm_device * dev,bool suspend)2943 static void s3_handle_mst(struct drm_device *dev, bool suspend)
2944 {
2945 	struct amdgpu_dm_connector *aconnector;
2946 	struct drm_connector *connector;
2947 	struct drm_connector_list_iter iter;
2948 	struct drm_dp_mst_topology_mgr *mgr;
2949 
2950 	drm_connector_list_iter_begin(dev, &iter);
2951 	drm_for_each_connector_iter(connector, &iter) {
2952 
2953 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2954 			continue;
2955 
2956 		aconnector = to_amdgpu_dm_connector(connector);
2957 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
2958 		    aconnector->mst_root)
2959 			continue;
2960 
2961 		mgr = &aconnector->mst_mgr;
2962 
2963 		if (suspend) {
2964 			drm_dp_mst_topology_mgr_suspend(mgr);
2965 		} else {
2966 			/* if extended timeout is supported in hardware,
2967 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
2968 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
2969 			 */
2970 			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
2971 			if (!dp_is_lttpr_present(aconnector->dc_link))
2972 				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
2973 
2974 			/* TODO: move resume_mst_branch_status() into drm mst resume again
2975 			 * once topology probing work is pulled out from mst resume into mst
2976 			 * resume 2nd step. mst resume 2nd step should be called after old
2977 			 * state getting restored (i.e. drm_atomic_helper_resume()).
2978 			 */
2979 			resume_mst_branch_status(mgr);
2980 		}
2981 	}
2982 	drm_connector_list_iter_end(&iter);
2983 }
2984 
amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device * adev)2985 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
2986 {
2987 	int ret = 0;
2988 
2989 	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
2990 	 * on window driver dc implementation.
2991 	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
2992 	 * should be passed to smu during boot up and resume from s3.
2993 	 * boot up: dc calculate dcn watermark clock settings within dc_create,
2994 	 * dcn20_resource_construct
2995 	 * then call pplib functions below to pass the settings to smu:
2996 	 * smu_set_watermarks_for_clock_ranges
2997 	 * smu_set_watermarks_table
2998 	 * navi10_set_watermarks_table
2999 	 * smu_write_watermarks_table
3000 	 *
3001 	 * For Renoir, clock settings of dcn watermark are also fixed values.
3002 	 * dc has implemented different flow for window driver:
3003 	 * dc_hardware_init / dc_set_power_state
3004 	 * dcn10_init_hw
3005 	 * notify_wm_ranges
3006 	 * set_wm_ranges
3007 	 * -- Linux
3008 	 * smu_set_watermarks_for_clock_ranges
3009 	 * renoir_set_watermarks_table
3010 	 * smu_write_watermarks_table
3011 	 *
3012 	 * For Linux,
3013 	 * dc_hardware_init -> amdgpu_dm_init
3014 	 * dc_set_power_state --> dm_resume
3015 	 *
3016 	 * therefore, this function apply to navi10/12/14 but not Renoir
3017 	 * *
3018 	 */
3019 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
3020 	case IP_VERSION(2, 0, 2):
3021 	case IP_VERSION(2, 0, 0):
3022 		break;
3023 	default:
3024 		return 0;
3025 	}
3026 
3027 	ret = amdgpu_dpm_write_watermarks_table(adev);
3028 	if (ret) {
3029 		drm_err(adev_to_drm(adev), "Failed to update WMTABLE!\n");
3030 		return ret;
3031 	}
3032 
3033 	return 0;
3034 }
3035 
dm_oem_i2c_hw_init(struct amdgpu_device * adev)3036 static int dm_oem_i2c_hw_init(struct amdgpu_device *adev)
3037 {
3038 	struct amdgpu_display_manager *dm = &adev->dm;
3039 	struct amdgpu_i2c_adapter *oem_i2c;
3040 	struct ddc_service *oem_ddc_service;
3041 	int r;
3042 
3043 	oem_ddc_service = dc_get_oem_i2c_device(adev->dm.dc);
3044 	if (oem_ddc_service) {
3045 		oem_i2c = create_i2c(oem_ddc_service, true);
3046 		if (!oem_i2c) {
3047 			drm_info(adev_to_drm(adev), "Failed to create oem i2c adapter data\n");
3048 			return -ENOMEM;
3049 		}
3050 
3051 		r = devm_i2c_add_adapter(adev->dev, &oem_i2c->base);
3052 		if (r) {
3053 			drm_info(adev_to_drm(adev), "Failed to register oem i2c\n");
3054 			kfree(oem_i2c);
3055 			return r;
3056 		}
3057 		dm->oem_i2c = oem_i2c;
3058 	}
3059 
3060 	return 0;
3061 }
3062 
3063 /**
3064  * dm_hw_init() - Initialize DC device
3065  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3066  *
3067  * Initialize the &struct amdgpu_display_manager device. This involves calling
3068  * the initializers of each DM component, then populating the struct with them.
3069  *
3070  * Although the function implies hardware initialization, both hardware and
3071  * software are initialized here. Splitting them out to their relevant init
3072  * hooks is a future TODO item.
3073  *
3074  * Some notable things that are initialized here:
3075  *
3076  * - Display Core, both software and hardware
3077  * - DC modules that we need (freesync and color management)
3078  * - DRM software states
3079  * - Interrupt sources and handlers
3080  * - Vblank support
3081  * - Debug FS entries, if enabled
3082  */
dm_hw_init(struct amdgpu_ip_block * ip_block)3083 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
3084 {
3085 	struct amdgpu_device *adev = ip_block->adev;
3086 	int r;
3087 
3088 	/* Create DAL display manager */
3089 	r = amdgpu_dm_init(adev);
3090 	if (r)
3091 		return r;
3092 	amdgpu_dm_hpd_init(adev);
3093 
3094 	r = dm_oem_i2c_hw_init(adev);
3095 	if (r)
3096 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
3097 
3098 	return 0;
3099 }
3100 
3101 /**
3102  * dm_hw_fini() - Teardown DC device
3103  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3104  *
3105  * Teardown components within &struct amdgpu_display_manager that require
3106  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
3107  * were loaded. Also flush IRQ workqueues and disable them.
3108  */
dm_hw_fini(struct amdgpu_ip_block * ip_block)3109 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
3110 {
3111 	struct amdgpu_device *adev = ip_block->adev;
3112 
3113 	amdgpu_dm_hpd_fini(adev);
3114 
3115 	amdgpu_dm_irq_fini(adev);
3116 	amdgpu_dm_fini(adev);
3117 	return 0;
3118 }
3119 
3120 
dm_gpureset_toggle_interrupts(struct amdgpu_device * adev,struct dc_state * state,bool enable)3121 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
3122 				 struct dc_state *state, bool enable)
3123 {
3124 	enum dc_irq_source irq_source;
3125 	struct amdgpu_crtc *acrtc;
3126 	int rc = -EBUSY;
3127 	int i = 0;
3128 
3129 	for (i = 0; i < state->stream_count; i++) {
3130 		acrtc = get_crtc_by_otg_inst(
3131 				adev, state->stream_status[i].primary_otg_inst);
3132 
3133 		if (acrtc && state->stream_status[i].plane_count != 0) {
3134 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
3135 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3136 			if (rc)
3137 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
3138 					 enable ? "enable" : "disable");
3139 
3140 			if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
3141 				if (enable) {
3142 					if (amdgpu_dm_crtc_vrr_active(
3143 							to_dm_crtc_state(acrtc->base.state)))
3144 						rc = amdgpu_dm_crtc_set_vupdate_irq(
3145 							&acrtc->base, true);
3146 				} else
3147 					rc = amdgpu_dm_crtc_set_vupdate_irq(
3148 							&acrtc->base, false);
3149 
3150 				if (rc)
3151 					drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
3152 						enable ? "en" : "dis");
3153 			}
3154 
3155 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3156 			/* During gpu-reset we disable and then enable vblank irq, so
3157 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
3158 			 */
3159 			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
3160 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
3161 		}
3162 	}
3163 
3164 }
3165 
DEFINE_FREE(state_release,struct dc_state *,if (_T)dc_state_release (_T))3166 DEFINE_FREE(state_release, struct dc_state *, if (_T) dc_state_release(_T))
3167 
3168 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
3169 {
3170 	struct dc_state *context __free(state_release) = NULL;
3171 	int i;
3172 	struct dc_stream_state *del_streams[MAX_PIPES];
3173 	int del_streams_count = 0;
3174 	struct dc_commit_streams_params params = {};
3175 
3176 	memset(del_streams, 0, sizeof(del_streams));
3177 
3178 	context = dc_state_create_current_copy(dc);
3179 	if (context == NULL)
3180 		return DC_ERROR_UNEXPECTED;
3181 
3182 	/* First remove from context all streams */
3183 	for (i = 0; i < context->stream_count; i++) {
3184 		struct dc_stream_state *stream = context->streams[i];
3185 
3186 		del_streams[del_streams_count++] = stream;
3187 	}
3188 
3189 	/* Remove all planes for removed streams and then remove the streams */
3190 	for (i = 0; i < del_streams_count; i++) {
3191 		enum dc_status res;
3192 
3193 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
3194 			return DC_FAIL_DETACH_SURFACES;
3195 
3196 		res = dc_state_remove_stream(dc, context, del_streams[i]);
3197 		if (res != DC_OK)
3198 			return res;
3199 	}
3200 
3201 	params.streams = context->streams;
3202 	params.stream_count = context->stream_count;
3203 
3204 	return dc_commit_streams(dc, &params);
3205 }
3206 
hpd_rx_irq_work_suspend(struct amdgpu_display_manager * dm)3207 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
3208 {
3209 	int i;
3210 
3211 	if (dm->hpd_rx_offload_wq) {
3212 		for (i = 0; i < dm->dc->caps.max_links; i++)
3213 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
3214 	}
3215 }
3216 
dm_cache_state(struct amdgpu_device * adev)3217 static int dm_cache_state(struct amdgpu_device *adev)
3218 {
3219 	int r;
3220 
3221 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
3222 	if (IS_ERR(adev->dm.cached_state)) {
3223 		r = PTR_ERR(adev->dm.cached_state);
3224 		adev->dm.cached_state = NULL;
3225 	}
3226 
3227 	return adev->dm.cached_state ? 0 : r;
3228 }
3229 
dm_destroy_cached_state(struct amdgpu_device * adev)3230 static void dm_destroy_cached_state(struct amdgpu_device *adev)
3231 {
3232 	struct amdgpu_display_manager *dm = &adev->dm;
3233 	struct drm_device *ddev = adev_to_drm(adev);
3234 	struct dm_plane_state *dm_new_plane_state;
3235 	struct drm_plane_state *new_plane_state;
3236 	struct dm_crtc_state *dm_new_crtc_state;
3237 	struct drm_crtc_state *new_crtc_state;
3238 	struct drm_plane *plane;
3239 	struct drm_crtc *crtc;
3240 	int i;
3241 
3242 	if (!dm->cached_state)
3243 		return;
3244 
3245 	/* Force mode set in atomic commit */
3246 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3247 		new_crtc_state->active_changed = true;
3248 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3249 		reset_freesync_config_for_crtc(dm_new_crtc_state);
3250 	}
3251 
3252 	/*
3253 	 * atomic_check is expected to create the dc states. We need to release
3254 	 * them here, since they were duplicated as part of the suspend
3255 	 * procedure.
3256 	 */
3257 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3258 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3259 		if (dm_new_crtc_state->stream) {
3260 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
3261 			dc_stream_release(dm_new_crtc_state->stream);
3262 			dm_new_crtc_state->stream = NULL;
3263 		}
3264 		dm_new_crtc_state->base.color_mgmt_changed = true;
3265 	}
3266 
3267 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
3268 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
3269 		if (dm_new_plane_state->dc_state) {
3270 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
3271 			dc_plane_state_release(dm_new_plane_state->dc_state);
3272 			dm_new_plane_state->dc_state = NULL;
3273 		}
3274 	}
3275 
3276 	drm_atomic_helper_resume(ddev, dm->cached_state);
3277 
3278 	dm->cached_state = NULL;
3279 }
3280 
dm_suspend(struct amdgpu_ip_block * ip_block)3281 static int dm_suspend(struct amdgpu_ip_block *ip_block)
3282 {
3283 	struct amdgpu_device *adev = ip_block->adev;
3284 	struct amdgpu_display_manager *dm = &adev->dm;
3285 
3286 	if (amdgpu_in_reset(adev)) {
3287 		enum dc_status res;
3288 
3289 		mutex_lock(&dm->dc_lock);
3290 
3291 		amdgpu_dm_ism_disable(dm);
3292 		dc_allow_idle_optimizations(adev->dm.dc, false);
3293 
3294 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
3295 
3296 		if (dm->cached_dc_state)
3297 			dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
3298 
3299 		res = amdgpu_dm_commit_zero_streams(dm->dc);
3300 		if (res != DC_OK) {
3301 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
3302 			return -EINVAL;
3303 		}
3304 
3305 		amdgpu_dm_irq_suspend(adev);
3306 
3307 		hpd_rx_irq_work_suspend(dm);
3308 
3309 		return 0;
3310 	}
3311 
3312 	if (!adev->dm.cached_state) {
3313 		int r = dm_cache_state(adev);
3314 
3315 		if (r)
3316 			return r;
3317 	}
3318 
3319 	s3_handle_hdmi_cec(adev_to_drm(adev), true);
3320 
3321 	s3_handle_mst(adev_to_drm(adev), true);
3322 
3323 	amdgpu_dm_irq_suspend(adev);
3324 
3325 	scoped_guard(mutex, &dm->dc_lock)
3326 		amdgpu_dm_ism_disable(dm);
3327 
3328 	hpd_rx_irq_work_suspend(dm);
3329 
3330 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
3331 
3332 	if (dm->dc->caps.ips_support && adev->in_s0ix)
3333 		dc_allow_idle_optimizations(dm->dc, true);
3334 
3335 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
3336 
3337 	return 0;
3338 }
3339 
3340 struct drm_connector *
amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state * state,struct drm_crtc * crtc)3341 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
3342 					     struct drm_crtc *crtc)
3343 {
3344 	u32 i;
3345 	struct drm_connector_state *new_con_state;
3346 	struct drm_connector *connector;
3347 	struct drm_crtc *crtc_from_state;
3348 
3349 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3350 		crtc_from_state = new_con_state->crtc;
3351 
3352 		if (crtc_from_state == crtc)
3353 			return connector;
3354 	}
3355 
3356 	return NULL;
3357 }
3358 
emulated_link_detect(struct dc_link * link)3359 static void emulated_link_detect(struct dc_link *link)
3360 {
3361 	struct dc_sink_init_data sink_init_data = { 0 };
3362 	struct display_sink_capability sink_caps = { 0 };
3363 	enum dc_edid_status edid_status;
3364 	struct dc_context *dc_ctx = link->ctx;
3365 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
3366 	struct dc_sink *sink = NULL;
3367 	struct dc_sink *prev_sink = NULL;
3368 
3369 	link->type = dc_connection_none;
3370 	prev_sink = link->local_sink;
3371 
3372 	if (prev_sink)
3373 		dc_sink_release(prev_sink);
3374 
3375 	switch (link->connector_signal) {
3376 	case SIGNAL_TYPE_HDMI_TYPE_A: {
3377 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3378 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
3379 		break;
3380 	}
3381 
3382 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
3383 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3384 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
3385 		break;
3386 	}
3387 
3388 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
3389 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3390 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
3391 		break;
3392 	}
3393 
3394 	case SIGNAL_TYPE_LVDS: {
3395 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3396 		sink_caps.signal = SIGNAL_TYPE_LVDS;
3397 		break;
3398 	}
3399 
3400 	case SIGNAL_TYPE_EDP: {
3401 		sink_caps.transaction_type =
3402 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3403 		sink_caps.signal = SIGNAL_TYPE_EDP;
3404 		break;
3405 	}
3406 
3407 	case SIGNAL_TYPE_DISPLAY_PORT: {
3408 		sink_caps.transaction_type =
3409 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3410 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
3411 		break;
3412 	}
3413 
3414 	default:
3415 		drm_err(dev, "Invalid connector type! signal:%d\n",
3416 			link->connector_signal);
3417 		return;
3418 	}
3419 
3420 	sink_init_data.link = link;
3421 	sink_init_data.sink_signal = sink_caps.signal;
3422 
3423 	sink = dc_sink_create(&sink_init_data);
3424 	if (!sink) {
3425 		drm_err(dev, "Failed to create sink!\n");
3426 		return;
3427 	}
3428 
3429 	/* dc_sink_create returns a new reference */
3430 	link->local_sink = sink;
3431 
3432 	edid_status = dm_helpers_read_local_edid(
3433 			link->ctx,
3434 			link,
3435 			sink);
3436 
3437 	if (edid_status != EDID_OK)
3438 		drm_err(dev, "Failed to read EDID\n");
3439 
3440 }
3441 
dm_gpureset_commit_state(struct dc_state * dc_state,struct amdgpu_display_manager * dm)3442 static void dm_gpureset_commit_state(struct dc_state *dc_state,
3443 				     struct amdgpu_display_manager *dm)
3444 {
3445 	struct {
3446 		struct dc_surface_update surface_updates[MAX_SURFACES];
3447 		struct dc_plane_info plane_infos[MAX_SURFACES];
3448 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3449 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3450 		struct dc_stream_update stream_update;
3451 	} *bundle __free(kfree);
3452 	int k, m;
3453 
3454 	bundle = kzalloc_obj(*bundle);
3455 
3456 	if (!bundle) {
3457 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
3458 		return;
3459 	}
3460 
3461 	for (k = 0; k < dc_state->stream_count; k++) {
3462 		bundle->stream_update.stream = dc_state->streams[k];
3463 
3464 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
3465 			bundle->surface_updates[m].surface =
3466 				dc_state->stream_status[k].plane_states[m];
3467 			bundle->surface_updates[m].surface->force_full_update =
3468 				true;
3469 		}
3470 
3471 		update_planes_and_stream_adapter(dm->dc,
3472 					 UPDATE_TYPE_FULL,
3473 					 dc_state->stream_status[k].plane_count,
3474 					 dc_state->streams[k],
3475 					 &bundle->stream_update,
3476 					 bundle->surface_updates);
3477 	}
3478 }
3479 
apply_delay_after_dpcd_poweroff(struct amdgpu_device * adev,struct dc_sink * sink)3480 static void apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
3481 					    struct dc_sink *sink)
3482 {
3483 	struct dc_panel_patch *ppatch = NULL;
3484 
3485 	if (!sink)
3486 		return;
3487 
3488 	ppatch = &sink->edid_caps.panel_patch;
3489 	if (ppatch->wait_after_dpcd_poweroff_ms) {
3490 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
3491 		drm_dbg_driver(adev_to_drm(adev),
3492 			       "%s: adding a %ds delay as w/a for panel\n",
3493 			       __func__,
3494 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
3495 	}
3496 }
3497 
3498 /**
3499  * amdgpu_dm_dump_links_and_sinks - Debug dump of all DC links and their sinks
3500  * @adev: amdgpu device pointer
3501  *
3502  * Iterates through all DC links and dumps information about local and remote
3503  * (MST) sinks. Should be called after connector detection is complete to see
3504  * the final state of all links.
3505  */
amdgpu_dm_dump_links_and_sinks(struct amdgpu_device * adev)3506 static void amdgpu_dm_dump_links_and_sinks(struct amdgpu_device *adev)
3507 {
3508 	struct dc *dc = adev->dm.dc;
3509 	struct drm_device *dev = adev_to_drm(adev);
3510 	int li;
3511 
3512 	if (!dc)
3513 		return;
3514 
3515 	for (li = 0; li < dc->link_count; li++) {
3516 		struct dc_link *l = dc->links[li];
3517 		const char *name = NULL;
3518 		int rs;
3519 
3520 		if (!l)
3521 			continue;
3522 		if (l->local_sink && l->local_sink->edid_caps.display_name[0])
3523 			name = l->local_sink->edid_caps.display_name;
3524 		else
3525 			name = "n/a";
3526 
3527 		drm_dbg_kms(dev,
3528 			"LINK_DUMP[%d]: local_sink=%p type=%d sink_signal=%d sink_count=%u edid_name=%s mst_capable=%d mst_alloc_streams=%d\n",
3529 			li,
3530 			l->local_sink,
3531 			l->type,
3532 			l->local_sink ? l->local_sink->sink_signal : SIGNAL_TYPE_NONE,
3533 			l->sink_count,
3534 			name,
3535 			l->dpcd_caps.is_mst_capable,
3536 			l->mst_stream_alloc_table.stream_count);
3537 
3538 		/* Dump remote (MST) sinks if any */
3539 		for (rs = 0; rs < l->sink_count; rs++) {
3540 			struct dc_sink *rsink = l->remote_sinks[rs];
3541 			const char *rname = NULL;
3542 
3543 			if (!rsink)
3544 				continue;
3545 			if (rsink->edid_caps.display_name[0])
3546 				rname = rsink->edid_caps.display_name;
3547 			else
3548 				rname = "n/a";
3549 			drm_dbg_kms(dev,
3550 				"  REMOTE_SINK[%d:%d]: sink=%p signal=%d edid_name=%s\n",
3551 				li, rs,
3552 				rsink,
3553 				rsink->sink_signal,
3554 				rname);
3555 		}
3556 	}
3557 }
3558 
dm_resume(struct amdgpu_ip_block * ip_block)3559 static int dm_resume(struct amdgpu_ip_block *ip_block)
3560 {
3561 	struct amdgpu_device *adev = ip_block->adev;
3562 	struct drm_device *ddev = adev_to_drm(adev);
3563 	struct amdgpu_display_manager *dm = &adev->dm;
3564 	struct amdgpu_dm_connector *aconnector;
3565 	struct drm_connector *connector;
3566 	struct drm_connector_list_iter iter;
3567 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
3568 	enum dc_connection_type new_connection_type = dc_connection_none;
3569 	struct dc_state *dc_state;
3570 	int i, r, j;
3571 	struct dc_commit_streams_params commit_params = {};
3572 
3573 	if (dm->dc->caps.ips_support) {
3574 		if (!amdgpu_in_reset(adev))
3575 			mutex_lock(&dm->dc_lock);
3576 
3577 		/* Need to set POWER_STATE_D0 first or it will not execute
3578 		 * idle_power_optimizations command to DMUB.
3579 		 */
3580 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3581 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
3582 
3583 		if (!amdgpu_in_reset(adev))
3584 			mutex_unlock(&dm->dc_lock);
3585 	}
3586 
3587 	if (amdgpu_in_reset(adev)) {
3588 		dc_state = dm->cached_dc_state;
3589 
3590 		/*
3591 		 * The dc->current_state is backed up into dm->cached_dc_state
3592 		 * before we commit 0 streams.
3593 		 *
3594 		 * DC will clear link encoder assignments on the real state
3595 		 * but the changes won't propagate over to the copy we made
3596 		 * before the 0 streams commit.
3597 		 *
3598 		 * DC expects that link encoder assignments are *not* valid
3599 		 * when committing a state, so as a workaround we can copy
3600 		 * off of the current state.
3601 		 *
3602 		 * We lose the previous assignments, but we had already
3603 		 * commit 0 streams anyway.
3604 		 */
3605 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
3606 
3607 		r = dm_dmub_hw_init(adev);
3608 		if (r) {
3609 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
3610 			return r;
3611 		}
3612 
3613 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3614 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3615 
3616 		dc_resume(dm->dc);
3617 
3618 		amdgpu_dm_ism_enable(dm);
3619 		amdgpu_dm_irq_resume_early(adev);
3620 
3621 		for (i = 0; i < dc_state->stream_count; i++) {
3622 			dc_state->streams[i]->mode_changed = true;
3623 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
3624 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
3625 					= 0xffffffff;
3626 			}
3627 		}
3628 
3629 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3630 			amdgpu_dm_outbox_init(adev);
3631 			dc_enable_dmub_outbox(adev->dm.dc);
3632 		}
3633 
3634 		commit_params.streams = dc_state->streams;
3635 		commit_params.stream_count = dc_state->stream_count;
3636 		dc_exit_ips_for_hw_access(dm->dc);
3637 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
3638 
3639 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
3640 
3641 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
3642 
3643 		dc_state_release(dm->cached_dc_state);
3644 		dm->cached_dc_state = NULL;
3645 
3646 		amdgpu_dm_irq_resume_late(adev);
3647 
3648 		mutex_unlock(&dm->dc_lock);
3649 
3650 		/* set the backlight after a reset */
3651 		for (i = 0; i < dm->num_of_edps; i++) {
3652 			if (dm->backlight_dev[i])
3653 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
3654 		}
3655 
3656 		return 0;
3657 	}
3658 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
3659 	dc_state_release(dm_state->context);
3660 	dm_state->context = dc_state_create(dm->dc, NULL);
3661 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
3662 
3663 	/* Before powering on DC we need to re-initialize DMUB. */
3664 	dm_dmub_hw_resume(adev);
3665 
3666 	/* Re-enable outbox interrupts for DPIA. */
3667 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3668 		amdgpu_dm_outbox_init(adev);
3669 		dc_enable_dmub_outbox(adev->dm.dc);
3670 	}
3671 
3672 	/* power on hardware */
3673 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3674 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3675 
3676 	/* program HPD filter */
3677 	dc_resume(dm->dc);
3678 
3679 	scoped_guard(mutex, &dm->dc_lock)
3680 		amdgpu_dm_ism_enable(dm);
3681 
3682 	/*
3683 	 * early enable HPD Rx IRQ, should be done before set mode as short
3684 	 * pulse interrupts are used for MST
3685 	 */
3686 	amdgpu_dm_irq_resume_early(adev);
3687 
3688 	s3_handle_hdmi_cec(ddev, false);
3689 
3690 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
3691 	s3_handle_mst(ddev, false);
3692 
3693 	/* Do detection*/
3694 	drm_connector_list_iter_begin(ddev, &iter);
3695 	drm_for_each_connector_iter(connector, &iter) {
3696 		bool ret;
3697 
3698 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3699 			continue;
3700 
3701 		aconnector = to_amdgpu_dm_connector(connector);
3702 
3703 		if (!aconnector->dc_link)
3704 			continue;
3705 
3706 		/*
3707 		 * this is the case when traversing through already created end sink
3708 		 * MST connectors, should be skipped
3709 		 */
3710 		if (aconnector->mst_root)
3711 			continue;
3712 
3713 		/* Skip eDP detection, when there is no sink present */
3714 		if (aconnector->dc_link->connector_signal == SIGNAL_TYPE_EDP &&
3715 		    !aconnector->dc_link->edp_sink_present)
3716 			continue;
3717 
3718 		guard(mutex)(&aconnector->hpd_lock);
3719 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3720 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3721 
3722 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3723 			emulated_link_detect(aconnector->dc_link);
3724 		} else {
3725 			guard(mutex)(&dm->dc_lock);
3726 			dc_exit_ips_for_hw_access(dm->dc);
3727 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
3728 			if (ret) {
3729 				/* w/a delay for certain panels */
3730 				apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3731 			}
3732 		}
3733 
3734 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
3735 			aconnector->fake_enable = false;
3736 
3737 		if (aconnector->dc_sink)
3738 			dc_sink_release(aconnector->dc_sink);
3739 		aconnector->dc_sink = NULL;
3740 		amdgpu_dm_update_connector_after_detect(aconnector);
3741 	}
3742 	drm_connector_list_iter_end(&iter);
3743 
3744 	dm_destroy_cached_state(adev);
3745 
3746 	/* Do mst topology probing after resuming cached state*/
3747 	drm_connector_list_iter_begin(ddev, &iter);
3748 	drm_for_each_connector_iter(connector, &iter) {
3749 		bool init = false;
3750 
3751 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3752 			continue;
3753 
3754 		aconnector = to_amdgpu_dm_connector(connector);
3755 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3756 		    aconnector->mst_root)
3757 			continue;
3758 
3759 		scoped_guard(mutex, &aconnector->mst_mgr.lock) {
3760 			init = !aconnector->mst_mgr.mst_primary;
3761 		}
3762 		if (init)
3763 			dm_helpers_dp_mst_start_top_mgr(aconnector->dc_link->ctx,
3764 				aconnector->dc_link, false);
3765 		else
3766 			drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
3767 	}
3768 	drm_connector_list_iter_end(&iter);
3769 
3770 	/* Debug dump: list all DC links and their associated sinks after detection
3771 	 * is complete for all connectors. This provides a comprehensive view of the
3772 	 * final state without repeating the dump for each connector.
3773 	 */
3774 	amdgpu_dm_dump_links_and_sinks(adev);
3775 
3776 	amdgpu_dm_irq_resume_late(adev);
3777 
3778 	amdgpu_dm_smu_write_watermarks_table(adev);
3779 
3780 	drm_kms_helper_hotplug_event(ddev);
3781 
3782 	return 0;
3783 }
3784 
3785 /**
3786  * DOC: DM Lifecycle
3787  *
3788  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
3789  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
3790  * the base driver's device list to be initialized and torn down accordingly.
3791  *
3792  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
3793  */
3794 
3795 static const struct amd_ip_funcs amdgpu_dm_funcs = {
3796 	.name = "dm",
3797 	.early_init = dm_early_init,
3798 	.late_init = dm_late_init,
3799 	.sw_init = dm_sw_init,
3800 	.sw_fini = dm_sw_fini,
3801 	.early_fini = amdgpu_dm_early_fini,
3802 	.hw_init = dm_hw_init,
3803 	.hw_fini = dm_hw_fini,
3804 	.suspend = dm_suspend,
3805 	.resume = dm_resume,
3806 	.is_idle = dm_is_idle,
3807 	.wait_for_idle = dm_wait_for_idle,
3808 	.check_soft_reset = dm_check_soft_reset,
3809 	.soft_reset = dm_soft_reset,
3810 	.set_clockgating_state = dm_set_clockgating_state,
3811 	.set_powergating_state = dm_set_powergating_state,
3812 };
3813 
3814 const struct amdgpu_ip_block_version dm_ip_block = {
3815 	.type = AMD_IP_BLOCK_TYPE_DCE,
3816 	.major = 1,
3817 	.minor = 0,
3818 	.rev = 0,
3819 	.funcs = &amdgpu_dm_funcs,
3820 };
3821 
3822 
3823 /**
3824  * DOC: atomic
3825  *
3826  * *WIP*
3827  */
3828 
3829 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
3830 	.fb_create = amdgpu_display_user_framebuffer_create,
3831 	.get_format_info = amdgpu_dm_plane_get_format_info,
3832 	.atomic_check = amdgpu_dm_atomic_check,
3833 	.atomic_commit = drm_atomic_helper_commit,
3834 };
3835 
3836 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
3837 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
3838 	.atomic_commit_setup = amdgpu_dm_atomic_setup_commit,
3839 };
3840 
3841 #define DDC_MANUFACTURERNAME_SAMSUNG 0x2D4C
3842 
dm_set_panel_type(struct amdgpu_dm_connector * aconnector)3843 static void dm_set_panel_type(struct amdgpu_dm_connector *aconnector)
3844 {
3845 	struct drm_connector *connector = &aconnector->base;
3846 	struct drm_display_info *display_info = &connector->display_info;
3847 	struct dc_link *link = aconnector->dc_link;
3848 	struct amdgpu_device *adev;
3849 
3850 	adev = drm_to_adev(connector->dev);
3851 
3852 	link->panel_type = PANEL_TYPE_NONE;
3853 
3854 	switch (display_info->amd_vsdb.panel_type) {
3855 	case AMD_VSDB_PANEL_TYPE_OLED:
3856 		link->panel_type = PANEL_TYPE_OLED;
3857 		break;
3858 	case AMD_VSDB_PANEL_TYPE_MINILED:
3859 		link->panel_type = PANEL_TYPE_MINILED;
3860 		break;
3861 	}
3862 
3863 	/* If VSDB didn't determine panel type, check DPCD ext caps */
3864 	if (link->panel_type == PANEL_TYPE_NONE) {
3865 		if (link->dpcd_sink_ext_caps.bits.miniled == 1)
3866 			link->panel_type = PANEL_TYPE_MINILED;
3867 		if (link->dpcd_sink_ext_caps.bits.oled == 1)
3868 			link->panel_type = PANEL_TYPE_OLED;
3869 	}
3870 
3871 	/*
3872 	 * TODO: get panel type from DID2 that has device technology field
3873 	 * to specify if it's OLED or not. But we need to wait for DID2
3874 	 * support in DC and EDID parser to be able to use it here.
3875 	 */
3876 
3877 	if (link->panel_type == PANEL_TYPE_NONE) {
3878 		struct drm_amd_vsdb_info *vsdb = &display_info->amd_vsdb;
3879 		u32 lum1_max = vsdb->luminance_range1.max_luminance;
3880 		u32 lum2_max = vsdb->luminance_range2.max_luminance;
3881 
3882 		if (vsdb->version && link->local_sink &&
3883 		    link->local_sink->edid_caps.manufacturer_id ==
3884 		    DDC_MANUFACTURERNAME_SAMSUNG &&
3885 		    lum1_max >= ((lum2_max * 3) / 2))
3886 			link->panel_type = PANEL_TYPE_MINILED;
3887 	}
3888 
3889 	if (link->panel_type == PANEL_TYPE_OLED)
3890 		drm_object_property_set_value(&connector->base,
3891 		    adev_to_drm(adev)->mode_config.panel_type_property,
3892 		    DRM_MODE_PANEL_TYPE_OLED);
3893 	else
3894 		drm_object_property_set_value(&connector->base,
3895 		    adev_to_drm(adev)->mode_config.panel_type_property,
3896 		    DRM_MODE_PANEL_TYPE_UNKNOWN);
3897 
3898 	drm_dbg_kms(aconnector->base.dev, "Panel type: %d\n", link->panel_type);
3899 }
3900 
update_connector_ext_caps(struct amdgpu_dm_connector * aconnector)3901 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
3902 {
3903 	const struct drm_panel_backlight_quirk *panel_backlight_quirk;
3904 	struct amdgpu_dm_backlight_caps *caps;
3905 	struct drm_connector *conn_base;
3906 	struct amdgpu_device *adev;
3907 	struct drm_luminance_range_info *luminance_range;
3908 	struct drm_device *drm;
3909 
3910 	if (aconnector->bl_idx == -1 ||
3911 	    aconnector->dc_link->connector_signal != SIGNAL_TYPE_EDP)
3912 		return;
3913 
3914 	conn_base = &aconnector->base;
3915 	drm = conn_base->dev;
3916 	adev = drm_to_adev(drm);
3917 
3918 	caps = &adev->dm.backlight_caps[aconnector->bl_idx];
3919 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
3920 	caps->aux_support = false;
3921 
3922 	if (caps->ext_caps->bits.oled == 1
3923 	    /*
3924 	     * ||
3925 	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
3926 	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
3927 	     */)
3928 		caps->aux_support = true;
3929 
3930 	if (amdgpu_backlight == 0)
3931 		caps->aux_support = false;
3932 	else if (amdgpu_backlight == 1)
3933 		caps->aux_support = true;
3934 	if (caps->aux_support)
3935 		aconnector->dc_link->backlight_control_type = BACKLIGHT_CONTROL_AMD_AUX;
3936 
3937 	luminance_range = &conn_base->display_info.luminance_range;
3938 
3939 	if (luminance_range->max_luminance)
3940 		caps->aux_max_input_signal = luminance_range->max_luminance;
3941 	else
3942 		caps->aux_max_input_signal = 512;
3943 
3944 	if (luminance_range->min_luminance)
3945 		caps->aux_min_input_signal = luminance_range->min_luminance;
3946 	else
3947 		caps->aux_min_input_signal = 1;
3948 
3949 	panel_backlight_quirk =
3950 		drm_get_panel_backlight_quirk(aconnector->drm_edid);
3951 	if (!IS_ERR_OR_NULL(panel_backlight_quirk)) {
3952 		if (panel_backlight_quirk->min_brightness) {
3953 			caps->min_input_signal =
3954 				panel_backlight_quirk->min_brightness - 1;
3955 			drm_info(drm,
3956 				 "Applying panel backlight quirk, min_brightness: %d\n",
3957 				 caps->min_input_signal);
3958 		}
3959 		if (panel_backlight_quirk->brightness_mask) {
3960 			drm_info(drm,
3961 				 "Applying panel backlight quirk, brightness_mask: 0x%X\n",
3962 				 panel_backlight_quirk->brightness_mask);
3963 			caps->brightness_mask =
3964 				panel_backlight_quirk->brightness_mask;
3965 		}
3966 	}
3967 }
3968 
DEFINE_FREE(sink_release,struct dc_sink *,if (_T)dc_sink_release (_T))3969 DEFINE_FREE(sink_release, struct dc_sink *, if (_T) dc_sink_release(_T))
3970 
3971 void amdgpu_dm_update_connector_after_detect(
3972 		struct amdgpu_dm_connector *aconnector)
3973 {
3974 	struct drm_connector *connector = &aconnector->base;
3975 	struct dc_sink *sink __free(sink_release) = NULL;
3976 	struct drm_device *dev = connector->dev;
3977 
3978 	/* MST handled by drm_mst framework */
3979 	if (aconnector->mst_mgr.mst_state == true)
3980 		return;
3981 
3982 	sink = aconnector->dc_link->local_sink;
3983 	if (sink)
3984 		dc_sink_retain(sink);
3985 
3986 	/*
3987 	 * Edid mgmt connector gets first update only in mode_valid hook and then
3988 	 * the connector sink is set to either fake or physical sink depends on link status.
3989 	 * Skip if already done during boot.
3990 	 */
3991 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
3992 			&& aconnector->dc_em_sink) {
3993 
3994 		/*
3995 		 * For S3 resume with headless use eml_sink to fake stream
3996 		 * because on resume connector->sink is set to NULL
3997 		 */
3998 		guard(mutex)(&dev->mode_config.mutex);
3999 
4000 		if (sink) {
4001 			if (aconnector->dc_sink) {
4002 				amdgpu_dm_update_freesync_caps(connector, NULL, true);
4003 				/*
4004 				 * retain and release below are used to
4005 				 * bump up refcount for sink because the link doesn't point
4006 				 * to it anymore after disconnect, so on next crtc to connector
4007 				 * reshuffle by UMD we will get into unwanted dc_sink release
4008 				 */
4009 				dc_sink_release(aconnector->dc_sink);
4010 			}
4011 			aconnector->dc_sink = sink;
4012 			dc_sink_retain(aconnector->dc_sink);
4013 			amdgpu_dm_update_freesync_caps(connector,
4014 					aconnector->drm_edid, true);
4015 		} else {
4016 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4017 			if (!aconnector->dc_sink) {
4018 				aconnector->dc_sink = aconnector->dc_em_sink;
4019 				dc_sink_retain(aconnector->dc_sink);
4020 			}
4021 		}
4022 
4023 		return;
4024 	}
4025 
4026 	/*
4027 	 * TODO: temporary guard to look for proper fix
4028 	 * if this sink is MST sink, we should not do anything
4029 	 */
4030 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
4031 		return;
4032 
4033 	if (aconnector->dc_sink == sink) {
4034 		/*
4035 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
4036 		 * Do nothing!!
4037 		 */
4038 		drm_dbg_kms(dev, "DCHPD: connector_id=%d: dc_sink didn't change.\n",
4039 				 aconnector->connector_id);
4040 		return;
4041 	}
4042 
4043 	drm_dbg_kms(dev, "DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
4044 		    aconnector->connector_id, aconnector->dc_sink, sink);
4045 
4046 	/* When polling, DRM has already locked the mutex for us. */
4047 	if (!drm_kms_helper_is_poll_worker())
4048 		mutex_lock(&dev->mode_config.mutex);
4049 
4050 	/*
4051 	 * 1. Update status of the drm connector
4052 	 * 2. Send an event and let userspace tell us what to do
4053 	 */
4054 	if (sink) {
4055 		/*
4056 		 * TODO: check if we still need the S3 mode update workaround.
4057 		 * If yes, put it here.
4058 		 */
4059 		if (aconnector->dc_sink) {
4060 			amdgpu_dm_update_freesync_caps(connector, NULL, true);
4061 			dc_sink_release(aconnector->dc_sink);
4062 		}
4063 
4064 		aconnector->dc_sink = sink;
4065 		dc_sink_retain(aconnector->dc_sink);
4066 		drm_edid_free(aconnector->drm_edid);
4067 		aconnector->drm_edid = NULL;
4068 		if (sink->dc_edid.length == 0) {
4069 			hdmi_cec_unset_edid(aconnector);
4070 			if (aconnector->dc_link->aux_mode) {
4071 				drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4072 			}
4073 		} else {
4074 			const struct edid *edid = (const struct edid *)sink->dc_edid.raw_edid;
4075 
4076 			aconnector->drm_edid = drm_edid_alloc(edid, sink->dc_edid.length);
4077 			drm_edid_connector_update(connector, aconnector->drm_edid);
4078 
4079 			hdmi_cec_set_edid(aconnector);
4080 			if (aconnector->dc_link->aux_mode)
4081 				drm_dp_cec_attach(&aconnector->dm_dp_aux.aux,
4082 						  connector->display_info.source_physical_address);
4083 		}
4084 
4085 		if (!aconnector->timing_requested) {
4086 			aconnector->timing_requested =
4087 				kzalloc_obj(struct dc_crtc_timing);
4088 			if (!aconnector->timing_requested)
4089 				drm_err(dev,
4090 					"failed to create aconnector->requested_timing\n");
4091 		}
4092 
4093 		amdgpu_dm_update_freesync_caps(connector, aconnector->drm_edid, true);
4094 		update_connector_ext_caps(aconnector);
4095 		dm_set_panel_type(aconnector);
4096 	} else {
4097 		hdmi_cec_unset_edid(aconnector);
4098 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
4099 		amdgpu_dm_update_freesync_caps(connector, NULL, true);
4100 		aconnector->num_modes = 0;
4101 		dc_sink_release(aconnector->dc_sink);
4102 		aconnector->dc_sink = NULL;
4103 		drm_edid_free(aconnector->drm_edid);
4104 		aconnector->drm_edid = NULL;
4105 		kfree(aconnector->timing_requested);
4106 		aconnector->timing_requested = NULL;
4107 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
4108 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
4109 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
4110 	}
4111 
4112 	update_subconnector_property(aconnector);
4113 
4114 	/* When polling, the mutex will be unlocked for us by DRM. */
4115 	if (!drm_kms_helper_is_poll_worker())
4116 		mutex_unlock(&dev->mode_config.mutex);
4117 }
4118 
are_sinks_equal(const struct dc_sink * sink1,const struct dc_sink * sink2)4119 static bool are_sinks_equal(const struct dc_sink *sink1, const struct dc_sink *sink2)
4120 {
4121 	if (!sink1 || !sink2)
4122 		return false;
4123 	if (sink1->sink_signal != sink2->sink_signal)
4124 		return false;
4125 
4126 	if (sink1->dc_edid.length != sink2->dc_edid.length)
4127 		return false;
4128 
4129 	if (memcmp(sink1->dc_edid.raw_edid, sink2->dc_edid.raw_edid,
4130 		   sink1->dc_edid.length) != 0)
4131 		return false;
4132 	return true;
4133 }
4134 
4135 
4136 /**
4137  * DOC: hdmi_hpd_debounce_work
4138  *
4139  * HDMI HPD debounce delay in milliseconds. When an HDMI display toggles HPD
4140  * (such as during power save transitions), this delay determines how long to
4141  * wait before processing the HPD event. This allows distinguishing between a
4142  * physical unplug (>hdmi_hpd_debounce_delay)
4143  * and a spontaneous RX HPD toggle (<hdmi_hpd_debounce_delay).
4144  *
4145  * If the toggle is less than this delay, the driver compares sink capabilities
4146  * and permits a hotplug event if they changed.
4147  *
4148  * The default value of 1500ms was chosen based on experimental testing with
4149  * various monitors that exhibit spontaneous HPD toggling behavior.
4150  */
hdmi_hpd_debounce_work(struct work_struct * work)4151 static void hdmi_hpd_debounce_work(struct work_struct *work)
4152 {
4153 	struct amdgpu_dm_connector *aconnector =
4154 		container_of(to_delayed_work(work), struct amdgpu_dm_connector,
4155 			     hdmi_hpd_debounce_work);
4156 	struct drm_connector *connector = &aconnector->base;
4157 	struct drm_device *dev = connector->dev;
4158 	struct amdgpu_device *adev = drm_to_adev(dev);
4159 	struct dc *dc = aconnector->dc_link->ctx->dc;
4160 	bool fake_reconnect = false;
4161 	bool reallow_idle = false;
4162 	bool ret = false;
4163 	guard(mutex)(&aconnector->hpd_lock);
4164 
4165 	/* Re-detect the display */
4166 	scoped_guard(mutex, &adev->dm.dc_lock) {
4167 		if (dc->caps.ips_support && dc->ctx->dmub_srv->idle_allowed) {
4168 			dc_allow_idle_optimizations(dc, false);
4169 			reallow_idle = true;
4170 		}
4171 		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4172 	}
4173 
4174 	if (ret) {
4175 		/* Apply workaround delay for certain panels */
4176 		apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4177 		/* Compare sinks to determine if this was a spontaneous HPD toggle */
4178 		if (are_sinks_equal(aconnector->dc_link->local_sink, aconnector->hdmi_prev_sink)) {
4179 			/*
4180 			* Sinks match - this was a spontaneous HDMI HPD toggle.
4181 			*/
4182 			drm_dbg_kms(dev, "HDMI HPD: Sink unchanged after debounce, internal re-enable\n");
4183 			fake_reconnect = true;
4184 		}
4185 
4186 		/* Update connector state */
4187 		amdgpu_dm_update_connector_after_detect(aconnector);
4188 
4189 		drm_modeset_lock_all(dev);
4190 		dm_restore_drm_connector_state(dev, connector);
4191 		drm_modeset_unlock_all(dev);
4192 
4193 		/* Only notify OS if sink actually changed */
4194 		if (!fake_reconnect && aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4195 			drm_kms_helper_hotplug_event(dev);
4196 	}
4197 
4198 	/* Release the cached sink reference */
4199 	if (aconnector->hdmi_prev_sink) {
4200 		dc_sink_release(aconnector->hdmi_prev_sink);
4201 		aconnector->hdmi_prev_sink = NULL;
4202 	}
4203 
4204 	scoped_guard(mutex, &adev->dm.dc_lock) {
4205 		if (reallow_idle && dc->caps.ips_support)
4206 			dc_allow_idle_optimizations(dc, true);
4207 	}
4208 }
4209 
handle_hpd_irq_helper(struct amdgpu_dm_connector * aconnector)4210 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
4211 {
4212 	struct drm_connector *connector = &aconnector->base;
4213 	struct drm_device *dev = connector->dev;
4214 	enum dc_connection_type new_connection_type = dc_connection_none;
4215 	struct amdgpu_device *adev = drm_to_adev(dev);
4216 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
4217 	struct dc *dc = aconnector->dc_link->ctx->dc;
4218 	bool ret = false;
4219 	bool debounce_required = false;
4220 
4221 	if (adev->dm.disable_hpd_irq)
4222 		return;
4223 
4224 	/*
4225 	 * In case of failure or MST no need to update connector status or notify the OS
4226 	 * since (for MST case) MST does this in its own context.
4227 	 */
4228 	guard(mutex)(&aconnector->hpd_lock);
4229 
4230 	if (adev->dm.hdcp_workqueue) {
4231 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
4232 		dm_con_state->update_hdcp = true;
4233 	}
4234 	if (aconnector->fake_enable)
4235 		aconnector->fake_enable = false;
4236 
4237 	aconnector->timing_changed = false;
4238 
4239 	if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
4240 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4241 
4242 	/*
4243 	 * Check for HDMI disconnect with debounce enabled.
4244 	 */
4245 	debounce_required = (aconnector->hdmi_hpd_debounce_delay_ms > 0 &&
4246 			      dc_is_hdmi_signal(aconnector->dc_link->connector_signal) &&
4247 			      new_connection_type == dc_connection_none &&
4248 			      aconnector->dc_link->local_sink != NULL);
4249 
4250 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
4251 		emulated_link_detect(aconnector->dc_link);
4252 
4253 		drm_modeset_lock_all(dev);
4254 		dm_restore_drm_connector_state(dev, connector);
4255 		drm_modeset_unlock_all(dev);
4256 
4257 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4258 			drm_kms_helper_connector_hotplug_event(connector);
4259 	} else if (debounce_required) {
4260 		/*
4261 		 * HDMI disconnect detected - schedule delayed work instead of
4262 		 * processing immediately. This allows us to coalesce spurious
4263 		 * HDMI signals from physical unplugs.
4264 		 */
4265 		drm_dbg_kms(dev, "HDMI HPD: Disconnect detected, scheduling debounce work (%u ms)\n",
4266 			    aconnector->hdmi_hpd_debounce_delay_ms);
4267 
4268 		/* Cache the current sink for later comparison */
4269 		if (aconnector->hdmi_prev_sink)
4270 			dc_sink_release(aconnector->hdmi_prev_sink);
4271 		aconnector->hdmi_prev_sink = aconnector->dc_link->local_sink;
4272 		if (aconnector->hdmi_prev_sink)
4273 			dc_sink_retain(aconnector->hdmi_prev_sink);
4274 
4275 		/* Schedule delayed detection. */
4276 		if (mod_delayed_work(system_percpu_wq,
4277 				 &aconnector->hdmi_hpd_debounce_work,
4278 				 msecs_to_jiffies(aconnector->hdmi_hpd_debounce_delay_ms)))
4279 			drm_dbg_kms(dev, "HDMI HPD: Re-scheduled debounce work\n");
4280 
4281 	} else {
4282 
4283 		/* If the aconnector->hdmi_hpd_debounce_work is scheduled, exit early */
4284 		if (delayed_work_pending(&aconnector->hdmi_hpd_debounce_work))
4285 			return;
4286 
4287 		scoped_guard(mutex, &adev->dm.dc_lock) {
4288 			dc_exit_ips_for_hw_access(dc);
4289 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4290 		}
4291 		if (ret) {
4292 			/* w/a delay for certain panels */
4293 			apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4294 			amdgpu_dm_update_connector_after_detect(aconnector);
4295 
4296 			drm_modeset_lock_all(dev);
4297 			dm_restore_drm_connector_state(dev, connector);
4298 			drm_modeset_unlock_all(dev);
4299 
4300 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4301 				drm_kms_helper_connector_hotplug_event(connector);
4302 		}
4303 	}
4304 }
4305 
handle_hpd_irq(void * param)4306 static void handle_hpd_irq(void *param)
4307 {
4308 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4309 
4310 	handle_hpd_irq_helper(aconnector);
4311 
4312 }
4313 
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)4314 static void schedule_hpd_rx_offload_work(struct amdgpu_device *adev, struct hpd_rx_irq_offload_work_queue *offload_wq,
4315 							union hpd_irq_data hpd_irq_data)
4316 {
4317 	struct hpd_rx_irq_offload_work *offload_work = kzalloc_obj(*offload_work);
4318 
4319 	if (!offload_work) {
4320 		drm_err(adev_to_drm(adev), "Failed to allocate hpd_rx_irq_offload_work.\n");
4321 		return;
4322 	}
4323 
4324 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
4325 	offload_work->data = hpd_irq_data;
4326 	offload_work->offload_wq = offload_wq;
4327 	offload_work->adev = adev;
4328 
4329 	queue_work(offload_wq->wq, &offload_work->work);
4330 	drm_dbg_kms(adev_to_drm(adev), "queue work to handle hpd_rx offload work");
4331 }
4332 
handle_hpd_rx_irq(void * param)4333 static void handle_hpd_rx_irq(void *param)
4334 {
4335 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4336 	struct drm_connector *connector = &aconnector->base;
4337 	struct drm_device *dev = connector->dev;
4338 	struct dc_link *dc_link = aconnector->dc_link;
4339 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
4340 	bool result = false;
4341 	enum dc_connection_type new_connection_type = dc_connection_none;
4342 	struct amdgpu_device *adev = drm_to_adev(dev);
4343 	union hpd_irq_data hpd_irq_data;
4344 	bool link_loss = false;
4345 	bool has_left_work = false;
4346 	int idx = dc_link->link_index;
4347 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
4348 	struct dc *dc = aconnector->dc_link->ctx->dc;
4349 
4350 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
4351 
4352 	if (adev->dm.disable_hpd_irq)
4353 		return;
4354 
4355 	/*
4356 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
4357 	 * conflict, after implement i2c helper, this mutex should be
4358 	 * retired.
4359 	 */
4360 	mutex_lock(&aconnector->hpd_lock);
4361 
4362 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
4363 						&link_loss, true, &has_left_work);
4364 
4365 	if (!has_left_work)
4366 		goto out;
4367 
4368 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
4369 		schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4370 		goto out;
4371 	}
4372 
4373 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
4374 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
4375 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
4376 			bool skip = false;
4377 
4378 			/*
4379 			 * DOWN_REP_MSG_RDY is also handled by polling method
4380 			 * mgr->cbs->poll_hpd_irq()
4381 			 */
4382 			spin_lock(&offload_wq->offload_lock);
4383 			skip = offload_wq->is_handling_mst_msg_rdy_event;
4384 
4385 			if (!skip)
4386 				offload_wq->is_handling_mst_msg_rdy_event = true;
4387 
4388 			spin_unlock(&offload_wq->offload_lock);
4389 
4390 			if (!skip)
4391 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4392 
4393 			goto out;
4394 		}
4395 
4396 		if (link_loss) {
4397 			bool skip = false;
4398 
4399 			spin_lock(&offload_wq->offload_lock);
4400 			skip = offload_wq->is_handling_link_loss;
4401 
4402 			if (!skip)
4403 				offload_wq->is_handling_link_loss = true;
4404 
4405 			spin_unlock(&offload_wq->offload_lock);
4406 
4407 			if (!skip)
4408 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4409 
4410 			goto out;
4411 		}
4412 	}
4413 
4414 out:
4415 	if (result && !is_mst_root_connector) {
4416 		/* Downstream Port status changed. */
4417 		if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
4418 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4419 
4420 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4421 			emulated_link_detect(dc_link);
4422 
4423 			if (aconnector->fake_enable)
4424 				aconnector->fake_enable = false;
4425 
4426 			amdgpu_dm_update_connector_after_detect(aconnector);
4427 
4428 
4429 			drm_modeset_lock_all(dev);
4430 			dm_restore_drm_connector_state(dev, connector);
4431 			drm_modeset_unlock_all(dev);
4432 
4433 			drm_kms_helper_connector_hotplug_event(connector);
4434 		} else {
4435 			bool ret = false;
4436 
4437 			mutex_lock(&adev->dm.dc_lock);
4438 			dc_exit_ips_for_hw_access(dc);
4439 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
4440 			mutex_unlock(&adev->dm.dc_lock);
4441 
4442 			if (ret) {
4443 				if (aconnector->fake_enable)
4444 					aconnector->fake_enable = false;
4445 
4446 				amdgpu_dm_update_connector_after_detect(aconnector);
4447 
4448 				drm_modeset_lock_all(dev);
4449 				dm_restore_drm_connector_state(dev, connector);
4450 				drm_modeset_unlock_all(dev);
4451 
4452 				drm_kms_helper_connector_hotplug_event(connector);
4453 			}
4454 		}
4455 	}
4456 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
4457 		if (adev->dm.hdcp_workqueue)
4458 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
4459 	}
4460 
4461 	if (dc_link->type != dc_connection_mst_branch)
4462 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
4463 
4464 	mutex_unlock(&aconnector->hpd_lock);
4465 }
4466 
register_hpd_handlers(struct amdgpu_device * adev)4467 static int register_hpd_handlers(struct amdgpu_device *adev)
4468 {
4469 	struct drm_device *dev = adev_to_drm(adev);
4470 	struct drm_connector *connector;
4471 	struct amdgpu_dm_connector *aconnector;
4472 	const struct dc_link *dc_link;
4473 	struct dc_interrupt_params int_params = {0};
4474 
4475 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4476 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4477 
4478 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
4479 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD,
4480 			dmub_hpd_callback, true)) {
4481 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4482 			return -EINVAL;
4483 		}
4484 
4485 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ,
4486 			dmub_hpd_callback, true)) {
4487 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4488 			return -EINVAL;
4489 		}
4490 
4491 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_SENSE_NOTIFY,
4492 			dmub_hpd_sense_callback, true)) {
4493 			drm_err(adev_to_drm(adev), "fail to register dmub hpd sense callback");
4494 			return -EINVAL;
4495 		}
4496 	}
4497 
4498 	list_for_each_entry(connector,
4499 			&dev->mode_config.connector_list, head)	{
4500 
4501 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
4502 			continue;
4503 
4504 		aconnector = to_amdgpu_dm_connector(connector);
4505 		dc_link = aconnector->dc_link;
4506 
4507 		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
4508 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4509 			int_params.irq_source = dc_link->irq_source_hpd;
4510 
4511 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4512 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1 ||
4513 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6) {
4514 				drm_err(adev_to_drm(adev), "Failed to register hpd irq!\n");
4515 				return -EINVAL;
4516 			}
4517 
4518 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4519 				handle_hpd_irq, (void *) aconnector))
4520 				return -ENOMEM;
4521 		}
4522 
4523 		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
4524 
4525 			/* Also register for DP short pulse (hpd_rx). */
4526 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4527 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
4528 
4529 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4530 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1RX ||
4531 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6RX) {
4532 				drm_err(adev_to_drm(adev), "Failed to register hpd rx irq!\n");
4533 				return -EINVAL;
4534 			}
4535 
4536 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4537 				handle_hpd_rx_irq, (void *) aconnector))
4538 				return -ENOMEM;
4539 		}
4540 	}
4541 	return 0;
4542 }
4543 
4544 /* Register IRQ sources and initialize IRQ callbacks */
dce110_register_irq_handlers(struct amdgpu_device * adev)4545 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
4546 {
4547 	struct dc *dc = adev->dm.dc;
4548 	struct common_irq_params *c_irq_params;
4549 	struct dc_interrupt_params int_params = {0};
4550 	int r;
4551 	int i;
4552 	unsigned int src_id;
4553 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4554 	/* Use different interrupts for VBLANK on DCE 6 vs. newer. */
4555 	const unsigned int vblank_d1 =
4556 		adev->dm.dc->ctx->dce_version >= DCE_VERSION_8_0
4557 		? VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0 : 1;
4558 
4559 	if (adev->family >= AMDGPU_FAMILY_AI)
4560 		client_id = SOC15_IH_CLIENTID_DCE;
4561 
4562 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4563 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4564 
4565 	/*
4566 	 * Actions of amdgpu_irq_add_id():
4567 	 * 1. Register a set() function with base driver.
4568 	 *    Base driver will call set() function to enable/disable an
4569 	 *    interrupt in DC hardware.
4570 	 * 2. Register amdgpu_dm_irq_handler().
4571 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4572 	 *    coming from DC hardware.
4573 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4574 	 *    for acknowledging and handling.
4575 	 */
4576 
4577 	/* Use VBLANK interrupt */
4578 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
4579 		src_id = vblank_d1 + i;
4580 		r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->crtc_irq);
4581 		if (r) {
4582 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4583 			return r;
4584 		}
4585 
4586 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4587 		int_params.irq_source =
4588 			dc_interrupt_to_irq_source(dc, src_id, 0);
4589 
4590 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4591 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4592 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4593 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4594 			return -EINVAL;
4595 		}
4596 
4597 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4598 
4599 		c_irq_params->adev = adev;
4600 		c_irq_params->irq_src = int_params.irq_source;
4601 
4602 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4603 			dm_crtc_high_irq, c_irq_params))
4604 			return -ENOMEM;
4605 	}
4606 
4607 	if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
4608 		/* Use VUPDATE interrupt */
4609 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
4610 			src_id = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT + i * 2;
4611 			r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->vupdate_irq);
4612 			if (r) {
4613 				drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4614 				return r;
4615 			}
4616 
4617 			int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4618 			int_params.irq_source =
4619 				dc_interrupt_to_irq_source(dc, src_id, 0);
4620 
4621 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4622 				int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4623 				int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4624 				drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4625 				return -EINVAL;
4626 			}
4627 
4628 			c_irq_params = &adev->dm.vupdate_params[
4629 				int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4630 			c_irq_params->adev = adev;
4631 			c_irq_params->irq_src = int_params.irq_source;
4632 
4633 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4634 				dm_vupdate_high_irq, c_irq_params))
4635 				return -ENOMEM;
4636 		}
4637 	}
4638 
4639 	/* Use GRPH_PFLIP interrupt */
4640 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4641 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4642 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4643 		if (r) {
4644 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4645 			return r;
4646 		}
4647 
4648 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4649 		int_params.irq_source =
4650 			dc_interrupt_to_irq_source(dc, i, 0);
4651 
4652 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4653 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4654 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4655 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4656 			return -EINVAL;
4657 		}
4658 
4659 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4660 
4661 		c_irq_params->adev = adev;
4662 		c_irq_params->irq_src = int_params.irq_source;
4663 
4664 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4665 			dm_pflip_high_irq, c_irq_params))
4666 			return -ENOMEM;
4667 	}
4668 
4669 	/* HPD */
4670 	r = amdgpu_irq_add_id(adev, client_id,
4671 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4672 	if (r) {
4673 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4674 		return r;
4675 	}
4676 
4677 	r = register_hpd_handlers(adev);
4678 
4679 	return r;
4680 }
4681 
4682 /* Register IRQ sources and initialize IRQ callbacks */
dcn10_register_irq_handlers(struct amdgpu_device * adev)4683 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
4684 {
4685 	struct dc *dc = adev->dm.dc;
4686 	struct common_irq_params *c_irq_params;
4687 	struct dc_interrupt_params int_params = {0};
4688 	int r;
4689 	int i;
4690 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4691 	static const unsigned int vrtl_int_srcid[] = {
4692 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
4693 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
4694 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
4695 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
4696 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
4697 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
4698 	};
4699 #endif
4700 
4701 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4702 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4703 
4704 	/*
4705 	 * Actions of amdgpu_irq_add_id():
4706 	 * 1. Register a set() function with base driver.
4707 	 *    Base driver will call set() function to enable/disable an
4708 	 *    interrupt in DC hardware.
4709 	 * 2. Register amdgpu_dm_irq_handler().
4710 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4711 	 *    coming from DC hardware.
4712 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4713 	 *    for acknowledging and handling.
4714 	 */
4715 
4716 	/* Use VSTARTUP interrupt */
4717 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
4718 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
4719 			i++) {
4720 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
4721 
4722 		if (r) {
4723 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4724 			return r;
4725 		}
4726 
4727 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4728 		int_params.irq_source =
4729 			dc_interrupt_to_irq_source(dc, i, 0);
4730 
4731 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4732 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4733 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4734 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4735 			return -EINVAL;
4736 		}
4737 
4738 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4739 
4740 		c_irq_params->adev = adev;
4741 		c_irq_params->irq_src = int_params.irq_source;
4742 
4743 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4744 			dm_crtc_high_irq, c_irq_params))
4745 			return -ENOMEM;
4746 	}
4747 
4748 	/* Use otg vertical line interrupt */
4749 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4750 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
4751 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
4752 				vrtl_int_srcid[i], &adev->vline0_irq);
4753 
4754 		if (r) {
4755 			drm_err(adev_to_drm(adev), "Failed to add vline0 irq id!\n");
4756 			return r;
4757 		}
4758 
4759 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4760 		int_params.irq_source =
4761 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
4762 
4763 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4764 			int_params.irq_source < DC_IRQ_SOURCE_DC1_VLINE0 ||
4765 			int_params.irq_source > DC_IRQ_SOURCE_DC6_VLINE0) {
4766 			drm_err(adev_to_drm(adev), "Failed to register vline0 irq!\n");
4767 			return -EINVAL;
4768 		}
4769 
4770 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
4771 					- DC_IRQ_SOURCE_DC1_VLINE0];
4772 
4773 		c_irq_params->adev = adev;
4774 		c_irq_params->irq_src = int_params.irq_source;
4775 
4776 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4777 			dm_dcn_vertical_interrupt0_high_irq,
4778 			c_irq_params))
4779 			return -ENOMEM;
4780 	}
4781 #endif
4782 
4783 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
4784 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
4785 	 * to trigger at end of each vblank, regardless of state of the lock,
4786 	 * matching DCE behaviour.
4787 	 */
4788 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
4789 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
4790 	     i++) {
4791 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
4792 
4793 		if (r) {
4794 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4795 			return r;
4796 		}
4797 
4798 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4799 		int_params.irq_source =
4800 			dc_interrupt_to_irq_source(dc, i, 0);
4801 
4802 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4803 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4804 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4805 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4806 			return -EINVAL;
4807 		}
4808 
4809 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4810 
4811 		c_irq_params->adev = adev;
4812 		c_irq_params->irq_src = int_params.irq_source;
4813 
4814 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4815 			dm_vupdate_high_irq, c_irq_params))
4816 			return -ENOMEM;
4817 	}
4818 
4819 	/* Use GRPH_PFLIP interrupt */
4820 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
4821 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
4822 			i++) {
4823 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
4824 		if (r) {
4825 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4826 			return r;
4827 		}
4828 
4829 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4830 		int_params.irq_source =
4831 			dc_interrupt_to_irq_source(dc, i, 0);
4832 
4833 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4834 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4835 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4836 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4837 			return -EINVAL;
4838 		}
4839 
4840 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4841 
4842 		c_irq_params->adev = adev;
4843 		c_irq_params->irq_src = int_params.irq_source;
4844 
4845 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4846 			dm_pflip_high_irq, c_irq_params))
4847 			return -ENOMEM;
4848 	}
4849 
4850 	/* HPD */
4851 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
4852 			&adev->hpd_irq);
4853 	if (r) {
4854 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4855 		return r;
4856 	}
4857 
4858 	r = register_hpd_handlers(adev);
4859 
4860 	return r;
4861 }
4862 /* Register Outbox IRQ sources and initialize IRQ callbacks */
register_outbox_irq_handlers(struct amdgpu_device * adev)4863 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
4864 {
4865 	struct dc *dc = adev->dm.dc;
4866 	struct common_irq_params *c_irq_params;
4867 	struct dc_interrupt_params int_params = {0};
4868 	int r, i;
4869 
4870 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4871 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4872 
4873 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
4874 			&adev->dmub_outbox_irq);
4875 	if (r) {
4876 		drm_err(adev_to_drm(adev), "Failed to add outbox irq id!\n");
4877 		return r;
4878 	}
4879 
4880 	if (dc->ctx->dmub_srv) {
4881 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
4882 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4883 		int_params.irq_source =
4884 		dc_interrupt_to_irq_source(dc, i, 0);
4885 
4886 		c_irq_params = &adev->dm.dmub_outbox_params[0];
4887 
4888 		c_irq_params->adev = adev;
4889 		c_irq_params->irq_src = int_params.irq_source;
4890 
4891 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4892 			dm_dmub_outbox1_low_irq, c_irq_params))
4893 			return -ENOMEM;
4894 	}
4895 
4896 	return 0;
4897 }
4898 
4899 /*
4900  * Acquires the lock for the atomic state object and returns
4901  * the new atomic state.
4902  *
4903  * This should only be called during atomic check.
4904  */
dm_atomic_get_state(struct drm_atomic_state * state,struct dm_atomic_state ** dm_state)4905 int dm_atomic_get_state(struct drm_atomic_state *state,
4906 			struct dm_atomic_state **dm_state)
4907 {
4908 	struct drm_device *dev = state->dev;
4909 	struct amdgpu_device *adev = drm_to_adev(dev);
4910 	struct amdgpu_display_manager *dm = &adev->dm;
4911 	struct drm_private_state *priv_state;
4912 
4913 	if (*dm_state)
4914 		return 0;
4915 
4916 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
4917 	if (IS_ERR(priv_state))
4918 		return PTR_ERR(priv_state);
4919 
4920 	*dm_state = to_dm_atomic_state(priv_state);
4921 
4922 	return 0;
4923 }
4924 
4925 static struct dm_atomic_state *
dm_atomic_get_new_state(struct drm_atomic_state * state)4926 dm_atomic_get_new_state(struct drm_atomic_state *state)
4927 {
4928 	struct drm_device *dev = state->dev;
4929 	struct amdgpu_device *adev = drm_to_adev(dev);
4930 	struct amdgpu_display_manager *dm = &adev->dm;
4931 	struct drm_private_obj *obj;
4932 	struct drm_private_state *new_obj_state;
4933 	int i;
4934 
4935 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
4936 		if (obj->funcs == dm->atomic_obj.funcs)
4937 			return to_dm_atomic_state(new_obj_state);
4938 	}
4939 
4940 	return NULL;
4941 }
4942 
4943 static struct drm_private_state *
dm_atomic_duplicate_state(struct drm_private_obj * obj)4944 dm_atomic_duplicate_state(struct drm_private_obj *obj)
4945 {
4946 	struct dm_atomic_state *old_state, *new_state;
4947 
4948 	new_state = kzalloc_obj(*new_state);
4949 	if (!new_state)
4950 		return NULL;
4951 
4952 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
4953 
4954 	old_state = to_dm_atomic_state(obj->state);
4955 
4956 	if (old_state && old_state->context)
4957 		new_state->context = dc_state_create_copy(old_state->context);
4958 
4959 	if (!new_state->context) {
4960 		kfree(new_state);
4961 		return NULL;
4962 	}
4963 
4964 	return &new_state->base;
4965 }
4966 
dm_atomic_destroy_state(struct drm_private_obj * obj,struct drm_private_state * state)4967 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
4968 				    struct drm_private_state *state)
4969 {
4970 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4971 
4972 	if (dm_state && dm_state->context)
4973 		dc_state_release(dm_state->context);
4974 
4975 	kfree(dm_state);
4976 }
4977 
4978 static struct drm_private_state *
dm_atomic_create_state(struct drm_private_obj * obj)4979 dm_atomic_create_state(struct drm_private_obj *obj)
4980 {
4981 	struct amdgpu_device *adev = drm_to_adev(obj->dev);
4982 	struct dm_atomic_state *dm_state;
4983 	struct dc_state *context;
4984 
4985 	dm_state = kzalloc_obj(*dm_state);
4986 	if (!dm_state)
4987 		return ERR_PTR(-ENOMEM);
4988 
4989 	context = dc_state_create_current_copy(adev->dm.dc);
4990 	if (!context) {
4991 		kfree(dm_state);
4992 		return ERR_PTR(-ENOMEM);
4993 	}
4994 
4995 	__drm_atomic_helper_private_obj_create_state(obj, &dm_state->base);
4996 	dm_state->context = context;
4997 
4998 	return &dm_state->base;
4999 }
5000 
5001 static struct drm_private_state_funcs dm_atomic_state_funcs = {
5002 	.atomic_create_state = dm_atomic_create_state,
5003 	.atomic_duplicate_state = dm_atomic_duplicate_state,
5004 	.atomic_destroy_state = dm_atomic_destroy_state,
5005 };
5006 
amdgpu_dm_mode_config_init(struct amdgpu_device * adev)5007 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
5008 {
5009 	int r;
5010 
5011 	adev->mode_info.mode_config_initialized = true;
5012 
5013 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
5014 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
5015 
5016 	adev_to_drm(adev)->mode_config.max_width = 16384;
5017 	adev_to_drm(adev)->mode_config.max_height = 16384;
5018 
5019 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
5020 	if (adev->asic_type == CHIP_HAWAII)
5021 		/* disable prefer shadow for now due to hibernation issues */
5022 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
5023 	else
5024 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
5025 	/* indicates support for immediate flip */
5026 	adev_to_drm(adev)->mode_config.async_page_flip = true;
5027 
5028 	drm_atomic_private_obj_init(adev_to_drm(adev),
5029 				    &adev->dm.atomic_obj,
5030 				    &dm_atomic_state_funcs);
5031 
5032 	r = amdgpu_display_modeset_create_props(adev);
5033 	if (r)
5034 		return r;
5035 
5036 #ifdef AMD_PRIVATE_COLOR
5037 	if (amdgpu_dm_create_color_properties(adev))
5038 		return -ENOMEM;
5039 #endif
5040 
5041 	r = amdgpu_dm_audio_init(adev);
5042 	if (r)
5043 		return r;
5044 
5045 	return 0;
5046 }
5047 
5048 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
5049 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
5050 #define AMDGPU_DM_MIN_SPREAD ((AMDGPU_DM_DEFAULT_MAX_BACKLIGHT - AMDGPU_DM_DEFAULT_MIN_BACKLIGHT) / 2)
5051 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
5052 
amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager * dm,int bl_idx)5053 static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
5054 					    int bl_idx)
5055 {
5056 	struct amdgpu_dm_backlight_caps *caps = &dm->backlight_caps[bl_idx];
5057 
5058 	if (caps->caps_valid)
5059 		return;
5060 
5061 #if defined(CONFIG_ACPI)
5062 	amdgpu_acpi_get_backlight_caps(caps);
5063 
5064 	/* validate the firmware value is sane */
5065 	if (caps->caps_valid) {
5066 		int spread = caps->max_input_signal - caps->min_input_signal;
5067 
5068 		if (caps->max_input_signal > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5069 		    caps->min_input_signal < 0 ||
5070 		    spread > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5071 		    spread < AMDGPU_DM_MIN_SPREAD) {
5072 			drm_dbg_kms(adev_to_drm(dm->adev), "DM: Invalid backlight caps: min=%d, max=%d\n",
5073 				      caps->min_input_signal, caps->max_input_signal);
5074 			caps->caps_valid = false;
5075 		}
5076 	}
5077 
5078 	if (!caps->caps_valid) {
5079 		caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5080 		caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5081 		caps->caps_valid = true;
5082 	}
5083 #else
5084 	if (caps->aux_support)
5085 		return;
5086 
5087 	caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5088 	caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5089 	caps->caps_valid = true;
5090 #endif
5091 }
5092 
get_brightness_range(const struct amdgpu_dm_backlight_caps * caps,unsigned int * min,unsigned int * max)5093 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
5094 				unsigned int *min, unsigned int *max)
5095 {
5096 	if (!caps)
5097 		return 0;
5098 
5099 	if (caps->aux_support) {
5100 		// Firmware limits are in nits, DC API wants millinits.
5101 		*max = 1000 * caps->aux_max_input_signal;
5102 		*min = 1000 * caps->aux_min_input_signal;
5103 	} else {
5104 		// Firmware limits are 8-bit, PWM control is 16-bit.
5105 		*max = 0x101 * caps->max_input_signal;
5106 		*min = 0x101 * caps->min_input_signal;
5107 	}
5108 	return 1;
5109 }
5110 
5111 /* Rescale from [min..max] to [0..AMDGPU_MAX_BL_LEVEL] */
scale_input_to_fw(int min,int max,u64 input)5112 static inline u32 scale_input_to_fw(int min, int max, u64 input)
5113 {
5114 	return DIV_ROUND_CLOSEST_ULL(input * AMDGPU_MAX_BL_LEVEL, max - min);
5115 }
5116 
5117 /* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [min..max] */
scale_fw_to_input(int min,int max,u64 input)5118 static inline u32 scale_fw_to_input(int min, int max, u64 input)
5119 {
5120 	return min + DIV_ROUND_CLOSEST_ULL(input * (max - min), AMDGPU_MAX_BL_LEVEL);
5121 }
5122 
convert_custom_brightness(const struct amdgpu_dm_backlight_caps * caps,unsigned int min,unsigned int max,uint32_t * user_brightness)5123 static void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps,
5124 				      unsigned int min, unsigned int max,
5125 				      uint32_t *user_brightness)
5126 {
5127 	u32 brightness = scale_input_to_fw(min, max, *user_brightness);
5128 	u8 lower_signal, upper_signal, upper_lum, lower_lum, lum;
5129 	int left, right;
5130 
5131 	if (amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)
5132 		return;
5133 
5134 	if (!caps->data_points)
5135 		return;
5136 
5137 	/*
5138 	 * Handle the case where brightness is below the first data point
5139 	 * Interpolate between (0,0) and (first_signal, first_lum)
5140 	 */
5141 	if (brightness < caps->luminance_data[0].input_signal) {
5142 		lum = DIV_ROUND_CLOSEST(caps->luminance_data[0].luminance * brightness,
5143 					caps->luminance_data[0].input_signal);
5144 		goto scale;
5145 	}
5146 
5147 	left = 0;
5148 	right = caps->data_points - 1;
5149 	while (left <= right) {
5150 		int mid = left + (right - left) / 2;
5151 		u8 signal = caps->luminance_data[mid].input_signal;
5152 
5153 		/* Exact match found */
5154 		if (signal == brightness) {
5155 			lum = caps->luminance_data[mid].luminance;
5156 			goto scale;
5157 		}
5158 
5159 		if (signal < brightness)
5160 			left = mid + 1;
5161 		else
5162 			right = mid - 1;
5163 	}
5164 
5165 	/* verify bound */
5166 	if (left >= caps->data_points)
5167 		left = caps->data_points - 1;
5168 
5169 	/* At this point, left > right */
5170 	lower_signal = caps->luminance_data[right].input_signal;
5171 	upper_signal = caps->luminance_data[left].input_signal;
5172 	lower_lum = caps->luminance_data[right].luminance;
5173 	upper_lum = caps->luminance_data[left].luminance;
5174 
5175 	/* interpolate */
5176 	if (right == left || !lower_lum)
5177 		lum = upper_lum;
5178 	else
5179 		lum = lower_lum + DIV_ROUND_CLOSEST((upper_lum - lower_lum) *
5180 						    (brightness - lower_signal),
5181 						    upper_signal - lower_signal);
5182 scale:
5183 	*user_brightness = scale_fw_to_input(min, max,
5184 					     DIV_ROUND_CLOSEST(lum * brightness, 101));
5185 }
5186 
convert_brightness_from_user(const struct amdgpu_dm_backlight_caps * caps,uint32_t brightness)5187 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
5188 					uint32_t brightness)
5189 {
5190 	unsigned int min, max;
5191 
5192 	if (!get_brightness_range(caps, &min, &max))
5193 		return brightness;
5194 
5195 	convert_custom_brightness(caps, min, max, &brightness);
5196 
5197 	// Rescale 0..max to min..max
5198 	return min + DIV_ROUND_CLOSEST_ULL((u64)(max - min) * brightness, max);
5199 }
5200 
convert_brightness_to_user(const struct amdgpu_dm_backlight_caps * caps,uint32_t brightness)5201 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
5202 				      uint32_t brightness)
5203 {
5204 	unsigned int min, max;
5205 
5206 	if (!get_brightness_range(caps, &min, &max))
5207 		return brightness;
5208 
5209 	if (brightness < min)
5210 		return 0;
5211 	// Rescale min..max to 0..max
5212 	return DIV_ROUND_CLOSEST_ULL((u64)max * (brightness - min),
5213 				 max - min);
5214 }
5215 
amdgpu_dm_backlight_set_level(struct amdgpu_display_manager * dm,int bl_idx,u32 user_brightness)5216 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
5217 					 int bl_idx,
5218 					 u32 user_brightness)
5219 {
5220 	struct amdgpu_dm_backlight_caps *caps;
5221 	struct dc_link *link;
5222 	u32 brightness;
5223 	bool rc, reallow_idle = false;
5224 	struct drm_connector *connector;
5225 
5226 	list_for_each_entry(connector, &dm->ddev->mode_config.connector_list, head) {
5227 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5228 
5229 		if (aconnector->bl_idx != bl_idx)
5230 			continue;
5231 
5232 		/* if connector is off, save the brightness for next time it's on */
5233 		if (!aconnector->base.encoder) {
5234 			dm->brightness[bl_idx] = user_brightness;
5235 			dm->actual_brightness[bl_idx] = 0;
5236 			return;
5237 		}
5238 	}
5239 
5240 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5241 	caps = &dm->backlight_caps[bl_idx];
5242 
5243 	dm->brightness[bl_idx] = user_brightness;
5244 	/* update scratch register */
5245 	if (bl_idx == 0)
5246 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
5247 	brightness = convert_brightness_from_user(caps, dm->brightness[bl_idx]);
5248 	link = (struct dc_link *)dm->backlight_link[bl_idx];
5249 
5250 	/* Apply brightness quirk */
5251 	if (caps->brightness_mask)
5252 		brightness |= caps->brightness_mask;
5253 
5254 	/* Change brightness based on AUX property */
5255 	mutex_lock(&dm->dc_lock);
5256 	if (dm->dc->caps.ips_support && dm->dc->ctx->dmub_srv->idle_allowed) {
5257 		dc_allow_idle_optimizations(dm->dc, false);
5258 		reallow_idle = true;
5259 	}
5260 
5261 	if (trace_amdgpu_dm_brightness_enabled()) {
5262 		trace_amdgpu_dm_brightness(__builtin_return_address(0),
5263 					   user_brightness,
5264 					   brightness,
5265 					   caps->aux_support,
5266 					   power_supply_is_system_supplied() > 0);
5267 	}
5268 
5269 	if (caps->aux_support) {
5270 		rc = dc_link_set_backlight_level_nits(link, true, brightness,
5271 						      AUX_BL_DEFAULT_TRANSITION_TIME_MS);
5272 		if (!rc)
5273 			DRM_DEBUG("DM: Failed to update backlight via AUX on eDP[%d]\n", bl_idx);
5274 	} else {
5275 		struct set_backlight_level_params backlight_level_params = { 0 };
5276 
5277 		backlight_level_params.backlight_pwm_u16_16 = brightness;
5278 		backlight_level_params.transition_time_in_ms = 0;
5279 
5280 		rc = dc_link_set_backlight_level(link, &backlight_level_params);
5281 		if (!rc)
5282 			DRM_DEBUG("DM: Failed to update backlight on eDP[%d]\n", bl_idx);
5283 	}
5284 
5285 	if (dm->dc->caps.ips_support && reallow_idle)
5286 		dc_allow_idle_optimizations(dm->dc, true);
5287 
5288 	mutex_unlock(&dm->dc_lock);
5289 
5290 	if (rc)
5291 		dm->actual_brightness[bl_idx] = user_brightness;
5292 }
5293 
amdgpu_dm_backlight_update_status(struct backlight_device * bd)5294 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
5295 {
5296 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5297 	int i;
5298 
5299 	for (i = 0; i < dm->num_of_edps; i++) {
5300 		if (bd == dm->backlight_dev[i])
5301 			break;
5302 	}
5303 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5304 		i = 0;
5305 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
5306 
5307 	return 0;
5308 }
5309 
amdgpu_dm_backlight_get_level(struct amdgpu_display_manager * dm,int bl_idx)5310 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
5311 					 int bl_idx)
5312 {
5313 	int ret;
5314 	struct amdgpu_dm_backlight_caps caps;
5315 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
5316 
5317 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5318 	caps = dm->backlight_caps[bl_idx];
5319 
5320 	if (caps.aux_support) {
5321 		u32 avg, peak;
5322 
5323 		if (!dc_link_get_backlight_level_nits(link, &avg, &peak))
5324 			return dm->brightness[bl_idx];
5325 		return convert_brightness_to_user(&caps, avg);
5326 	}
5327 
5328 	ret = dc_link_get_backlight_level(link);
5329 
5330 	if (ret == DC_ERROR_UNEXPECTED)
5331 		return dm->brightness[bl_idx];
5332 
5333 	return convert_brightness_to_user(&caps, ret);
5334 }
5335 
amdgpu_dm_backlight_get_brightness(struct backlight_device * bd)5336 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
5337 {
5338 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5339 	int i;
5340 
5341 	for (i = 0; i < dm->num_of_edps; i++) {
5342 		if (bd == dm->backlight_dev[i])
5343 			break;
5344 	}
5345 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5346 		i = 0;
5347 	return amdgpu_dm_backlight_get_level(dm, i);
5348 }
5349 
5350 static const struct backlight_ops amdgpu_dm_backlight_ops = {
5351 	.options = BL_CORE_SUSPENDRESUME,
5352 	.get_brightness = amdgpu_dm_backlight_get_brightness,
5353 	.update_status	= amdgpu_dm_backlight_update_status,
5354 };
5355 
5356 static void
amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector * aconnector)5357 amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector *aconnector)
5358 {
5359 	struct drm_device *drm = aconnector->base.dev;
5360 	struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
5361 	struct backlight_properties props = { 0 };
5362 	struct amdgpu_dm_backlight_caps *caps;
5363 	char bl_name[16];
5364 	int min, max;
5365 	int real_brightness;
5366 	int init_brightness;
5367 
5368 	if (aconnector->bl_idx == -1)
5369 		return;
5370 
5371 	if (!acpi_video_backlight_use_native()) {
5372 		drm_info(drm, "Skipping amdgpu DM backlight registration\n");
5373 		/* Try registering an ACPI video backlight device instead. */
5374 		acpi_video_register_backlight();
5375 		return;
5376 	}
5377 
5378 	caps = &dm->backlight_caps[aconnector->bl_idx];
5379 	if (get_brightness_range(caps, &min, &max)) {
5380 		if (power_supply_is_system_supplied() > 0)
5381 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->ac_level, 100);
5382 		else
5383 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->dc_level, 100);
5384 		/* min is zero, so max needs to be adjusted */
5385 		props.max_brightness = max - min;
5386 		drm_dbg(drm, "Backlight caps: min: %d, max: %d, ac %d, dc %d\n", min, max,
5387 			caps->ac_level, caps->dc_level);
5388 	} else
5389 		props.brightness = props.max_brightness = MAX_BACKLIGHT_LEVEL;
5390 
5391 	init_brightness = props.brightness;
5392 
5393 	if (caps->data_points && !(amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)) {
5394 		drm_info(drm, "Using custom brightness curve\n");
5395 		props.scale = BACKLIGHT_SCALE_NON_LINEAR;
5396 	} else
5397 		props.scale = BACKLIGHT_SCALE_LINEAR;
5398 	props.type = BACKLIGHT_RAW;
5399 
5400 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
5401 		 drm->primary->index + aconnector->bl_idx);
5402 
5403 	dm->backlight_dev[aconnector->bl_idx] =
5404 		backlight_device_register(bl_name, aconnector->base.kdev, dm,
5405 					  &amdgpu_dm_backlight_ops, &props);
5406 	dm->brightness[aconnector->bl_idx] = props.brightness;
5407 
5408 	if (IS_ERR(dm->backlight_dev[aconnector->bl_idx])) {
5409 		drm_err(drm, "DM: Backlight registration failed!\n");
5410 		dm->backlight_dev[aconnector->bl_idx] = NULL;
5411 	} else {
5412 		/*
5413 		 * dm->brightness[x] can be inconsistent just after startup until
5414 		 * ops.get_brightness is called.
5415 		 */
5416 		real_brightness =
5417 			amdgpu_dm_backlight_ops.get_brightness(dm->backlight_dev[aconnector->bl_idx]);
5418 
5419 		if (real_brightness != init_brightness) {
5420 			dm->actual_brightness[aconnector->bl_idx] = real_brightness;
5421 			dm->brightness[aconnector->bl_idx] = real_brightness;
5422 		}
5423 		drm_dbg_driver(drm, "DM: Registered Backlight device: %s\n", bl_name);
5424 	}
5425 }
5426 
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)5427 static int initialize_plane(struct amdgpu_display_manager *dm,
5428 			    struct amdgpu_mode_info *mode_info, int plane_id,
5429 			    enum drm_plane_type plane_type,
5430 			    const struct dc_plane_cap *plane_cap)
5431 {
5432 	struct drm_plane *plane;
5433 	unsigned long possible_crtcs;
5434 	int ret = 0;
5435 
5436 	plane = kzalloc_obj(struct drm_plane);
5437 	if (!plane) {
5438 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
5439 		return -ENOMEM;
5440 	}
5441 	plane->type = plane_type;
5442 
5443 	/*
5444 	 * HACK: IGT tests expect that the primary plane for a CRTC
5445 	 * can only have one possible CRTC. Only expose support for
5446 	 * any CRTC if they're not going to be used as a primary plane
5447 	 * for a CRTC - like overlay or underlay planes.
5448 	 */
5449 	possible_crtcs = 1 << plane_id;
5450 	if (plane_id >= dm->dc->caps.max_streams)
5451 		possible_crtcs = 0xff;
5452 
5453 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
5454 
5455 	if (ret) {
5456 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
5457 		kfree(plane);
5458 		return ret;
5459 	}
5460 
5461 	if (mode_info)
5462 		mode_info->planes[plane_id] = plane;
5463 
5464 	return ret;
5465 }
5466 
5467 
setup_backlight_device(struct amdgpu_display_manager * dm,struct amdgpu_dm_connector * aconnector)5468 static void setup_backlight_device(struct amdgpu_display_manager *dm,
5469 				   struct amdgpu_dm_connector *aconnector)
5470 {
5471 	struct amdgpu_dm_backlight_caps *caps;
5472 	struct dc_link *link = aconnector->dc_link;
5473 	int bl_idx = dm->num_of_edps;
5474 
5475 	if (!(link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) ||
5476 	    link->type == dc_connection_none)
5477 		return;
5478 
5479 	if (dm->num_of_edps >= AMDGPU_DM_MAX_NUM_EDP) {
5480 		drm_warn(adev_to_drm(dm->adev), "Too much eDP connections, skipping backlight setup for additional eDPs\n");
5481 		return;
5482 	}
5483 
5484 	aconnector->bl_idx = bl_idx;
5485 
5486 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5487 	dm->backlight_link[bl_idx] = link;
5488 	dm->num_of_edps++;
5489 
5490 	update_connector_ext_caps(aconnector);
5491 	caps = &dm->backlight_caps[aconnector->bl_idx];
5492 
5493 	/* Only offer ABM property when non-OLED and user didn't turn off by module parameter */
5494 	if (caps->ext_caps && !caps->ext_caps->bits.oled && amdgpu_dm_abm_level < 0)
5495 		drm_object_attach_property(&aconnector->base.base,
5496 					   dm->adev->mode_info.abm_level_property,
5497 					   ABM_SYSFS_CONTROL);
5498 }
5499 
5500 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
5501 
5502 /*
5503  * In this architecture, the association
5504  * connector -> encoder -> crtc
5505  * id not really requried. The crtc and connector will hold the
5506  * display_index as an abstraction to use with DAL component
5507  *
5508  * Returns 0 on success
5509  */
amdgpu_dm_initialize_drm_device(struct amdgpu_device * adev)5510 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
5511 {
5512 	struct amdgpu_display_manager *dm = &adev->dm;
5513 	s32 i;
5514 	struct amdgpu_dm_connector *aconnector = NULL;
5515 	struct amdgpu_encoder *aencoder = NULL;
5516 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5517 	u32 link_cnt;
5518 	s32 primary_planes;
5519 	enum dc_connection_type new_connection_type = dc_connection_none;
5520 	const struct dc_plane_cap *plane;
5521 	bool psr_feature_enabled = false;
5522 	bool replay_feature_enabled = false;
5523 	int max_overlay = dm->dc->caps.max_slave_planes;
5524 
5525 	dm->display_indexes_num = dm->dc->caps.max_streams;
5526 	/* Update the actual used number of crtc */
5527 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
5528 
5529 	amdgpu_dm_set_irq_funcs(adev);
5530 
5531 	link_cnt = dm->dc->caps.max_links;
5532 	if (amdgpu_dm_mode_config_init(dm->adev)) {
5533 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
5534 		return -EINVAL;
5535 	}
5536 
5537 	/* There is one primary plane per CRTC */
5538 	primary_planes = dm->dc->caps.max_streams;
5539 	if (primary_planes > AMDGPU_MAX_PLANES) {
5540 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
5541 		return -EINVAL;
5542 	}
5543 
5544 	/*
5545 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
5546 	 * Order is reversed to match iteration order in atomic check.
5547 	 */
5548 	for (i = (primary_planes - 1); i >= 0; i--) {
5549 		plane = &dm->dc->caps.planes[i];
5550 
5551 		if (initialize_plane(dm, mode_info, i,
5552 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
5553 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
5554 			goto fail;
5555 		}
5556 	}
5557 
5558 	/*
5559 	 * Initialize overlay planes, index starting after primary planes.
5560 	 * These planes have a higher DRM index than the primary planes since
5561 	 * they should be considered as having a higher z-order.
5562 	 * Order is reversed to match iteration order in atomic check.
5563 	 *
5564 	 * Only support DCN for now, and only expose one so we don't encourage
5565 	 * userspace to use up all the pipes.
5566 	 */
5567 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
5568 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
5569 
5570 		/* Do not create overlay if MPO disabled */
5571 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
5572 			break;
5573 
5574 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
5575 			continue;
5576 
5577 		if (!plane->pixel_format_support.argb8888)
5578 			continue;
5579 
5580 		if (max_overlay-- == 0)
5581 			break;
5582 
5583 		if (initialize_plane(dm, NULL, primary_planes + i,
5584 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
5585 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
5586 			goto fail;
5587 		}
5588 	}
5589 
5590 	for (i = 0; i < dm->dc->caps.max_streams; i++)
5591 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
5592 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
5593 			goto fail;
5594 		}
5595 
5596 	/* Use Outbox interrupt */
5597 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5598 	case IP_VERSION(3, 0, 0):
5599 	case IP_VERSION(3, 1, 2):
5600 	case IP_VERSION(3, 1, 3):
5601 	case IP_VERSION(3, 1, 4):
5602 	case IP_VERSION(3, 1, 5):
5603 	case IP_VERSION(3, 1, 6):
5604 	case IP_VERSION(3, 2, 0):
5605 	case IP_VERSION(3, 2, 1):
5606 	case IP_VERSION(2, 1, 0):
5607 	case IP_VERSION(3, 5, 0):
5608 	case IP_VERSION(3, 5, 1):
5609 	case IP_VERSION(3, 6, 0):
5610 	case IP_VERSION(4, 0, 1):
5611 	case IP_VERSION(4, 2, 0):
5612 		if (register_outbox_irq_handlers(dm->adev)) {
5613 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5614 			goto fail;
5615 		}
5616 		break;
5617 	default:
5618 		drm_dbg_kms(adev_to_drm(adev), "Unsupported DCN IP version for outbox: 0x%X\n",
5619 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
5620 	}
5621 
5622 	/* Determine whether to enable PSR support by default. */
5623 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
5624 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5625 		case IP_VERSION(3, 1, 2):
5626 		case IP_VERSION(3, 1, 3):
5627 		case IP_VERSION(3, 1, 4):
5628 		case IP_VERSION(3, 1, 5):
5629 		case IP_VERSION(3, 1, 6):
5630 		case IP_VERSION(3, 2, 0):
5631 		case IP_VERSION(3, 2, 1):
5632 		case IP_VERSION(3, 5, 0):
5633 		case IP_VERSION(3, 5, 1):
5634 		case IP_VERSION(3, 6, 0):
5635 		case IP_VERSION(4, 0, 1):
5636 		case IP_VERSION(4, 2, 0):
5637 			psr_feature_enabled = true;
5638 			break;
5639 		default:
5640 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
5641 			break;
5642 		}
5643 	}
5644 
5645 	/* Determine whether to enable Replay support by default. */
5646 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
5647 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5648 		case IP_VERSION(3, 1, 4):
5649 		case IP_VERSION(3, 2, 0):
5650 		case IP_VERSION(3, 2, 1):
5651 		case IP_VERSION(3, 5, 0):
5652 		case IP_VERSION(3, 5, 1):
5653 		case IP_VERSION(3, 6, 0):
5654 		case IP_VERSION(4, 2, 0):
5655 			replay_feature_enabled = true;
5656 			break;
5657 
5658 		default:
5659 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
5660 			break;
5661 		}
5662 	}
5663 
5664 	if (link_cnt > MAX_LINKS) {
5665 		drm_err(adev_to_drm(adev),
5666 			"KMS: Cannot support more than %d display indexes\n",
5667 				MAX_LINKS);
5668 		goto fail;
5669 	}
5670 
5671 	/* loops over all connectors on the board */
5672 	for (i = 0; i < link_cnt; i++) {
5673 		struct dc_link *link = NULL;
5674 
5675 		link = dc_get_link_at_index(dm->dc, i);
5676 
5677 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
5678 			struct amdgpu_dm_wb_connector *wbcon = kzalloc_obj(*wbcon);
5679 
5680 			if (!wbcon) {
5681 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
5682 				continue;
5683 			}
5684 
5685 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
5686 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
5687 				kfree(wbcon);
5688 				continue;
5689 			}
5690 
5691 			link->psr_settings.psr_feature_enabled = false;
5692 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
5693 
5694 			continue;
5695 		}
5696 
5697 		aconnector = kzalloc_obj(*aconnector);
5698 		if (!aconnector)
5699 			goto fail;
5700 
5701 		aencoder = kzalloc_obj(*aencoder);
5702 		if (!aencoder)
5703 			goto fail;
5704 
5705 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
5706 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
5707 			goto fail;
5708 		}
5709 
5710 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
5711 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
5712 			goto fail;
5713 		}
5714 
5715 		if (dm->hpd_rx_offload_wq)
5716 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
5717 				aconnector;
5718 
5719 		if (!dc_link_detect_connection_type(link, &new_connection_type))
5720 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
5721 
5722 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
5723 			emulated_link_detect(link);
5724 			amdgpu_dm_update_connector_after_detect(aconnector);
5725 		} else {
5726 			bool ret = false;
5727 
5728 			mutex_lock(&dm->dc_lock);
5729 			dc_exit_ips_for_hw_access(dm->dc);
5730 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
5731 			mutex_unlock(&dm->dc_lock);
5732 
5733 			if (ret) {
5734 				amdgpu_dm_update_connector_after_detect(aconnector);
5735 				setup_backlight_device(dm, aconnector);
5736 
5737 				/* Disable PSR if Replay can be enabled */
5738 				if (replay_feature_enabled)
5739 					if (amdgpu_dm_set_replay_caps(link, aconnector))
5740 						psr_feature_enabled = false;
5741 
5742 				if (psr_feature_enabled) {
5743 					amdgpu_dm_set_psr_caps(link);
5744 					drm_info(adev_to_drm(adev), "%s: PSR support %d, DC PSR ver %d, sink PSR ver %d DPCD caps 0x%x su_y_granularity %d\n",
5745 						 aconnector->base.name,
5746 						 link->psr_settings.psr_feature_enabled,
5747 						 link->psr_settings.psr_version,
5748 						 link->dpcd_caps.psr_info.psr_version,
5749 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
5750 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
5751 				}
5752 			}
5753 		}
5754 		amdgpu_set_panel_orientation(&aconnector->base);
5755 	}
5756 
5757 	/* Debug dump: list all DC links and their associated sinks after detection
5758 	 * is complete for all connectors. This provides a comprehensive view of the
5759 	 * final state without repeating the dump for each connector.
5760 	 */
5761 	amdgpu_dm_dump_links_and_sinks(adev);
5762 
5763 	/* Software is initialized. Now we can register interrupt handlers. */
5764 	switch (adev->asic_type) {
5765 #if defined(CONFIG_DRM_AMD_DC_SI)
5766 	case CHIP_TAHITI:
5767 	case CHIP_PITCAIRN:
5768 	case CHIP_VERDE:
5769 	case CHIP_OLAND:
5770 #endif
5771 	case CHIP_BONAIRE:
5772 	case CHIP_HAWAII:
5773 	case CHIP_KAVERI:
5774 	case CHIP_KABINI:
5775 	case CHIP_MULLINS:
5776 	case CHIP_TONGA:
5777 	case CHIP_FIJI:
5778 	case CHIP_CARRIZO:
5779 	case CHIP_STONEY:
5780 	case CHIP_POLARIS11:
5781 	case CHIP_POLARIS10:
5782 	case CHIP_POLARIS12:
5783 	case CHIP_VEGAM:
5784 	case CHIP_VEGA10:
5785 	case CHIP_VEGA12:
5786 	case CHIP_VEGA20:
5787 		if (dce110_register_irq_handlers(dm->adev)) {
5788 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5789 			goto fail;
5790 		}
5791 		break;
5792 	default:
5793 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5794 		case IP_VERSION(1, 0, 0):
5795 		case IP_VERSION(1, 0, 1):
5796 		case IP_VERSION(2, 0, 2):
5797 		case IP_VERSION(2, 0, 3):
5798 		case IP_VERSION(2, 0, 0):
5799 		case IP_VERSION(2, 1, 0):
5800 		case IP_VERSION(3, 0, 0):
5801 		case IP_VERSION(3, 0, 2):
5802 		case IP_VERSION(3, 0, 3):
5803 		case IP_VERSION(3, 0, 1):
5804 		case IP_VERSION(3, 1, 2):
5805 		case IP_VERSION(3, 1, 3):
5806 		case IP_VERSION(3, 1, 4):
5807 		case IP_VERSION(3, 1, 5):
5808 		case IP_VERSION(3, 1, 6):
5809 		case IP_VERSION(3, 2, 0):
5810 		case IP_VERSION(3, 2, 1):
5811 		case IP_VERSION(3, 5, 0):
5812 		case IP_VERSION(3, 5, 1):
5813 		case IP_VERSION(3, 6, 0):
5814 		case IP_VERSION(4, 0, 1):
5815 		case IP_VERSION(4, 2, 0):
5816 			if (dcn10_register_irq_handlers(dm->adev)) {
5817 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5818 				goto fail;
5819 			}
5820 			break;
5821 		default:
5822 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
5823 					amdgpu_ip_version(adev, DCE_HWIP, 0));
5824 			goto fail;
5825 		}
5826 		break;
5827 	}
5828 
5829 	return 0;
5830 fail:
5831 	kfree(aencoder);
5832 	kfree(aconnector);
5833 
5834 	return -EINVAL;
5835 }
5836 
amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager * dm)5837 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
5838 {
5839 	if (dm->atomic_obj.state)
5840 		drm_atomic_private_obj_fini(&dm->atomic_obj);
5841 }
5842 
5843 /******************************************************************************
5844  * amdgpu_display_funcs functions
5845  *****************************************************************************/
5846 
5847 /*
5848  * dm_bandwidth_update - program display watermarks
5849  *
5850  * @adev: amdgpu_device pointer
5851  *
5852  * Calculate and program the display watermarks and line buffer allocation.
5853  */
dm_bandwidth_update(struct amdgpu_device * adev)5854 static void dm_bandwidth_update(struct amdgpu_device *adev)
5855 {
5856 	/* TODO: implement later */
5857 }
5858 
5859 static const struct amdgpu_display_funcs dm_display_funcs = {
5860 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
5861 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
5862 	.backlight_set_level = NULL, /* never called for DC */
5863 	.backlight_get_level = NULL, /* never called for DC */
5864 	.hpd_sense = NULL,/* called unconditionally */
5865 	.hpd_set_polarity = NULL, /* called unconditionally */
5866 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
5867 	.page_flip_get_scanoutpos =
5868 		dm_crtc_get_scanoutpos,/* called unconditionally */
5869 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
5870 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
5871 };
5872 
5873 #if defined(CONFIG_DEBUG_KERNEL_DC)
5874 
s3_debug_store(struct device * device,struct device_attribute * attr,const char * buf,size_t count)5875 static ssize_t s3_debug_store(struct device *device,
5876 			      struct device_attribute *attr,
5877 			      const char *buf,
5878 			      size_t count)
5879 {
5880 	int ret;
5881 	int s3_state;
5882 	struct drm_device *drm_dev = dev_get_drvdata(device);
5883 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
5884 	struct amdgpu_ip_block *ip_block;
5885 
5886 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
5887 	if (!ip_block)
5888 		return -EINVAL;
5889 
5890 	ret = kstrtoint(buf, 0, &s3_state);
5891 
5892 	if (ret == 0) {
5893 		if (s3_state) {
5894 			dm_resume(ip_block);
5895 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
5896 		} else
5897 			dm_suspend(ip_block);
5898 	}
5899 
5900 	return ret == 0 ? count : 0;
5901 }
5902 
5903 DEVICE_ATTR_WO(s3_debug);
5904 
5905 #endif
5906 
dm_init_microcode(struct amdgpu_device * adev)5907 static int dm_init_microcode(struct amdgpu_device *adev)
5908 {
5909 	char *fw_name_dmub;
5910 	int r;
5911 
5912 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5913 	case IP_VERSION(2, 1, 0):
5914 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
5915 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
5916 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
5917 		break;
5918 	case IP_VERSION(3, 0, 0):
5919 		if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(10, 3, 0))
5920 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
5921 		else
5922 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
5923 		break;
5924 	case IP_VERSION(3, 0, 1):
5925 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
5926 		break;
5927 	case IP_VERSION(3, 0, 2):
5928 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
5929 		break;
5930 	case IP_VERSION(3, 0, 3):
5931 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
5932 		break;
5933 	case IP_VERSION(3, 1, 2):
5934 	case IP_VERSION(3, 1, 3):
5935 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
5936 		break;
5937 	case IP_VERSION(3, 1, 4):
5938 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
5939 		break;
5940 	case IP_VERSION(3, 1, 5):
5941 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
5942 		break;
5943 	case IP_VERSION(3, 1, 6):
5944 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
5945 		break;
5946 	case IP_VERSION(3, 2, 0):
5947 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
5948 		break;
5949 	case IP_VERSION(3, 2, 1):
5950 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
5951 		break;
5952 	case IP_VERSION(3, 5, 0):
5953 		fw_name_dmub = FIRMWARE_DCN_35_DMUB;
5954 		break;
5955 	case IP_VERSION(3, 5, 1):
5956 		fw_name_dmub = FIRMWARE_DCN_351_DMUB;
5957 		break;
5958 	case IP_VERSION(3, 6, 0):
5959 		fw_name_dmub = FIRMWARE_DCN_36_DMUB;
5960 		break;
5961 	case IP_VERSION(4, 0, 1):
5962 		fw_name_dmub = FIRMWARE_DCN_401_DMUB;
5963 		break;
5964 	case IP_VERSION(4, 2, 0):
5965 		fw_name_dmub = FIRMWARE_DCN_42_DMUB;
5966 		break;
5967 	default:
5968 		/* ASIC doesn't support DMUB. */
5969 		return 0;
5970 	}
5971 	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, AMDGPU_UCODE_REQUIRED,
5972 				 "%s", fw_name_dmub);
5973 	return r;
5974 }
5975 
dm_early_init(struct amdgpu_ip_block * ip_block)5976 static int dm_early_init(struct amdgpu_ip_block *ip_block)
5977 {
5978 	struct amdgpu_device *adev = ip_block->adev;
5979 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5980 	struct atom_context *ctx = mode_info->atom_context;
5981 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
5982 	u16 data_offset;
5983 
5984 	/* if there is no object header, skip DM */
5985 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
5986 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
5987 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
5988 		return -ENOENT;
5989 	}
5990 
5991 	switch (adev->asic_type) {
5992 #if defined(CONFIG_DRM_AMD_DC_SI)
5993 	case CHIP_TAHITI:
5994 	case CHIP_PITCAIRN:
5995 	case CHIP_VERDE:
5996 		adev->mode_info.num_crtc = 6;
5997 		adev->mode_info.num_hpd = 6;
5998 		adev->mode_info.num_dig = 6;
5999 		break;
6000 	case CHIP_OLAND:
6001 		adev->mode_info.num_crtc = 2;
6002 		adev->mode_info.num_hpd = 2;
6003 		adev->mode_info.num_dig = 2;
6004 		break;
6005 #endif
6006 	case CHIP_BONAIRE:
6007 	case CHIP_HAWAII:
6008 		adev->mode_info.num_crtc = 6;
6009 		adev->mode_info.num_hpd = 6;
6010 		adev->mode_info.num_dig = 6;
6011 		break;
6012 	case CHIP_KAVERI:
6013 		adev->mode_info.num_crtc = 4;
6014 		adev->mode_info.num_hpd = 6;
6015 		adev->mode_info.num_dig = 7;
6016 		break;
6017 	case CHIP_KABINI:
6018 	case CHIP_MULLINS:
6019 		adev->mode_info.num_crtc = 2;
6020 		adev->mode_info.num_hpd = 6;
6021 		adev->mode_info.num_dig = 6;
6022 		break;
6023 	case CHIP_FIJI:
6024 	case CHIP_TONGA:
6025 		adev->mode_info.num_crtc = 6;
6026 		adev->mode_info.num_hpd = 6;
6027 		adev->mode_info.num_dig = 7;
6028 		break;
6029 	case CHIP_CARRIZO:
6030 		adev->mode_info.num_crtc = 3;
6031 		adev->mode_info.num_hpd = 6;
6032 		adev->mode_info.num_dig = 9;
6033 		break;
6034 	case CHIP_STONEY:
6035 		adev->mode_info.num_crtc = 2;
6036 		adev->mode_info.num_hpd = 6;
6037 		adev->mode_info.num_dig = 9;
6038 		break;
6039 	case CHIP_POLARIS11:
6040 	case CHIP_POLARIS12:
6041 		adev->mode_info.num_crtc = 5;
6042 		adev->mode_info.num_hpd = 5;
6043 		adev->mode_info.num_dig = 5;
6044 		break;
6045 	case CHIP_POLARIS10:
6046 	case CHIP_VEGAM:
6047 		adev->mode_info.num_crtc = 6;
6048 		adev->mode_info.num_hpd = 6;
6049 		adev->mode_info.num_dig = 6;
6050 		break;
6051 	case CHIP_VEGA10:
6052 	case CHIP_VEGA12:
6053 	case CHIP_VEGA20:
6054 		adev->mode_info.num_crtc = 6;
6055 		adev->mode_info.num_hpd = 6;
6056 		adev->mode_info.num_dig = 6;
6057 		break;
6058 	default:
6059 
6060 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
6061 		case IP_VERSION(2, 0, 2):
6062 		case IP_VERSION(3, 0, 0):
6063 			adev->mode_info.num_crtc = 6;
6064 			adev->mode_info.num_hpd = 6;
6065 			adev->mode_info.num_dig = 6;
6066 			break;
6067 		case IP_VERSION(2, 0, 0):
6068 		case IP_VERSION(3, 0, 2):
6069 			adev->mode_info.num_crtc = 5;
6070 			adev->mode_info.num_hpd = 5;
6071 			adev->mode_info.num_dig = 5;
6072 			break;
6073 		case IP_VERSION(2, 0, 3):
6074 		case IP_VERSION(3, 0, 3):
6075 			adev->mode_info.num_crtc = 2;
6076 			adev->mode_info.num_hpd = 2;
6077 			adev->mode_info.num_dig = 2;
6078 			break;
6079 		case IP_VERSION(1, 0, 0):
6080 		case IP_VERSION(1, 0, 1):
6081 		case IP_VERSION(3, 0, 1):
6082 		case IP_VERSION(2, 1, 0):
6083 		case IP_VERSION(3, 1, 2):
6084 		case IP_VERSION(3, 1, 3):
6085 		case IP_VERSION(3, 1, 4):
6086 		case IP_VERSION(3, 1, 5):
6087 		case IP_VERSION(3, 1, 6):
6088 		case IP_VERSION(3, 2, 0):
6089 		case IP_VERSION(3, 2, 1):
6090 		case IP_VERSION(3, 5, 0):
6091 		case IP_VERSION(3, 5, 1):
6092 		case IP_VERSION(3, 6, 0):
6093 		case IP_VERSION(4, 0, 1):
6094 		case IP_VERSION(4, 2, 0):
6095 			adev->mode_info.num_crtc = 4;
6096 			adev->mode_info.num_hpd = 4;
6097 			adev->mode_info.num_dig = 4;
6098 			break;
6099 		default:
6100 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
6101 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6102 			return -EINVAL;
6103 		}
6104 		break;
6105 	}
6106 
6107 	if (adev->mode_info.funcs == NULL)
6108 		adev->mode_info.funcs = &dm_display_funcs;
6109 
6110 	/*
6111 	 * Note: Do NOT change adev->reg.audio_endpt.rreg and
6112 	 * adev->reg.audio_endpt.wreg because they are initialised in
6113 	 * amdgpu_device_init()
6114 	 */
6115 #if defined(CONFIG_DEBUG_KERNEL_DC)
6116 	device_create_file(
6117 		adev_to_drm(adev)->dev,
6118 		&dev_attr_s3_debug);
6119 #endif
6120 	adev->dc_enabled = true;
6121 
6122 	return dm_init_microcode(adev);
6123 }
6124 
modereset_required(struct drm_crtc_state * crtc_state)6125 static bool modereset_required(struct drm_crtc_state *crtc_state)
6126 {
6127 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
6128 }
6129 
amdgpu_dm_encoder_destroy(struct drm_encoder * encoder)6130 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
6131 {
6132 	drm_encoder_cleanup(encoder);
6133 	kfree(encoder);
6134 }
6135 
6136 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
6137 	.destroy = amdgpu_dm_encoder_destroy,
6138 };
6139 
6140 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)6141 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
6142 			    const enum surface_pixel_format format,
6143 			    enum dc_color_space *color_space)
6144 {
6145 	bool full_range;
6146 
6147 	*color_space = COLOR_SPACE_SRGB;
6148 
6149 	/* Ignore properties when DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE is set */
6150 	if (plane_state->state && plane_state->state->plane_color_pipeline)
6151 		return 0;
6152 
6153 	/* DRM color properties only affect non-RGB formats. */
6154 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
6155 		return 0;
6156 
6157 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
6158 
6159 	switch (plane_state->color_encoding) {
6160 	case DRM_COLOR_YCBCR_BT601:
6161 		if (full_range)
6162 			*color_space = COLOR_SPACE_YCBCR601;
6163 		else
6164 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
6165 		break;
6166 
6167 	case DRM_COLOR_YCBCR_BT709:
6168 		if (full_range)
6169 			*color_space = COLOR_SPACE_YCBCR709;
6170 		else
6171 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
6172 		break;
6173 
6174 	case DRM_COLOR_YCBCR_BT2020:
6175 		if (full_range)
6176 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
6177 		else
6178 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6179 		break;
6180 
6181 	default:
6182 		return -EINVAL;
6183 	}
6184 
6185 	return 0;
6186 }
6187 
6188 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)6189 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
6190 			    const struct drm_plane_state *plane_state,
6191 			    const u64 tiling_flags,
6192 			    struct dc_plane_info *plane_info,
6193 			    struct dc_plane_address *address,
6194 			    bool tmz_surface)
6195 {
6196 	const struct drm_framebuffer *fb = plane_state->fb;
6197 	const struct amdgpu_framebuffer *afb =
6198 		to_amdgpu_framebuffer(plane_state->fb);
6199 	int ret;
6200 
6201 	memset(plane_info, 0, sizeof(*plane_info));
6202 
6203 	switch (fb->format->format) {
6204 	case DRM_FORMAT_C8:
6205 		plane_info->format =
6206 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
6207 		break;
6208 	case DRM_FORMAT_RGB565:
6209 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
6210 		break;
6211 	case DRM_FORMAT_XRGB8888:
6212 	case DRM_FORMAT_ARGB8888:
6213 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6214 		break;
6215 	case DRM_FORMAT_XRGB2101010:
6216 	case DRM_FORMAT_ARGB2101010:
6217 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
6218 		break;
6219 	case DRM_FORMAT_XBGR2101010:
6220 	case DRM_FORMAT_ABGR2101010:
6221 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
6222 		break;
6223 	case DRM_FORMAT_XBGR8888:
6224 	case DRM_FORMAT_ABGR8888:
6225 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
6226 		break;
6227 	case DRM_FORMAT_NV21:
6228 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
6229 		break;
6230 	case DRM_FORMAT_NV12:
6231 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
6232 		break;
6233 	case DRM_FORMAT_P010:
6234 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
6235 		break;
6236 	case DRM_FORMAT_XRGB16161616F:
6237 	case DRM_FORMAT_ARGB16161616F:
6238 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
6239 		break;
6240 	case DRM_FORMAT_XBGR16161616F:
6241 	case DRM_FORMAT_ABGR16161616F:
6242 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
6243 		break;
6244 	case DRM_FORMAT_XRGB16161616:
6245 	case DRM_FORMAT_ARGB16161616:
6246 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
6247 		break;
6248 	case DRM_FORMAT_XBGR16161616:
6249 	case DRM_FORMAT_ABGR16161616:
6250 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
6251 		break;
6252 	default:
6253 		drm_err(adev_to_drm(adev),
6254 			"Unsupported screen format %p4cc\n",
6255 			&fb->format->format);
6256 		return -EINVAL;
6257 	}
6258 
6259 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
6260 	case DRM_MODE_ROTATE_0:
6261 		plane_info->rotation = ROTATION_ANGLE_0;
6262 		break;
6263 	case DRM_MODE_ROTATE_90:
6264 		plane_info->rotation = ROTATION_ANGLE_90;
6265 		break;
6266 	case DRM_MODE_ROTATE_180:
6267 		plane_info->rotation = ROTATION_ANGLE_180;
6268 		break;
6269 	case DRM_MODE_ROTATE_270:
6270 		plane_info->rotation = ROTATION_ANGLE_270;
6271 		break;
6272 	default:
6273 		plane_info->rotation = ROTATION_ANGLE_0;
6274 		break;
6275 	}
6276 
6277 
6278 	plane_info->visible = true;
6279 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
6280 
6281 	plane_info->layer_index = plane_state->normalized_zpos;
6282 
6283 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
6284 					  &plane_info->color_space);
6285 	if (ret)
6286 		return ret;
6287 
6288 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
6289 					   plane_info->rotation, tiling_flags,
6290 					   &plane_info->tiling_info,
6291 					   &plane_info->plane_size,
6292 					   &plane_info->dcc, address,
6293 					   tmz_surface);
6294 	if (ret)
6295 		return ret;
6296 
6297 	amdgpu_dm_plane_fill_blending_from_plane_state(
6298 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
6299 		&plane_info->global_alpha, &plane_info->global_alpha_value);
6300 
6301 	return 0;
6302 }
6303 
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)6304 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
6305 				    struct dc_plane_state *dc_plane_state,
6306 				    struct drm_plane_state *plane_state,
6307 				    struct drm_crtc_state *crtc_state)
6308 {
6309 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6310 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
6311 	struct dc_scaling_info scaling_info;
6312 	struct dc_plane_info plane_info;
6313 	int ret;
6314 
6315 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
6316 	if (ret)
6317 		return ret;
6318 
6319 	dc_plane_state->src_rect = scaling_info.src_rect;
6320 	dc_plane_state->dst_rect = scaling_info.dst_rect;
6321 	dc_plane_state->clip_rect = scaling_info.clip_rect;
6322 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
6323 
6324 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
6325 					  afb->tiling_flags,
6326 					  &plane_info,
6327 					  &dc_plane_state->address,
6328 					  afb->tmz_surface);
6329 	if (ret)
6330 		return ret;
6331 
6332 	dc_plane_state->format = plane_info.format;
6333 	dc_plane_state->color_space = plane_info.color_space;
6334 	dc_plane_state->format = plane_info.format;
6335 	dc_plane_state->plane_size = plane_info.plane_size;
6336 	dc_plane_state->rotation = plane_info.rotation;
6337 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
6338 	dc_plane_state->stereo_format = plane_info.stereo_format;
6339 	dc_plane_state->tiling_info = plane_info.tiling_info;
6340 	dc_plane_state->visible = plane_info.visible;
6341 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
6342 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
6343 	dc_plane_state->global_alpha = plane_info.global_alpha;
6344 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
6345 	dc_plane_state->dcc = plane_info.dcc;
6346 	dc_plane_state->layer_index = plane_info.layer_index;
6347 	dc_plane_state->flip_int_enabled = true;
6348 
6349 	/*
6350 	 * Always set input transfer function, since plane state is refreshed
6351 	 * every time.
6352 	 */
6353 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
6354 						plane_state,
6355 						dc_plane_state);
6356 	if (ret)
6357 		return ret;
6358 
6359 	return 0;
6360 }
6361 
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)6362 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
6363 				      struct rect *dirty_rect, int32_t x,
6364 				      s32 y, s32 width, s32 height,
6365 				      int *i, bool ffu)
6366 {
6367 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
6368 
6369 	dirty_rect->x = x;
6370 	dirty_rect->y = y;
6371 	dirty_rect->width = width;
6372 	dirty_rect->height = height;
6373 
6374 	if (ffu)
6375 		drm_dbg(plane->dev,
6376 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
6377 			plane->base.id, width, height);
6378 	else
6379 		drm_dbg(plane->dev,
6380 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
6381 			plane->base.id, x, y, width, height);
6382 
6383 	(*i)++;
6384 }
6385 
6386 /**
6387  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
6388  *
6389  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
6390  *         remote fb
6391  * @old_plane_state: Old state of @plane
6392  * @new_plane_state: New state of @plane
6393  * @crtc_state: New state of CRTC connected to the @plane
6394  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
6395  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
6396  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
6397  *             that have changed will be updated. If PSR SU is not enabled,
6398  *             or if damage clips are not available, the entire screen will be updated.
6399  * @dirty_regions_changed: dirty regions changed
6400  *
6401  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
6402  * (referred to as "damage clips" in DRM nomenclature) that require updating on
6403  * the eDP remote buffer. The responsibility of specifying the dirty regions is
6404  * amdgpu_dm's.
6405  *
6406  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
6407  * plane with regions that require flushing to the eDP remote buffer. In
6408  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
6409  * implicitly provide damage clips without any client support via the plane
6410  * bounds.
6411  */
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)6412 static void fill_dc_dirty_rects(struct drm_plane *plane,
6413 				struct drm_plane_state *old_plane_state,
6414 				struct drm_plane_state *new_plane_state,
6415 				struct drm_crtc_state *crtc_state,
6416 				struct dc_flip_addrs *flip_addrs,
6417 				bool is_psr_su,
6418 				bool *dirty_regions_changed)
6419 {
6420 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6421 	struct rect *dirty_rects = flip_addrs->dirty_rects;
6422 	u32 num_clips;
6423 	struct drm_mode_rect *clips;
6424 	bool bb_changed;
6425 	bool fb_changed;
6426 	u32 i = 0;
6427 	*dirty_regions_changed = false;
6428 
6429 	/*
6430 	 * Cursor plane has it's own dirty rect update interface. See
6431 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
6432 	 */
6433 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
6434 		return;
6435 
6436 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
6437 		goto ffu;
6438 
6439 	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
6440 	clips = drm_plane_get_damage_clips(new_plane_state);
6441 
6442 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
6443 						   is_psr_su)))
6444 		goto ffu;
6445 
6446 	if (!dm_crtc_state->mpo_requested) {
6447 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
6448 			goto ffu;
6449 
6450 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
6451 			fill_dc_dirty_rect(new_plane_state->plane,
6452 					   &dirty_rects[flip_addrs->dirty_rect_count],
6453 					   clips->x1, clips->y1,
6454 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
6455 					   &flip_addrs->dirty_rect_count,
6456 					   false);
6457 		return;
6458 	}
6459 
6460 	/*
6461 	 * MPO is requested. Add entire plane bounding box to dirty rects if
6462 	 * flipped to or damaged.
6463 	 *
6464 	 * If plane is moved or resized, also add old bounding box to dirty
6465 	 * rects.
6466 	 */
6467 	fb_changed = old_plane_state->fb->base.id !=
6468 		     new_plane_state->fb->base.id;
6469 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
6470 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
6471 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
6472 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
6473 
6474 	drm_dbg(plane->dev,
6475 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
6476 		new_plane_state->plane->base.id,
6477 		bb_changed, fb_changed, num_clips);
6478 
6479 	*dirty_regions_changed = bb_changed;
6480 
6481 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
6482 		goto ffu;
6483 
6484 	if (bb_changed) {
6485 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6486 				   new_plane_state->crtc_x,
6487 				   new_plane_state->crtc_y,
6488 				   new_plane_state->crtc_w,
6489 				   new_plane_state->crtc_h, &i, false);
6490 
6491 		/* Add old plane bounding-box if plane is moved or resized */
6492 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6493 				   old_plane_state->crtc_x,
6494 				   old_plane_state->crtc_y,
6495 				   old_plane_state->crtc_w,
6496 				   old_plane_state->crtc_h, &i, false);
6497 	}
6498 
6499 	if (num_clips) {
6500 		for (; i < num_clips; clips++)
6501 			fill_dc_dirty_rect(new_plane_state->plane,
6502 					   &dirty_rects[i], clips->x1,
6503 					   clips->y1, clips->x2 - clips->x1,
6504 					   clips->y2 - clips->y1, &i, false);
6505 	} else if (fb_changed && !bb_changed) {
6506 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6507 				   new_plane_state->crtc_x,
6508 				   new_plane_state->crtc_y,
6509 				   new_plane_state->crtc_w,
6510 				   new_plane_state->crtc_h, &i, false);
6511 	}
6512 
6513 	flip_addrs->dirty_rect_count = i;
6514 	return;
6515 
6516 ffu:
6517 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
6518 			   dm_crtc_state->base.mode.crtc_hdisplay,
6519 			   dm_crtc_state->base.mode.crtc_vdisplay,
6520 			   &flip_addrs->dirty_rect_count, true);
6521 }
6522 
update_stream_scaling_settings(struct drm_device * dev,const struct drm_display_mode * mode,const struct dm_connector_state * dm_state,struct dc_stream_state * stream)6523 static void update_stream_scaling_settings(struct drm_device *dev,
6524 					   const struct drm_display_mode *mode,
6525 					   const struct dm_connector_state *dm_state,
6526 					   struct dc_stream_state *stream)
6527 {
6528 	enum amdgpu_rmx_type rmx_type;
6529 
6530 	struct rect src = { 0 }; /* viewport in composition space*/
6531 	struct rect dst = { 0 }; /* stream addressable area */
6532 
6533 	/* no mode. nothing to be done */
6534 	if (!mode)
6535 		return;
6536 
6537 	/* Full screen scaling by default */
6538 	src.width = mode->hdisplay;
6539 	src.height = mode->vdisplay;
6540 	dst.width = stream->timing.h_addressable;
6541 	dst.height = stream->timing.v_addressable;
6542 
6543 	if (dm_state) {
6544 		rmx_type = dm_state->scaling;
6545 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
6546 			if (src.width * dst.height <
6547 					src.height * dst.width) {
6548 				/* height needs less upscaling/more downscaling */
6549 				dst.width = src.width *
6550 						dst.height / src.height;
6551 			} else {
6552 				/* width needs less upscaling/more downscaling */
6553 				dst.height = src.height *
6554 						dst.width / src.width;
6555 			}
6556 		} else if (rmx_type == RMX_CENTER) {
6557 			dst = src;
6558 		}
6559 
6560 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
6561 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
6562 
6563 		if (dm_state->underscan_enable) {
6564 			dst.x += dm_state->underscan_hborder / 2;
6565 			dst.y += dm_state->underscan_vborder / 2;
6566 			dst.width -= dm_state->underscan_hborder;
6567 			dst.height -= dm_state->underscan_vborder;
6568 		}
6569 	}
6570 
6571 	stream->src = src;
6572 	stream->dst = dst;
6573 
6574 	drm_dbg_kms(dev, "Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
6575 		    dst.x, dst.y, dst.width, dst.height);
6576 
6577 }
6578 
6579 static enum dc_color_depth
convert_color_depth_from_display_info(const struct drm_connector * connector,bool is_y420,int requested_bpc)6580 convert_color_depth_from_display_info(const struct drm_connector *connector,
6581 				      bool is_y420, int requested_bpc)
6582 {
6583 	u8 bpc;
6584 
6585 	if (is_y420) {
6586 		bpc = 8;
6587 
6588 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
6589 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
6590 			bpc = 16;
6591 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
6592 			bpc = 12;
6593 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
6594 			bpc = 10;
6595 	} else {
6596 		bpc = (uint8_t)connector->display_info.bpc;
6597 		/* Assume 8 bpc by default if no bpc is specified. */
6598 		bpc = bpc ? bpc : 8;
6599 	}
6600 
6601 	if (requested_bpc > 0) {
6602 		/*
6603 		 * Cap display bpc based on the user requested value.
6604 		 *
6605 		 * The value for state->max_bpc may not correctly updated
6606 		 * depending on when the connector gets added to the state
6607 		 * or if this was called outside of atomic check, so it
6608 		 * can't be used directly.
6609 		 */
6610 		bpc = min_t(u8, bpc, requested_bpc);
6611 
6612 		/* Round down to the nearest even number. */
6613 		bpc = bpc - (bpc & 1);
6614 	}
6615 
6616 	switch (bpc) {
6617 	case 0:
6618 		/*
6619 		 * Temporary Work around, DRM doesn't parse color depth for
6620 		 * EDID revision before 1.4
6621 		 * TODO: Fix edid parsing
6622 		 */
6623 		return COLOR_DEPTH_888;
6624 	case 6:
6625 		return COLOR_DEPTH_666;
6626 	case 8:
6627 		return COLOR_DEPTH_888;
6628 	case 10:
6629 		return COLOR_DEPTH_101010;
6630 	case 12:
6631 		return COLOR_DEPTH_121212;
6632 	case 14:
6633 		return COLOR_DEPTH_141414;
6634 	case 16:
6635 		return COLOR_DEPTH_161616;
6636 	default:
6637 		return COLOR_DEPTH_UNDEFINED;
6638 	}
6639 }
6640 
6641 static enum dc_aspect_ratio
get_aspect_ratio(const struct drm_display_mode * mode_in)6642 get_aspect_ratio(const struct drm_display_mode *mode_in)
6643 {
6644 	/* 1-1 mapping, since both enums follow the HDMI spec. */
6645 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
6646 }
6647 
6648 static enum dc_color_space
get_output_color_space(const struct dc_crtc_timing * dc_crtc_timing,const struct drm_connector_state * connector_state)6649 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
6650 		       const struct drm_connector_state *connector_state)
6651 {
6652 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
6653 
6654 	switch (connector_state->colorspace) {
6655 	case DRM_MODE_COLORIMETRY_BT601_YCC:
6656 		if (dc_crtc_timing->flags.Y_ONLY)
6657 			color_space = COLOR_SPACE_YCBCR601_LIMITED;
6658 		else
6659 			color_space = COLOR_SPACE_YCBCR601;
6660 		break;
6661 	case DRM_MODE_COLORIMETRY_BT709_YCC:
6662 		if (dc_crtc_timing->flags.Y_ONLY)
6663 			color_space = COLOR_SPACE_YCBCR709_LIMITED;
6664 		else
6665 			color_space = COLOR_SPACE_YCBCR709;
6666 		break;
6667 	case DRM_MODE_COLORIMETRY_OPRGB:
6668 		color_space = COLOR_SPACE_ADOBERGB;
6669 		break;
6670 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
6671 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
6672 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
6673 			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
6674 		else
6675 			color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6676 		break;
6677 	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
6678 	default:
6679 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
6680 			color_space = COLOR_SPACE_SRGB;
6681 			if (connector_state->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_LIMITED)
6682 				color_space = COLOR_SPACE_SRGB_LIMITED;
6683 		/*
6684 		 * 27030khz is the separation point between HDTV and SDTV
6685 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
6686 		 * respectively
6687 		 */
6688 		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
6689 			if (dc_crtc_timing->flags.Y_ONLY)
6690 				color_space =
6691 					COLOR_SPACE_YCBCR709_LIMITED;
6692 			else
6693 				color_space = COLOR_SPACE_YCBCR709;
6694 		} else {
6695 			if (dc_crtc_timing->flags.Y_ONLY)
6696 				color_space =
6697 					COLOR_SPACE_YCBCR601_LIMITED;
6698 			else
6699 				color_space = COLOR_SPACE_YCBCR601;
6700 		}
6701 		break;
6702 	}
6703 
6704 	return color_space;
6705 }
6706 
6707 static enum display_content_type
get_output_content_type(const struct drm_connector_state * connector_state)6708 get_output_content_type(const struct drm_connector_state *connector_state)
6709 {
6710 	switch (connector_state->content_type) {
6711 	default:
6712 	case DRM_MODE_CONTENT_TYPE_NO_DATA:
6713 		return DISPLAY_CONTENT_TYPE_NO_DATA;
6714 	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
6715 		return DISPLAY_CONTENT_TYPE_GRAPHICS;
6716 	case DRM_MODE_CONTENT_TYPE_PHOTO:
6717 		return DISPLAY_CONTENT_TYPE_PHOTO;
6718 	case DRM_MODE_CONTENT_TYPE_CINEMA:
6719 		return DISPLAY_CONTENT_TYPE_CINEMA;
6720 	case DRM_MODE_CONTENT_TYPE_GAME:
6721 		return DISPLAY_CONTENT_TYPE_GAME;
6722 	}
6723 }
6724 
adjust_colour_depth_from_display_info(struct dc_crtc_timing * timing_out,const struct drm_display_info * info)6725 static bool adjust_colour_depth_from_display_info(
6726 	struct dc_crtc_timing *timing_out,
6727 	const struct drm_display_info *info)
6728 {
6729 	enum dc_color_depth depth = timing_out->display_color_depth;
6730 	int normalized_clk;
6731 
6732 	do {
6733 		normalized_clk = timing_out->pix_clk_100hz / 10;
6734 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
6735 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
6736 			normalized_clk /= 2;
6737 		/* Adjusting pix clock following on HDMI spec based on colour depth */
6738 		switch (depth) {
6739 		case COLOR_DEPTH_888:
6740 			break;
6741 		case COLOR_DEPTH_101010:
6742 			normalized_clk = (normalized_clk * 30) / 24;
6743 			break;
6744 		case COLOR_DEPTH_121212:
6745 			normalized_clk = (normalized_clk * 36) / 24;
6746 			break;
6747 		case COLOR_DEPTH_161616:
6748 			normalized_clk = (normalized_clk * 48) / 24;
6749 			break;
6750 		default:
6751 			/* The above depths are the only ones valid for HDMI. */
6752 			return false;
6753 		}
6754 		if (normalized_clk <= info->max_tmds_clock) {
6755 			timing_out->display_color_depth = depth;
6756 			return true;
6757 		}
6758 	} while (--depth > COLOR_DEPTH_666);
6759 	return false;
6760 }
6761 
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)6762 static void fill_stream_properties_from_drm_display_mode(
6763 	struct dc_stream_state *stream,
6764 	const struct drm_display_mode *mode_in,
6765 	const struct drm_connector *connector,
6766 	const struct drm_connector_state *connector_state,
6767 	const struct dc_stream_state *old_stream,
6768 	int requested_bpc)
6769 {
6770 	struct dc_crtc_timing *timing_out = &stream->timing;
6771 	const struct drm_display_info *info = &connector->display_info;
6772 	struct amdgpu_dm_connector *aconnector = NULL;
6773 	struct hdmi_vendor_infoframe hv_frame;
6774 	struct hdmi_avi_infoframe avi_frame;
6775 	ssize_t err;
6776 
6777 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
6778 		aconnector = to_amdgpu_dm_connector(connector);
6779 
6780 	memset(&hv_frame, 0, sizeof(hv_frame));
6781 	memset(&avi_frame, 0, sizeof(avi_frame));
6782 
6783 	timing_out->h_border_left = 0;
6784 	timing_out->h_border_right = 0;
6785 	timing_out->v_border_top = 0;
6786 	timing_out->v_border_bottom = 0;
6787 	/* TODO: un-hardcode */
6788 	if (drm_mode_is_420_only(info, mode_in)
6789 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6790 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6791 	else if (drm_mode_is_420_also(info, mode_in)
6792 			&& aconnector
6793 			&& aconnector->force_yuv420_output)
6794 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6795 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR422))
6796 			&& aconnector
6797 			&& aconnector->force_yuv422_output)
6798 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR422;
6799 	else if ((connector->display_info.color_formats & BIT(DRM_OUTPUT_COLOR_FORMAT_YCBCR444))
6800 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6801 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
6802 	else
6803 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
6804 
6805 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
6806 	timing_out->display_color_depth = convert_color_depth_from_display_info(
6807 		connector,
6808 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
6809 		requested_bpc);
6810 	timing_out->scan_type = SCANNING_TYPE_NODATA;
6811 	timing_out->hdmi_vic = 0;
6812 
6813 	if (old_stream) {
6814 		timing_out->vic = old_stream->timing.vic;
6815 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
6816 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
6817 	} else {
6818 		timing_out->vic = drm_match_cea_mode(mode_in);
6819 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
6820 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
6821 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
6822 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
6823 	}
6824 
6825 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
6826 		err = drm_hdmi_avi_infoframe_from_display_mode(&avi_frame,
6827 							       (struct drm_connector *)connector,
6828 							       mode_in);
6829 		if (err < 0)
6830 			drm_warn_once(connector->dev, "Failed to setup avi infoframe on connector %s: %zd\n",
6831 				      connector->name, err);
6832 		timing_out->vic = avi_frame.video_code;
6833 		err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame,
6834 								  (struct drm_connector *)connector,
6835 								  mode_in);
6836 		if (err < 0)
6837 			drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n",
6838 				      connector->name, err);
6839 		timing_out->hdmi_vic = hv_frame.vic;
6840 	}
6841 
6842 	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
6843 		timing_out->h_addressable = mode_in->hdisplay;
6844 		timing_out->h_total = mode_in->htotal;
6845 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
6846 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
6847 		timing_out->v_total = mode_in->vtotal;
6848 		timing_out->v_addressable = mode_in->vdisplay;
6849 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
6850 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
6851 		timing_out->pix_clk_100hz = mode_in->clock * 10;
6852 	} else {
6853 		timing_out->h_addressable = mode_in->crtc_hdisplay;
6854 		timing_out->h_total = mode_in->crtc_htotal;
6855 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
6856 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
6857 		timing_out->v_total = mode_in->crtc_vtotal;
6858 		timing_out->v_addressable = mode_in->crtc_vdisplay;
6859 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
6860 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
6861 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
6862 	}
6863 
6864 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
6865 
6866 	stream->out_transfer_func.type = TF_TYPE_PREDEFINED;
6867 	stream->out_transfer_func.tf = TRANSFER_FUNCTION_SRGB;
6868 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
6869 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
6870 		    drm_mode_is_420_also(info, mode_in) &&
6871 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
6872 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6873 			adjust_colour_depth_from_display_info(timing_out, info);
6874 		}
6875 	}
6876 
6877 	stream->output_color_space = get_output_color_space(timing_out, connector_state);
6878 	stream->content_type = get_output_content_type(connector_state);
6879 }
6880 
fill_audio_info(struct audio_info * audio_info,const struct drm_connector * drm_connector,const struct dc_sink * dc_sink)6881 static void fill_audio_info(struct audio_info *audio_info,
6882 			    const struct drm_connector *drm_connector,
6883 			    const struct dc_sink *dc_sink)
6884 {
6885 	int i = 0;
6886 	int cea_revision = 0;
6887 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
6888 
6889 	audio_info->manufacture_id = edid_caps->manufacturer_id;
6890 	audio_info->product_id = edid_caps->product_id;
6891 
6892 	cea_revision = drm_connector->display_info.cea_rev;
6893 
6894 	strscpy(audio_info->display_name,
6895 		edid_caps->display_name,
6896 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
6897 
6898 	if (cea_revision >= 3) {
6899 		audio_info->mode_count = edid_caps->audio_mode_count;
6900 
6901 		for (i = 0; i < audio_info->mode_count; ++i) {
6902 			audio_info->modes[i].format_code =
6903 					(enum audio_format_code)
6904 					(edid_caps->audio_modes[i].format_code);
6905 			audio_info->modes[i].channel_count =
6906 					edid_caps->audio_modes[i].channel_count;
6907 			audio_info->modes[i].sample_rates.all =
6908 					edid_caps->audio_modes[i].sample_rate;
6909 			audio_info->modes[i].sample_size =
6910 					edid_caps->audio_modes[i].sample_size;
6911 		}
6912 	}
6913 
6914 	audio_info->flags.all = edid_caps->speaker_flags;
6915 
6916 	/* TODO: We only check for the progressive mode, check for interlace mode too */
6917 	if (drm_connector->latency_present[0]) {
6918 		audio_info->video_latency = drm_connector->video_latency[0];
6919 		audio_info->audio_latency = drm_connector->audio_latency[0];
6920 	}
6921 
6922 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
6923 
6924 }
6925 
6926 static void
copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode * src_mode,struct drm_display_mode * dst_mode)6927 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
6928 				      struct drm_display_mode *dst_mode)
6929 {
6930 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
6931 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
6932 	dst_mode->crtc_clock = src_mode->crtc_clock;
6933 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
6934 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
6935 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
6936 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
6937 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
6938 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
6939 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
6940 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
6941 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
6942 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
6943 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
6944 }
6945 
6946 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)6947 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
6948 					const struct drm_display_mode *native_mode,
6949 					bool scale_enabled)
6950 {
6951 	if (scale_enabled || (
6952 	    native_mode->clock == drm_mode->clock &&
6953 	    native_mode->htotal == drm_mode->htotal &&
6954 	    native_mode->vtotal == drm_mode->vtotal)) {
6955 		if (native_mode->crtc_clock)
6956 			copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
6957 	} else {
6958 		/* no scaling nor amdgpu inserted, no need to patch */
6959 	}
6960 }
6961 
6962 static struct dc_sink *
create_fake_sink(struct drm_device * dev,struct dc_link * link)6963 create_fake_sink(struct drm_device *dev, struct dc_link *link)
6964 {
6965 	struct dc_sink_init_data sink_init_data = { 0 };
6966 	struct dc_sink *sink = NULL;
6967 
6968 	sink_init_data.link = link;
6969 	sink_init_data.sink_signal = link->connector_signal;
6970 
6971 	sink = dc_sink_create(&sink_init_data);
6972 	if (!sink) {
6973 		drm_err(dev, "Failed to create sink!\n");
6974 		return NULL;
6975 	}
6976 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
6977 
6978 	return sink;
6979 }
6980 
set_multisync_trigger_params(struct dc_stream_state * stream)6981 static void set_multisync_trigger_params(
6982 		struct dc_stream_state *stream)
6983 {
6984 	struct dc_stream_state *master = NULL;
6985 
6986 	if (stream->triggered_crtc_reset.enabled) {
6987 		master = stream->triggered_crtc_reset.event_source;
6988 		stream->triggered_crtc_reset.event =
6989 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
6990 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
6991 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
6992 	}
6993 }
6994 
set_master_stream(struct dc_stream_state * stream_set[],int stream_count)6995 static void set_master_stream(struct dc_stream_state *stream_set[],
6996 			      int stream_count)
6997 {
6998 	int j, highest_rfr = 0, master_stream = 0;
6999 
7000 	for (j = 0;  j < stream_count; j++) {
7001 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
7002 			int refresh_rate = 0;
7003 
7004 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
7005 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
7006 			if (refresh_rate > highest_rfr) {
7007 				highest_rfr = refresh_rate;
7008 				master_stream = j;
7009 			}
7010 		}
7011 	}
7012 	for (j = 0;  j < stream_count; j++) {
7013 		if (stream_set[j])
7014 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
7015 	}
7016 }
7017 
dm_enable_per_frame_crtc_master_sync(struct dc_state * context)7018 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
7019 {
7020 	int i = 0;
7021 	struct dc_stream_state *stream;
7022 
7023 	if (context->stream_count < 2)
7024 		return;
7025 	for (i = 0; i < context->stream_count ; i++) {
7026 		if (!context->streams[i])
7027 			continue;
7028 		/*
7029 		 * TODO: add a function to read AMD VSDB bits and set
7030 		 * crtc_sync_master.multi_sync_enabled flag
7031 		 * For now it's set to false
7032 		 */
7033 	}
7034 
7035 	set_master_stream(context->streams, context->stream_count);
7036 
7037 	for (i = 0; i < context->stream_count ; i++) {
7038 		stream = context->streams[i];
7039 
7040 		if (!stream)
7041 			continue;
7042 
7043 		set_multisync_trigger_params(stream);
7044 	}
7045 }
7046 
7047 /**
7048  * DOC: FreeSync Video
7049  *
7050  * When a userspace application wants to play a video, the content follows a
7051  * standard format definition that usually specifies the FPS for that format.
7052  * The below list illustrates some video format and the expected FPS,
7053  * respectively:
7054  *
7055  * - TV/NTSC (23.976 FPS)
7056  * - Cinema (24 FPS)
7057  * - TV/PAL (25 FPS)
7058  * - TV/NTSC (29.97 FPS)
7059  * - TV/NTSC (30 FPS)
7060  * - Cinema HFR (48 FPS)
7061  * - TV/PAL (50 FPS)
7062  * - Commonly used (60 FPS)
7063  * - Multiples of 24 (48,72,96 FPS)
7064  *
7065  * The list of standards video format is not huge and can be added to the
7066  * connector modeset list beforehand. With that, userspace can leverage
7067  * FreeSync to extends the front porch in order to attain the target refresh
7068  * rate. Such a switch will happen seamlessly, without screen blanking or
7069  * reprogramming of the output in any other way. If the userspace requests a
7070  * modesetting change compatible with FreeSync modes that only differ in the
7071  * refresh rate, DC will skip the full update and avoid blink during the
7072  * transition. For example, the video player can change the modesetting from
7073  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
7074  * causing any display blink. This same concept can be applied to a mode
7075  * setting change.
7076  */
7077 static struct drm_display_mode *
get_highest_refresh_rate_mode(struct amdgpu_dm_connector * aconnector,bool use_probed_modes)7078 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
7079 		bool use_probed_modes)
7080 {
7081 	struct drm_display_mode *m, *m_pref = NULL;
7082 	u16 current_refresh, highest_refresh;
7083 	struct list_head *list_head = use_probed_modes ?
7084 		&aconnector->base.probed_modes :
7085 		&aconnector->base.modes;
7086 
7087 	if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
7088 		return NULL;
7089 
7090 	if (aconnector->freesync_vid_base.clock != 0)
7091 		return &aconnector->freesync_vid_base;
7092 
7093 	/* Find the preferred mode */
7094 	list_for_each_entry(m, list_head, head) {
7095 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
7096 			m_pref = m;
7097 			break;
7098 		}
7099 	}
7100 
7101 	if (!m_pref) {
7102 		/* Probably an EDID with no preferred mode. Fallback to first entry */
7103 		m_pref = list_first_entry_or_null(
7104 				&aconnector->base.modes, struct drm_display_mode, head);
7105 		if (!m_pref) {
7106 			drm_dbg_driver(aconnector->base.dev, "No preferred mode found in EDID\n");
7107 			return NULL;
7108 		}
7109 	}
7110 
7111 	highest_refresh = drm_mode_vrefresh(m_pref);
7112 
7113 	/*
7114 	 * Find the mode with highest refresh rate with same resolution.
7115 	 * For some monitors, preferred mode is not the mode with highest
7116 	 * supported refresh rate.
7117 	 */
7118 	list_for_each_entry(m, list_head, head) {
7119 		current_refresh  = drm_mode_vrefresh(m);
7120 
7121 		if (m->hdisplay == m_pref->hdisplay &&
7122 		    m->vdisplay == m_pref->vdisplay &&
7123 		    highest_refresh < current_refresh) {
7124 			highest_refresh = current_refresh;
7125 			m_pref = m;
7126 		}
7127 	}
7128 
7129 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
7130 	return m_pref;
7131 }
7132 
is_freesync_video_mode(const struct drm_display_mode * mode,struct amdgpu_dm_connector * aconnector)7133 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
7134 		struct amdgpu_dm_connector *aconnector)
7135 {
7136 	struct drm_display_mode *high_mode;
7137 	int timing_diff;
7138 
7139 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
7140 	if (!high_mode || !mode)
7141 		return false;
7142 
7143 	timing_diff = high_mode->vtotal - mode->vtotal;
7144 
7145 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
7146 	    high_mode->hdisplay != mode->hdisplay ||
7147 	    high_mode->vdisplay != mode->vdisplay ||
7148 	    high_mode->hsync_start != mode->hsync_start ||
7149 	    high_mode->hsync_end != mode->hsync_end ||
7150 	    high_mode->htotal != mode->htotal ||
7151 	    high_mode->hskew != mode->hskew ||
7152 	    high_mode->vscan != mode->vscan ||
7153 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
7154 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
7155 		return false;
7156 	else
7157 		return true;
7158 }
7159 
7160 #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)7161 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
7162 			    struct dc_sink *sink, struct dc_stream_state *stream,
7163 			    struct dsc_dec_dpcd_caps *dsc_caps)
7164 {
7165 	stream->timing.flags.DSC = 0;
7166 	dsc_caps->is_dsc_supported = false;
7167 
7168 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
7169 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
7170 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
7171 			sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
7172 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7173 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7174 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7175 				dsc_caps);
7176 	}
7177 }
7178 
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)7179 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
7180 				    struct dc_sink *sink, struct dc_stream_state *stream,
7181 				    struct dsc_dec_dpcd_caps *dsc_caps,
7182 				    uint32_t max_dsc_target_bpp_limit_override)
7183 {
7184 	const struct dc_link_settings *verified_link_cap = NULL;
7185 	u32 link_bw_in_kbps;
7186 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
7187 	struct dc *dc = sink->ctx->dc;
7188 	struct dc_dsc_bw_range bw_range = {0};
7189 	struct dc_dsc_config dsc_cfg = {0};
7190 	struct dc_dsc_config_options dsc_options = {0};
7191 
7192 	dc_dsc_get_default_config_option(dc, &dsc_options);
7193 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7194 
7195 	verified_link_cap = dc_link_get_link_cap(stream->link);
7196 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
7197 	edp_min_bpp_x16 = 8 * 16;
7198 	edp_max_bpp_x16 = 8 * 16;
7199 
7200 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
7201 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
7202 
7203 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
7204 		edp_min_bpp_x16 = edp_max_bpp_x16;
7205 
7206 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
7207 				dc->debug.dsc_min_slice_height_override,
7208 				edp_min_bpp_x16, edp_max_bpp_x16,
7209 				dsc_caps,
7210 				&stream->timing,
7211 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7212 				&bw_range)) {
7213 
7214 		if (bw_range.max_kbps < link_bw_in_kbps) {
7215 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7216 					dsc_caps,
7217 					&dsc_options,
7218 					0,
7219 					&stream->timing,
7220 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7221 					&dsc_cfg)) {
7222 				stream->timing.dsc_cfg = dsc_cfg;
7223 				stream->timing.flags.DSC = 1;
7224 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
7225 			}
7226 			return;
7227 		}
7228 	}
7229 
7230 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7231 				dsc_caps,
7232 				&dsc_options,
7233 				link_bw_in_kbps,
7234 				&stream->timing,
7235 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7236 				&dsc_cfg)) {
7237 		stream->timing.dsc_cfg = dsc_cfg;
7238 		stream->timing.flags.DSC = 1;
7239 	}
7240 }
7241 
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)7242 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
7243 					struct dc_sink *sink, struct dc_stream_state *stream,
7244 					struct dsc_dec_dpcd_caps *dsc_caps)
7245 {
7246 	struct drm_connector *drm_connector = &aconnector->base;
7247 	u32 link_bandwidth_kbps;
7248 	struct dc *dc = sink->ctx->dc;
7249 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
7250 	u32 dsc_max_supported_bw_in_kbps;
7251 	u32 max_dsc_target_bpp_limit_override =
7252 		drm_connector->display_info.max_dsc_bpp;
7253 	struct dc_dsc_config_options dsc_options = {0};
7254 
7255 	dc_dsc_get_default_config_option(dc, &dsc_options);
7256 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7257 
7258 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
7259 							dc_link_get_link_cap(aconnector->dc_link));
7260 
7261 	/* Set DSC policy according to dsc_clock_en */
7262 	dc_dsc_policy_set_enable_dsc_when_not_needed(
7263 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
7264 
7265 	if (sink->sink_signal == SIGNAL_TYPE_EDP &&
7266 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
7267 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
7268 
7269 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
7270 
7271 	} else if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
7272 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
7273 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7274 						dsc_caps,
7275 						&dsc_options,
7276 						link_bandwidth_kbps,
7277 						&stream->timing,
7278 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7279 						&stream->timing.dsc_cfg)) {
7280 				stream->timing.flags.DSC = 1;
7281 				drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from SST RX\n",
7282 							__func__, drm_connector->name);
7283 			}
7284 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7285 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
7286 					dc_link_get_highest_encoding_format(aconnector->dc_link));
7287 			max_supported_bw_in_kbps = link_bandwidth_kbps;
7288 			dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
7289 
7290 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
7291 					max_supported_bw_in_kbps > 0 &&
7292 					dsc_max_supported_bw_in_kbps > 0)
7293 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7294 						dsc_caps,
7295 						&dsc_options,
7296 						dsc_max_supported_bw_in_kbps,
7297 						&stream->timing,
7298 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7299 						&stream->timing.dsc_cfg)) {
7300 					stream->timing.flags.DSC = 1;
7301 					drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from DP-HDMI PCON\n",
7302 									 __func__, drm_connector->name);
7303 				}
7304 		}
7305 	}
7306 
7307 	/* Overwrite the stream flag if DSC is enabled through debugfs */
7308 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
7309 		stream->timing.flags.DSC = 1;
7310 
7311 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
7312 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
7313 
7314 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
7315 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
7316 
7317 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
7318 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
7319 }
7320 #endif
7321 
7322 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)7323 create_stream_for_sink(struct drm_connector *connector,
7324 		       const struct drm_display_mode *drm_mode,
7325 		       const struct dm_connector_state *dm_state,
7326 		       const struct dc_stream_state *old_stream,
7327 		       int requested_bpc)
7328 {
7329 	struct drm_device *dev = connector->dev;
7330 	struct amdgpu_dm_connector *aconnector = NULL;
7331 	struct drm_display_mode *preferred_mode = NULL;
7332 	const struct drm_connector_state *con_state = &dm_state->base;
7333 	struct dc_stream_state *stream = NULL;
7334 	struct drm_display_mode mode;
7335 	struct drm_display_mode saved_mode;
7336 	struct drm_display_mode *freesync_mode = NULL;
7337 	bool native_mode_found = false;
7338 	bool recalculate_timing = false;
7339 	bool scale = dm_state->scaling != RMX_OFF;
7340 	int mode_refresh;
7341 	int preferred_refresh = 0;
7342 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
7343 #if defined(CONFIG_DRM_AMD_DC_FP)
7344 	struct dsc_dec_dpcd_caps dsc_caps;
7345 #endif
7346 	struct dc_link *link = NULL;
7347 	struct dc_sink *sink = NULL;
7348 
7349 	drm_mode_init(&mode, drm_mode);
7350 	memset(&saved_mode, 0, sizeof(saved_mode));
7351 
7352 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK) {
7353 		aconnector = NULL;
7354 		aconnector = to_amdgpu_dm_connector(connector);
7355 		link = aconnector->dc_link;
7356 	} else {
7357 		struct drm_writeback_connector *wbcon = NULL;
7358 		struct amdgpu_dm_wb_connector *dm_wbcon = NULL;
7359 
7360 		wbcon = drm_connector_to_writeback(connector);
7361 		dm_wbcon = to_amdgpu_dm_wb_connector(wbcon);
7362 		link = dm_wbcon->link;
7363 	}
7364 
7365 	if (!aconnector || !aconnector->dc_sink) {
7366 		sink = create_fake_sink(dev, link);
7367 		if (!sink)
7368 			return stream;
7369 
7370 	} else {
7371 		sink = aconnector->dc_sink;
7372 		dc_sink_retain(sink);
7373 	}
7374 
7375 	stream = dc_create_stream_for_sink(sink);
7376 
7377 	if (stream == NULL) {
7378 		drm_err(dev, "Failed to create stream for sink!\n");
7379 		goto finish;
7380 	}
7381 
7382 	/* We leave this NULL for writeback connectors */
7383 	stream->dm_stream_context = aconnector;
7384 
7385 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
7386 		connector->display_info.hdmi.scdc.scrambling.low_rates;
7387 
7388 	list_for_each_entry(preferred_mode, &connector->modes, head) {
7389 		/* Search for preferred mode */
7390 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
7391 			native_mode_found = true;
7392 			break;
7393 		}
7394 	}
7395 	if (!native_mode_found)
7396 		preferred_mode = list_first_entry_or_null(
7397 				&connector->modes,
7398 				struct drm_display_mode,
7399 				head);
7400 
7401 	mode_refresh = drm_mode_vrefresh(&mode);
7402 
7403 	if (preferred_mode == NULL) {
7404 		/*
7405 		 * This may not be an error, the use case is when we have no
7406 		 * usermode calls to reset and set mode upon hotplug. In this
7407 		 * case, we call set mode ourselves to restore the previous mode
7408 		 * and the modelist may not be filled in time.
7409 		 */
7410 		drm_dbg_driver(dev, "No preferred mode found\n");
7411 	} else if (aconnector) {
7412 		recalculate_timing = amdgpu_freesync_vid_mode &&
7413 				 is_freesync_video_mode(&mode, aconnector);
7414 		if (recalculate_timing) {
7415 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
7416 			drm_mode_copy(&saved_mode, &mode);
7417 			saved_mode.picture_aspect_ratio = mode.picture_aspect_ratio;
7418 			drm_mode_copy(&mode, freesync_mode);
7419 			mode.picture_aspect_ratio = saved_mode.picture_aspect_ratio;
7420 		} else {
7421 			decide_crtc_timing_for_drm_display_mode(
7422 					&mode, preferred_mode, scale);
7423 
7424 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
7425 		}
7426 	}
7427 
7428 	if (recalculate_timing)
7429 		drm_mode_set_crtcinfo(&saved_mode, 0);
7430 
7431 	/*
7432 	 * If scaling is enabled and refresh rate didn't change
7433 	 * we copy the vic and polarities of the old timings
7434 	 */
7435 	if (!scale || mode_refresh != preferred_refresh)
7436 		fill_stream_properties_from_drm_display_mode(
7437 			stream, &mode, connector, con_state, NULL,
7438 			requested_bpc);
7439 	else
7440 		fill_stream_properties_from_drm_display_mode(
7441 			stream, &mode, connector, con_state, old_stream,
7442 			requested_bpc);
7443 
7444 	/* The rest isn't needed for writeback connectors */
7445 	if (!aconnector)
7446 		goto finish;
7447 
7448 	if (aconnector->timing_changed) {
7449 		drm_dbg(aconnector->base.dev,
7450 			"overriding timing for automated test, bpc %d, changing to %d\n",
7451 			stream->timing.display_color_depth,
7452 			aconnector->timing_requested->display_color_depth);
7453 		stream->timing = *aconnector->timing_requested;
7454 	}
7455 
7456 #if defined(CONFIG_DRM_AMD_DC_FP)
7457 	/* SST DSC determination policy */
7458 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
7459 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
7460 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
7461 #endif
7462 
7463 	update_stream_scaling_settings(dev, &mode, dm_state, stream);
7464 
7465 	fill_audio_info(
7466 		&stream->audio_info,
7467 		connector,
7468 		sink);
7469 
7470 	update_stream_signal(stream, sink);
7471 
7472 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
7473 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket);
7474 
7475 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT ||
7476 	    stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
7477 	    stream->signal == SIGNAL_TYPE_EDP) {
7478 		const struct dc_edid_caps *edid_caps;
7479 		unsigned int disable_colorimetry = 0;
7480 
7481 		if (aconnector->dc_sink) {
7482 			edid_caps = &aconnector->dc_sink->edid_caps;
7483 			disable_colorimetry = edid_caps->panel_patch.disable_colorimetry;
7484 		}
7485 
7486 		//
7487 		// should decide stream support vsc sdp colorimetry capability
7488 		// before building vsc info packet
7489 		//
7490 		stream->use_vsc_sdp_for_colorimetry = stream->link->dpcd_caps.dpcd_rev.raw >= 0x14 &&
7491 						      stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED &&
7492 						      !disable_colorimetry;
7493 
7494 		if (stream->out_transfer_func.tf == TRANSFER_FUNCTION_GAMMA22)
7495 			tf = TRANSFER_FUNC_GAMMA_22;
7496 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
7497 		aconnector->sr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
7498 
7499 	}
7500 finish:
7501 	dc_sink_release(sink);
7502 
7503 	return stream;
7504 }
7505 
7506 /**
7507  * amdgpu_dm_connector_poll - Poll a connector to see if it's connected to a display
7508  * @aconnector: DM connector to poll (owns @base drm_connector and @dc_link)
7509  * @force: if true, force polling even when DAC load detection was used
7510  *
7511  * Used for connectors that don't support HPD (hotplug detection) to
7512  * periodically check whether the connector is connected to a display.
7513  *
7514  * When connection was determined via DAC load detection, we avoid
7515  * re-running it on normal polls to prevent visible glitches, unless
7516  * @force is set.
7517  *
7518  * Return: The probed connector status (connected/disconnected/unknown).
7519  */
7520 static enum drm_connector_status
amdgpu_dm_connector_poll(struct amdgpu_dm_connector * aconnector,bool force)7521 amdgpu_dm_connector_poll(struct amdgpu_dm_connector *aconnector, bool force)
7522 {
7523 	struct drm_connector *connector = &aconnector->base;
7524 	struct drm_device *dev = connector->dev;
7525 	struct amdgpu_device *adev = drm_to_adev(dev);
7526 	struct dc_link *link = aconnector->dc_link;
7527 	enum dc_connection_type conn_type = dc_connection_none;
7528 	enum drm_connector_status status = connector_status_disconnected;
7529 
7530 	/* When we determined the connection using DAC load detection,
7531 	 * do NOT poll the connector do detect disconnect because
7532 	 * that would run DAC load detection again which can cause
7533 	 * visible visual glitches.
7534 	 *
7535 	 * Only allow to poll such a connector again when forcing.
7536 	 */
7537 	if (!force && link->local_sink && link->type == dc_connection_analog_load)
7538 		return connector->status;
7539 
7540 	mutex_lock(&aconnector->hpd_lock);
7541 
7542 	if (dc_link_detect_connection_type(aconnector->dc_link, &conn_type) &&
7543 	    conn_type != dc_connection_none) {
7544 		mutex_lock(&adev->dm.dc_lock);
7545 
7546 		/* Only call full link detection when a sink isn't created yet,
7547 		 * ie. just when the display is plugged in, otherwise we risk flickering.
7548 		 */
7549 		if (link->local_sink ||
7550 			dc_link_detect(link, DETECT_REASON_HPD))
7551 			status = connector_status_connected;
7552 
7553 		mutex_unlock(&adev->dm.dc_lock);
7554 	}
7555 
7556 	if (connector->status != status) {
7557 		if (status == connector_status_disconnected) {
7558 			if (link->local_sink)
7559 				dc_sink_release(link->local_sink);
7560 
7561 			link->local_sink = NULL;
7562 			link->dpcd_sink_count = 0;
7563 			link->type = dc_connection_none;
7564 		}
7565 
7566 		amdgpu_dm_update_connector_after_detect(aconnector);
7567 	}
7568 
7569 	mutex_unlock(&aconnector->hpd_lock);
7570 	return status;
7571 }
7572 
7573 /**
7574  * amdgpu_dm_connector_detect() - Detect whether a DRM connector is connected to a display
7575  *
7576  * A connector is considered connected when it has a sink that is not NULL.
7577  * For connectors that support HPD (hotplug detection), the connection is
7578  * handled in the HPD interrupt.
7579  * For connectors that may not support HPD, such as analog connectors,
7580  * DRM will call this function repeatedly to poll them.
7581  *
7582  * Notes:
7583  * 1. This interface is NOT called in context of HPD irq.
7584  * 2. This interface *is called* in context of user-mode ioctl. Which
7585  *    makes it a bad place for *any* MST-related activity.
7586  *
7587  * @connector: The DRM connector we are checking. We convert it to
7588  *             amdgpu_dm_connector so we can read the DC link and state.
7589  * @force:     If true, do a full detect again. This is used even when
7590  *             a lighter check would normally be used to avoid flicker.
7591  *
7592  * Return: The connector status (connected, disconnected, or unknown).
7593  *
7594  */
7595 static enum drm_connector_status
amdgpu_dm_connector_detect(struct drm_connector * connector,bool force)7596 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
7597 {
7598 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7599 
7600 	update_subconnector_property(aconnector);
7601 
7602 	if (aconnector->base.force == DRM_FORCE_ON ||
7603 		aconnector->base.force == DRM_FORCE_ON_DIGITAL)
7604 		return connector_status_connected;
7605 	else if (aconnector->base.force == DRM_FORCE_OFF)
7606 		return connector_status_disconnected;
7607 
7608 	/* Poll analog connectors and only when either
7609 	 * disconnected or connected to an analog display.
7610 	 */
7611 	if (drm_kms_helper_is_poll_worker() &&
7612 		dc_connector_supports_analog(aconnector->dc_link->link_id.id) &&
7613 		(!aconnector->dc_sink || aconnector->dc_sink->edid_caps.analog))
7614 		return amdgpu_dm_connector_poll(aconnector, force);
7615 
7616 	return (aconnector->dc_sink ? connector_status_connected :
7617 			connector_status_disconnected);
7618 }
7619 
amdgpu_dm_connector_atomic_set_property(struct drm_connector * connector,struct drm_connector_state * connector_state,struct drm_property * property,uint64_t val)7620 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
7621 					    struct drm_connector_state *connector_state,
7622 					    struct drm_property *property,
7623 					    uint64_t val)
7624 {
7625 	struct drm_device *dev = connector->dev;
7626 	struct amdgpu_device *adev = drm_to_adev(dev);
7627 	struct dm_connector_state *dm_old_state =
7628 		to_dm_connector_state(connector->state);
7629 	struct dm_connector_state *dm_new_state =
7630 		to_dm_connector_state(connector_state);
7631 
7632 	int ret = -EINVAL;
7633 
7634 	if (property == dev->mode_config.scaling_mode_property) {
7635 		enum amdgpu_rmx_type rmx_type;
7636 
7637 		switch (val) {
7638 		case DRM_MODE_SCALE_CENTER:
7639 			rmx_type = RMX_CENTER;
7640 			break;
7641 		case DRM_MODE_SCALE_ASPECT:
7642 			rmx_type = RMX_ASPECT;
7643 			break;
7644 		case DRM_MODE_SCALE_FULLSCREEN:
7645 			rmx_type = RMX_FULL;
7646 			break;
7647 		case DRM_MODE_SCALE_NONE:
7648 		default:
7649 			rmx_type = RMX_OFF;
7650 			break;
7651 		}
7652 
7653 		if (dm_old_state->scaling == rmx_type)
7654 			return 0;
7655 
7656 		dm_new_state->scaling = rmx_type;
7657 		ret = 0;
7658 	} else if (property == adev->mode_info.underscan_hborder_property) {
7659 		dm_new_state->underscan_hborder = val;
7660 		ret = 0;
7661 	} else if (property == adev->mode_info.underscan_vborder_property) {
7662 		dm_new_state->underscan_vborder = val;
7663 		ret = 0;
7664 	} else if (property == adev->mode_info.underscan_property) {
7665 		dm_new_state->underscan_enable = val;
7666 		ret = 0;
7667 	} else if (property == adev->mode_info.abm_level_property) {
7668 		switch (val) {
7669 		case ABM_SYSFS_CONTROL:
7670 			dm_new_state->abm_sysfs_forbidden = false;
7671 			break;
7672 		case ABM_LEVEL_OFF:
7673 			dm_new_state->abm_sysfs_forbidden = true;
7674 			dm_new_state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7675 			break;
7676 		default:
7677 			dm_new_state->abm_sysfs_forbidden = true;
7678 			dm_new_state->abm_level = val;
7679 		}
7680 		ret = 0;
7681 	}
7682 
7683 	return ret;
7684 }
7685 
amdgpu_dm_connector_atomic_get_property(struct drm_connector * connector,const struct drm_connector_state * state,struct drm_property * property,uint64_t * val)7686 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
7687 					    const struct drm_connector_state *state,
7688 					    struct drm_property *property,
7689 					    uint64_t *val)
7690 {
7691 	struct drm_device *dev = connector->dev;
7692 	struct amdgpu_device *adev = drm_to_adev(dev);
7693 	struct dm_connector_state *dm_state =
7694 		to_dm_connector_state(state);
7695 	int ret = -EINVAL;
7696 
7697 	if (property == dev->mode_config.scaling_mode_property) {
7698 		switch (dm_state->scaling) {
7699 		case RMX_CENTER:
7700 			*val = DRM_MODE_SCALE_CENTER;
7701 			break;
7702 		case RMX_ASPECT:
7703 			*val = DRM_MODE_SCALE_ASPECT;
7704 			break;
7705 		case RMX_FULL:
7706 			*val = DRM_MODE_SCALE_FULLSCREEN;
7707 			break;
7708 		case RMX_OFF:
7709 		default:
7710 			*val = DRM_MODE_SCALE_NONE;
7711 			break;
7712 		}
7713 		ret = 0;
7714 	} else if (property == adev->mode_info.underscan_hborder_property) {
7715 		*val = dm_state->underscan_hborder;
7716 		ret = 0;
7717 	} else if (property == adev->mode_info.underscan_vborder_property) {
7718 		*val = dm_state->underscan_vborder;
7719 		ret = 0;
7720 	} else if (property == adev->mode_info.underscan_property) {
7721 		*val = dm_state->underscan_enable;
7722 		ret = 0;
7723 	} else if (property == adev->mode_info.abm_level_property) {
7724 		if (!dm_state->abm_sysfs_forbidden)
7725 			*val = ABM_SYSFS_CONTROL;
7726 		else
7727 			*val = (dm_state->abm_level != ABM_LEVEL_IMMEDIATE_DISABLE) ?
7728 				dm_state->abm_level : 0;
7729 		ret = 0;
7730 	}
7731 
7732 	return ret;
7733 }
7734 
7735 /**
7736  * DOC: panel power savings
7737  *
7738  * The display manager allows you to set your desired **panel power savings**
7739  * level (between 0-4, with 0 representing off), e.g. using the following::
7740  *
7741  *   # echo 3 > /sys/class/drm/card0-eDP-1/amdgpu/panel_power_savings
7742  *
7743  * Modifying this value can have implications on color accuracy, so tread
7744  * carefully.
7745  */
7746 
panel_power_savings_show(struct device * device,struct device_attribute * attr,char * buf)7747 static ssize_t panel_power_savings_show(struct device *device,
7748 					struct device_attribute *attr,
7749 					char *buf)
7750 {
7751 	struct drm_connector *connector = dev_get_drvdata(device);
7752 	struct drm_device *dev = connector->dev;
7753 	u8 val;
7754 
7755 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
7756 	val = to_dm_connector_state(connector->state)->abm_level ==
7757 		ABM_LEVEL_IMMEDIATE_DISABLE ? 0 :
7758 		to_dm_connector_state(connector->state)->abm_level;
7759 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
7760 
7761 	return sysfs_emit(buf, "%u\n", val);
7762 }
7763 
panel_power_savings_store(struct device * device,struct device_attribute * attr,const char * buf,size_t count)7764 static ssize_t panel_power_savings_store(struct device *device,
7765 					 struct device_attribute *attr,
7766 					 const char *buf, size_t count)
7767 {
7768 	struct drm_connector *connector = dev_get_drvdata(device);
7769 	struct drm_device *dev = connector->dev;
7770 	long val;
7771 	int ret;
7772 
7773 	ret = kstrtol(buf, 0, &val);
7774 
7775 	if (ret)
7776 		return ret;
7777 
7778 	if (val < 0 || val > 4)
7779 		return -EINVAL;
7780 
7781 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
7782 	if (to_dm_connector_state(connector->state)->abm_sysfs_forbidden)
7783 		ret = -EBUSY;
7784 	else
7785 		to_dm_connector_state(connector->state)->abm_level = val ?:
7786 			ABM_LEVEL_IMMEDIATE_DISABLE;
7787 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
7788 
7789 	if (ret)
7790 		return ret;
7791 
7792 	drm_kms_helper_hotplug_event(dev);
7793 
7794 	return count;
7795 }
7796 
7797 static DEVICE_ATTR_RW(panel_power_savings);
7798 
7799 static struct attribute *amdgpu_attrs[] = {
7800 	&dev_attr_panel_power_savings.attr,
7801 	NULL
7802 };
7803 
7804 static const struct attribute_group amdgpu_group = {
7805 	.name = "amdgpu",
7806 	.attrs = amdgpu_attrs
7807 };
7808 
7809 static bool
amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector * amdgpu_dm_connector)7810 amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector *amdgpu_dm_connector)
7811 {
7812 	if (amdgpu_dm_abm_level >= 0)
7813 		return false;
7814 
7815 	if (amdgpu_dm_connector->base.connector_type != DRM_MODE_CONNECTOR_eDP)
7816 		return false;
7817 
7818 	/* check for OLED panels */
7819 	if (amdgpu_dm_connector->bl_idx >= 0) {
7820 		struct drm_device *drm = amdgpu_dm_connector->base.dev;
7821 		struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
7822 		struct amdgpu_dm_backlight_caps *caps;
7823 
7824 		caps = &dm->backlight_caps[amdgpu_dm_connector->bl_idx];
7825 		if (caps->aux_support)
7826 			return false;
7827 	}
7828 
7829 	return true;
7830 }
7831 
amdgpu_dm_connector_unregister(struct drm_connector * connector)7832 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
7833 {
7834 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
7835 
7836 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector))
7837 		sysfs_remove_group(&connector->kdev->kobj, &amdgpu_group);
7838 
7839 	cec_notifier_conn_unregister(amdgpu_dm_connector->notifier);
7840 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
7841 }
7842 
amdgpu_dm_connector_destroy(struct drm_connector * connector)7843 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
7844 {
7845 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7846 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
7847 	struct amdgpu_display_manager *dm = &adev->dm;
7848 
7849 	/*
7850 	 * Call only if mst_mgr was initialized before since it's not done
7851 	 * for all connector types.
7852 	 */
7853 	if (aconnector->mst_mgr.dev)
7854 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
7855 
7856 	/* Cancel and flush any pending HDMI HPD debounce work */
7857 	if (aconnector->hdmi_hpd_debounce_delay_ms) {
7858 		cancel_delayed_work_sync(&aconnector->hdmi_hpd_debounce_work);
7859 		if (aconnector->hdmi_prev_sink) {
7860 			dc_sink_release(aconnector->hdmi_prev_sink);
7861 			aconnector->hdmi_prev_sink = NULL;
7862 		}
7863 	}
7864 
7865 	if (aconnector->bl_idx != -1) {
7866 		backlight_device_unregister(dm->backlight_dev[aconnector->bl_idx]);
7867 		dm->backlight_dev[aconnector->bl_idx] = NULL;
7868 	}
7869 
7870 	if (aconnector->dc_em_sink)
7871 		dc_sink_release(aconnector->dc_em_sink);
7872 	aconnector->dc_em_sink = NULL;
7873 	if (aconnector->dc_sink)
7874 		dc_sink_release(aconnector->dc_sink);
7875 	aconnector->dc_sink = NULL;
7876 
7877 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
7878 	drm_connector_unregister(connector);
7879 	drm_connector_cleanup(connector);
7880 	kfree(aconnector->dm_dp_aux.aux.name);
7881 
7882 	kfree(connector);
7883 }
7884 
amdgpu_dm_connector_funcs_reset(struct drm_connector * connector)7885 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
7886 {
7887 	struct dm_connector_state *state =
7888 		to_dm_connector_state(connector->state);
7889 
7890 	if (connector->state)
7891 		__drm_atomic_helper_connector_destroy_state(connector->state);
7892 
7893 	kfree(state);
7894 
7895 	state = kzalloc_obj(*state);
7896 
7897 	if (state) {
7898 		state->scaling = RMX_OFF;
7899 		state->underscan_enable = false;
7900 		state->underscan_hborder = 0;
7901 		state->underscan_vborder = 0;
7902 		state->base.max_requested_bpc = 8;
7903 		state->vcpi_slots = 0;
7904 		state->pbn = 0;
7905 
7906 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) {
7907 			if (amdgpu_dm_abm_level <= 0)
7908 				state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7909 			else
7910 				state->abm_level = amdgpu_dm_abm_level;
7911 		}
7912 
7913 		__drm_atomic_helper_connector_reset(connector, &state->base);
7914 	}
7915 }
7916 
7917 struct drm_connector_state *
amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector * connector)7918 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
7919 {
7920 	struct dm_connector_state *state =
7921 		to_dm_connector_state(connector->state);
7922 
7923 	struct dm_connector_state *new_state =
7924 			kmemdup(state, sizeof(*state), GFP_KERNEL);
7925 
7926 	if (!new_state)
7927 		return NULL;
7928 
7929 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
7930 
7931 	new_state->freesync_capable = state->freesync_capable;
7932 	new_state->abm_level = state->abm_level;
7933 	new_state->scaling = state->scaling;
7934 	new_state->underscan_enable = state->underscan_enable;
7935 	new_state->underscan_hborder = state->underscan_hborder;
7936 	new_state->underscan_vborder = state->underscan_vborder;
7937 	new_state->vcpi_slots = state->vcpi_slots;
7938 	new_state->pbn = state->pbn;
7939 	return &new_state->base;
7940 }
7941 
7942 static int
amdgpu_dm_connector_late_register(struct drm_connector * connector)7943 amdgpu_dm_connector_late_register(struct drm_connector *connector)
7944 {
7945 	struct amdgpu_dm_connector *amdgpu_dm_connector =
7946 		to_amdgpu_dm_connector(connector);
7947 	int r;
7948 
7949 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector)) {
7950 		r = sysfs_create_group(&connector->kdev->kobj,
7951 				       &amdgpu_group);
7952 		if (r)
7953 			return r;
7954 	}
7955 
7956 	amdgpu_dm_register_backlight_device(amdgpu_dm_connector);
7957 
7958 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
7959 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
7960 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
7961 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
7962 		if (r)
7963 			return r;
7964 	}
7965 
7966 #if defined(CONFIG_DEBUG_FS)
7967 	connector_debugfs_init(amdgpu_dm_connector);
7968 #endif
7969 
7970 	return 0;
7971 }
7972 
amdgpu_dm_connector_funcs_force(struct drm_connector * connector)7973 static void amdgpu_dm_connector_funcs_force(struct drm_connector *connector)
7974 {
7975 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7976 	struct dc_link *dc_link = aconnector->dc_link;
7977 	struct dc_sink *dc_em_sink = aconnector->dc_em_sink;
7978 	const struct drm_edid *drm_edid;
7979 	struct i2c_adapter *ddc;
7980 	struct drm_device *dev = connector->dev;
7981 
7982 	if (dc_link && dc_link->aux_mode)
7983 		ddc = &aconnector->dm_dp_aux.aux.ddc;
7984 	else
7985 		ddc = &aconnector->i2c->base;
7986 
7987 	drm_edid = drm_edid_read_ddc(connector, ddc);
7988 	drm_edid_connector_update(connector, drm_edid);
7989 	if (!drm_edid) {
7990 		drm_err(dev, "No EDID found on connector: %s.\n", connector->name);
7991 		return;
7992 	}
7993 
7994 	aconnector->drm_edid = drm_edid;
7995 	/* Update emulated (virtual) sink's EDID */
7996 	if (dc_em_sink && dc_link) {
7997 		// FIXME: Get rid of drm_edid_raw()
7998 		const struct edid *edid = drm_edid_raw(drm_edid);
7999 
8000 		memset(&dc_em_sink->edid_caps, 0, sizeof(struct dc_edid_caps));
8001 		memmove(dc_em_sink->dc_edid.raw_edid, edid,
8002 			(edid->extensions + 1) * EDID_LENGTH);
8003 		dm_helpers_parse_edid_caps(
8004 			dc_link,
8005 			&dc_em_sink->dc_edid,
8006 			&dc_em_sink->edid_caps);
8007 	}
8008 }
8009 
8010 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
8011 	.reset = amdgpu_dm_connector_funcs_reset,
8012 	.detect = amdgpu_dm_connector_detect,
8013 	.fill_modes = drm_helper_probe_single_connector_modes,
8014 	.destroy = amdgpu_dm_connector_destroy,
8015 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
8016 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
8017 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
8018 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
8019 	.late_register = amdgpu_dm_connector_late_register,
8020 	.early_unregister = amdgpu_dm_connector_unregister,
8021 	.force = amdgpu_dm_connector_funcs_force
8022 };
8023 
get_modes(struct drm_connector * connector)8024 static int get_modes(struct drm_connector *connector)
8025 {
8026 	return amdgpu_dm_connector_get_modes(connector);
8027 }
8028 
create_eml_sink(struct amdgpu_dm_connector * aconnector)8029 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
8030 {
8031 	struct drm_connector *connector = &aconnector->base;
8032 	struct dc_link *dc_link = aconnector->dc_link;
8033 	struct dc_sink_init_data init_params = {
8034 			.link = aconnector->dc_link,
8035 			.sink_signal = SIGNAL_TYPE_VIRTUAL
8036 	};
8037 	const struct drm_edid *drm_edid;
8038 	const struct edid *edid;
8039 	struct i2c_adapter *ddc;
8040 
8041 	if (dc_link && dc_link->aux_mode)
8042 		ddc = &aconnector->dm_dp_aux.aux.ddc;
8043 	else
8044 		ddc = &aconnector->i2c->base;
8045 
8046 	drm_edid = drm_edid_read_ddc(connector, ddc);
8047 	drm_edid_connector_update(connector, drm_edid);
8048 	if (!drm_edid) {
8049 		drm_err(connector->dev, "No EDID found on connector: %s.\n", connector->name);
8050 		return;
8051 	}
8052 
8053 	if (connector->display_info.is_hdmi)
8054 		init_params.sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
8055 
8056 	aconnector->drm_edid = drm_edid;
8057 
8058 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
8059 	aconnector->dc_em_sink = dc_link_add_remote_sink(
8060 		aconnector->dc_link,
8061 		(uint8_t *)edid,
8062 		(edid->extensions + 1) * EDID_LENGTH,
8063 		&init_params);
8064 
8065 	if (aconnector->base.force == DRM_FORCE_ON) {
8066 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
8067 		aconnector->dc_link->local_sink :
8068 		aconnector->dc_em_sink;
8069 		if (aconnector->dc_sink)
8070 			dc_sink_retain(aconnector->dc_sink);
8071 	}
8072 }
8073 
handle_edid_mgmt(struct amdgpu_dm_connector * aconnector)8074 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
8075 {
8076 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
8077 
8078 	/*
8079 	 * In case of headless boot with force on for DP managed connector
8080 	 * Those settings have to be != 0 to get initial modeset
8081 	 */
8082 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
8083 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
8084 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
8085 	}
8086 
8087 	create_eml_sink(aconnector);
8088 }
8089 
dm_validate_stream_and_context(struct dc * dc,struct dc_stream_state * stream)8090 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
8091 						struct dc_stream_state *stream)
8092 {
8093 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
8094 	struct dc_plane_state *dc_plane_state = NULL;
8095 	struct dc_state *dc_state = NULL;
8096 
8097 	if (!stream)
8098 		goto cleanup;
8099 
8100 	dc_plane_state = dc_create_plane_state(dc);
8101 	if (!dc_plane_state)
8102 		goto cleanup;
8103 
8104 	dc_state = dc_state_create(dc, NULL);
8105 	if (!dc_state)
8106 		goto cleanup;
8107 
8108 	/* populate stream to plane */
8109 	dc_plane_state->src_rect.height  = stream->src.height;
8110 	dc_plane_state->src_rect.width   = stream->src.width;
8111 	dc_plane_state->dst_rect.height  = stream->src.height;
8112 	dc_plane_state->dst_rect.width   = stream->src.width;
8113 	dc_plane_state->clip_rect.height = stream->src.height;
8114 	dc_plane_state->clip_rect.width  = stream->src.width;
8115 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
8116 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
8117 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
8118 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
8119 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
8120 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
8121 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
8122 	dc_plane_state->rotation = ROTATION_ANGLE_0;
8123 	dc_plane_state->is_tiling_rotated = false;
8124 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
8125 
8126 	dc_result = dc_validate_stream(dc, stream);
8127 	if (dc_result == DC_OK)
8128 		dc_result = dc_validate_plane(dc, dc_plane_state);
8129 
8130 	if (dc_result == DC_OK)
8131 		dc_result = dc_state_add_stream(dc, dc_state, stream);
8132 
8133 	if (dc_result == DC_OK && !dc_state_add_plane(
8134 						dc,
8135 						stream,
8136 						dc_plane_state,
8137 						dc_state))
8138 		dc_result = DC_FAIL_ATTACH_SURFACES;
8139 
8140 	if (dc_result == DC_OK)
8141 		dc_result = dc_validate_global_state(dc, dc_state, DC_VALIDATE_MODE_ONLY);
8142 
8143 cleanup:
8144 	if (dc_state)
8145 		dc_state_release(dc_state);
8146 
8147 	if (dc_plane_state)
8148 		dc_plane_state_release(dc_plane_state);
8149 
8150 	return dc_result;
8151 }
8152 
8153 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)8154 create_validate_stream_for_sink(struct drm_connector *connector,
8155 				const struct drm_display_mode *drm_mode,
8156 				const struct dm_connector_state *dm_state,
8157 				const struct dc_stream_state *old_stream)
8158 {
8159 	struct amdgpu_dm_connector *aconnector = NULL;
8160 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8161 	struct dc_stream_state *stream;
8162 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
8163 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
8164 	enum dc_status dc_result = DC_OK;
8165 	uint8_t bpc_limit = 6;
8166 
8167 	if (!dm_state)
8168 		return NULL;
8169 
8170 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
8171 		aconnector = to_amdgpu_dm_connector(connector);
8172 
8173 	if (aconnector &&
8174 	    (aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
8175 	     aconnector->dc_link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER))
8176 		bpc_limit = 8;
8177 
8178 	do {
8179 		drm_dbg_kms(connector->dev, "Trying with %d bpc\n", requested_bpc);
8180 		stream = create_stream_for_sink(connector, drm_mode,
8181 						dm_state, old_stream,
8182 						requested_bpc);
8183 		if (stream == NULL) {
8184 			drm_err(adev_to_drm(adev), "Failed to create stream for sink!\n");
8185 			break;
8186 		}
8187 
8188 		dc_result = dc_validate_stream(adev->dm.dc, stream);
8189 
8190 		if (!aconnector) /* writeback connector */
8191 			return stream;
8192 
8193 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
8194 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
8195 
8196 		if (dc_result == DC_OK)
8197 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
8198 
8199 		if (dc_result != DC_OK) {
8200 			drm_dbg_kms(connector->dev, "Pruned mode %d x %d (clk %d) %s %s -- %s\n",
8201 				      drm_mode->hdisplay,
8202 				      drm_mode->vdisplay,
8203 				      drm_mode->clock,
8204 				      dc_pixel_encoding_to_str(stream->timing.pixel_encoding),
8205 				      dc_color_depth_to_str(stream->timing.display_color_depth),
8206 				      dc_status_to_str(dc_result));
8207 
8208 			dc_stream_release(stream);
8209 			stream = NULL;
8210 			requested_bpc -= 2; /* lower bpc to retry validation */
8211 		}
8212 
8213 	} while (stream == NULL && requested_bpc >= bpc_limit);
8214 
8215 	switch (dc_result) {
8216 	/*
8217 	 * If we failed to validate DP bandwidth stream with the requested RGB color depth,
8218 	 * we try to fallback and configure in order:
8219 	 * YUV422 (8bpc, 6bpc)
8220 	 * YUV420 (8bpc, 6bpc)
8221 	 */
8222 	case DC_FAIL_ENC_VALIDATE:
8223 	case DC_EXCEED_DONGLE_CAP:
8224 	case DC_NO_DP_LINK_BANDWIDTH:
8225 		/* recursively entered twice and already tried both YUV422 and YUV420 */
8226 		if (aconnector->force_yuv422_output && aconnector->force_yuv420_output)
8227 			break;
8228 		/* first failure; try YUV422 */
8229 		if (!aconnector->force_yuv422_output) {
8230 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV422\n",
8231 				    __func__, __LINE__, dc_result);
8232 			aconnector->force_yuv422_output = true;
8233 		/* recursively entered and YUV422 failed, try YUV420 */
8234 		} else if (!aconnector->force_yuv420_output) {
8235 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV420\n",
8236 				    __func__, __LINE__, dc_result);
8237 			aconnector->force_yuv420_output = true;
8238 		}
8239 		stream = create_validate_stream_for_sink(connector, drm_mode,
8240 							 dm_state, old_stream);
8241 		aconnector->force_yuv422_output = false;
8242 		aconnector->force_yuv420_output = false;
8243 		break;
8244 	case DC_OK:
8245 		break;
8246 	default:
8247 		drm_dbg_kms(connector->dev, "%s:%d Unhandled validation failure %d\n",
8248 			    __func__, __LINE__, dc_result);
8249 		break;
8250 	}
8251 
8252 	return stream;
8253 }
8254 
amdgpu_dm_connector_mode_valid(struct drm_connector * connector,const struct drm_display_mode * mode)8255 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
8256 				   const struct drm_display_mode *mode)
8257 {
8258 	int result = MODE_ERROR;
8259 	struct dc_sink *dc_sink;
8260 	struct drm_display_mode *test_mode;
8261 	/* TODO: Unhardcode stream count */
8262 	struct dc_stream_state *stream;
8263 	/* we always have an amdgpu_dm_connector here since we got
8264 	 * here via the amdgpu_dm_connector_helper_funcs
8265 	 */
8266 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8267 
8268 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
8269 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
8270 		return result;
8271 
8272 	/*
8273 	 * Only run this the first time mode_valid is called to initilialize
8274 	 * EDID mgmt
8275 	 */
8276 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
8277 		!aconnector->dc_em_sink)
8278 		handle_edid_mgmt(aconnector);
8279 
8280 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
8281 
8282 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
8283 				aconnector->base.force != DRM_FORCE_ON) {
8284 		drm_err(connector->dev, "dc_sink is NULL!\n");
8285 		goto fail;
8286 	}
8287 
8288 	test_mode = drm_mode_duplicate(connector->dev, mode);
8289 	if (!test_mode)
8290 		goto fail;
8291 
8292 	drm_mode_set_crtcinfo(test_mode, 0);
8293 
8294 	stream = create_validate_stream_for_sink(connector, test_mode,
8295 						 to_dm_connector_state(connector->state),
8296 						 NULL);
8297 	drm_mode_destroy(connector->dev, test_mode);
8298 	if (stream) {
8299 		dc_stream_release(stream);
8300 		result = MODE_OK;
8301 	}
8302 
8303 fail:
8304 	/* TODO: error handling*/
8305 	return result;
8306 }
8307 
fill_hdr_info_packet(const struct drm_connector_state * state,struct dc_info_packet * out)8308 static int fill_hdr_info_packet(const struct drm_connector_state *state,
8309 				struct dc_info_packet *out)
8310 {
8311 	struct hdmi_drm_infoframe frame;
8312 	unsigned char buf[30]; /* 26 + 4 */
8313 	ssize_t len;
8314 	int ret, i;
8315 
8316 	memset(out, 0, sizeof(*out));
8317 
8318 	if (!state->hdr_output_metadata)
8319 		return 0;
8320 
8321 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
8322 	if (ret)
8323 		return ret;
8324 
8325 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
8326 	if (len < 0)
8327 		return (int)len;
8328 
8329 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
8330 	if (len != 30)
8331 		return -EINVAL;
8332 
8333 	/* Prepare the infopacket for DC. */
8334 	switch (state->connector->connector_type) {
8335 	case DRM_MODE_CONNECTOR_HDMIA:
8336 		out->hb0 = 0x87; /* type */
8337 		out->hb1 = 0x01; /* version */
8338 		out->hb2 = 0x1A; /* length */
8339 		out->sb[0] = buf[3]; /* checksum */
8340 		i = 1;
8341 		break;
8342 
8343 	case DRM_MODE_CONNECTOR_DisplayPort:
8344 	case DRM_MODE_CONNECTOR_eDP:
8345 		out->hb0 = 0x00; /* sdp id, zero */
8346 		out->hb1 = 0x87; /* type */
8347 		out->hb2 = 0x1D; /* payload len - 1 */
8348 		out->hb3 = (0x13 << 2); /* sdp version */
8349 		out->sb[0] = 0x01; /* version */
8350 		out->sb[1] = 0x1A; /* length */
8351 		i = 2;
8352 		break;
8353 
8354 	default:
8355 		return -EINVAL;
8356 	}
8357 
8358 	memcpy(&out->sb[i], &buf[4], 26);
8359 	out->valid = true;
8360 
8361 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
8362 		       sizeof(out->sb), false);
8363 
8364 	return 0;
8365 }
8366 
8367 static int
amdgpu_dm_connector_atomic_check(struct drm_connector * conn,struct drm_atomic_state * state)8368 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
8369 				 struct drm_atomic_state *state)
8370 {
8371 	struct drm_connector_state *new_con_state =
8372 		drm_atomic_get_new_connector_state(state, conn);
8373 	struct drm_connector_state *old_con_state =
8374 		drm_atomic_get_old_connector_state(state, conn);
8375 	struct drm_crtc *crtc = new_con_state->crtc;
8376 	struct drm_crtc_state *new_crtc_state;
8377 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
8378 	int ret;
8379 
8380 	if (WARN_ON(unlikely(!old_con_state || !new_con_state)))
8381 		return -EINVAL;
8382 
8383 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
8384 
8385 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
8386 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
8387 		if (ret < 0)
8388 			return ret;
8389 	}
8390 
8391 	if (!crtc)
8392 		return 0;
8393 
8394 	if (new_con_state->privacy_screen_sw_state != old_con_state->privacy_screen_sw_state) {
8395 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8396 		if (IS_ERR(new_crtc_state))
8397 			return PTR_ERR(new_crtc_state);
8398 
8399 		new_crtc_state->mode_changed = true;
8400 	}
8401 
8402 	if (new_con_state->colorspace != old_con_state->colorspace) {
8403 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8404 		if (IS_ERR(new_crtc_state))
8405 			return PTR_ERR(new_crtc_state);
8406 
8407 		new_crtc_state->mode_changed = true;
8408 	}
8409 
8410 	if (new_con_state->content_type != old_con_state->content_type) {
8411 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8412 		if (IS_ERR(new_crtc_state))
8413 			return PTR_ERR(new_crtc_state);
8414 
8415 		new_crtc_state->mode_changed = true;
8416 	}
8417 
8418 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
8419 		struct dc_info_packet hdr_infopacket;
8420 
8421 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
8422 		if (ret)
8423 			return ret;
8424 
8425 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8426 		if (IS_ERR(new_crtc_state))
8427 			return PTR_ERR(new_crtc_state);
8428 
8429 		/*
8430 		 * DC considers the stream backends changed if the
8431 		 * static metadata changes. Forcing the modeset also
8432 		 * gives a simple way for userspace to switch from
8433 		 * 8bpc to 10bpc when setting the metadata to enter
8434 		 * or exit HDR.
8435 		 *
8436 		 * Changing the static metadata after it's been
8437 		 * set is permissible, however. So only force a
8438 		 * modeset if we're entering or exiting HDR.
8439 		 */
8440 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
8441 			!old_con_state->hdr_output_metadata ||
8442 			!new_con_state->hdr_output_metadata;
8443 	}
8444 
8445 	return 0;
8446 }
8447 
8448 static const struct drm_connector_helper_funcs
8449 amdgpu_dm_connector_helper_funcs = {
8450 	/*
8451 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
8452 	 * modes will be filtered by drm_mode_validate_size(), and those modes
8453 	 * are missing after user start lightdm. So we need to renew modes list.
8454 	 * in get_modes call back, not just return the modes count
8455 	 */
8456 	.get_modes = get_modes,
8457 	.mode_valid = amdgpu_dm_connector_mode_valid,
8458 	.atomic_check = amdgpu_dm_connector_atomic_check,
8459 };
8460 
dm_encoder_helper_disable(struct drm_encoder * encoder)8461 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
8462 {
8463 
8464 }
8465 
convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)8466 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
8467 {
8468 	switch (display_color_depth) {
8469 	case COLOR_DEPTH_666:
8470 		return 6;
8471 	case COLOR_DEPTH_888:
8472 		return 8;
8473 	case COLOR_DEPTH_101010:
8474 		return 10;
8475 	case COLOR_DEPTH_121212:
8476 		return 12;
8477 	case COLOR_DEPTH_141414:
8478 		return 14;
8479 	case COLOR_DEPTH_161616:
8480 		return 16;
8481 	default:
8482 		break;
8483 	}
8484 	return 0;
8485 }
8486 
dm_encoder_helper_atomic_check(struct drm_encoder * encoder,struct drm_crtc_state * crtc_state,struct drm_connector_state * conn_state)8487 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
8488 					  struct drm_crtc_state *crtc_state,
8489 					  struct drm_connector_state *conn_state)
8490 {
8491 	struct drm_atomic_state *state = crtc_state->state;
8492 	struct drm_connector *connector = conn_state->connector;
8493 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8494 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
8495 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
8496 	struct drm_dp_mst_topology_mgr *mst_mgr;
8497 	struct drm_dp_mst_port *mst_port;
8498 	struct drm_dp_mst_topology_state *mst_state;
8499 	enum dc_color_depth color_depth;
8500 	int clock, bpp = 0;
8501 	bool is_y420 = false;
8502 
8503 	if ((connector->connector_type == DRM_MODE_CONNECTOR_eDP) ||
8504 	    (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)) {
8505 		struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8506 		struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8507 		enum drm_mode_status result;
8508 
8509 		result = drm_crtc_helper_mode_valid_fixed(encoder->crtc, adjusted_mode, native_mode);
8510 		if (result != MODE_OK && dm_new_connector_state->scaling == RMX_OFF) {
8511 			drm_dbg_driver(encoder->dev,
8512 				       "mode %dx%d@%dHz is not native, enabling scaling\n",
8513 				       adjusted_mode->hdisplay, adjusted_mode->vdisplay,
8514 				       drm_mode_vrefresh(adjusted_mode));
8515 			dm_new_connector_state->scaling = RMX_ASPECT;
8516 		}
8517 		return 0;
8518 	}
8519 
8520 	if (!aconnector->mst_output_port)
8521 		return 0;
8522 
8523 	mst_port = aconnector->mst_output_port;
8524 	mst_mgr = &aconnector->mst_root->mst_mgr;
8525 
8526 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
8527 		return 0;
8528 
8529 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
8530 	if (IS_ERR(mst_state))
8531 		return PTR_ERR(mst_state);
8532 
8533 	mst_state->pbn_div.full = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
8534 
8535 	if (!state->duplicated) {
8536 		int max_bpc = conn_state->max_requested_bpc;
8537 
8538 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
8539 			  aconnector->force_yuv420_output;
8540 		color_depth = convert_color_depth_from_display_info(connector,
8541 								    is_y420,
8542 								    max_bpc);
8543 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
8544 		clock = adjusted_mode->clock;
8545 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
8546 	}
8547 
8548 	dm_new_connector_state->vcpi_slots =
8549 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
8550 					      dm_new_connector_state->pbn);
8551 	if (dm_new_connector_state->vcpi_slots < 0) {
8552 		drm_dbg_atomic(connector->dev, "failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
8553 		return dm_new_connector_state->vcpi_slots;
8554 	}
8555 	return 0;
8556 }
8557 
8558 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
8559 	.disable = dm_encoder_helper_disable,
8560 	.atomic_check = dm_encoder_helper_atomic_check
8561 };
8562 
dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state * state,struct dc_state * dc_state,struct dsc_mst_fairness_vars * vars)8563 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state *state,
8564 					    struct dc_state *dc_state,
8565 					    struct dsc_mst_fairness_vars *vars)
8566 {
8567 	struct dc_stream_state *stream = NULL;
8568 	struct drm_connector *connector;
8569 	struct drm_connector_state *new_con_state;
8570 	struct amdgpu_dm_connector *aconnector;
8571 	struct dm_connector_state *dm_conn_state;
8572 	int i, j, ret;
8573 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
8574 
8575 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8576 
8577 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
8578 			continue;
8579 
8580 		aconnector = to_amdgpu_dm_connector(connector);
8581 
8582 		if (!aconnector->mst_output_port)
8583 			continue;
8584 
8585 		if (!new_con_state || !new_con_state->crtc)
8586 			continue;
8587 
8588 		dm_conn_state = to_dm_connector_state(new_con_state);
8589 
8590 		for (j = 0; j < dc_state->stream_count; j++) {
8591 			stream = dc_state->streams[j];
8592 			if (!stream)
8593 				continue;
8594 
8595 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
8596 				break;
8597 
8598 			stream = NULL;
8599 		}
8600 
8601 		if (!stream)
8602 			continue;
8603 
8604 		pbn_div = dm_mst_get_pbn_divider(stream->link);
8605 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
8606 		for (j = 0; j < dc_state->stream_count; j++) {
8607 			if (vars[j].aconnector == aconnector) {
8608 				pbn = vars[j].pbn;
8609 				break;
8610 			}
8611 		}
8612 
8613 		if (j == dc_state->stream_count || pbn_div == 0)
8614 			continue;
8615 
8616 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
8617 
8618 		if (stream->timing.flags.DSC != 1) {
8619 			dm_conn_state->pbn = pbn;
8620 			dm_conn_state->vcpi_slots = slot_num;
8621 
8622 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
8623 							   dm_conn_state->pbn, false);
8624 			if (ret < 0)
8625 				return ret;
8626 
8627 			continue;
8628 		}
8629 
8630 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
8631 		if (vcpi < 0)
8632 			return vcpi;
8633 
8634 		dm_conn_state->pbn = pbn;
8635 		dm_conn_state->vcpi_slots = vcpi;
8636 	}
8637 	return 0;
8638 }
8639 
to_drm_connector_type(enum signal_type st,uint32_t connector_id)8640 static int to_drm_connector_type(enum signal_type st, uint32_t connector_id)
8641 {
8642 	switch (st) {
8643 	case SIGNAL_TYPE_HDMI_TYPE_A:
8644 		return DRM_MODE_CONNECTOR_HDMIA;
8645 	case SIGNAL_TYPE_EDP:
8646 		return DRM_MODE_CONNECTOR_eDP;
8647 	case SIGNAL_TYPE_LVDS:
8648 		return DRM_MODE_CONNECTOR_LVDS;
8649 	case SIGNAL_TYPE_RGB:
8650 		return DRM_MODE_CONNECTOR_VGA;
8651 	case SIGNAL_TYPE_DISPLAY_PORT:
8652 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
8653 		/* External DP bridges have a different connector type. */
8654 		if (connector_id == CONNECTOR_ID_VGA)
8655 			return DRM_MODE_CONNECTOR_VGA;
8656 		else if (connector_id == CONNECTOR_ID_LVDS)
8657 			return DRM_MODE_CONNECTOR_LVDS;
8658 
8659 		return DRM_MODE_CONNECTOR_DisplayPort;
8660 	case SIGNAL_TYPE_DVI_DUAL_LINK:
8661 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
8662 		if (connector_id == CONNECTOR_ID_SINGLE_LINK_DVII ||
8663 			connector_id == CONNECTOR_ID_DUAL_LINK_DVII)
8664 			return DRM_MODE_CONNECTOR_DVII;
8665 
8666 		return DRM_MODE_CONNECTOR_DVID;
8667 	case SIGNAL_TYPE_VIRTUAL:
8668 		return DRM_MODE_CONNECTOR_VIRTUAL;
8669 
8670 	default:
8671 		return DRM_MODE_CONNECTOR_Unknown;
8672 	}
8673 }
8674 
amdgpu_dm_connector_to_encoder(struct drm_connector * connector)8675 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
8676 {
8677 	struct drm_encoder *encoder;
8678 
8679 	/* There is only one encoder per connector */
8680 	drm_connector_for_each_possible_encoder(connector, encoder)
8681 		return encoder;
8682 
8683 	return NULL;
8684 }
8685 
amdgpu_dm_get_native_mode(struct drm_connector * connector)8686 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
8687 {
8688 	struct drm_encoder *encoder;
8689 	struct amdgpu_encoder *amdgpu_encoder;
8690 
8691 	encoder = amdgpu_dm_connector_to_encoder(connector);
8692 
8693 	if (encoder == NULL)
8694 		return;
8695 
8696 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8697 
8698 	amdgpu_encoder->native_mode.clock = 0;
8699 
8700 	if (!list_empty(&connector->probed_modes)) {
8701 		struct drm_display_mode *preferred_mode = NULL;
8702 
8703 		list_for_each_entry(preferred_mode,
8704 				    &connector->probed_modes,
8705 				    head) {
8706 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
8707 				amdgpu_encoder->native_mode = *preferred_mode;
8708 
8709 			break;
8710 		}
8711 
8712 	}
8713 }
8714 
8715 static struct drm_display_mode *
amdgpu_dm_create_common_mode(struct drm_encoder * encoder,const char * name,int hdisplay,int vdisplay)8716 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
8717 			     const char *name,
8718 			     int hdisplay, int vdisplay)
8719 {
8720 	struct drm_device *dev = encoder->dev;
8721 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8722 	struct drm_display_mode *mode = NULL;
8723 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8724 
8725 	mode = drm_mode_duplicate(dev, native_mode);
8726 
8727 	if (mode == NULL)
8728 		return NULL;
8729 
8730 	mode->hdisplay = hdisplay;
8731 	mode->vdisplay = vdisplay;
8732 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8733 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
8734 
8735 	return mode;
8736 
8737 }
8738 
8739 static const struct amdgpu_dm_mode_size {
8740 	char name[DRM_DISPLAY_MODE_LEN];
8741 	int w;
8742 	int h;
8743 } common_modes[] = {
8744 	{  "640x480",  640,  480},
8745 	{  "800x600",  800,  600},
8746 	{ "1024x768", 1024,  768},
8747 	{ "1280x720", 1280,  720},
8748 	{ "1280x800", 1280,  800},
8749 	{"1280x1024", 1280, 1024},
8750 	{ "1440x900", 1440,  900},
8751 	{"1680x1050", 1680, 1050},
8752 	{"1600x1200", 1600, 1200},
8753 	{"1920x1080", 1920, 1080},
8754 	{"1920x1200", 1920, 1200}
8755 };
8756 
amdgpu_dm_connector_add_common_modes(struct drm_encoder * encoder,struct drm_connector * connector)8757 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
8758 						 struct drm_connector *connector)
8759 {
8760 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8761 	struct drm_display_mode *mode = NULL;
8762 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8763 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8764 				to_amdgpu_dm_connector(connector);
8765 	int i;
8766 	int n;
8767 
8768 	if ((connector->connector_type != DRM_MODE_CONNECTOR_eDP) &&
8769 	    (connector->connector_type != DRM_MODE_CONNECTOR_LVDS))
8770 		return;
8771 
8772 	n = ARRAY_SIZE(common_modes);
8773 
8774 	for (i = 0; i < n; i++) {
8775 		struct drm_display_mode *curmode = NULL;
8776 		bool mode_existed = false;
8777 
8778 		if (common_modes[i].w > native_mode->hdisplay ||
8779 		    common_modes[i].h > native_mode->vdisplay ||
8780 		   (common_modes[i].w == native_mode->hdisplay &&
8781 		    common_modes[i].h == native_mode->vdisplay))
8782 			continue;
8783 
8784 		list_for_each_entry(curmode, &connector->probed_modes, head) {
8785 			if (common_modes[i].w == curmode->hdisplay &&
8786 			    common_modes[i].h == curmode->vdisplay) {
8787 				mode_existed = true;
8788 				break;
8789 			}
8790 		}
8791 
8792 		if (mode_existed)
8793 			continue;
8794 
8795 		mode = amdgpu_dm_create_common_mode(encoder,
8796 				common_modes[i].name, common_modes[i].w,
8797 				common_modes[i].h);
8798 		if (!mode)
8799 			continue;
8800 
8801 		drm_mode_probed_add(connector, mode);
8802 		amdgpu_dm_connector->num_modes++;
8803 	}
8804 }
8805 
amdgpu_set_panel_orientation(struct drm_connector * connector)8806 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
8807 {
8808 	struct drm_encoder *encoder;
8809 	struct amdgpu_encoder *amdgpu_encoder;
8810 	const struct drm_display_mode *native_mode;
8811 
8812 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
8813 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
8814 		return;
8815 
8816 	mutex_lock(&connector->dev->mode_config.mutex);
8817 	amdgpu_dm_connector_get_modes(connector);
8818 	mutex_unlock(&connector->dev->mode_config.mutex);
8819 
8820 	encoder = amdgpu_dm_connector_to_encoder(connector);
8821 	if (!encoder)
8822 		return;
8823 
8824 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8825 
8826 	native_mode = &amdgpu_encoder->native_mode;
8827 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
8828 		return;
8829 
8830 	drm_connector_set_panel_orientation_with_quirk(connector,
8831 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
8832 						       native_mode->hdisplay,
8833 						       native_mode->vdisplay);
8834 }
8835 
amdgpu_dm_connector_ddc_get_modes(struct drm_connector * connector,const struct drm_edid * drm_edid)8836 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
8837 					      const struct drm_edid *drm_edid)
8838 {
8839 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8840 			to_amdgpu_dm_connector(connector);
8841 
8842 	if (drm_edid) {
8843 		/* empty probed_modes */
8844 		INIT_LIST_HEAD(&connector->probed_modes);
8845 		amdgpu_dm_connector->num_modes =
8846 				drm_edid_connector_add_modes(connector);
8847 
8848 		/* sorting the probed modes before calling function
8849 		 * amdgpu_dm_get_native_mode() since EDID can have
8850 		 * more than one preferred mode. The modes that are
8851 		 * later in the probed mode list could be of higher
8852 		 * and preferred resolution. For example, 3840x2160
8853 		 * resolution in base EDID preferred timing and 4096x2160
8854 		 * preferred resolution in DID extension block later.
8855 		 */
8856 		drm_mode_sort(&connector->probed_modes);
8857 		amdgpu_dm_get_native_mode(connector);
8858 
8859 		/* Freesync capabilities are reset by calling
8860 		 * drm_edid_connector_add_modes() and need to be
8861 		 * restored here.
8862 		 */
8863 		amdgpu_dm_update_freesync_caps(connector, drm_edid, false);
8864 	} else {
8865 		amdgpu_dm_connector->num_modes = 0;
8866 	}
8867 }
8868 
is_duplicate_mode(struct amdgpu_dm_connector * aconnector,struct drm_display_mode * mode)8869 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
8870 			      struct drm_display_mode *mode)
8871 {
8872 	struct drm_display_mode *m;
8873 
8874 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
8875 		if (drm_mode_equal(m, mode))
8876 			return true;
8877 	}
8878 
8879 	return false;
8880 }
8881 
add_fs_modes(struct amdgpu_dm_connector * aconnector)8882 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
8883 {
8884 	const struct drm_display_mode *m;
8885 	struct drm_display_mode *new_mode;
8886 	uint i;
8887 	u32 new_modes_count = 0;
8888 
8889 	/* Standard FPS values
8890 	 *
8891 	 * 23.976       - TV/NTSC
8892 	 * 24           - Cinema
8893 	 * 25           - TV/PAL
8894 	 * 29.97        - TV/NTSC
8895 	 * 30           - TV/NTSC
8896 	 * 48           - Cinema HFR
8897 	 * 50           - TV/PAL
8898 	 * 60           - Commonly used
8899 	 * 48,72,96,120 - Multiples of 24
8900 	 */
8901 	static const u32 common_rates[] = {
8902 		23976, 24000, 25000, 29970, 30000,
8903 		48000, 50000, 60000, 72000, 96000, 120000
8904 	};
8905 
8906 	/*
8907 	 * Find mode with highest refresh rate with the same resolution
8908 	 * as the preferred mode. Some monitors report a preferred mode
8909 	 * with lower resolution than the highest refresh rate supported.
8910 	 */
8911 
8912 	m = get_highest_refresh_rate_mode(aconnector, true);
8913 	if (!m)
8914 		return 0;
8915 
8916 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
8917 		u64 target_vtotal, target_vtotal_diff;
8918 		u64 num, den;
8919 
8920 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
8921 			continue;
8922 
8923 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
8924 		    common_rates[i] > aconnector->max_vfreq * 1000)
8925 			continue;
8926 
8927 		num = (unsigned long long)m->clock * 1000 * 1000;
8928 		den = common_rates[i] * (unsigned long long)m->htotal;
8929 		target_vtotal = div_u64(num, den);
8930 		target_vtotal_diff = target_vtotal - m->vtotal;
8931 
8932 		/* Check for illegal modes */
8933 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
8934 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
8935 		    m->vtotal + target_vtotal_diff < m->vsync_end)
8936 			continue;
8937 
8938 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
8939 		if (!new_mode)
8940 			goto out;
8941 
8942 		new_mode->vtotal += (u16)target_vtotal_diff;
8943 		new_mode->vsync_start += (u16)target_vtotal_diff;
8944 		new_mode->vsync_end += (u16)target_vtotal_diff;
8945 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8946 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
8947 
8948 		if (!is_duplicate_mode(aconnector, new_mode)) {
8949 			drm_mode_probed_add(&aconnector->base, new_mode);
8950 			new_modes_count += 1;
8951 		} else
8952 			drm_mode_destroy(aconnector->base.dev, new_mode);
8953 	}
8954  out:
8955 	return new_modes_count;
8956 }
8957 
amdgpu_dm_connector_add_freesync_modes(struct drm_connector * connector,const struct drm_edid * drm_edid)8958 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
8959 						   const struct drm_edid *drm_edid)
8960 {
8961 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8962 		to_amdgpu_dm_connector(connector);
8963 
8964 	if (!(amdgpu_freesync_vid_mode && drm_edid))
8965 		return;
8966 
8967 	if (!amdgpu_dm_connector->dc_sink || !amdgpu_dm_connector->dc_link)
8968 		return;
8969 
8970 	if (!dc_supports_vrr(amdgpu_dm_connector->dc_sink->ctx->dce_version))
8971 		return;
8972 
8973 	if (dc_connector_supports_analog(amdgpu_dm_connector->dc_link->link_id.id) &&
8974 	    amdgpu_dm_connector->dc_sink->edid_caps.analog)
8975 		return;
8976 
8977 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
8978 		amdgpu_dm_connector->num_modes +=
8979 			add_fs_modes(amdgpu_dm_connector);
8980 }
8981 
amdgpu_dm_connector_get_modes(struct drm_connector * connector)8982 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
8983 {
8984 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8985 			to_amdgpu_dm_connector(connector);
8986 	struct dc_link *dc_link = amdgpu_dm_connector->dc_link;
8987 	struct drm_encoder *encoder;
8988 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
8989 	struct dc_link_settings *verified_link_cap = &dc_link->verified_link_cap;
8990 	const struct dc *dc = dc_link->dc;
8991 
8992 	encoder = amdgpu_dm_connector_to_encoder(connector);
8993 
8994 	if (!drm_edid) {
8995 		amdgpu_dm_connector->num_modes =
8996 				drm_add_modes_noedid(connector, 640, 480);
8997 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
8998 			amdgpu_dm_connector->num_modes +=
8999 				drm_add_modes_noedid(connector, 1920, 1080);
9000 
9001 		if (amdgpu_dm_connector->dc_sink &&
9002 		    amdgpu_dm_connector->dc_sink->edid_caps.analog &&
9003 		    dc_connector_supports_analog(dc_link->link_id.id)) {
9004 			/* Analog monitor connected by DAC load detection.
9005 			 * Add common modes. It will be up to the user to select one that works.
9006 			 */
9007 			for (int i = 0; i < ARRAY_SIZE(common_modes); i++)
9008 				amdgpu_dm_connector->num_modes += drm_add_modes_noedid(
9009 					connector, common_modes[i].w, common_modes[i].h);
9010 		}
9011 	} else {
9012 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
9013 		if (encoder)
9014 			amdgpu_dm_connector_add_common_modes(encoder, connector);
9015 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
9016 	}
9017 	amdgpu_dm_fbc_init(connector);
9018 
9019 	return amdgpu_dm_connector->num_modes;
9020 }
9021 
9022 static const u32 supported_colorspaces =
9023 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
9024 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
9025 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
9026 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
9027 
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)9028 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
9029 				     struct amdgpu_dm_connector *aconnector,
9030 				     int connector_type,
9031 				     struct dc_link *link,
9032 				     int link_index)
9033 {
9034 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
9035 
9036 	/*
9037 	 * Some of the properties below require access to state, like bpc.
9038 	 * Allocate some default initial connector state with our reset helper.
9039 	 */
9040 	if (aconnector->base.funcs->reset)
9041 		aconnector->base.funcs->reset(&aconnector->base);
9042 
9043 	aconnector->connector_id = link_index;
9044 	aconnector->bl_idx = -1;
9045 	aconnector->dc_link = link;
9046 	aconnector->base.interlace_allowed = false;
9047 	aconnector->base.doublescan_allowed = false;
9048 	aconnector->base.stereo_allowed = false;
9049 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
9050 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
9051 	aconnector->audio_inst = -1;
9052 	aconnector->pack_sdp_v1_3 = false;
9053 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
9054 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
9055 	mutex_init(&aconnector->hpd_lock);
9056 	mutex_init(&aconnector->handle_mst_msg_ready);
9057 
9058 	/*
9059 	 * If HDMI HPD debounce delay is set, use the minimum between selected
9060 	 * value and AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS
9061 	 */
9062 	if (amdgpu_hdmi_hpd_debounce_delay_ms) {
9063 		aconnector->hdmi_hpd_debounce_delay_ms = min(amdgpu_hdmi_hpd_debounce_delay_ms,
9064 							     AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS);
9065 		INIT_DELAYED_WORK(&aconnector->hdmi_hpd_debounce_work, hdmi_hpd_debounce_work);
9066 		aconnector->hdmi_prev_sink = NULL;
9067 	} else {
9068 		aconnector->hdmi_hpd_debounce_delay_ms = 0;
9069 	}
9070 
9071 	/*
9072 	 * configure support HPD hot plug connector_>polled default value is 0
9073 	 * which means HPD hot plug not supported
9074 	 */
9075 	switch (connector_type) {
9076 	case DRM_MODE_CONNECTOR_HDMIA:
9077 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9078 		aconnector->base.ycbcr_420_allowed =
9079 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
9080 		break;
9081 	case DRM_MODE_CONNECTOR_DisplayPort:
9082 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9083 		link->link_enc = link_enc_cfg_get_link_enc(link);
9084 		ASSERT(link->link_enc);
9085 		if (link->link_enc)
9086 			aconnector->base.ycbcr_420_allowed =
9087 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
9088 		break;
9089 	case DRM_MODE_CONNECTOR_DVID:
9090 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9091 		break;
9092 	case DRM_MODE_CONNECTOR_DVII:
9093 	case DRM_MODE_CONNECTOR_VGA:
9094 		aconnector->base.polled =
9095 			DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT;
9096 		break;
9097 	default:
9098 		break;
9099 	}
9100 
9101 	drm_object_attach_property(&aconnector->base.base,
9102 				dm->ddev->mode_config.scaling_mode_property,
9103 				DRM_MODE_SCALE_NONE);
9104 
9105 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA
9106 		|| (connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root))
9107 		drm_connector_attach_broadcast_rgb_property(&aconnector->base);
9108 
9109 	drm_object_attach_property(&aconnector->base.base,
9110 				adev->mode_info.underscan_property,
9111 				UNDERSCAN_OFF);
9112 	drm_object_attach_property(&aconnector->base.base,
9113 				adev->mode_info.underscan_hborder_property,
9114 				0);
9115 	drm_object_attach_property(&aconnector->base.base,
9116 				adev->mode_info.underscan_vborder_property,
9117 				0);
9118 
9119 	if (!aconnector->mst_root)
9120 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
9121 
9122 	aconnector->base.state->max_bpc = 16;
9123 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
9124 
9125 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9126 		/* Content Type is currently only implemented for HDMI. */
9127 		drm_connector_attach_content_type_property(&aconnector->base);
9128 	}
9129 
9130 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9131 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
9132 			drm_connector_attach_colorspace_property(&aconnector->base);
9133 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
9134 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
9135 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
9136 			drm_connector_attach_colorspace_property(&aconnector->base);
9137 	}
9138 
9139 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9140 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
9141 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
9142 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
9143 
9144 		if (!aconnector->mst_root)
9145 			drm_connector_attach_vrr_capable_property(&aconnector->base);
9146 
9147 		if (adev->dm.hdcp_workqueue)
9148 			drm_connector_attach_content_protection_property(&aconnector->base, true);
9149 	}
9150 
9151 	if (connector_type == DRM_MODE_CONNECTOR_eDP) {
9152 		struct drm_privacy_screen *privacy_screen;
9153 
9154 		drm_connector_attach_panel_type_property(&aconnector->base);
9155 
9156 		privacy_screen = drm_privacy_screen_get(adev_to_drm(adev)->dev, NULL);
9157 		if (!IS_ERR(privacy_screen)) {
9158 			drm_connector_attach_privacy_screen_provider(&aconnector->base,
9159 								     privacy_screen);
9160 		} else if (PTR_ERR(privacy_screen) != -ENODEV) {
9161 			drm_warn(adev_to_drm(adev), "Error getting privacy-screen\n");
9162 		}
9163 	}
9164 }
9165 
amdgpu_dm_i2c_xfer(struct i2c_adapter * i2c_adap,struct i2c_msg * msgs,int num)9166 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
9167 			      struct i2c_msg *msgs, int num)
9168 {
9169 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
9170 	struct ddc_service *ddc_service = i2c->ddc_service;
9171 	struct i2c_command cmd;
9172 	int i;
9173 	int result = -EIO;
9174 
9175 	if (!ddc_service->ddc_pin)
9176 		return result;
9177 
9178 	cmd.payloads = kzalloc_objs(struct i2c_payload, num);
9179 
9180 	if (!cmd.payloads)
9181 		return result;
9182 
9183 	cmd.number_of_payloads = num;
9184 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
9185 	cmd.speed = 100;
9186 
9187 	for (i = 0; i < num; i++) {
9188 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
9189 		cmd.payloads[i].address = msgs[i].addr;
9190 		cmd.payloads[i].length = msgs[i].len;
9191 		cmd.payloads[i].data = msgs[i].buf;
9192 	}
9193 
9194 	if (i2c->oem) {
9195 		if (dc_submit_i2c_oem(
9196 			    ddc_service->ctx->dc,
9197 			    &cmd))
9198 			result = num;
9199 	} else {
9200 		if (dc_submit_i2c(
9201 			    ddc_service->ctx->dc,
9202 			    ddc_service->link->link_index,
9203 			    &cmd))
9204 			result = num;
9205 	}
9206 
9207 	kfree(cmd.payloads);
9208 	return result;
9209 }
9210 
amdgpu_dm_i2c_func(struct i2c_adapter * adap)9211 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
9212 {
9213 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
9214 }
9215 
9216 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
9217 	.master_xfer = amdgpu_dm_i2c_xfer,
9218 	.functionality = amdgpu_dm_i2c_func,
9219 };
9220 
9221 static struct amdgpu_i2c_adapter *
create_i2c(struct ddc_service * ddc_service,bool oem)9222 create_i2c(struct ddc_service *ddc_service, bool oem)
9223 {
9224 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
9225 	struct amdgpu_i2c_adapter *i2c;
9226 
9227 	i2c = kzalloc_obj(struct amdgpu_i2c_adapter);
9228 	if (!i2c)
9229 		return NULL;
9230 	i2c->base.owner = THIS_MODULE;
9231 	i2c->base.dev.parent = &adev->pdev->dev;
9232 	i2c->base.algo = &amdgpu_dm_i2c_algo;
9233 	if (oem)
9234 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c OEM bus");
9235 	else
9236 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d",
9237 			 ddc_service->link->link_index);
9238 	i2c_set_adapdata(&i2c->base, i2c);
9239 	i2c->ddc_service = ddc_service;
9240 	i2c->oem = oem;
9241 
9242 	return i2c;
9243 }
9244 
amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector * aconnector)9245 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
9246 {
9247 	struct cec_connector_info conn_info;
9248 	struct drm_device *ddev = aconnector->base.dev;
9249 	struct device *hdmi_dev = ddev->dev;
9250 
9251 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
9252 		drm_info(ddev, "HDMI-CEC feature masked\n");
9253 		return -EINVAL;
9254 	}
9255 
9256 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
9257 	aconnector->notifier =
9258 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
9259 	if (!aconnector->notifier) {
9260 		drm_err(ddev, "Failed to create cec notifier\n");
9261 		return -ENOMEM;
9262 	}
9263 
9264 	return 0;
9265 }
9266 
9267 /*
9268  * Note: this function assumes that dc_link_detect() was called for the
9269  * dc_link which will be represented by this aconnector.
9270  */
amdgpu_dm_connector_init(struct amdgpu_display_manager * dm,struct amdgpu_dm_connector * aconnector,u32 link_index,struct amdgpu_encoder * aencoder)9271 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
9272 				    struct amdgpu_dm_connector *aconnector,
9273 				    u32 link_index,
9274 				    struct amdgpu_encoder *aencoder)
9275 {
9276 	int res = 0;
9277 	int connector_type;
9278 	struct dc *dc = dm->dc;
9279 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
9280 	struct amdgpu_i2c_adapter *i2c;
9281 
9282 	/* Not needed for writeback connector */
9283 	link->priv = aconnector;
9284 
9285 
9286 	i2c = create_i2c(link->ddc, false);
9287 	if (!i2c) {
9288 		drm_err(adev_to_drm(dm->adev), "Failed to create i2c adapter data\n");
9289 		return -ENOMEM;
9290 	}
9291 
9292 	aconnector->i2c = i2c;
9293 	res = devm_i2c_add_adapter(dm->adev->dev, &i2c->base);
9294 
9295 	if (res) {
9296 		drm_err(adev_to_drm(dm->adev), "Failed to register hw i2c %d\n", link->link_index);
9297 		goto out_free;
9298 	}
9299 
9300 	connector_type = to_drm_connector_type(link->connector_signal, link->link_id.id);
9301 
9302 	res = drm_connector_init_with_ddc(
9303 			dm->ddev,
9304 			&aconnector->base,
9305 			&amdgpu_dm_connector_funcs,
9306 			connector_type,
9307 			&i2c->base);
9308 
9309 	if (res) {
9310 		drm_err(adev_to_drm(dm->adev), "connector_init failed\n");
9311 		aconnector->connector_id = -1;
9312 		goto out_free;
9313 	}
9314 
9315 	drm_connector_helper_add(
9316 			&aconnector->base,
9317 			&amdgpu_dm_connector_helper_funcs);
9318 
9319 	amdgpu_dm_connector_init_helper(
9320 		dm,
9321 		aconnector,
9322 		connector_type,
9323 		link,
9324 		link_index);
9325 
9326 	drm_connector_attach_encoder(
9327 		&aconnector->base, &aencoder->base);
9328 
9329 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9330 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
9331 		amdgpu_dm_initialize_hdmi_connector(aconnector);
9332 
9333 	if (dc_is_dp_signal(link->connector_signal))
9334 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
9335 
9336 out_free:
9337 	if (res) {
9338 		kfree(i2c);
9339 		aconnector->i2c = NULL;
9340 	}
9341 	return res;
9342 }
9343 
amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device * adev)9344 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
9345 {
9346 	switch (adev->mode_info.num_crtc) {
9347 	case 1:
9348 		return 0x1;
9349 	case 2:
9350 		return 0x3;
9351 	case 3:
9352 		return 0x7;
9353 	case 4:
9354 		return 0xf;
9355 	case 5:
9356 		return 0x1f;
9357 	case 6:
9358 	default:
9359 		return 0x3f;
9360 	}
9361 }
9362 
amdgpu_dm_encoder_init(struct drm_device * dev,struct amdgpu_encoder * aencoder,uint32_t link_index)9363 static int amdgpu_dm_encoder_init(struct drm_device *dev,
9364 				  struct amdgpu_encoder *aencoder,
9365 				  uint32_t link_index)
9366 {
9367 	struct amdgpu_device *adev = drm_to_adev(dev);
9368 
9369 	int res = drm_encoder_init(dev,
9370 				   &aencoder->base,
9371 				   &amdgpu_dm_encoder_funcs,
9372 				   DRM_MODE_ENCODER_TMDS,
9373 				   NULL);
9374 
9375 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
9376 
9377 	if (!res)
9378 		aencoder->encoder_id = link_index;
9379 	else
9380 		aencoder->encoder_id = -1;
9381 
9382 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
9383 
9384 	return res;
9385 }
9386 
manage_dm_interrupts(struct amdgpu_device * adev,struct amdgpu_crtc * acrtc,struct dm_crtc_state * acrtc_state)9387 static void manage_dm_interrupts(struct amdgpu_device *adev,
9388 				 struct amdgpu_crtc *acrtc,
9389 				 struct dm_crtc_state *acrtc_state)
9390 {	/*
9391 	 * We cannot be sure that the frontend index maps to the same
9392 	 * backend index - some even map to more than one.
9393 	 * So we have to go through the CRTC to find the right IRQ.
9394 	 */
9395 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
9396 			adev,
9397 			acrtc->crtc_id);
9398 	struct drm_device *dev = adev_to_drm(adev);
9399 
9400 	struct drm_vblank_crtc_config config = {0};
9401 	struct dc_crtc_timing *timing;
9402 	int offdelay;
9403 
9404 	if (acrtc_state) {
9405 		timing = &acrtc_state->stream->timing;
9406 
9407 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
9408 			   IP_VERSION(3, 5, 0) ||
9409 			   !(adev->flags & AMD_IS_APU)) {
9410 			/*
9411 			 * Older HW and DGPU have issues with instant off;
9412 			 * use a 2 frame offdelay.
9413 			 */
9414 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
9415 						      timing->v_total *
9416 						      timing->h_total,
9417 						      timing->pix_clk_100hz);
9418 
9419 			config.offdelay_ms = offdelay ?: 30;
9420 		} else {
9421 			/* offdelay_ms = 0 will never disable vblank */
9422 			config.offdelay_ms = 1;
9423 			config.disable_immediate = true;
9424 		}
9425 
9426 		drm_crtc_vblank_on_config(&acrtc->base,
9427 					  &config);
9428 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_get.*/
9429 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9430 		case IP_VERSION(3, 0, 0):
9431 		case IP_VERSION(3, 0, 2):
9432 		case IP_VERSION(3, 0, 3):
9433 		case IP_VERSION(3, 2, 0):
9434 			if (amdgpu_irq_get(adev, &adev->pageflip_irq, irq_type))
9435 				drm_err(dev, "DM_IRQ: Cannot get pageflip irq!\n");
9436 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9437 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
9438 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
9439 #endif
9440 		}
9441 
9442 	} else {
9443 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
9444 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9445 		case IP_VERSION(3, 0, 0):
9446 		case IP_VERSION(3, 0, 2):
9447 		case IP_VERSION(3, 0, 3):
9448 		case IP_VERSION(3, 2, 0):
9449 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9450 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
9451 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
9452 #endif
9453 			if (amdgpu_irq_put(adev, &adev->pageflip_irq, irq_type))
9454 				drm_err(dev, "DM_IRQ: Cannot put pageflip irq!\n");
9455 		}
9456 
9457 		drm_crtc_vblank_off(&acrtc->base);
9458 	}
9459 }
9460 
dm_update_pflip_irq_state(struct amdgpu_device * adev,struct amdgpu_crtc * acrtc)9461 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
9462 				      struct amdgpu_crtc *acrtc)
9463 {
9464 	int irq_type =
9465 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
9466 
9467 	/**
9468 	 * This reads the current state for the IRQ and force reapplies
9469 	 * the setting to hardware.
9470 	 */
9471 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
9472 }
9473 
9474 static bool
is_scaling_state_different(const struct dm_connector_state * dm_state,const struct dm_connector_state * old_dm_state)9475 is_scaling_state_different(const struct dm_connector_state *dm_state,
9476 			   const struct dm_connector_state *old_dm_state)
9477 {
9478 	if (dm_state->scaling != old_dm_state->scaling)
9479 		return true;
9480 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
9481 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
9482 			return true;
9483 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
9484 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
9485 			return true;
9486 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
9487 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
9488 		return true;
9489 	return false;
9490 }
9491 
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)9492 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
9493 					    struct drm_crtc_state *old_crtc_state,
9494 					    struct drm_connector_state *new_conn_state,
9495 					    struct drm_connector_state *old_conn_state,
9496 					    const struct drm_connector *connector,
9497 					    struct hdcp_workqueue *hdcp_w)
9498 {
9499 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
9500 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
9501 
9502 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
9503 		connector->index, connector->status, connector->dpms);
9504 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
9505 		old_conn_state->content_protection, new_conn_state->content_protection);
9506 
9507 	if (old_crtc_state)
9508 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9509 		old_crtc_state->enable,
9510 		old_crtc_state->active,
9511 		old_crtc_state->mode_changed,
9512 		old_crtc_state->active_changed,
9513 		old_crtc_state->connectors_changed);
9514 
9515 	if (new_crtc_state)
9516 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9517 		new_crtc_state->enable,
9518 		new_crtc_state->active,
9519 		new_crtc_state->mode_changed,
9520 		new_crtc_state->active_changed,
9521 		new_crtc_state->connectors_changed);
9522 
9523 	/* hdcp content type change */
9524 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
9525 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
9526 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9527 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
9528 		return true;
9529 	}
9530 
9531 	/* CP is being re enabled, ignore this */
9532 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
9533 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9534 		if (new_crtc_state && new_crtc_state->mode_changed) {
9535 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9536 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
9537 			return true;
9538 		}
9539 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
9540 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
9541 		return false;
9542 	}
9543 
9544 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
9545 	 *
9546 	 * Handles:	UNDESIRED -> ENABLED
9547 	 */
9548 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
9549 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
9550 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9551 
9552 	/* Stream removed and re-enabled
9553 	 *
9554 	 * Can sometimes overlap with the HPD case,
9555 	 * thus set update_hdcp to false to avoid
9556 	 * setting HDCP multiple times.
9557 	 *
9558 	 * Handles:	DESIRED -> DESIRED (Special case)
9559 	 */
9560 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
9561 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
9562 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9563 		dm_con_state->update_hdcp = false;
9564 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
9565 			__func__);
9566 		return true;
9567 	}
9568 
9569 	/* Hot-plug, headless s3, dpms
9570 	 *
9571 	 * Only start HDCP if the display is connected/enabled.
9572 	 * update_hdcp flag will be set to false until the next
9573 	 * HPD comes in.
9574 	 *
9575 	 * Handles:	DESIRED -> DESIRED (Special case)
9576 	 */
9577 	if (dm_con_state->update_hdcp &&
9578 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
9579 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
9580 		dm_con_state->update_hdcp = false;
9581 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
9582 			__func__);
9583 		return true;
9584 	}
9585 
9586 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
9587 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9588 			if (new_crtc_state && new_crtc_state->mode_changed) {
9589 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
9590 					__func__);
9591 				return true;
9592 			}
9593 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
9594 				__func__);
9595 			return false;
9596 		}
9597 
9598 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
9599 		return false;
9600 	}
9601 
9602 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9603 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
9604 			__func__);
9605 		return true;
9606 	}
9607 
9608 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
9609 	return false;
9610 }
9611 
remove_stream(struct amdgpu_device * adev,struct amdgpu_crtc * acrtc,struct dc_stream_state * stream)9612 static void remove_stream(struct amdgpu_device *adev,
9613 			  struct amdgpu_crtc *acrtc,
9614 			  struct dc_stream_state *stream)
9615 {
9616 	/* this is the update mode case */
9617 
9618 	acrtc->otg_inst = -1;
9619 	acrtc->enabled = false;
9620 }
9621 
prepare_flip_isr(struct amdgpu_crtc * acrtc)9622 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
9623 {
9624 
9625 	assert_spin_locked(&acrtc->base.dev->event_lock);
9626 	WARN_ON(acrtc->event);
9627 
9628 	acrtc->event = acrtc->base.state->event;
9629 
9630 	/* Set the flip status */
9631 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
9632 
9633 	/* Mark this event as consumed */
9634 	acrtc->base.state->event = NULL;
9635 
9636 	drm_dbg_state(acrtc->base.dev,
9637 		      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
9638 		      acrtc->crtc_id);
9639 }
9640 
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)9641 static void update_freesync_state_on_stream(
9642 	struct amdgpu_display_manager *dm,
9643 	struct dm_crtc_state *new_crtc_state,
9644 	struct dc_stream_state *new_stream,
9645 	struct dc_plane_state *surface,
9646 	u32 flip_timestamp_in_us)
9647 {
9648 	struct mod_vrr_params vrr_params;
9649 	struct dc_info_packet vrr_infopacket = {0};
9650 	struct amdgpu_device *adev = dm->adev;
9651 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9652 	unsigned long flags;
9653 	bool pack_sdp_v1_3 = false;
9654 	struct amdgpu_dm_connector *aconn;
9655 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
9656 
9657 	if (!new_stream)
9658 		return;
9659 
9660 	/*
9661 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9662 	 * For now it's sufficient to just guard against these conditions.
9663 	 */
9664 
9665 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9666 		return;
9667 
9668 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9669 	vrr_params = acrtc->dm_irq_params.vrr_params;
9670 
9671 	if (surface) {
9672 		mod_freesync_handle_preflip(
9673 			dm->freesync_module,
9674 			surface,
9675 			new_stream,
9676 			flip_timestamp_in_us,
9677 			&vrr_params);
9678 
9679 		if (adev->family < AMDGPU_FAMILY_AI &&
9680 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
9681 			mod_freesync_handle_v_update(dm->freesync_module,
9682 						     new_stream, &vrr_params);
9683 
9684 			/* Need to call this before the frame ends. */
9685 			dc_stream_adjust_vmin_vmax(dm->dc,
9686 						   new_crtc_state->stream,
9687 						   &vrr_params.adjust);
9688 		}
9689 	}
9690 
9691 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
9692 
9693 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
9694 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
9695 
9696 		if (aconn->vsdb_info.amd_vsdb_version == 1)
9697 			packet_type = PACKET_TYPE_FS_V1;
9698 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
9699 			packet_type = PACKET_TYPE_FS_V2;
9700 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
9701 			packet_type = PACKET_TYPE_FS_V3;
9702 
9703 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
9704 					&new_stream->adaptive_sync_infopacket);
9705 	}
9706 
9707 	mod_freesync_build_vrr_infopacket(
9708 		dm->freesync_module,
9709 		new_stream,
9710 		&vrr_params,
9711 		packet_type,
9712 		TRANSFER_FUNC_UNKNOWN,
9713 		&vrr_infopacket,
9714 		pack_sdp_v1_3);
9715 
9716 	new_crtc_state->freesync_vrr_info_changed |=
9717 		(memcmp(&new_crtc_state->vrr_infopacket,
9718 			&vrr_infopacket,
9719 			sizeof(vrr_infopacket)) != 0);
9720 
9721 	acrtc->dm_irq_params.vrr_params = vrr_params;
9722 	new_crtc_state->vrr_infopacket = vrr_infopacket;
9723 
9724 	new_stream->vrr_infopacket = vrr_infopacket;
9725 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
9726 
9727 	if (new_crtc_state->freesync_vrr_info_changed)
9728 		drm_dbg_kms(adev_to_drm(adev), "VRR packet update: crtc=%u enabled=%d state=%d",
9729 			      new_crtc_state->base.crtc->base.id,
9730 			      (int)new_crtc_state->base.vrr_enabled,
9731 			      (int)vrr_params.state);
9732 
9733 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9734 }
9735 
update_stream_irq_parameters(struct amdgpu_display_manager * dm,struct dm_crtc_state * new_crtc_state)9736 static void update_stream_irq_parameters(
9737 	struct amdgpu_display_manager *dm,
9738 	struct dm_crtc_state *new_crtc_state)
9739 {
9740 	struct dc_stream_state *new_stream = new_crtc_state->stream;
9741 	struct mod_vrr_params vrr_params;
9742 	struct mod_freesync_config config = new_crtc_state->freesync_config;
9743 	struct amdgpu_device *adev = dm->adev;
9744 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9745 	unsigned long flags;
9746 
9747 	if (!new_stream)
9748 		return;
9749 
9750 	/*
9751 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9752 	 * For now it's sufficient to just guard against these conditions.
9753 	 */
9754 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9755 		return;
9756 
9757 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9758 	vrr_params = acrtc->dm_irq_params.vrr_params;
9759 
9760 	if (new_crtc_state->vrr_supported &&
9761 	    config.min_refresh_in_uhz &&
9762 	    config.max_refresh_in_uhz) {
9763 		/*
9764 		 * if freesync compatible mode was set, config.state will be set
9765 		 * in atomic check
9766 		 */
9767 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
9768 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
9769 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
9770 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
9771 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
9772 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
9773 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
9774 		} else {
9775 			config.state = new_crtc_state->base.vrr_enabled ?
9776 						     VRR_STATE_ACTIVE_VARIABLE :
9777 						     VRR_STATE_INACTIVE;
9778 		}
9779 	} else {
9780 		config.state = VRR_STATE_UNSUPPORTED;
9781 	}
9782 
9783 	mod_freesync_build_vrr_params(dm->freesync_module,
9784 				      new_stream,
9785 				      &config, &vrr_params);
9786 
9787 	new_crtc_state->freesync_config = config;
9788 	/* Copy state for access from DM IRQ handler */
9789 	acrtc->dm_irq_params.freesync_config = config;
9790 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
9791 	acrtc->dm_irq_params.vrr_params = vrr_params;
9792 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9793 }
9794 
amdgpu_dm_handle_vrr_transition(struct dm_crtc_state * old_state,struct dm_crtc_state * new_state)9795 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
9796 					    struct dm_crtc_state *new_state)
9797 {
9798 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
9799 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
9800 
9801 	if (!old_vrr_active && new_vrr_active) {
9802 		/* Transition VRR inactive -> active:
9803 		 * While VRR is active, we must not disable vblank irq, as a
9804 		 * reenable after disable would compute bogus vblank/pflip
9805 		 * timestamps if it likely happened inside display front-porch.
9806 		 *
9807 		 * We also need vupdate irq for the actual core vblank handling
9808 		 * at end of vblank.
9809 		 */
9810 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
9811 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
9812 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR off->on: Get vblank ref\n",
9813 				 __func__, new_state->base.crtc->base.id);
9814 	} else if (old_vrr_active && !new_vrr_active) {
9815 		/* Transition VRR active -> inactive:
9816 		 * Allow vblank irq disable again for fixed refresh rate.
9817 		 */
9818 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
9819 		drm_crtc_vblank_put(new_state->base.crtc);
9820 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR on->off: Drop vblank ref\n",
9821 				 __func__, new_state->base.crtc->base.id);
9822 	}
9823 }
9824 
amdgpu_dm_commit_cursors(struct drm_atomic_state * state)9825 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
9826 {
9827 	struct drm_plane *plane;
9828 	struct drm_plane_state *old_plane_state;
9829 	int i;
9830 
9831 	/*
9832 	 * TODO: Make this per-stream so we don't issue redundant updates for
9833 	 * commits with multiple streams.
9834 	 */
9835 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
9836 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
9837 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
9838 }
9839 
get_mem_type(struct drm_framebuffer * fb)9840 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
9841 {
9842 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
9843 
9844 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
9845 }
9846 
amdgpu_dm_update_cursor(struct drm_plane * plane,struct drm_plane_state * old_plane_state,struct dc_stream_update * update)9847 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
9848 				    struct drm_plane_state *old_plane_state,
9849 				    struct dc_stream_update *update)
9850 {
9851 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
9852 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
9853 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
9854 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
9855 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
9856 	uint64_t address = afb ? afb->address : 0;
9857 	struct dc_cursor_position position = {0};
9858 	struct dc_cursor_attributes attributes;
9859 	int ret;
9860 
9861 	if (!plane->state->fb && !old_plane_state->fb)
9862 		return;
9863 
9864 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
9865 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
9866 		       plane->state->crtc_h);
9867 
9868 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
9869 	if (ret)
9870 		return;
9871 
9872 	if (!position.enable) {
9873 		/* turn off cursor */
9874 		if (crtc_state && crtc_state->stream) {
9875 			dc_stream_set_cursor_position(crtc_state->stream,
9876 						      &position);
9877 			update->cursor_position = &crtc_state->stream->cursor_position;
9878 		}
9879 		return;
9880 	}
9881 
9882 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
9883 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
9884 
9885 	memset(&attributes, 0, sizeof(attributes));
9886 	attributes.address.high_part = upper_32_bits(address);
9887 	attributes.address.low_part  = lower_32_bits(address);
9888 	attributes.width             = plane->state->crtc_w;
9889 	attributes.height            = plane->state->crtc_h;
9890 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
9891 	attributes.rotation_angle    = 0;
9892 	attributes.attribute_flags.value = 0;
9893 
9894 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
9895 	 * legacy gamma setup.
9896 	 */
9897 	if (crtc_state->cm_is_degamma_srgb &&
9898 	    adev->dm.dc->caps.color.dpp.gamma_corr)
9899 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
9900 
9901 	if (afb)
9902 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
9903 
9904 	if (crtc_state->stream) {
9905 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
9906 						     &attributes))
9907 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
9908 
9909 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
9910 
9911 		if (!dc_stream_set_cursor_position(crtc_state->stream,
9912 						   &position))
9913 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
9914 
9915 		update->cursor_position = &crtc_state->stream->cursor_position;
9916 	}
9917 }
9918 
amdgpu_dm_enable_self_refresh(struct amdgpu_crtc * acrtc_attach,const struct dm_crtc_state * acrtc_state,const u64 current_ts)9919 static void amdgpu_dm_enable_self_refresh(struct amdgpu_crtc *acrtc_attach,
9920 					  const struct dm_crtc_state *acrtc_state,
9921 					  const u64 current_ts)
9922 {
9923 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
9924 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
9925 	struct amdgpu_dm_connector *aconn =
9926 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
9927 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
9928 
9929 	if (acrtc_state->update_type > UPDATE_TYPE_FAST) {
9930 		if (pr->config.replay_supported && !pr->replay_feature_enabled)
9931 			amdgpu_dm_link_setup_replay(acrtc_state->stream->link, aconn);
9932 		else if (psr->psr_version != DC_PSR_VERSION_UNSUPPORTED &&
9933 			     !psr->psr_feature_enabled)
9934 			if (!aconn->disallow_edp_enter_psr)
9935 				amdgpu_dm_link_setup_psr(acrtc_state->stream);
9936 	}
9937 
9938 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
9939 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
9940 	    (psr->psr_feature_enabled || pr->config.replay_supported)) {
9941 		if (aconn->sr_skip_count > 0)
9942 			aconn->sr_skip_count--;
9943 
9944 		/* Allow SR when skip count is 0. */
9945 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
9946 
9947 		/*
9948 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
9949 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
9950 		 * can be enabled immediately once OS demonstrates an
9951 		 * adequate number of fast atomic commits to notify KMD
9952 		 * of update events.
9953 		 * See `amdgpu_dm_crtc_vblank_control_worker()`.
9954 		 */
9955 		if (!vrr_active &&
9956 		    acrtc_attach->dm_irq_params.allow_sr_entry &&
9957 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
9958 		    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
9959 #endif
9960 		    (current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
9961 			if (pr->replay_feature_enabled && !pr->replay_allow_active)
9962 				amdgpu_dm_replay_enable(acrtc_state->stream, true);
9963 			if (psr->psr_version == DC_PSR_VERSION_SU_1 &&
9964 			    !psr->psr_allow_active && !aconn->disallow_edp_enter_psr)
9965 				amdgpu_dm_psr_enable(acrtc_state->stream);
9966 		}
9967 	} else {
9968 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
9969 	}
9970 }
9971 
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)9972 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
9973 				    struct drm_device *dev,
9974 				    struct amdgpu_display_manager *dm,
9975 				    struct drm_crtc *pcrtc,
9976 				    bool wait_for_vblank)
9977 {
9978 	u32 i;
9979 	u64 timestamp_ns = ktime_get_ns();
9980 	struct drm_plane *plane;
9981 	struct drm_plane_state *old_plane_state, *new_plane_state;
9982 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
9983 	struct drm_crtc_state *new_pcrtc_state =
9984 			drm_atomic_get_new_crtc_state(state, pcrtc);
9985 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
9986 	struct dm_crtc_state *dm_old_crtc_state =
9987 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
9988 	int planes_count = 0, vpos, hpos;
9989 	unsigned long flags;
9990 	u32 target_vblank, last_flip_vblank;
9991 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
9992 	bool cursor_update = false;
9993 	bool pflip_present = false;
9994 	bool dirty_rects_changed = false;
9995 	bool updated_planes_and_streams = false;
9996 	struct {
9997 		struct dc_surface_update surface_updates[MAX_SURFACES];
9998 		struct dc_plane_info plane_infos[MAX_SURFACES];
9999 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
10000 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
10001 		struct dc_stream_update stream_update;
10002 	} *bundle;
10003 
10004 	bundle = kzalloc_obj(*bundle);
10005 
10006 	if (!bundle) {
10007 		drm_err(dev, "Failed to allocate update bundle\n");
10008 		goto cleanup;
10009 	}
10010 
10011 	/*
10012 	 * Disable the cursor first if we're disabling all the planes.
10013 	 * It'll remain on the screen after the planes are re-enabled
10014 	 * if we don't.
10015 	 *
10016 	 * If the cursor is transitioning from native to overlay mode, the
10017 	 * native cursor needs to be disabled first.
10018 	 */
10019 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
10020 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10021 		struct dc_cursor_position cursor_position = {0};
10022 
10023 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
10024 						   &cursor_position))
10025 			drm_err(dev, "DC failed to disable native cursor\n");
10026 
10027 		bundle->stream_update.cursor_position =
10028 				&acrtc_state->stream->cursor_position;
10029 	}
10030 
10031 	if (acrtc_state->active_planes == 0 &&
10032 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10033 		amdgpu_dm_commit_cursors(state);
10034 
10035 	/* update planes when needed */
10036 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
10037 		struct drm_crtc *crtc = new_plane_state->crtc;
10038 		struct drm_crtc_state *new_crtc_state;
10039 		struct drm_framebuffer *fb = new_plane_state->fb;
10040 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
10041 		bool plane_needs_flip;
10042 		struct dc_plane_state *dc_plane;
10043 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
10044 
10045 		/* Cursor plane is handled after stream updates */
10046 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
10047 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
10048 			if ((fb && crtc == pcrtc) ||
10049 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
10050 				cursor_update = true;
10051 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
10052 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
10053 			}
10054 
10055 			continue;
10056 		}
10057 
10058 		if (!fb || !crtc || pcrtc != crtc)
10059 			continue;
10060 
10061 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
10062 		if (!new_crtc_state->active)
10063 			continue;
10064 
10065 		dc_plane = dm_new_plane_state->dc_state;
10066 		if (!dc_plane)
10067 			continue;
10068 
10069 		bundle->surface_updates[planes_count].surface = dc_plane;
10070 		if (new_pcrtc_state->color_mgmt_changed) {
10071 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
10072 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
10073 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
10074 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
10075 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
10076 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
10077 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
10078 		}
10079 
10080 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
10081 				     &bundle->scaling_infos[planes_count]);
10082 
10083 		bundle->surface_updates[planes_count].scaling_info =
10084 			&bundle->scaling_infos[planes_count];
10085 
10086 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
10087 
10088 		pflip_present = pflip_present || plane_needs_flip;
10089 
10090 		if (!plane_needs_flip) {
10091 			planes_count += 1;
10092 			continue;
10093 		}
10094 
10095 		fill_dc_plane_info_and_addr(
10096 			dm->adev, new_plane_state,
10097 			afb->tiling_flags,
10098 			&bundle->plane_infos[planes_count],
10099 			&bundle->flip_addrs[planes_count].address,
10100 			afb->tmz_surface);
10101 
10102 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
10103 				 new_plane_state->plane->index,
10104 				 bundle->plane_infos[planes_count].dcc.enable);
10105 
10106 		bundle->surface_updates[planes_count].plane_info =
10107 			&bundle->plane_infos[planes_count];
10108 
10109 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
10110 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
10111 			fill_dc_dirty_rects(plane, old_plane_state,
10112 					    new_plane_state, new_crtc_state,
10113 					    &bundle->flip_addrs[planes_count],
10114 					    acrtc_state->stream->link->psr_settings.psr_version ==
10115 					    DC_PSR_VERSION_SU_1,
10116 					    &dirty_rects_changed);
10117 
10118 			/*
10119 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
10120 			 * and enabled it again after dirty regions are stable to avoid video glitch.
10121 			 * PSR-SU will be enabled in
10122 			 * amdgpu_dm_crtc_vblank_control_worker() if user
10123 			 * pause the video during the PSR-SU was disabled.
10124 			 */
10125 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
10126 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
10127 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
10128 			    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
10129 #endif
10130 			    dirty_rects_changed) {
10131 				mutex_lock(&dm->dc_lock);
10132 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
10133 				timestamp_ns;
10134 				if (acrtc_state->stream->link->psr_settings.psr_allow_active)
10135 					amdgpu_dm_psr_disable(acrtc_state->stream, true);
10136 				mutex_unlock(&dm->dc_lock);
10137 			}
10138 		}
10139 
10140 		/*
10141 		 * Only allow immediate flips for fast updates that don't
10142 		 * change memory domain, FB pitch, DCC state, rotation or
10143 		 * mirroring.
10144 		 *
10145 		 * dm_crtc_helper_atomic_check() only accepts async flips with
10146 		 * fast updates.
10147 		 */
10148 		if (crtc->state->async_flip &&
10149 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
10150 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
10151 			drm_warn_once(state->dev,
10152 				      "[PLANE:%d:%s] async flip with non-fast update\n",
10153 				      plane->base.id, plane->name);
10154 
10155 		bundle->flip_addrs[planes_count].flip_immediate =
10156 			crtc->state->async_flip &&
10157 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
10158 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
10159 
10160 		timestamp_ns = ktime_get_ns();
10161 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
10162 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
10163 		bundle->surface_updates[planes_count].surface = dc_plane;
10164 
10165 		if (!bundle->surface_updates[planes_count].surface) {
10166 			drm_err(dev, "No surface for CRTC: id=%d\n",
10167 					acrtc_attach->crtc_id);
10168 			continue;
10169 		}
10170 
10171 		if (plane == pcrtc->primary)
10172 			update_freesync_state_on_stream(
10173 				dm,
10174 				acrtc_state,
10175 				acrtc_state->stream,
10176 				dc_plane,
10177 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
10178 
10179 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
10180 				 __func__,
10181 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
10182 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
10183 
10184 		planes_count += 1;
10185 
10186 	}
10187 
10188 	if (pflip_present) {
10189 		if (!vrr_active) {
10190 			/* Use old throttling in non-vrr fixed refresh rate mode
10191 			 * to keep flip scheduling based on target vblank counts
10192 			 * working in a backwards compatible way, e.g., for
10193 			 * clients using the GLX_OML_sync_control extension or
10194 			 * DRI3/Present extension with defined target_msc.
10195 			 */
10196 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
10197 		} else {
10198 			/* For variable refresh rate mode only:
10199 			 * Get vblank of last completed flip to avoid > 1 vrr
10200 			 * flips per video frame by use of throttling, but allow
10201 			 * flip programming anywhere in the possibly large
10202 			 * variable vrr vblank interval for fine-grained flip
10203 			 * timing control and more opportunity to avoid stutter
10204 			 * on late submission of flips.
10205 			 */
10206 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10207 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
10208 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10209 		}
10210 
10211 		target_vblank = last_flip_vblank + wait_for_vblank;
10212 
10213 		/*
10214 		 * Wait until we're out of the vertical blank period before the one
10215 		 * targeted by the flip
10216 		 */
10217 		while ((acrtc_attach->enabled &&
10218 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
10219 							    0, &vpos, &hpos, NULL,
10220 							    NULL, &pcrtc->hwmode)
10221 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
10222 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
10223 			(int)(target_vblank -
10224 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
10225 			usleep_range(1000, 1100);
10226 		}
10227 
10228 		/**
10229 		 * Prepare the flip event for the pageflip interrupt to handle.
10230 		 *
10231 		 * This only works in the case where we've already turned on the
10232 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
10233 		 * from 0 -> n planes we have to skip a hardware generated event
10234 		 * and rely on sending it from software.
10235 		 */
10236 		if (acrtc_attach->base.state->event &&
10237 		    acrtc_state->active_planes > 0) {
10238 			drm_crtc_vblank_get(pcrtc);
10239 
10240 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10241 
10242 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
10243 			prepare_flip_isr(acrtc_attach);
10244 
10245 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10246 		}
10247 
10248 		if (acrtc_state->stream) {
10249 			if (acrtc_state->freesync_vrr_info_changed)
10250 				bundle->stream_update.vrr_infopacket =
10251 					&acrtc_state->stream->vrr_infopacket;
10252 		}
10253 	} else if (cursor_update && acrtc_state->active_planes > 0) {
10254 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10255 		if (acrtc_attach->base.state->event) {
10256 			drm_crtc_vblank_get(pcrtc);
10257 			acrtc_attach->event = acrtc_attach->base.state->event;
10258 			acrtc_attach->base.state->event = NULL;
10259 		}
10260 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10261 	}
10262 
10263 	/* Update the planes if changed or disable if we don't have any. */
10264 	if ((planes_count || acrtc_state->active_planes == 0) &&
10265 		acrtc_state->stream) {
10266 		/*
10267 		 * If PSR or idle optimizations are enabled then flush out
10268 		 * any pending work before hardware programming.
10269 		 */
10270 		if (dm->vblank_control_workqueue)
10271 			flush_workqueue(dm->vblank_control_workqueue);
10272 
10273 		bundle->stream_update.stream = acrtc_state->stream;
10274 		if (new_pcrtc_state->mode_changed) {
10275 			bundle->stream_update.src = acrtc_state->stream->src;
10276 			bundle->stream_update.dst = acrtc_state->stream->dst;
10277 		}
10278 
10279 		if (new_pcrtc_state->color_mgmt_changed) {
10280 			/*
10281 			 * TODO: This isn't fully correct since we've actually
10282 			 * already modified the stream in place.
10283 			 */
10284 			bundle->stream_update.gamut_remap =
10285 				&acrtc_state->stream->gamut_remap_matrix;
10286 			bundle->stream_update.output_csc_transform =
10287 				&acrtc_state->stream->csc_color_matrix;
10288 			bundle->stream_update.out_transfer_func =
10289 				&acrtc_state->stream->out_transfer_func;
10290 			bundle->stream_update.lut3d_func =
10291 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
10292 			bundle->stream_update.func_shaper =
10293 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
10294 		}
10295 
10296 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
10297 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
10298 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
10299 
10300 		mutex_lock(&dm->dc_lock);
10301 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) || vrr_active) {
10302 			if (acrtc_state->stream->link->replay_settings.replay_allow_active)
10303 				amdgpu_dm_replay_disable(acrtc_state->stream);
10304 			if (acrtc_state->stream->link->psr_settings.psr_allow_active)
10305 				amdgpu_dm_psr_disable(acrtc_state->stream, true);
10306 		}
10307 		mutex_unlock(&dm->dc_lock);
10308 
10309 		/*
10310 		 * If FreeSync state on the stream has changed then we need to
10311 		 * re-adjust the min/max bounds now that DC doesn't handle this
10312 		 * as part of commit.
10313 		 */
10314 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
10315 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10316 			dc_stream_adjust_vmin_vmax(
10317 				dm->dc, acrtc_state->stream,
10318 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
10319 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10320 		}
10321 		mutex_lock(&dm->dc_lock);
10322 		update_planes_and_stream_adapter(dm->dc,
10323 					 acrtc_state->update_type,
10324 					 planes_count,
10325 					 acrtc_state->stream,
10326 					 &bundle->stream_update,
10327 					 bundle->surface_updates);
10328 		updated_planes_and_streams = true;
10329 
10330 		/**
10331 		 * Enable or disable the interrupts on the backend.
10332 		 *
10333 		 * Most pipes are put into power gating when unused.
10334 		 *
10335 		 * When power gating is enabled on a pipe we lose the
10336 		 * interrupt enablement state when power gating is disabled.
10337 		 *
10338 		 * So we need to update the IRQ control state in hardware
10339 		 * whenever the pipe turns on (since it could be previously
10340 		 * power gated) or off (since some pipes can't be power gated
10341 		 * on some ASICs).
10342 		 */
10343 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
10344 			dm_update_pflip_irq_state(drm_to_adev(dev),
10345 						  acrtc_attach);
10346 
10347 		amdgpu_dm_enable_self_refresh(acrtc_attach, acrtc_state, timestamp_ns);
10348 		mutex_unlock(&dm->dc_lock);
10349 	}
10350 
10351 	/*
10352 	 * Update cursor state *after* programming all the planes.
10353 	 * This avoids redundant programming in the case where we're going
10354 	 * to be disabling a single plane - those pipes are being disabled.
10355 	 */
10356 	if (acrtc_state->active_planes &&
10357 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
10358 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10359 		amdgpu_dm_commit_cursors(state);
10360 
10361 cleanup:
10362 	kfree(bundle);
10363 }
10364 
amdgpu_dm_commit_audio(struct drm_device * dev,struct drm_atomic_state * state)10365 static void amdgpu_dm_commit_audio(struct drm_device *dev,
10366 				   struct drm_atomic_state *state)
10367 {
10368 	struct amdgpu_device *adev = drm_to_adev(dev);
10369 	struct amdgpu_dm_connector *aconnector;
10370 	struct drm_connector *connector;
10371 	struct drm_connector_state *old_con_state, *new_con_state;
10372 	struct drm_crtc_state *new_crtc_state;
10373 	struct dm_crtc_state *new_dm_crtc_state;
10374 	const struct dc_stream_status *status;
10375 	int i, inst;
10376 
10377 	/* Notify device removals. */
10378 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10379 		if (old_con_state->crtc != new_con_state->crtc) {
10380 			/* CRTC changes require notification. */
10381 			goto notify;
10382 		}
10383 
10384 		if (!new_con_state->crtc)
10385 			continue;
10386 
10387 		new_crtc_state = drm_atomic_get_new_crtc_state(
10388 			state, new_con_state->crtc);
10389 
10390 		if (!new_crtc_state)
10391 			continue;
10392 
10393 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10394 			continue;
10395 
10396 notify:
10397 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10398 			continue;
10399 
10400 		aconnector = to_amdgpu_dm_connector(connector);
10401 
10402 		mutex_lock(&adev->dm.audio_lock);
10403 		inst = aconnector->audio_inst;
10404 		aconnector->audio_inst = -1;
10405 		mutex_unlock(&adev->dm.audio_lock);
10406 
10407 		amdgpu_dm_audio_eld_notify(adev, inst);
10408 	}
10409 
10410 	/* Notify audio device additions. */
10411 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10412 		if (!new_con_state->crtc)
10413 			continue;
10414 
10415 		new_crtc_state = drm_atomic_get_new_crtc_state(
10416 			state, new_con_state->crtc);
10417 
10418 		if (!new_crtc_state)
10419 			continue;
10420 
10421 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10422 			continue;
10423 
10424 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
10425 		if (!new_dm_crtc_state->stream)
10426 			continue;
10427 
10428 		status = dc_stream_get_status(new_dm_crtc_state->stream);
10429 		if (!status)
10430 			continue;
10431 
10432 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10433 			continue;
10434 
10435 		aconnector = to_amdgpu_dm_connector(connector);
10436 
10437 		mutex_lock(&adev->dm.audio_lock);
10438 		inst = status->audio_inst;
10439 		aconnector->audio_inst = inst;
10440 		mutex_unlock(&adev->dm.audio_lock);
10441 
10442 		amdgpu_dm_audio_eld_notify(adev, inst);
10443 	}
10444 }
10445 
10446 /*
10447  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
10448  * @crtc_state: the DRM CRTC state
10449  * @stream_state: the DC stream state.
10450  *
10451  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
10452  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
10453  */
amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state * crtc_state,struct dc_stream_state * stream_state)10454 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
10455 						struct dc_stream_state *stream_state)
10456 {
10457 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
10458 }
10459 
dm_clear_writeback(struct amdgpu_display_manager * dm,struct dm_crtc_state * crtc_state)10460 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
10461 			      struct dm_crtc_state *crtc_state)
10462 {
10463 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
10464 }
10465 
amdgpu_dm_commit_streams(struct drm_atomic_state * state,struct dc_state * dc_state)10466 static void amdgpu_dm_commit_streams(struct drm_atomic_state *state,
10467 					struct dc_state *dc_state)
10468 {
10469 	struct drm_device *dev = state->dev;
10470 	struct amdgpu_device *adev = drm_to_adev(dev);
10471 	struct amdgpu_display_manager *dm = &adev->dm;
10472 	struct drm_crtc *crtc;
10473 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10474 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10475 	struct drm_connector_state *old_con_state;
10476 	struct drm_connector *connector;
10477 	bool mode_set_reset_required = false;
10478 	u32 i;
10479 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
10480 	bool set_backlight_level = false;
10481 
10482 	/* Disable writeback */
10483 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
10484 		struct dm_connector_state *dm_old_con_state;
10485 		struct amdgpu_crtc *acrtc;
10486 
10487 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
10488 			continue;
10489 
10490 		old_crtc_state = NULL;
10491 
10492 		dm_old_con_state = to_dm_connector_state(old_con_state);
10493 		if (!dm_old_con_state->base.crtc)
10494 			continue;
10495 
10496 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
10497 		if (acrtc)
10498 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10499 
10500 		if (!acrtc || !acrtc->wb_enabled)
10501 			continue;
10502 
10503 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10504 
10505 		dm_clear_writeback(dm, dm_old_crtc_state);
10506 		acrtc->wb_enabled = false;
10507 	}
10508 
10509 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
10510 				      new_crtc_state, i) {
10511 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10512 
10513 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10514 
10515 		if (old_crtc_state->active &&
10516 		    (!new_crtc_state->active ||
10517 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10518 			manage_dm_interrupts(adev, acrtc, NULL);
10519 			dc_stream_release(dm_old_crtc_state->stream);
10520 		}
10521 	}
10522 
10523 	drm_atomic_helper_calc_timestamping_constants(state);
10524 
10525 	/* update changed items */
10526 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10527 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10528 
10529 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10530 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10531 
10532 		drm_dbg_state(state->dev,
10533 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
10534 			acrtc->crtc_id,
10535 			new_crtc_state->enable,
10536 			new_crtc_state->active,
10537 			new_crtc_state->planes_changed,
10538 			new_crtc_state->mode_changed,
10539 			new_crtc_state->active_changed,
10540 			new_crtc_state->connectors_changed);
10541 
10542 		/* Disable cursor if disabling crtc */
10543 		if (old_crtc_state->active && !new_crtc_state->active) {
10544 			struct dc_cursor_position position;
10545 
10546 			memset(&position, 0, sizeof(position));
10547 			mutex_lock(&dm->dc_lock);
10548 			dc_exit_ips_for_hw_access(dm->dc);
10549 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
10550 			mutex_unlock(&dm->dc_lock);
10551 		}
10552 
10553 		/* Copy all transient state flags into dc state */
10554 		if (dm_new_crtc_state->stream) {
10555 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
10556 							    dm_new_crtc_state->stream);
10557 		}
10558 
10559 		/* handles headless hotplug case, updating new_state and
10560 		 * aconnector as needed
10561 		 */
10562 
10563 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
10564 
10565 			drm_dbg_atomic(dev,
10566 				       "Atomic commit: SET crtc id %d: [%p]\n",
10567 				       acrtc->crtc_id, acrtc);
10568 
10569 			if (!dm_new_crtc_state->stream) {
10570 				/*
10571 				 * this could happen because of issues with
10572 				 * userspace notifications delivery.
10573 				 * In this case userspace tries to set mode on
10574 				 * display which is disconnected in fact.
10575 				 * dc_sink is NULL in this case on aconnector.
10576 				 * We expect reset mode will come soon.
10577 				 *
10578 				 * This can also happen when unplug is done
10579 				 * during resume sequence ended
10580 				 *
10581 				 * In this case, we want to pretend we still
10582 				 * have a sink to keep the pipe running so that
10583 				 * hw state is consistent with the sw state
10584 				 */
10585 				drm_dbg_atomic(dev,
10586 					       "Failed to create new stream for crtc %d\n",
10587 						acrtc->base.base.id);
10588 				continue;
10589 			}
10590 
10591 			if (dm_old_crtc_state->stream)
10592 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10593 
10594 			pm_runtime_get_noresume(dev->dev);
10595 
10596 			acrtc->enabled = true;
10597 			acrtc->hw_mode = new_crtc_state->mode;
10598 			crtc->hwmode = new_crtc_state->mode;
10599 			mode_set_reset_required = true;
10600 			set_backlight_level = true;
10601 		} else if (modereset_required(new_crtc_state)) {
10602 			drm_dbg_atomic(dev,
10603 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
10604 				       acrtc->crtc_id, acrtc);
10605 			/* i.e. reset mode */
10606 			if (dm_old_crtc_state->stream)
10607 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10608 
10609 			mode_set_reset_required = true;
10610 		}
10611 	} /* for_each_crtc_in_state() */
10612 
10613 	/* if there mode set or reset, disable eDP PSR, Replay */
10614 	if (mode_set_reset_required) {
10615 		if (dm->vblank_control_workqueue)
10616 			flush_workqueue(dm->vblank_control_workqueue);
10617 
10618 		amdgpu_dm_replay_disable_all(dm);
10619 		amdgpu_dm_psr_disable_all(dm);
10620 	}
10621 
10622 	dm_enable_per_frame_crtc_master_sync(dc_state);
10623 	mutex_lock(&dm->dc_lock);
10624 	dc_exit_ips_for_hw_access(dm->dc);
10625 	WARN_ON(!dc_commit_streams(dm->dc, &params));
10626 
10627 	/* Allow idle optimization when vblank count is 0 for display off */
10628 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
10629 		dc_allow_idle_optimizations(dm->dc, true);
10630 	mutex_unlock(&dm->dc_lock);
10631 
10632 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10633 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10634 
10635 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10636 
10637 		if (dm_new_crtc_state->stream != NULL) {
10638 			const struct dc_stream_status *status =
10639 					dc_stream_get_status(dm_new_crtc_state->stream);
10640 
10641 			if (!status)
10642 				status = dc_state_get_stream_status(dc_state,
10643 									 dm_new_crtc_state->stream);
10644 			if (!status)
10645 				drm_err(dev,
10646 					"got no status for stream %p on acrtc%p\n",
10647 					dm_new_crtc_state->stream, acrtc);
10648 			else
10649 				acrtc->otg_inst = status->primary_otg_inst;
10650 		}
10651 	}
10652 
10653 	/* During boot up and resume the DC layer will reset the panel brightness
10654 	 * to fix a flicker issue.
10655 	 * It will cause the dm->actual_brightness is not the current panel brightness
10656 	 * level. (the dm->brightness is the correct panel level)
10657 	 * So we set the backlight level with dm->brightness value after set mode
10658 	 */
10659 	if (set_backlight_level) {
10660 		for (i = 0; i < dm->num_of_edps; i++) {
10661 			if (dm->backlight_dev[i])
10662 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
10663 		}
10664 	}
10665 }
10666 
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)10667 static void dm_set_writeback(struct amdgpu_display_manager *dm,
10668 			      struct dm_crtc_state *crtc_state,
10669 			      struct drm_connector *connector,
10670 			      struct drm_connector_state *new_con_state)
10671 {
10672 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
10673 	struct amdgpu_device *adev = dm->adev;
10674 	struct amdgpu_crtc *acrtc;
10675 	struct dc_writeback_info *wb_info;
10676 	struct pipe_ctx *pipe = NULL;
10677 	struct amdgpu_framebuffer *afb;
10678 	int i = 0;
10679 
10680 	wb_info = kzalloc_obj(*wb_info);
10681 	if (!wb_info) {
10682 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
10683 		return;
10684 	}
10685 
10686 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
10687 	if (!acrtc) {
10688 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
10689 		kfree(wb_info);
10690 		return;
10691 	}
10692 
10693 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
10694 	if (!afb) {
10695 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
10696 		kfree(wb_info);
10697 		return;
10698 	}
10699 
10700 	for (i = 0; i < MAX_PIPES; i++) {
10701 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
10702 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
10703 			break;
10704 		}
10705 	}
10706 
10707 	/* fill in wb_info */
10708 	wb_info->wb_enabled = true;
10709 
10710 	wb_info->dwb_pipe_inst = 0;
10711 	wb_info->dwb_params.dwbscl_black_color = 0;
10712 	wb_info->dwb_params.hdr_mult = 0x1F000;
10713 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
10714 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
10715 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
10716 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
10717 
10718 	/* width & height from crtc */
10719 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
10720 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
10721 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
10722 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
10723 
10724 	wb_info->dwb_params.cnv_params.crop_en = false;
10725 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
10726 
10727 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
10728 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
10729 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
10730 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
10731 
10732 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
10733 
10734 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
10735 
10736 	wb_info->dwb_params.scaler_taps.h_taps = 1;
10737 	wb_info->dwb_params.scaler_taps.v_taps = 1;
10738 	wb_info->dwb_params.scaler_taps.h_taps_c = 1;
10739 	wb_info->dwb_params.scaler_taps.v_taps_c = 1;
10740 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
10741 
10742 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
10743 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
10744 
10745 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
10746 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
10747 		wb_info->mcif_buf_params.chroma_address[i] = 0;
10748 	}
10749 
10750 	wb_info->mcif_buf_params.p_vmid = 1;
10751 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
10752 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
10753 		wb_info->mcif_warmup_params.region_size =
10754 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
10755 	}
10756 	wb_info->mcif_warmup_params.p_vmid = 1;
10757 	wb_info->writeback_source_plane = pipe->plane_state;
10758 
10759 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
10760 
10761 	acrtc->wb_pending = true;
10762 	acrtc->wb_conn = wb_conn;
10763 	drm_writeback_queue_job(wb_conn, new_con_state);
10764 }
10765 
amdgpu_dm_update_hdcp(struct drm_atomic_state * state)10766 static void amdgpu_dm_update_hdcp(struct drm_atomic_state *state)
10767 {
10768 	struct drm_connector_state *old_con_state, *new_con_state;
10769 	struct drm_device *dev = state->dev;
10770 	struct drm_connector *connector;
10771 	struct amdgpu_device *adev = drm_to_adev(dev);
10772 	int i;
10773 
10774 	if (!adev->dm.hdcp_workqueue)
10775 		return;
10776 
10777 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10778 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10779 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10780 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10781 		struct dm_crtc_state *dm_new_crtc_state;
10782 		struct amdgpu_dm_connector *aconnector;
10783 
10784 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10785 			continue;
10786 
10787 		aconnector = to_amdgpu_dm_connector(connector);
10788 
10789 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
10790 
10791 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
10792 			connector->index, connector->status, connector->dpms);
10793 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
10794 			old_con_state->content_protection, new_con_state->content_protection);
10795 
10796 		if (aconnector->dc_sink) {
10797 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
10798 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
10799 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
10800 				aconnector->dc_sink->edid_caps.display_name);
10801 			}
10802 		}
10803 
10804 		new_crtc_state = NULL;
10805 		old_crtc_state = NULL;
10806 
10807 		if (acrtc) {
10808 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
10809 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10810 		}
10811 
10812 		if (old_crtc_state)
10813 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
10814 			old_crtc_state->enable,
10815 			old_crtc_state->active,
10816 			old_crtc_state->mode_changed,
10817 			old_crtc_state->active_changed,
10818 			old_crtc_state->connectors_changed);
10819 
10820 		if (new_crtc_state)
10821 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
10822 			new_crtc_state->enable,
10823 			new_crtc_state->active,
10824 			new_crtc_state->mode_changed,
10825 			new_crtc_state->active_changed,
10826 			new_crtc_state->connectors_changed);
10827 
10828 
10829 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10830 
10831 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
10832 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
10833 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
10834 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
10835 			dm_new_con_state->update_hdcp = true;
10836 			continue;
10837 		}
10838 
10839 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
10840 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
10841 			/* when display is unplugged from mst hub, connctor will
10842 			 * be destroyed within dm_dp_mst_connector_destroy. connector
10843 			 * hdcp perperties, like type, undesired, desired, enabled,
10844 			 * will be lost. So, save hdcp properties into hdcp_work within
10845 			 * amdgpu_dm_atomic_commit_tail. if the same display is
10846 			 * plugged back with same display index, its hdcp properties
10847 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
10848 			 */
10849 
10850 			bool enable_encryption = false;
10851 
10852 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
10853 				enable_encryption = true;
10854 
10855 			if (aconnector->dc_link && aconnector->dc_sink &&
10856 				aconnector->dc_link->type == dc_connection_mst_branch) {
10857 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
10858 				struct hdcp_workqueue *hdcp_w =
10859 					&hdcp_work[aconnector->dc_link->link_index];
10860 
10861 				hdcp_w->hdcp_content_type[connector->index] =
10862 					new_con_state->hdcp_content_type;
10863 				hdcp_w->content_protection[connector->index] =
10864 					new_con_state->content_protection;
10865 			}
10866 
10867 			if (new_crtc_state && new_crtc_state->mode_changed &&
10868 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
10869 				enable_encryption = true;
10870 
10871 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
10872 
10873 			if (aconnector->dc_link)
10874 				hdcp_update_display(
10875 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
10876 					new_con_state->hdcp_content_type, enable_encryption);
10877 		}
10878 	}
10879 }
10880 
amdgpu_dm_atomic_setup_commit(struct drm_atomic_state * state)10881 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_state *state)
10882 {
10883 	struct drm_crtc *crtc;
10884 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10885 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10886 	int i, ret;
10887 
10888 	ret = drm_dp_mst_atomic_setup_commit(state);
10889 	if (ret)
10890 		return ret;
10891 
10892 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10893 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10894 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10895 		/*
10896 		 * Color management settings. We also update color properties
10897 		 * when a modeset is needed, to ensure it gets reprogrammed.
10898 		 */
10899 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
10900 		    (dm_new_crtc_state->base.color_mgmt_changed ||
10901 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
10902 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10903 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
10904 			if (ret) {
10905 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
10906 				return ret;
10907 			}
10908 		}
10909 	}
10910 
10911 	return 0;
10912 }
10913 
10914 /**
10915  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
10916  * @state: The atomic state to commit
10917  *
10918  * This will tell DC to commit the constructed DC state from atomic_check,
10919  * programming the hardware. Any failures here implies a hardware failure, since
10920  * atomic check should have filtered anything non-kosher.
10921  */
amdgpu_dm_atomic_commit_tail(struct drm_atomic_state * state)10922 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
10923 {
10924 	struct drm_device *dev = state->dev;
10925 	struct amdgpu_device *adev = drm_to_adev(dev);
10926 	struct amdgpu_display_manager *dm = &adev->dm;
10927 	struct dm_atomic_state *dm_state;
10928 	struct dc_state *dc_state = NULL;
10929 	u32 i, j;
10930 	struct drm_crtc *crtc;
10931 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10932 	unsigned long flags;
10933 	bool wait_for_vblank = true;
10934 	struct drm_connector *connector;
10935 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
10936 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10937 	int crtc_disable_count = 0;
10938 
10939 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
10940 
10941 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
10942 	drm_dp_mst_atomic_wait_for_dependencies(state);
10943 
10944 	dm_state = dm_atomic_get_new_state(state);
10945 	if (dm_state && dm_state->context) {
10946 		dc_state = dm_state->context;
10947 		amdgpu_dm_commit_streams(state, dc_state);
10948 	}
10949 
10950 	amdgpu_dm_update_hdcp(state);
10951 
10952 	/* Handle connector state changes */
10953 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10954 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10955 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
10956 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10957 		struct dc_surface_update *dummy_updates;
10958 		struct dc_stream_update stream_update;
10959 		struct dc_info_packet hdr_packet;
10960 		struct dc_stream_status *status = NULL;
10961 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
10962 
10963 		memset(&stream_update, 0, sizeof(stream_update));
10964 
10965 		if (acrtc) {
10966 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
10967 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10968 		}
10969 
10970 		/* Skip any modesets/resets */
10971 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
10972 			continue;
10973 
10974 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10975 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10976 
10977 		scaling_changed = is_scaling_state_different(dm_new_con_state,
10978 							     dm_old_con_state);
10979 
10980 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
10981 			(dm_old_crtc_state->stream->output_color_space !=
10982 				get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
10983 			output_color_space_changed = true;
10984 
10985 		abm_changed = dm_new_crtc_state->abm_level !=
10986 			      dm_old_crtc_state->abm_level;
10987 
10988 		hdr_changed =
10989 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
10990 
10991 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
10992 			continue;
10993 
10994 		stream_update.stream = dm_new_crtc_state->stream;
10995 		if (scaling_changed) {
10996 			update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
10997 					dm_new_con_state, dm_new_crtc_state->stream);
10998 
10999 			stream_update.src = dm_new_crtc_state->stream->src;
11000 			stream_update.dst = dm_new_crtc_state->stream->dst;
11001 		}
11002 
11003 		if (output_color_space_changed) {
11004 			dm_new_crtc_state->stream->output_color_space
11005 				= get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
11006 
11007 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
11008 		}
11009 
11010 		if (abm_changed) {
11011 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
11012 
11013 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
11014 		}
11015 
11016 		if (hdr_changed) {
11017 			fill_hdr_info_packet(new_con_state, &hdr_packet);
11018 			stream_update.hdr_static_metadata = &hdr_packet;
11019 		}
11020 
11021 		status = dc_stream_get_status(dm_new_crtc_state->stream);
11022 
11023 		if (WARN_ON(!status))
11024 			continue;
11025 
11026 		WARN_ON(!status->plane_count);
11027 
11028 		/*
11029 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
11030 		 * Here we create an empty update on each plane.
11031 		 * To fix this, DC should permit updating only stream properties.
11032 		 */
11033 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
11034 		if (!dummy_updates) {
11035 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
11036 			continue;
11037 		}
11038 		for (j = 0; j < status->plane_count; j++)
11039 			dummy_updates[j].surface = status->plane_states[j];
11040 
11041 		sort(dummy_updates, status->plane_count,
11042 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
11043 
11044 		mutex_lock(&dm->dc_lock);
11045 		dc_exit_ips_for_hw_access(dm->dc);
11046 		dc_update_planes_and_stream(dm->dc,
11047 					    dummy_updates,
11048 					    status->plane_count,
11049 					    dm_new_crtc_state->stream,
11050 					    &stream_update);
11051 		mutex_unlock(&dm->dc_lock);
11052 		kfree(dummy_updates);
11053 
11054 		drm_connector_update_privacy_screen(new_con_state);
11055 	}
11056 
11057 	/**
11058 	 * Enable interrupts for CRTCs that are newly enabled or went through
11059 	 * a modeset. It was intentionally deferred until after the front end
11060 	 * state was modified to wait until the OTG was on and so the IRQ
11061 	 * handlers didn't access stale or invalid state.
11062 	 */
11063 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11064 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11065 #ifdef CONFIG_DEBUG_FS
11066 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
11067 #endif
11068 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
11069 		if (old_crtc_state->active && !new_crtc_state->active)
11070 			crtc_disable_count++;
11071 
11072 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11073 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11074 
11075 		/* For freesync config update on crtc state and params for irq */
11076 		update_stream_irq_parameters(dm, dm_new_crtc_state);
11077 
11078 #ifdef CONFIG_DEBUG_FS
11079 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11080 		cur_crc_src = acrtc->dm_irq_params.crc_src;
11081 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11082 #endif
11083 
11084 		if (new_crtc_state->active &&
11085 		    (!old_crtc_state->active ||
11086 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11087 			dc_stream_retain(dm_new_crtc_state->stream);
11088 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
11089 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
11090 		}
11091 		/* Handle vrr on->off / off->on transitions */
11092 		amdgpu_dm_handle_vrr_transition(dm_old_crtc_state, dm_new_crtc_state);
11093 
11094 #ifdef CONFIG_DEBUG_FS
11095 		if (new_crtc_state->active &&
11096 		    (!old_crtc_state->active ||
11097 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11098 			/**
11099 			 * Frontend may have changed so reapply the CRC capture
11100 			 * settings for the stream.
11101 			 */
11102 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
11103 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
11104 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
11105 					uint8_t cnt;
11106 
11107 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11108 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
11109 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
11110 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
11111 
11112 							/**
11113 							 * It takes 2 frames for HW to stably generate CRC when
11114 							 * resuming from suspend, so we set skip_frame_cnt 2.
11115 							 */
11116 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
11117 						}
11118 					}
11119 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11120 				}
11121 #endif
11122 				if (amdgpu_dm_crtc_configure_crc_source(
11123 					crtc, dm_new_crtc_state, cur_crc_src))
11124 					drm_dbg_atomic(dev, "Failed to configure crc source");
11125 			}
11126 		}
11127 #endif
11128 	}
11129 
11130 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
11131 		if (new_crtc_state->async_flip)
11132 			wait_for_vblank = false;
11133 
11134 	/* update planes when needed per crtc*/
11135 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
11136 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11137 
11138 		if (dm_new_crtc_state->stream)
11139 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
11140 	}
11141 
11142 	/* Enable writeback */
11143 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11144 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11145 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11146 
11147 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11148 			continue;
11149 
11150 		if (!new_con_state->writeback_job)
11151 			continue;
11152 
11153 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11154 
11155 		if (!new_crtc_state)
11156 			continue;
11157 
11158 		if (acrtc->wb_enabled)
11159 			continue;
11160 
11161 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11162 
11163 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
11164 		acrtc->wb_enabled = true;
11165 	}
11166 
11167 	/* Update audio instances for each connector. */
11168 	amdgpu_dm_commit_audio(dev, state);
11169 
11170 	/* restore the backlight level */
11171 	for (i = 0; i < dm->num_of_edps; i++) {
11172 		if (dm->backlight_dev[i] &&
11173 		    (dm->actual_brightness[i] != dm->brightness[i]))
11174 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11175 	}
11176 
11177 	/*
11178 	 * send vblank event on all events not handled in flip and
11179 	 * mark consumed event for drm_atomic_helper_commit_hw_done
11180 	 */
11181 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11182 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11183 
11184 		if (new_crtc_state->event)
11185 			drm_send_event_locked(dev, &new_crtc_state->event->base);
11186 
11187 		new_crtc_state->event = NULL;
11188 	}
11189 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11190 
11191 	/* Signal HW programming completion */
11192 	drm_atomic_helper_commit_hw_done(state);
11193 
11194 	if (wait_for_vblank)
11195 		drm_atomic_helper_wait_for_flip_done(dev, state);
11196 
11197 	drm_atomic_helper_cleanup_planes(dev, state);
11198 
11199 	/* Don't free the memory if we are hitting this as part of suspend.
11200 	 * This way we don't free any memory during suspend; see
11201 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
11202 	 * non-suspend modeset or when the driver is torn down.
11203 	 */
11204 	if (!adev->in_suspend) {
11205 		/* return the stolen vga memory back to VRAM */
11206 		if (!adev->mman.keep_stolen_vga_memory)
11207 			amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_VGA);
11208 		amdgpu_ttm_unmark_vram_reserved(adev, AMDGPU_RESV_STOLEN_EXTENDED);
11209 	}
11210 
11211 	/*
11212 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
11213 	 * so we can put the GPU into runtime suspend if we're not driving any
11214 	 * displays anymore
11215 	 */
11216 	for (i = 0; i < crtc_disable_count; i++)
11217 		pm_runtime_put_autosuspend(dev->dev);
11218 	pm_runtime_mark_last_busy(dev->dev);
11219 
11220 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
11221 }
11222 
dm_force_atomic_commit(struct drm_connector * connector)11223 static int dm_force_atomic_commit(struct drm_connector *connector)
11224 {
11225 	int ret = 0;
11226 	struct drm_device *ddev = connector->dev;
11227 	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
11228 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11229 	struct drm_plane *plane = disconnected_acrtc->base.primary;
11230 	struct drm_connector_state *conn_state;
11231 	struct drm_crtc_state *crtc_state;
11232 	struct drm_plane_state *plane_state;
11233 
11234 	if (!state)
11235 		return -ENOMEM;
11236 
11237 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
11238 
11239 	/* Construct an atomic state to restore previous display setting */
11240 
11241 	/*
11242 	 * Attach connectors to drm_atomic_state
11243 	 */
11244 	conn_state = drm_atomic_get_connector_state(state, connector);
11245 
11246 	/* Check for error in getting connector state */
11247 	if (IS_ERR(conn_state)) {
11248 		ret = PTR_ERR(conn_state);
11249 		goto out;
11250 	}
11251 
11252 	/* Attach crtc to drm_atomic_state*/
11253 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
11254 
11255 	/* Check for error in getting crtc state */
11256 	if (IS_ERR(crtc_state)) {
11257 		ret = PTR_ERR(crtc_state);
11258 		goto out;
11259 	}
11260 
11261 	/* force a restore */
11262 	crtc_state->mode_changed = true;
11263 
11264 	/* Attach plane to drm_atomic_state */
11265 	plane_state = drm_atomic_get_plane_state(state, plane);
11266 
11267 	/* Check for error in getting plane state */
11268 	if (IS_ERR(plane_state)) {
11269 		ret = PTR_ERR(plane_state);
11270 		goto out;
11271 	}
11272 
11273 	/* Call commit internally with the state we just constructed */
11274 	ret = drm_atomic_commit(state);
11275 
11276 out:
11277 	drm_atomic_state_put(state);
11278 	if (ret)
11279 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
11280 
11281 	return ret;
11282 }
11283 
11284 /*
11285  * This function handles all cases when set mode does not come upon hotplug.
11286  * This includes when a display is unplugged then plugged back into the
11287  * same port and when running without usermode desktop manager supprot
11288  */
dm_restore_drm_connector_state(struct drm_device * dev,struct drm_connector * connector)11289 void dm_restore_drm_connector_state(struct drm_device *dev,
11290 				    struct drm_connector *connector)
11291 {
11292 	struct amdgpu_dm_connector *aconnector;
11293 	struct amdgpu_crtc *disconnected_acrtc;
11294 	struct dm_crtc_state *acrtc_state;
11295 
11296 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11297 		return;
11298 
11299 	aconnector = to_amdgpu_dm_connector(connector);
11300 
11301 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
11302 		return;
11303 
11304 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11305 	if (!disconnected_acrtc)
11306 		return;
11307 
11308 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
11309 	if (!acrtc_state->stream)
11310 		return;
11311 
11312 	/*
11313 	 * If the previous sink is not released and different from the current,
11314 	 * we deduce we are in a state where we can not rely on usermode call
11315 	 * to turn on the display, so we do it here
11316 	 */
11317 	if (acrtc_state->stream->sink != aconnector->dc_sink)
11318 		dm_force_atomic_commit(&aconnector->base);
11319 }
11320 
11321 /*
11322  * Grabs all modesetting locks to serialize against any blocking commits,
11323  * Waits for completion of all non blocking commits.
11324  */
do_aquire_global_lock(struct drm_device * dev,struct drm_atomic_state * state)11325 static int do_aquire_global_lock(struct drm_device *dev,
11326 				 struct drm_atomic_state *state)
11327 {
11328 	struct drm_crtc *crtc;
11329 	struct drm_crtc_commit *commit;
11330 	long ret;
11331 
11332 	/*
11333 	 * Adding all modeset locks to aquire_ctx will
11334 	 * ensure that when the framework release it the
11335 	 * extra locks we are locking here will get released to
11336 	 */
11337 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
11338 	if (ret)
11339 		return ret;
11340 
11341 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
11342 		spin_lock(&crtc->commit_lock);
11343 		commit = list_first_entry_or_null(&crtc->commit_list,
11344 				struct drm_crtc_commit, commit_entry);
11345 		if (commit)
11346 			drm_crtc_commit_get(commit);
11347 		spin_unlock(&crtc->commit_lock);
11348 
11349 		if (!commit)
11350 			continue;
11351 
11352 		/*
11353 		 * Make sure all pending HW programming completed and
11354 		 * page flips done
11355 		 */
11356 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
11357 
11358 		if (ret > 0)
11359 			ret = wait_for_completion_interruptible_timeout(
11360 					&commit->flip_done, 10*HZ);
11361 
11362 		if (ret == 0)
11363 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
11364 				  crtc->base.id, crtc->name);
11365 
11366 		drm_crtc_commit_put(commit);
11367 	}
11368 
11369 	return ret < 0 ? ret : 0;
11370 }
11371 
get_freesync_config_for_crtc(struct dm_crtc_state * new_crtc_state,struct dm_connector_state * new_con_state)11372 static void get_freesync_config_for_crtc(
11373 	struct dm_crtc_state *new_crtc_state,
11374 	struct dm_connector_state *new_con_state)
11375 {
11376 	struct mod_freesync_config config = {0};
11377 	struct amdgpu_dm_connector *aconnector;
11378 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
11379 	int vrefresh = drm_mode_vrefresh(mode);
11380 	bool fs_vid_mode = false;
11381 
11382 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11383 		return;
11384 
11385 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
11386 
11387 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
11388 					vrefresh >= aconnector->min_vfreq &&
11389 					vrefresh <= aconnector->max_vfreq;
11390 
11391 	if (new_crtc_state->vrr_supported) {
11392 		new_crtc_state->stream->ignore_msa_timing_param = true;
11393 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
11394 
11395 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
11396 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
11397 		config.vsif_supported = true;
11398 		config.btr = true;
11399 
11400 		if (fs_vid_mode) {
11401 			config.state = VRR_STATE_ACTIVE_FIXED;
11402 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
11403 			goto out;
11404 		} else if (new_crtc_state->base.vrr_enabled) {
11405 			config.state = VRR_STATE_ACTIVE_VARIABLE;
11406 		} else {
11407 			config.state = VRR_STATE_INACTIVE;
11408 		}
11409 	} else {
11410 		config.state = VRR_STATE_UNSUPPORTED;
11411 	}
11412 out:
11413 	new_crtc_state->freesync_config = config;
11414 }
11415 
reset_freesync_config_for_crtc(struct dm_crtc_state * new_crtc_state)11416 static void reset_freesync_config_for_crtc(
11417 	struct dm_crtc_state *new_crtc_state)
11418 {
11419 	new_crtc_state->vrr_supported = false;
11420 
11421 	memset(&new_crtc_state->vrr_infopacket, 0,
11422 	       sizeof(new_crtc_state->vrr_infopacket));
11423 }
11424 
11425 static bool
is_timing_unchanged_for_freesync(struct drm_crtc_state * old_crtc_state,struct drm_crtc_state * new_crtc_state)11426 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
11427 				 struct drm_crtc_state *new_crtc_state)
11428 {
11429 	const struct drm_display_mode *old_mode, *new_mode;
11430 
11431 	if (!old_crtc_state || !new_crtc_state)
11432 		return false;
11433 
11434 	old_mode = &old_crtc_state->mode;
11435 	new_mode = &new_crtc_state->mode;
11436 
11437 	if (old_mode->clock       == new_mode->clock &&
11438 	    old_mode->hdisplay    == new_mode->hdisplay &&
11439 	    old_mode->vdisplay    == new_mode->vdisplay &&
11440 	    old_mode->htotal      == new_mode->htotal &&
11441 	    old_mode->vtotal      != new_mode->vtotal &&
11442 	    old_mode->hsync_start == new_mode->hsync_start &&
11443 	    old_mode->vsync_start != new_mode->vsync_start &&
11444 	    old_mode->hsync_end   == new_mode->hsync_end &&
11445 	    old_mode->vsync_end   != new_mode->vsync_end &&
11446 	    old_mode->hskew       == new_mode->hskew &&
11447 	    old_mode->vscan       == new_mode->vscan &&
11448 	    (old_mode->vsync_end - old_mode->vsync_start) ==
11449 	    (new_mode->vsync_end - new_mode->vsync_start))
11450 		return true;
11451 
11452 	return false;
11453 }
11454 
set_freesync_fixed_config(struct dm_crtc_state * dm_new_crtc_state)11455 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
11456 {
11457 	u64 num, den, res;
11458 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
11459 
11460 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
11461 
11462 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
11463 	den = (unsigned long long)new_crtc_state->mode.htotal *
11464 	      (unsigned long long)new_crtc_state->mode.vtotal;
11465 
11466 	res = div_u64(num, den);
11467 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
11468 }
11469 
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)11470 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
11471 			 struct drm_atomic_state *state,
11472 			 struct drm_crtc *crtc,
11473 			 struct drm_crtc_state *old_crtc_state,
11474 			 struct drm_crtc_state *new_crtc_state,
11475 			 bool enable,
11476 			 bool *lock_and_validation_needed)
11477 {
11478 	struct dm_atomic_state *dm_state = NULL;
11479 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11480 	struct dc_stream_state *new_stream;
11481 	struct amdgpu_device *adev = dm->adev;
11482 	int ret = 0;
11483 
11484 	/*
11485 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
11486 	 * update changed items
11487 	 */
11488 	struct amdgpu_crtc *acrtc = NULL;
11489 	struct drm_connector *connector = NULL;
11490 	struct amdgpu_dm_connector *aconnector = NULL;
11491 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
11492 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
11493 
11494 	new_stream = NULL;
11495 
11496 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11497 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11498 	acrtc = to_amdgpu_crtc(crtc);
11499 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
11500 	if (connector)
11501 		aconnector = to_amdgpu_dm_connector(connector);
11502 
11503 	/* TODO This hack should go away */
11504 	if (connector && enable) {
11505 		/* Make sure fake sink is created in plug-in scenario */
11506 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
11507 									connector);
11508 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
11509 									connector);
11510 
11511 		if (WARN_ON(!drm_new_conn_state)) {
11512 			ret = -EINVAL;
11513 			goto fail;
11514 		}
11515 
11516 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
11517 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
11518 
11519 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11520 			goto skip_modeset;
11521 
11522 		new_stream = create_validate_stream_for_sink(connector,
11523 							     &new_crtc_state->mode,
11524 							     dm_new_conn_state,
11525 							     dm_old_crtc_state->stream);
11526 
11527 		/*
11528 		 * we can have no stream on ACTION_SET if a display
11529 		 * was disconnected during S3, in this case it is not an
11530 		 * error, the OS will be updated after detection, and
11531 		 * will do the right thing on next atomic commit
11532 		 */
11533 
11534 		if (!new_stream) {
11535 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
11536 					__func__, acrtc->base.base.id);
11537 			ret = -ENOMEM;
11538 			goto fail;
11539 		}
11540 
11541 		/*
11542 		 * TODO: Check VSDB bits to decide whether this should
11543 		 * be enabled or not.
11544 		 */
11545 		new_stream->triggered_crtc_reset.enabled =
11546 			dm->force_timing_sync;
11547 
11548 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11549 
11550 		ret = fill_hdr_info_packet(drm_new_conn_state,
11551 					   &new_stream->hdr_static_metadata);
11552 		if (ret)
11553 			goto fail;
11554 
11555 		/*
11556 		 * If we already removed the old stream from the context
11557 		 * (and set the new stream to NULL) then we can't reuse
11558 		 * the old stream even if the stream and scaling are unchanged.
11559 		 * We'll hit the BUG_ON and black screen.
11560 		 *
11561 		 * TODO: Refactor this function to allow this check to work
11562 		 * in all conditions.
11563 		 */
11564 		if (amdgpu_freesync_vid_mode &&
11565 		    dm_new_crtc_state->stream &&
11566 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
11567 			goto skip_modeset;
11568 
11569 		if (dm_new_crtc_state->stream &&
11570 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11571 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
11572 			new_crtc_state->mode_changed = false;
11573 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
11574 					 new_crtc_state->mode_changed);
11575 		}
11576 	}
11577 
11578 	/* mode_changed flag may get updated above, need to check again */
11579 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11580 		goto skip_modeset;
11581 
11582 	drm_dbg_state(state->dev,
11583 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
11584 		acrtc->crtc_id,
11585 		new_crtc_state->enable,
11586 		new_crtc_state->active,
11587 		new_crtc_state->planes_changed,
11588 		new_crtc_state->mode_changed,
11589 		new_crtc_state->active_changed,
11590 		new_crtc_state->connectors_changed);
11591 
11592 	/* Remove stream for any changed/disabled CRTC */
11593 	if (!enable) {
11594 
11595 		if (!dm_old_crtc_state->stream)
11596 			goto skip_modeset;
11597 
11598 		/* Unset freesync video if it was active before */
11599 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
11600 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
11601 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
11602 		}
11603 
11604 		/* Now check if we should set freesync video mode */
11605 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
11606 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11607 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
11608 		    is_timing_unchanged_for_freesync(new_crtc_state,
11609 						     old_crtc_state)) {
11610 			new_crtc_state->mode_changed = false;
11611 			drm_dbg_driver(adev_to_drm(adev),
11612 				"Mode change not required for front porch change, setting mode_changed to %d",
11613 				new_crtc_state->mode_changed);
11614 
11615 			set_freesync_fixed_config(dm_new_crtc_state);
11616 
11617 			goto skip_modeset;
11618 		} else if (amdgpu_freesync_vid_mode && aconnector &&
11619 			   is_freesync_video_mode(&new_crtc_state->mode,
11620 						  aconnector)) {
11621 			struct drm_display_mode *high_mode;
11622 
11623 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
11624 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
11625 				set_freesync_fixed_config(dm_new_crtc_state);
11626 		}
11627 
11628 		ret = dm_atomic_get_state(state, &dm_state);
11629 		if (ret)
11630 			goto fail;
11631 
11632 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
11633 				crtc->base.id);
11634 
11635 		/* i.e. reset mode */
11636 		if (dc_state_remove_stream(
11637 				dm->dc,
11638 				dm_state->context,
11639 				dm_old_crtc_state->stream) != DC_OK) {
11640 			ret = -EINVAL;
11641 			goto fail;
11642 		}
11643 
11644 		dc_stream_release(dm_old_crtc_state->stream);
11645 		dm_new_crtc_state->stream = NULL;
11646 
11647 		reset_freesync_config_for_crtc(dm_new_crtc_state);
11648 
11649 		*lock_and_validation_needed = true;
11650 
11651 	} else {/* Add stream for any updated/enabled CRTC */
11652 		/*
11653 		 * Quick fix to prevent NULL pointer on new_stream when
11654 		 * added MST connectors not found in existing crtc_state in the chained mode
11655 		 * TODO: need to dig out the root cause of that
11656 		 */
11657 		if (!connector)
11658 			goto skip_modeset;
11659 
11660 		if (modereset_required(new_crtc_state))
11661 			goto skip_modeset;
11662 
11663 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
11664 				     dm_old_crtc_state->stream)) {
11665 
11666 			WARN_ON(dm_new_crtc_state->stream);
11667 
11668 			ret = dm_atomic_get_state(state, &dm_state);
11669 			if (ret)
11670 				goto fail;
11671 
11672 			dm_new_crtc_state->stream = new_stream;
11673 
11674 			dc_stream_retain(new_stream);
11675 
11676 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
11677 					 crtc->base.id);
11678 
11679 			if (dc_state_add_stream(
11680 					dm->dc,
11681 					dm_state->context,
11682 					dm_new_crtc_state->stream) != DC_OK) {
11683 				ret = -EINVAL;
11684 				goto fail;
11685 			}
11686 
11687 			*lock_and_validation_needed = true;
11688 		}
11689 	}
11690 
11691 skip_modeset:
11692 	/* Release extra reference */
11693 	if (new_stream)
11694 		dc_stream_release(new_stream);
11695 
11696 	/*
11697 	 * We want to do dc stream updates that do not require a
11698 	 * full modeset below.
11699 	 */
11700 	if (!(enable && connector && new_crtc_state->active))
11701 		return 0;
11702 	/*
11703 	 * Given above conditions, the dc state cannot be NULL because:
11704 	 * 1. We're in the process of enabling CRTCs (just been added
11705 	 *    to the dc context, or already is on the context)
11706 	 * 2. Has a valid connector attached, and
11707 	 * 3. Is currently active and enabled.
11708 	 * => The dc stream state currently exists.
11709 	 */
11710 	BUG_ON(dm_new_crtc_state->stream == NULL);
11711 
11712 	/* Scaling or underscan settings */
11713 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
11714 				drm_atomic_crtc_needs_modeset(new_crtc_state))
11715 		update_stream_scaling_settings(adev_to_drm(adev),
11716 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
11717 
11718 	/* ABM settings */
11719 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11720 
11721 	/*
11722 	 * Color management settings. We also update color properties
11723 	 * when a modeset is needed, to ensure it gets reprogrammed.
11724 	 */
11725 	if (dm_new_crtc_state->base.color_mgmt_changed ||
11726 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11727 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
11728 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
11729 		if (ret)
11730 			goto fail;
11731 	}
11732 
11733 	/* Update Freesync settings. */
11734 	get_freesync_config_for_crtc(dm_new_crtc_state,
11735 				     dm_new_conn_state);
11736 
11737 	return ret;
11738 
11739 fail:
11740 	if (new_stream)
11741 		dc_stream_release(new_stream);
11742 	return ret;
11743 }
11744 
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)11745 static bool should_reset_plane(struct drm_atomic_state *state,
11746 			       struct drm_plane *plane,
11747 			       struct drm_plane_state *old_plane_state,
11748 			       struct drm_plane_state *new_plane_state)
11749 {
11750 	struct drm_plane *other;
11751 	struct drm_plane_state *old_other_state, *new_other_state;
11752 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11753 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
11754 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
11755 	struct drm_connector_state *new_con_state;
11756 	struct drm_connector *connector;
11757 	int i;
11758 
11759 	/*
11760 	 * TODO: Remove this hack for all asics once it proves that the
11761 	 * fast updates works fine on DCN3.2+.
11762 	 */
11763 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
11764 	    state->allow_modeset)
11765 		return true;
11766 
11767 	/* Check for writeback commit */
11768 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11769 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11770 			continue;
11771 
11772 		if (new_con_state->writeback_job)
11773 			return true;
11774 	}
11775 
11776 	if (amdgpu_in_reset(adev) && state->allow_modeset)
11777 		return true;
11778 
11779 	/* Exit early if we know that we're adding or removing the plane. */
11780 	if (old_plane_state->crtc != new_plane_state->crtc)
11781 		return true;
11782 
11783 	/* old crtc == new_crtc == NULL, plane not in context. */
11784 	if (!new_plane_state->crtc)
11785 		return false;
11786 
11787 	new_crtc_state =
11788 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
11789 	old_crtc_state =
11790 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
11791 
11792 	if (!new_crtc_state)
11793 		return true;
11794 
11795 	/*
11796 	 * A change in cursor mode means a new dc pipe needs to be acquired or
11797 	 * released from the state
11798 	 */
11799 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
11800 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
11801 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
11802 	    old_dm_crtc_state != NULL &&
11803 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
11804 		return true;
11805 	}
11806 
11807 	/* CRTC Degamma changes currently require us to recreate planes. */
11808 	if (new_crtc_state->color_mgmt_changed)
11809 		return true;
11810 
11811 	/*
11812 	 * On zpos change, planes need to be reordered by removing and re-adding
11813 	 * them one by one to the dc state, in order of descending zpos.
11814 	 *
11815 	 * TODO: We can likely skip bandwidth validation if the only thing that
11816 	 * changed about the plane was it'z z-ordering.
11817 	 */
11818 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
11819 		return true;
11820 
11821 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
11822 		return true;
11823 
11824 	/*
11825 	 * If there are any new primary or overlay planes being added or
11826 	 * removed then the z-order can potentially change. To ensure
11827 	 * correct z-order and pipe acquisition the current DC architecture
11828 	 * requires us to remove and recreate all existing planes.
11829 	 *
11830 	 * TODO: Come up with a more elegant solution for this.
11831 	 */
11832 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
11833 		struct amdgpu_framebuffer *old_afb, *new_afb;
11834 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
11835 
11836 		dm_new_other_state = to_dm_plane_state(new_other_state);
11837 		dm_old_other_state = to_dm_plane_state(old_other_state);
11838 
11839 		if (other->type == DRM_PLANE_TYPE_CURSOR)
11840 			continue;
11841 
11842 		if (old_other_state->crtc != new_plane_state->crtc &&
11843 		    new_other_state->crtc != new_plane_state->crtc)
11844 			continue;
11845 
11846 		if (old_other_state->crtc != new_other_state->crtc)
11847 			return true;
11848 
11849 		/* Src/dst size and scaling updates. */
11850 		if (old_other_state->src_w != new_other_state->src_w ||
11851 		    old_other_state->src_h != new_other_state->src_h ||
11852 		    old_other_state->crtc_w != new_other_state->crtc_w ||
11853 		    old_other_state->crtc_h != new_other_state->crtc_h)
11854 			return true;
11855 
11856 		/* Rotation / mirroring updates. */
11857 		if (old_other_state->rotation != new_other_state->rotation)
11858 			return true;
11859 
11860 		/* Blending updates. */
11861 		if (old_other_state->pixel_blend_mode !=
11862 		    new_other_state->pixel_blend_mode)
11863 			return true;
11864 
11865 		/* Alpha updates. */
11866 		if (old_other_state->alpha != new_other_state->alpha)
11867 			return true;
11868 
11869 		/* Colorspace changes. */
11870 		if (old_other_state->color_range != new_other_state->color_range ||
11871 		    old_other_state->color_encoding != new_other_state->color_encoding)
11872 			return true;
11873 
11874 		/* HDR/Transfer Function changes. */
11875 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
11876 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
11877 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
11878 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
11879 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
11880 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
11881 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
11882 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
11883 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
11884 			return true;
11885 
11886 		/* Framebuffer checks fall at the end. */
11887 		if (!old_other_state->fb || !new_other_state->fb)
11888 			continue;
11889 
11890 		/* Pixel format changes can require bandwidth updates. */
11891 		if (old_other_state->fb->format != new_other_state->fb->format)
11892 			return true;
11893 
11894 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
11895 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
11896 
11897 		/* Tiling and DCC changes also require bandwidth updates. */
11898 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
11899 		    old_afb->base.modifier != new_afb->base.modifier)
11900 			return true;
11901 	}
11902 
11903 	return false;
11904 }
11905 
dm_check_cursor_fb(struct amdgpu_crtc * new_acrtc,struct drm_plane_state * new_plane_state,struct drm_framebuffer * fb)11906 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
11907 			      struct drm_plane_state *new_plane_state,
11908 			      struct drm_framebuffer *fb)
11909 {
11910 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
11911 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
11912 	unsigned int pitch;
11913 	bool linear;
11914 
11915 	if (fb->width > new_acrtc->max_cursor_width ||
11916 	    fb->height > new_acrtc->max_cursor_height) {
11917 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB size %dx%d\n",
11918 				 new_plane_state->fb->width,
11919 				 new_plane_state->fb->height);
11920 		return -EINVAL;
11921 	}
11922 	if (new_plane_state->src_w != fb->width << 16 ||
11923 	    new_plane_state->src_h != fb->height << 16) {
11924 		drm_dbg_atomic(adev_to_drm(adev), "Cropping not supported for cursor plane\n");
11925 		return -EINVAL;
11926 	}
11927 
11928 	/* Pitch in pixels */
11929 	pitch = fb->pitches[0] / fb->format->cpp[0];
11930 
11931 	if (fb->width != pitch) {
11932 		drm_dbg_atomic(adev_to_drm(adev), "Cursor FB width %d doesn't match pitch %d",
11933 				 fb->width, pitch);
11934 		return -EINVAL;
11935 	}
11936 
11937 	switch (pitch) {
11938 	case 64:
11939 	case 128:
11940 	case 256:
11941 		/* FB pitch is supported by cursor plane */
11942 		break;
11943 	default:
11944 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB pitch %d px\n", pitch);
11945 		return -EINVAL;
11946 	}
11947 
11948 	/* Core DRM takes care of checking FB modifiers, so we only need to
11949 	 * check tiling flags when the FB doesn't have a modifier.
11950 	 */
11951 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
11952 		if (adev->family == AMDGPU_FAMILY_GC_12_0_0) {
11953 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
11954 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
11955 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
11956 		} else {
11957 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
11958 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
11959 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
11960 		}
11961 		if (!linear) {
11962 			drm_dbg_atomic(adev_to_drm(adev), "Cursor FB not linear");
11963 			return -EINVAL;
11964 		}
11965 	}
11966 
11967 	return 0;
11968 }
11969 
11970 /*
11971  * Helper function for checking the cursor in native mode
11972  */
dm_check_native_cursor_state(struct drm_crtc * new_plane_crtc,struct drm_plane * plane,struct drm_plane_state * new_plane_state,bool enable)11973 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
11974 					struct drm_plane *plane,
11975 					struct drm_plane_state *new_plane_state,
11976 					bool enable)
11977 {
11978 
11979 	struct amdgpu_crtc *new_acrtc;
11980 	int ret;
11981 
11982 	if (!enable || !new_plane_crtc ||
11983 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
11984 		return 0;
11985 
11986 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
11987 
11988 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
11989 		drm_dbg_atomic(new_plane_crtc->dev, "Cropping not supported for cursor plane\n");
11990 		return -EINVAL;
11991 	}
11992 
11993 	if (new_plane_state->fb) {
11994 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
11995 						new_plane_state->fb);
11996 		if (ret)
11997 			return ret;
11998 	}
11999 
12000 	return 0;
12001 }
12002 
dm_should_update_native_cursor(struct drm_atomic_state * state,struct drm_crtc * old_plane_crtc,struct drm_crtc * new_plane_crtc,bool enable)12003 static bool dm_should_update_native_cursor(struct drm_atomic_state *state,
12004 					   struct drm_crtc *old_plane_crtc,
12005 					   struct drm_crtc *new_plane_crtc,
12006 					   bool enable)
12007 {
12008 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12009 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12010 
12011 	if (!enable) {
12012 		if (old_plane_crtc == NULL)
12013 			return true;
12014 
12015 		old_crtc_state = drm_atomic_get_old_crtc_state(
12016 			state, old_plane_crtc);
12017 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12018 
12019 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12020 	} else {
12021 		if (new_plane_crtc == NULL)
12022 			return true;
12023 
12024 		new_crtc_state = drm_atomic_get_new_crtc_state(
12025 			state, new_plane_crtc);
12026 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12027 
12028 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
12029 	}
12030 }
12031 
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)12032 static int dm_update_plane_state(struct dc *dc,
12033 				 struct drm_atomic_state *state,
12034 				 struct drm_plane *plane,
12035 				 struct drm_plane_state *old_plane_state,
12036 				 struct drm_plane_state *new_plane_state,
12037 				 bool enable,
12038 				 bool *lock_and_validation_needed,
12039 				 bool *is_top_most_overlay)
12040 {
12041 
12042 	struct dm_atomic_state *dm_state = NULL;
12043 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
12044 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12045 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
12046 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
12047 	bool needs_reset, update_native_cursor;
12048 	int ret = 0;
12049 
12050 
12051 	new_plane_crtc = new_plane_state->crtc;
12052 	old_plane_crtc = old_plane_state->crtc;
12053 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
12054 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
12055 
12056 	update_native_cursor = dm_should_update_native_cursor(state,
12057 							      old_plane_crtc,
12058 							      new_plane_crtc,
12059 							      enable);
12060 
12061 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
12062 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12063 						    new_plane_state, enable);
12064 		if (ret)
12065 			return ret;
12066 
12067 		return 0;
12068 	}
12069 
12070 	needs_reset = should_reset_plane(state, plane, old_plane_state,
12071 					 new_plane_state);
12072 
12073 	/* Remove any changed/removed planes */
12074 	if (!enable) {
12075 		if (!needs_reset)
12076 			return 0;
12077 
12078 		if (!old_plane_crtc)
12079 			return 0;
12080 
12081 		old_crtc_state = drm_atomic_get_old_crtc_state(
12082 				state, old_plane_crtc);
12083 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12084 
12085 		if (!dm_old_crtc_state->stream)
12086 			return 0;
12087 
12088 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
12089 				plane->base.id, old_plane_crtc->base.id);
12090 
12091 		ret = dm_atomic_get_state(state, &dm_state);
12092 		if (ret)
12093 			return ret;
12094 
12095 		if (!dc_state_remove_plane(
12096 				dc,
12097 				dm_old_crtc_state->stream,
12098 				dm_old_plane_state->dc_state,
12099 				dm_state->context)) {
12100 
12101 			return -EINVAL;
12102 		}
12103 
12104 		if (dm_old_plane_state->dc_state)
12105 			dc_plane_state_release(dm_old_plane_state->dc_state);
12106 
12107 		dm_new_plane_state->dc_state = NULL;
12108 
12109 		*lock_and_validation_needed = true;
12110 
12111 	} else { /* Add new planes */
12112 		struct dc_plane_state *dc_new_plane_state;
12113 
12114 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
12115 			return 0;
12116 
12117 		if (!new_plane_crtc)
12118 			return 0;
12119 
12120 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
12121 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12122 
12123 		if (!dm_new_crtc_state->stream)
12124 			return 0;
12125 
12126 		if (!needs_reset)
12127 			return 0;
12128 
12129 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
12130 		if (ret)
12131 			goto out;
12132 
12133 		WARN_ON(dm_new_plane_state->dc_state);
12134 
12135 		dc_new_plane_state = dc_create_plane_state(dc);
12136 		if (!dc_new_plane_state) {
12137 			ret = -ENOMEM;
12138 			goto out;
12139 		}
12140 
12141 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
12142 				 plane->base.id, new_plane_crtc->base.id);
12143 
12144 		ret = fill_dc_plane_attributes(
12145 			drm_to_adev(new_plane_crtc->dev),
12146 			dc_new_plane_state,
12147 			new_plane_state,
12148 			new_crtc_state);
12149 		if (ret) {
12150 			dc_plane_state_release(dc_new_plane_state);
12151 			goto out;
12152 		}
12153 
12154 		ret = dm_atomic_get_state(state, &dm_state);
12155 		if (ret) {
12156 			dc_plane_state_release(dc_new_plane_state);
12157 			goto out;
12158 		}
12159 
12160 		/*
12161 		 * Any atomic check errors that occur after this will
12162 		 * not need a release. The plane state will be attached
12163 		 * to the stream, and therefore part of the atomic
12164 		 * state. It'll be released when the atomic state is
12165 		 * cleaned.
12166 		 */
12167 		if (!dc_state_add_plane(
12168 				dc,
12169 				dm_new_crtc_state->stream,
12170 				dc_new_plane_state,
12171 				dm_state->context)) {
12172 
12173 			dc_plane_state_release(dc_new_plane_state);
12174 			ret = -EINVAL;
12175 			goto out;
12176 		}
12177 
12178 		dm_new_plane_state->dc_state = dc_new_plane_state;
12179 
12180 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
12181 
12182 		/* Tell DC to do a full surface update every time there
12183 		 * is a plane change. Inefficient, but works for now.
12184 		 */
12185 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
12186 
12187 		*lock_and_validation_needed = true;
12188 	}
12189 
12190 out:
12191 	/* If enabling cursor overlay failed, attempt fallback to native mode */
12192 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
12193 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12194 						    new_plane_state, enable);
12195 		if (ret)
12196 			return ret;
12197 
12198 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
12199 	}
12200 
12201 	return ret;
12202 }
12203 
dm_get_oriented_plane_size(struct drm_plane_state * plane_state,int * src_w,int * src_h)12204 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
12205 				       int *src_w, int *src_h)
12206 {
12207 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
12208 	case DRM_MODE_ROTATE_90:
12209 	case DRM_MODE_ROTATE_270:
12210 		*src_w = plane_state->src_h >> 16;
12211 		*src_h = plane_state->src_w >> 16;
12212 		break;
12213 	case DRM_MODE_ROTATE_0:
12214 	case DRM_MODE_ROTATE_180:
12215 	default:
12216 		*src_w = plane_state->src_w >> 16;
12217 		*src_h = plane_state->src_h >> 16;
12218 		break;
12219 	}
12220 }
12221 
12222 static void
dm_get_plane_scale(struct drm_plane_state * plane_state,int * out_plane_scale_w,int * out_plane_scale_h)12223 dm_get_plane_scale(struct drm_plane_state *plane_state,
12224 		   int *out_plane_scale_w, int *out_plane_scale_h)
12225 {
12226 	int plane_src_w, plane_src_h;
12227 
12228 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
12229 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
12230 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
12231 }
12232 
12233 /*
12234  * The normalized_zpos value cannot be used by this iterator directly. It's only
12235  * calculated for enabled planes, potentially causing normalized_zpos collisions
12236  * between enabled/disabled planes in the atomic state. We need a unique value
12237  * so that the iterator will not generate the same object twice, or loop
12238  * indefinitely.
12239  */
__get_next_zpos(struct drm_atomic_state * state,struct __drm_planes_state * prev)12240 static inline struct __drm_planes_state *__get_next_zpos(
12241 	struct drm_atomic_state *state,
12242 	struct __drm_planes_state *prev)
12243 {
12244 	unsigned int highest_zpos = 0, prev_zpos = 256;
12245 	uint32_t highest_id = 0, prev_id = UINT_MAX;
12246 	struct drm_plane_state *new_plane_state;
12247 	struct drm_plane *plane;
12248 	int i, highest_i = -1;
12249 
12250 	if (prev != NULL) {
12251 		prev_zpos = prev->new_state->zpos;
12252 		prev_id = prev->ptr->base.id;
12253 	}
12254 
12255 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
12256 		/* Skip planes with higher zpos than the previously returned */
12257 		if (new_plane_state->zpos > prev_zpos ||
12258 		    (new_plane_state->zpos == prev_zpos &&
12259 		     plane->base.id >= prev_id))
12260 			continue;
12261 
12262 		/* Save the index of the plane with highest zpos */
12263 		if (new_plane_state->zpos > highest_zpos ||
12264 		    (new_plane_state->zpos == highest_zpos &&
12265 		     plane->base.id > highest_id)) {
12266 			highest_zpos = new_plane_state->zpos;
12267 			highest_id = plane->base.id;
12268 			highest_i = i;
12269 		}
12270 	}
12271 
12272 	if (highest_i < 0)
12273 		return NULL;
12274 
12275 	return &state->planes[highest_i];
12276 }
12277 
12278 /*
12279  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
12280  * by descending zpos, as read from the new plane state. This is the same
12281  * ordering as defined by drm_atomic_normalize_zpos().
12282  */
12283 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
12284 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
12285 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
12286 		for_each_if(((plane) = __i->ptr,				\
12287 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
12288 			     (old_plane_state) = __i->old_state,		\
12289 			     (new_plane_state) = __i->new_state, 1))
12290 
add_affected_mst_dsc_crtcs(struct drm_atomic_state * state,struct drm_crtc * crtc)12291 static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
12292 {
12293 	struct drm_connector *connector;
12294 	struct drm_connector_state *conn_state, *old_conn_state;
12295 	struct amdgpu_dm_connector *aconnector = NULL;
12296 	int i;
12297 
12298 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
12299 		if (!conn_state->crtc)
12300 			conn_state = old_conn_state;
12301 
12302 		if (conn_state->crtc != crtc)
12303 			continue;
12304 
12305 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
12306 			continue;
12307 
12308 		aconnector = to_amdgpu_dm_connector(connector);
12309 		if (!aconnector->mst_output_port || !aconnector->mst_root)
12310 			aconnector = NULL;
12311 		else
12312 			break;
12313 	}
12314 
12315 	if (!aconnector)
12316 		return 0;
12317 
12318 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
12319 }
12320 
12321 /**
12322  * DOC: Cursor Modes - Native vs Overlay
12323  *
12324  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
12325  * plane. It does not require a dedicated hw plane to enable, but it is
12326  * subjected to the same z-order and scaling as the hw plane. It also has format
12327  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
12328  * hw plane.
12329  *
12330  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
12331  * own scaling and z-pos. It also has no blending restrictions. It lends to a
12332  * cursor behavior more akin to a DRM client's expectations. However, it does
12333  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
12334  * available.
12335  */
12336 
12337 /**
12338  * dm_plane_color_pipeline_active() - Check if a plane's color pipeline active.
12339  * @state: DRM atomic state
12340  * @plane: DRM plane to check
12341  * @use_old: if true, inspect the old colorop states; otherwise the new ones
12342  *
12343  * A color pipeline may be selected (color_pipeline != NULL) but still is
12344  * inactive if every colorop in the chain is bypassed.  Only return
12345  * true when at least one colorop has bypass == false, meaning the cursor
12346  * would be subjected to the transformation in native mode.
12347  *
12348  * Return: true if the pipeline modifies pixels, false otherwise.
12349  */
dm_plane_color_pipeline_active(struct drm_atomic_state * state,struct drm_plane * plane,bool use_old)12350 static bool dm_plane_color_pipeline_active(struct drm_atomic_state *state,
12351 					   struct drm_plane *plane,
12352 					   bool use_old)
12353 {
12354 	struct drm_colorop *colorop;
12355 	struct drm_colorop_state *old_colorop_state, *new_colorop_state;
12356 	int i;
12357 
12358 	for_each_oldnew_colorop_in_state(state, colorop, old_colorop_state, new_colorop_state, i) {
12359 		struct drm_colorop_state *cstate = use_old ? old_colorop_state : new_colorop_state;
12360 
12361 		if (cstate->colorop->plane != plane)
12362 			continue;
12363 		if (!cstate->bypass)
12364 			return true;
12365 	}
12366 	return false;
12367 }
12368 
12369 /**
12370  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
12371  * @adev: amdgpu device
12372  * @state: DRM atomic state
12373  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
12374  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
12375  *
12376  * Get whether the cursor should be enabled in native mode, or overlay mode, on
12377  * the dm_crtc_state.
12378  *
12379  * The cursor should be enabled in overlay mode if there exists an underlying
12380  * plane - on which the cursor may be blended - that is either YUV formatted,
12381  * scaled differently from the cursor, or has a color pipeline active.
12382  *
12383  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
12384  * calling this function.
12385  *
12386  * Return: 0 on success, or an error code if getting the cursor plane state
12387  * failed.
12388  */
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)12389 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
12390 				   struct drm_atomic_state *state,
12391 				   struct dm_crtc_state *dm_crtc_state,
12392 				   enum amdgpu_dm_cursor_mode *cursor_mode)
12393 {
12394 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
12395 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
12396 	struct drm_plane *plane;
12397 	bool consider_mode_change = false;
12398 	bool entire_crtc_covered = false;
12399 	bool cursor_changed = false;
12400 	int underlying_scale_w, underlying_scale_h;
12401 	int cursor_scale_w, cursor_scale_h;
12402 	int i;
12403 
12404 	/* Overlay cursor not supported on HW before DCN
12405 	 * DCN401/420 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
12406 	 * as previous DCN generations, so enable native mode on DCN401/420
12407 	 */
12408 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1) ||
12409 	    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0)) {
12410 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12411 		return 0;
12412 	}
12413 
12414 	/* Init cursor_mode to be the same as current */
12415 	*cursor_mode = dm_crtc_state->cursor_mode;
12416 
12417 	/*
12418 	 * Cursor mode can change if a plane's format changes, scale changes, is
12419 	 * enabled/disabled, z-order changes, or color management properties change.
12420 	 */
12421 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
12422 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
12423 
12424 		/* Only care about planes on this CRTC */
12425 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
12426 			continue;
12427 
12428 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
12429 			cursor_changed = true;
12430 
12431 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
12432 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
12433 		    old_plane_state->fb->format != plane_state->fb->format) {
12434 			consider_mode_change = true;
12435 			break;
12436 		}
12437 
12438 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
12439 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
12440 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
12441 			consider_mode_change = true;
12442 			break;
12443 		}
12444 
12445 		if (dm_plane_color_pipeline_active(state, plane, true) !=
12446 		    dm_plane_color_pipeline_active(state, plane, false)) {
12447 			consider_mode_change = true;
12448 			break;
12449 		}
12450 	}
12451 
12452 	if (!consider_mode_change && !crtc_state->zpos_changed)
12453 		return 0;
12454 
12455 	/*
12456 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
12457 	 * no need to set cursor mode. This avoids needlessly locking the cursor
12458 	 * state.
12459 	 */
12460 	if (!cursor_changed &&
12461 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
12462 		return 0;
12463 	}
12464 
12465 	cursor_state = drm_atomic_get_plane_state(state,
12466 						  crtc_state->crtc->cursor);
12467 	if (IS_ERR(cursor_state))
12468 		return PTR_ERR(cursor_state);
12469 
12470 	/* Cursor is disabled */
12471 	if (!cursor_state->fb)
12472 		return 0;
12473 
12474 	/* For all planes in descending z-order (all of which are below cursor
12475 	 * as per zpos definitions), check their scaling and format
12476 	 */
12477 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
12478 
12479 		/* Only care about non-cursor planes on this CRTC */
12480 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
12481 		    plane->type == DRM_PLANE_TYPE_CURSOR)
12482 			continue;
12483 
12484 		/* Underlying plane is YUV format - use overlay cursor */
12485 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
12486 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12487 			return 0;
12488 		}
12489 
12490 		/* Underlying plane has an active color pipeline - cursor would be transformed */
12491 		if (dm_plane_color_pipeline_active(state, plane, false)) {
12492 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12493 			return 0;
12494 		}
12495 
12496 		dm_get_plane_scale(plane_state,
12497 				   &underlying_scale_w, &underlying_scale_h);
12498 		dm_get_plane_scale(cursor_state,
12499 				   &cursor_scale_w, &cursor_scale_h);
12500 
12501 		/* Underlying plane has different scale - use overlay cursor */
12502 		if (cursor_scale_w != underlying_scale_w &&
12503 		    cursor_scale_h != underlying_scale_h) {
12504 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12505 			return 0;
12506 		}
12507 
12508 		/* If this plane covers the whole CRTC, no need to check planes underneath */
12509 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
12510 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
12511 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
12512 			entire_crtc_covered = true;
12513 			break;
12514 		}
12515 	}
12516 
12517 	/* If planes do not cover the entire CRTC, use overlay mode to enable
12518 	 * cursor over holes
12519 	 */
12520 	if (entire_crtc_covered)
12521 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12522 	else
12523 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12524 
12525 	return 0;
12526 }
12527 
amdgpu_dm_crtc_mem_type_changed(struct drm_device * dev,struct drm_atomic_state * state,struct drm_crtc_state * crtc_state)12528 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
12529 					    struct drm_atomic_state *state,
12530 					    struct drm_crtc_state *crtc_state)
12531 {
12532 	struct drm_plane *plane;
12533 	struct drm_plane_state *new_plane_state, *old_plane_state;
12534 
12535 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
12536 		new_plane_state = drm_atomic_get_plane_state(state, plane);
12537 		old_plane_state = drm_atomic_get_plane_state(state, plane);
12538 
12539 		if (IS_ERR(new_plane_state) || IS_ERR(old_plane_state)) {
12540 			drm_err(dev, "Failed to get plane state for plane %s\n", plane->name);
12541 			return false;
12542 		}
12543 
12544 		if (old_plane_state->fb && new_plane_state->fb &&
12545 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
12546 			return true;
12547 	}
12548 
12549 	return false;
12550 }
12551 
12552 /**
12553  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
12554  *
12555  * @dev: The DRM device
12556  * @state: The atomic state to commit
12557  *
12558  * Validate that the given atomic state is programmable by DC into hardware.
12559  * This involves constructing a &struct dc_state reflecting the new hardware
12560  * state we wish to commit, then querying DC to see if it is programmable. It's
12561  * important not to modify the existing DC state. Otherwise, atomic_check
12562  * may unexpectedly commit hardware changes.
12563  *
12564  * When validating the DC state, it's important that the right locks are
12565  * acquired. For full updates case which removes/adds/updates streams on one
12566  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
12567  * that any such full update commit will wait for completion of any outstanding
12568  * flip using DRMs synchronization events.
12569  *
12570  * Note that DM adds the affected connectors for all CRTCs in state, when that
12571  * might not seem necessary. This is because DC stream creation requires the
12572  * DC sink, which is tied to the DRM connector state. Cleaning this up should
12573  * be possible but non-trivial - a possible TODO item.
12574  *
12575  * Return: -Error code if validation failed.
12576  */
amdgpu_dm_atomic_check(struct drm_device * dev,struct drm_atomic_state * state)12577 static int amdgpu_dm_atomic_check(struct drm_device *dev,
12578 				  struct drm_atomic_state *state)
12579 {
12580 	struct amdgpu_device *adev = drm_to_adev(dev);
12581 	struct dm_atomic_state *dm_state = NULL;
12582 	struct dc *dc = adev->dm.dc;
12583 	struct drm_connector *connector;
12584 	struct drm_connector_state *old_con_state, *new_con_state;
12585 	struct drm_crtc *crtc;
12586 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12587 	struct drm_plane *plane;
12588 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
12589 	enum dc_status status;
12590 	int ret, i;
12591 	bool lock_and_validation_needed = false;
12592 	bool is_top_most_overlay = true;
12593 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12594 	struct drm_dp_mst_topology_mgr *mgr;
12595 	struct drm_dp_mst_topology_state *mst_state;
12596 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
12597 
12598 	trace_amdgpu_dm_atomic_check_begin(state);
12599 
12600 	ret = drm_atomic_helper_check_modeset(dev, state);
12601 	if (ret) {
12602 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
12603 		goto fail;
12604 	}
12605 
12606 	/* Check connector changes */
12607 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
12608 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
12609 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
12610 
12611 		/* Skip connectors that are disabled or part of modeset already. */
12612 		if (!new_con_state->crtc)
12613 			continue;
12614 
12615 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
12616 		if (IS_ERR(new_crtc_state)) {
12617 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
12618 			ret = PTR_ERR(new_crtc_state);
12619 			goto fail;
12620 		}
12621 
12622 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
12623 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
12624 			new_crtc_state->connectors_changed = true;
12625 	}
12626 
12627 	if (dc_resource_is_dsc_encoding_supported(dc)) {
12628 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12629 			dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12630 			dm_new_crtc_state->mode_changed_independent_from_dsc = new_crtc_state->mode_changed;
12631 		}
12632 
12633 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12634 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
12635 				ret = add_affected_mst_dsc_crtcs(state, crtc);
12636 				if (ret) {
12637 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
12638 					goto fail;
12639 				}
12640 			}
12641 		}
12642 	}
12643 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12644 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12645 
12646 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
12647 		    !new_crtc_state->color_mgmt_changed &&
12648 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
12649 			dm_old_crtc_state->dsc_force_changed == false)
12650 			continue;
12651 
12652 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
12653 		if (ret) {
12654 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
12655 			goto fail;
12656 		}
12657 
12658 		if (!new_crtc_state->enable)
12659 			continue;
12660 
12661 		ret = drm_atomic_add_affected_connectors(state, crtc);
12662 		if (ret) {
12663 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
12664 			goto fail;
12665 		}
12666 
12667 		ret = drm_atomic_add_affected_planes(state, crtc);
12668 		if (ret) {
12669 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
12670 			goto fail;
12671 		}
12672 
12673 		if (dm_old_crtc_state->dsc_force_changed)
12674 			new_crtc_state->mode_changed = true;
12675 	}
12676 
12677 	/*
12678 	 * Add all primary and overlay planes on the CRTC to the state
12679 	 * whenever a plane is enabled to maintain correct z-ordering
12680 	 * and to enable fast surface updates.
12681 	 */
12682 	drm_for_each_crtc(crtc, dev) {
12683 		bool modified = false;
12684 
12685 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
12686 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12687 				continue;
12688 
12689 			if (new_plane_state->crtc == crtc ||
12690 			    old_plane_state->crtc == crtc) {
12691 				modified = true;
12692 				break;
12693 			}
12694 		}
12695 
12696 		if (!modified)
12697 			continue;
12698 
12699 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
12700 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12701 				continue;
12702 
12703 			new_plane_state =
12704 				drm_atomic_get_plane_state(state, plane);
12705 
12706 			if (IS_ERR(new_plane_state)) {
12707 				ret = PTR_ERR(new_plane_state);
12708 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
12709 				goto fail;
12710 			}
12711 		}
12712 	}
12713 
12714 	/*
12715 	 * DC consults the zpos (layer_index in DC terminology) to determine the
12716 	 * hw plane on which to enable the hw cursor (see
12717 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
12718 	 * atomic state, so call drm helper to normalize zpos.
12719 	 */
12720 	ret = drm_atomic_normalize_zpos(dev, state);
12721 	if (ret) {
12722 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
12723 		goto fail;
12724 	}
12725 
12726 	/*
12727 	 * Determine whether cursors on each CRTC should be enabled in native or
12728 	 * overlay mode.
12729 	 */
12730 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12731 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12732 
12733 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
12734 					      &dm_new_crtc_state->cursor_mode);
12735 		if (ret) {
12736 			drm_dbg(dev, "Failed to determine cursor mode\n");
12737 			goto fail;
12738 		}
12739 
12740 		/*
12741 		 * If overlay cursor is needed, DC cannot go through the
12742 		 * native cursor update path. All enabled planes on the CRTC
12743 		 * need to be added for DC to not disable a plane by mistake
12744 		 */
12745 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
12746 			if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
12747 				drm_dbg(dev, "Overlay cursor not supported on DCE\n");
12748 				ret = -EINVAL;
12749 				goto fail;
12750 			}
12751 
12752 			ret = drm_atomic_add_affected_planes(state, crtc);
12753 			if (ret)
12754 				goto fail;
12755 		}
12756 	}
12757 
12758 	/* Remove exiting planes if they are modified */
12759 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
12760 
12761 		ret = dm_update_plane_state(dc, state, plane,
12762 					    old_plane_state,
12763 					    new_plane_state,
12764 					    false,
12765 					    &lock_and_validation_needed,
12766 					    &is_top_most_overlay);
12767 		if (ret) {
12768 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
12769 			goto fail;
12770 		}
12771 	}
12772 
12773 	/* Disable all crtcs which require disable */
12774 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12775 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
12776 					   old_crtc_state,
12777 					   new_crtc_state,
12778 					   false,
12779 					   &lock_and_validation_needed);
12780 		if (ret) {
12781 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
12782 			goto fail;
12783 		}
12784 	}
12785 
12786 	/* Enable all crtcs which require enable */
12787 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12788 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
12789 					   old_crtc_state,
12790 					   new_crtc_state,
12791 					   true,
12792 					   &lock_and_validation_needed);
12793 		if (ret) {
12794 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
12795 			goto fail;
12796 		}
12797 	}
12798 
12799 	/* Add new/modified planes */
12800 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
12801 		ret = dm_update_plane_state(dc, state, plane,
12802 					    old_plane_state,
12803 					    new_plane_state,
12804 					    true,
12805 					    &lock_and_validation_needed,
12806 					    &is_top_most_overlay);
12807 		if (ret) {
12808 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
12809 			goto fail;
12810 		}
12811 	}
12812 
12813 #if defined(CONFIG_DRM_AMD_DC_FP)
12814 	if (dc_resource_is_dsc_encoding_supported(dc)) {
12815 		ret = pre_validate_dsc(state, &dm_state, vars);
12816 		if (ret != 0)
12817 			goto fail;
12818 	}
12819 #endif
12820 
12821 	/* Run this here since we want to validate the streams we created */
12822 	ret = drm_atomic_helper_check_planes(dev, state);
12823 	if (ret) {
12824 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
12825 		goto fail;
12826 	}
12827 
12828 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12829 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12830 		if (dm_new_crtc_state->mpo_requested)
12831 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
12832 	}
12833 
12834 	/* Check cursor restrictions */
12835 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12836 		enum amdgpu_dm_cursor_mode required_cursor_mode;
12837 		int is_rotated, is_scaled;
12838 
12839 		/* Overlay cusor not subject to native cursor restrictions */
12840 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12841 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
12842 			continue;
12843 
12844 		/* Check if rotation or scaling is enabled on DCN401 */
12845 		if ((drm_plane_mask(crtc->cursor) & new_crtc_state->plane_mask) &&
12846 		    (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 2, 0) ||
12847 		    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1))) {
12848 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
12849 
12850 			is_rotated = new_cursor_state &&
12851 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
12852 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
12853 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
12854 
12855 			if (is_rotated || is_scaled) {
12856 				drm_dbg_driver(
12857 					crtc->dev,
12858 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
12859 					crtc->base.id, crtc->name);
12860 				ret = -EINVAL;
12861 				goto fail;
12862 			}
12863 		}
12864 
12865 		/* If HW can only do native cursor, check restrictions again */
12866 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
12867 					      &required_cursor_mode);
12868 		if (ret) {
12869 			drm_dbg_driver(crtc->dev,
12870 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
12871 				       crtc->base.id, crtc->name);
12872 			goto fail;
12873 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
12874 			drm_dbg_driver(crtc->dev,
12875 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling, YUV, or color pipeline restrictions\n",
12876 				       crtc->base.id, crtc->name);
12877 			ret = -EINVAL;
12878 			goto fail;
12879 		}
12880 	}
12881 
12882 	if (state->legacy_cursor_update) {
12883 		/*
12884 		 * This is a fast cursor update coming from the plane update
12885 		 * helper, check if it can be done asynchronously for better
12886 		 * performance.
12887 		 */
12888 		state->async_update =
12889 			!drm_atomic_helper_async_check(dev, state);
12890 
12891 		/*
12892 		 * Skip the remaining global validation if this is an async
12893 		 * update. Cursor updates can be done without affecting
12894 		 * state or bandwidth calcs and this avoids the performance
12895 		 * penalty of locking the private state object and
12896 		 * allocating a new dc_state.
12897 		 */
12898 		if (state->async_update)
12899 			return 0;
12900 	}
12901 
12902 	/* Check scaling and underscan changes*/
12903 	/* TODO Removed scaling changes validation due to inability to commit
12904 	 * new stream into context w\o causing full reset. Need to
12905 	 * decide how to handle.
12906 	 */
12907 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
12908 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
12909 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
12910 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
12911 
12912 		/* Skip any modesets/resets */
12913 		if (!acrtc || drm_atomic_crtc_needs_modeset(
12914 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
12915 			continue;
12916 
12917 		/* Skip any thing not scale or underscan changes */
12918 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
12919 			continue;
12920 
12921 		lock_and_validation_needed = true;
12922 	}
12923 
12924 	/* set the slot info for each mst_state based on the link encoding format */
12925 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
12926 		struct amdgpu_dm_connector *aconnector;
12927 		struct drm_connector *connector;
12928 		struct drm_connector_list_iter iter;
12929 		u8 link_coding_cap;
12930 
12931 		drm_connector_list_iter_begin(dev, &iter);
12932 		drm_for_each_connector_iter(connector, &iter) {
12933 			if (connector->index == mst_state->mgr->conn_base_id) {
12934 				aconnector = to_amdgpu_dm_connector(connector);
12935 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
12936 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
12937 
12938 				break;
12939 			}
12940 		}
12941 		drm_connector_list_iter_end(&iter);
12942 	}
12943 
12944 	/**
12945 	 * Streams and planes are reset when there are changes that affect
12946 	 * bandwidth. Anything that affects bandwidth needs to go through
12947 	 * DC global validation to ensure that the configuration can be applied
12948 	 * to hardware.
12949 	 *
12950 	 * We have to currently stall out here in atomic_check for outstanding
12951 	 * commits to finish in this case because our IRQ handlers reference
12952 	 * DRM state directly - we can end up disabling interrupts too early
12953 	 * if we don't.
12954 	 *
12955 	 * TODO: Remove this stall and drop DM state private objects.
12956 	 */
12957 	if (lock_and_validation_needed) {
12958 		ret = dm_atomic_get_state(state, &dm_state);
12959 		if (ret) {
12960 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
12961 			goto fail;
12962 		}
12963 
12964 		ret = do_aquire_global_lock(dev, state);
12965 		if (ret) {
12966 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
12967 			goto fail;
12968 		}
12969 
12970 #if defined(CONFIG_DRM_AMD_DC_FP)
12971 		if (dc_resource_is_dsc_encoding_supported(dc)) {
12972 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
12973 			if (ret) {
12974 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
12975 				ret = -EINVAL;
12976 				goto fail;
12977 			}
12978 		}
12979 #endif
12980 
12981 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
12982 		if (ret) {
12983 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
12984 			goto fail;
12985 		}
12986 
12987 		/*
12988 		 * Perform validation of MST topology in the state:
12989 		 * We need to perform MST atomic check before calling
12990 		 * dc_validate_global_state(), or there is a chance
12991 		 * to get stuck in an infinite loop and hang eventually.
12992 		 */
12993 		ret = drm_dp_mst_atomic_check(state);
12994 		if (ret) {
12995 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
12996 			goto fail;
12997 		}
12998 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
12999 		if (status != DC_OK) {
13000 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
13001 				       dc_status_to_str(status), status);
13002 			ret = -EINVAL;
13003 			goto fail;
13004 		}
13005 	} else {
13006 		/*
13007 		 * The commit is a fast update. Fast updates shouldn't change
13008 		 * the DC context, affect global validation, and can have their
13009 		 * commit work done in parallel with other commits not touching
13010 		 * the same resource. If we have a new DC context as part of
13011 		 * the DM atomic state from validation we need to free it and
13012 		 * retain the existing one instead.
13013 		 *
13014 		 * Furthermore, since the DM atomic state only contains the DC
13015 		 * context and can safely be annulled, we can free the state
13016 		 * and clear the associated private object now to free
13017 		 * some memory and avoid a possible use-after-free later.
13018 		 */
13019 
13020 		for (i = 0; i < state->num_private_objs; i++) {
13021 			struct drm_private_obj *obj = state->private_objs[i].ptr;
13022 
13023 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
13024 				int j = state->num_private_objs-1;
13025 
13026 				dm_atomic_destroy_state(obj,
13027 						state->private_objs[i].state_to_destroy);
13028 
13029 				/* If i is not at the end of the array then the
13030 				 * last element needs to be moved to where i was
13031 				 * before the array can safely be truncated.
13032 				 */
13033 				if (i != j)
13034 					state->private_objs[i] =
13035 						state->private_objs[j];
13036 
13037 				state->private_objs[j].ptr = NULL;
13038 				state->private_objs[j].state_to_destroy = NULL;
13039 				state->private_objs[j].old_state = NULL;
13040 				state->private_objs[j].new_state = NULL;
13041 
13042 				state->num_private_objs = j;
13043 				break;
13044 			}
13045 		}
13046 	}
13047 
13048 	/* Store the overall update type for use later in atomic check. */
13049 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
13050 		struct dm_crtc_state *dm_new_crtc_state =
13051 			to_dm_crtc_state(new_crtc_state);
13052 
13053 		/*
13054 		 * Only allow async flips for fast updates that don't change
13055 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
13056 		 */
13057 		if (new_crtc_state->async_flip &&
13058 		    (lock_and_validation_needed ||
13059 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
13060 			drm_dbg_atomic(crtc->dev,
13061 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
13062 				       crtc->base.id, crtc->name);
13063 			ret = -EINVAL;
13064 			goto fail;
13065 		}
13066 
13067 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
13068 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
13069 	}
13070 
13071 	/* Must be success */
13072 	WARN_ON(ret);
13073 
13074 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13075 
13076 	return ret;
13077 
13078 fail:
13079 	if (ret == -EDEADLK)
13080 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
13081 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
13082 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
13083 	else
13084 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
13085 
13086 	trace_amdgpu_dm_atomic_check_finish(state, ret);
13087 
13088 	return ret;
13089 }
13090 
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)13091 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
13092 		unsigned int offset,
13093 		unsigned int total_length,
13094 		u8 *data,
13095 		unsigned int length,
13096 		struct amdgpu_hdmi_vsdb_info *vsdb)
13097 {
13098 	bool res;
13099 	union dmub_rb_cmd cmd;
13100 	struct dmub_cmd_send_edid_cea *input;
13101 	struct dmub_cmd_edid_cea_output *output;
13102 
13103 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
13104 		return false;
13105 
13106 	memset(&cmd, 0, sizeof(cmd));
13107 
13108 	input = &cmd.edid_cea.data.input;
13109 
13110 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
13111 	cmd.edid_cea.header.sub_type = 0;
13112 	cmd.edid_cea.header.payload_bytes =
13113 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
13114 	input->offset = offset;
13115 	input->length = length;
13116 	input->cea_total_length = total_length;
13117 	memcpy(input->payload, data, length);
13118 
13119 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
13120 	if (!res) {
13121 		drm_err(adev_to_drm(dm->adev), "EDID CEA parser failed\n");
13122 		return false;
13123 	}
13124 
13125 	output = &cmd.edid_cea.data.output;
13126 
13127 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
13128 		if (!output->ack.success) {
13129 			drm_err(adev_to_drm(dm->adev), "EDID CEA ack failed at offset %d\n",
13130 					output->ack.offset);
13131 		}
13132 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
13133 		if (!output->amd_vsdb.vsdb_found)
13134 			return false;
13135 
13136 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
13137 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
13138 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
13139 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
13140 		vsdb->freesync_mccs_vcp_code = output->amd_vsdb.freesync_mccs_vcp_code;
13141 	} else {
13142 		drm_warn(adev_to_drm(dm->adev), "Unknown EDID CEA parser results\n");
13143 		return false;
13144 	}
13145 
13146 	return true;
13147 }
13148 
parse_edid_cea_dmcu(struct amdgpu_display_manager * dm,u8 * edid_ext,int len,struct amdgpu_hdmi_vsdb_info * vsdb_info)13149 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
13150 		u8 *edid_ext, int len,
13151 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13152 {
13153 	int i;
13154 
13155 	/* send extension block to DMCU for parsing */
13156 	for (i = 0; i < len; i += 8) {
13157 		bool res;
13158 		int offset;
13159 
13160 		/* send 8 bytes a time */
13161 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
13162 			return false;
13163 
13164 		if (i+8 == len) {
13165 			/* EDID block sent completed, expect result */
13166 			int version, min_rate, max_rate;
13167 
13168 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
13169 			if (res) {
13170 				/* amd vsdb found */
13171 				vsdb_info->freesync_supported = 1;
13172 				vsdb_info->amd_vsdb_version = version;
13173 				vsdb_info->min_refresh_rate_hz = min_rate;
13174 				vsdb_info->max_refresh_rate_hz = max_rate;
13175 				/* Not enabled on DMCU*/
13176 				vsdb_info->freesync_mccs_vcp_code = 0;
13177 				return true;
13178 			}
13179 			/* not amd vsdb */
13180 			return false;
13181 		}
13182 
13183 		/* check for ack*/
13184 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
13185 		if (!res)
13186 			return false;
13187 	}
13188 
13189 	return false;
13190 }
13191 
parse_edid_cea_dmub(struct amdgpu_display_manager * dm,u8 * edid_ext,int len,struct amdgpu_hdmi_vsdb_info * vsdb_info)13192 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
13193 		u8 *edid_ext, int len,
13194 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13195 {
13196 	int i;
13197 
13198 	/* send extension block to DMCU for parsing */
13199 	for (i = 0; i < len; i += 8) {
13200 		/* send 8 bytes a time */
13201 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
13202 			return false;
13203 	}
13204 
13205 	return vsdb_info->freesync_supported;
13206 }
13207 
parse_edid_cea(struct amdgpu_dm_connector * aconnector,u8 * edid_ext,int len,struct amdgpu_hdmi_vsdb_info * vsdb_info)13208 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
13209 		u8 *edid_ext, int len,
13210 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13211 {
13212 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
13213 	bool ret;
13214 
13215 	mutex_lock(&adev->dm.dc_lock);
13216 	if (adev->dm.dmub_srv)
13217 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
13218 	else
13219 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
13220 	mutex_unlock(&adev->dm.dc_lock);
13221 	return ret;
13222 }
13223 
parse_edid_displayid_vrr(struct drm_connector * connector,const struct edid * edid)13224 static void parse_edid_displayid_vrr(struct drm_connector *connector,
13225 				     const struct edid *edid)
13226 {
13227 	u8 *edid_ext = NULL;
13228 	int i;
13229 	int j = 0;
13230 	u16 min_vfreq;
13231 	u16 max_vfreq;
13232 
13233 	if (!edid || !edid->extensions)
13234 		return;
13235 
13236 	/* Find DisplayID extension */
13237 	for (i = 0; i < edid->extensions; i++) {
13238 		edid_ext = (void *)(edid + (i + 1));
13239 		if (edid_ext[0] == DISPLAYID_EXT)
13240 			break;
13241 	}
13242 
13243 	if (i == edid->extensions)
13244 		return;
13245 
13246 	while (j < EDID_LENGTH) {
13247 		/* Get dynamic video timing range from DisplayID if available */
13248 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
13249 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
13250 			min_vfreq = edid_ext[j+9];
13251 			if (edid_ext[j+1] & 7)
13252 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
13253 			else
13254 				max_vfreq = edid_ext[j+10];
13255 
13256 			if (max_vfreq && min_vfreq) {
13257 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
13258 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
13259 
13260 				return;
13261 			}
13262 		}
13263 		j++;
13264 	}
13265 }
13266 
get_amd_vsdb(struct amdgpu_dm_connector * aconnector,struct amdgpu_hdmi_vsdb_info * vsdb_info)13267 static int get_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13268 			struct amdgpu_hdmi_vsdb_info *vsdb_info)
13269 {
13270 	struct drm_connector *connector = &aconnector->base;
13271 
13272 	vsdb_info->replay_mode = connector->display_info.amd_vsdb.replay_mode;
13273 	vsdb_info->amd_vsdb_version = connector->display_info.amd_vsdb.version;
13274 
13275 	return connector->display_info.amd_vsdb.version != 0;
13276 }
13277 
parse_hdmi_amd_vsdb(struct amdgpu_dm_connector * aconnector,const struct edid * edid,struct amdgpu_hdmi_vsdb_info * vsdb_info)13278 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13279 			       const struct edid *edid,
13280 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
13281 {
13282 	u8 *edid_ext = NULL;
13283 	int i;
13284 	bool valid_vsdb_found = false;
13285 
13286 	/*----- drm_find_cea_extension() -----*/
13287 	/* No EDID or EDID extensions */
13288 	if (edid == NULL || edid->extensions == 0)
13289 		return -ENODEV;
13290 
13291 	/* Find CEA extension */
13292 	for (i = 0; i < edid->extensions; i++) {
13293 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
13294 		if (edid_ext[0] == CEA_EXT)
13295 			break;
13296 	}
13297 
13298 	if (i == edid->extensions)
13299 		return -ENODEV;
13300 
13301 	/*----- cea_db_offsets() -----*/
13302 	if (edid_ext[0] != CEA_EXT)
13303 		return -ENODEV;
13304 
13305 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
13306 
13307 	return valid_vsdb_found ? i : -ENODEV;
13308 }
13309 
13310 /**
13311  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
13312  *
13313  * @connector: Connector to query.
13314  * @drm_edid: DRM EDID from monitor
13315  * @do_mccs: Controls whether MCCS (Monitor Control Command Set) over
13316  *	      DDC (Display Data Channel) transactions are performed. When true,
13317  *	      the driver queries the monitor to get or update additional FreeSync
13318  *	      capability information. When false, these transactions are skipped.
13319  *
13320  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
13321  * track of some of the display information in the internal data struct used by
13322  * amdgpu_dm. This function checks which type of connector we need to set the
13323  * FreeSync parameters.
13324  */
amdgpu_dm_update_freesync_caps(struct drm_connector * connector,const struct drm_edid * drm_edid,bool do_mccs)13325 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
13326 				    const struct drm_edid *drm_edid, bool do_mccs)
13327 {
13328 	int i = 0;
13329 	struct amdgpu_dm_connector *amdgpu_dm_connector =
13330 			to_amdgpu_dm_connector(connector);
13331 	struct dm_connector_state *dm_con_state = NULL;
13332 	struct dc_sink *sink;
13333 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
13334 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
13335 	const struct edid *edid;
13336 	bool freesync_capable = false;
13337 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
13338 
13339 	if (!connector->state) {
13340 		drm_err(adev_to_drm(adev), "%s - Connector has no state", __func__);
13341 		goto update;
13342 	}
13343 
13344 	sink = amdgpu_dm_connector->dc_sink ?
13345 		amdgpu_dm_connector->dc_sink :
13346 		amdgpu_dm_connector->dc_em_sink;
13347 
13348 	drm_edid_connector_update(connector, drm_edid);
13349 
13350 	if (!drm_edid || !sink) {
13351 		dm_con_state = to_dm_connector_state(connector->state);
13352 
13353 		amdgpu_dm_connector->min_vfreq = 0;
13354 		amdgpu_dm_connector->max_vfreq = 0;
13355 		freesync_capable = false;
13356 
13357 		goto update;
13358 	}
13359 
13360 	dm_con_state = to_dm_connector_state(connector->state);
13361 
13362 	if (!adev->dm.freesync_module || !dc_supports_vrr(sink->ctx->dce_version))
13363 		goto update;
13364 
13365 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
13366 
13367 	/* Some eDP panels only have the refresh rate range info in DisplayID */
13368 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
13369 	     connector->display_info.monitor_range.max_vfreq == 0))
13370 		parse_edid_displayid_vrr(connector, edid);
13371 
13372 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
13373 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
13374 		if (amdgpu_dm_connector->dc_link &&
13375 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
13376 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
13377 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
13378 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13379 				freesync_capable = true;
13380 		}
13381 
13382 		get_amd_vsdb(amdgpu_dm_connector, &vsdb_info);
13383 
13384 		if (vsdb_info.replay_mode) {
13385 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
13386 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
13387 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
13388 		}
13389 
13390 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
13391 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13392 		if (i >= 0) {
13393 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13394 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13395 
13396 			if (vsdb_info.freesync_supported) {
13397 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13398 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13399 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13400 					freesync_capable = true;
13401 
13402 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13403 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13404 			}
13405 		}
13406 	}
13407 
13408 	if (amdgpu_dm_connector->dc_link)
13409 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
13410 
13411 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
13412 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13413 		if (i >= 0) {
13414 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13415 			sink->edid_caps.freesync_vcp_code = vsdb_info.freesync_mccs_vcp_code;
13416 
13417 			if (vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
13418 				amdgpu_dm_connector->pack_sdp_v1_3 = true;
13419 				amdgpu_dm_connector->as_type = as_type;
13420 
13421 				amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13422 				amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13423 				if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13424 					freesync_capable = true;
13425 
13426 				connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13427 				connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13428 			}
13429 		}
13430 	}
13431 
13432 	/* Handle MCCS */
13433 	if (do_mccs)
13434 		dm_helpers_read_mccs_caps(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13435 
13436 	if ((sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
13437 		as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) &&
13438 		(!sink->edid_caps.freesync_vcp_code ||
13439 		(sink->edid_caps.freesync_vcp_code && !sink->mccs_caps.freesync_supported)))
13440 		freesync_capable = false;
13441 
13442 	if (do_mccs && sink->mccs_caps.freesync_supported && freesync_capable)
13443 		dm_helpers_mccs_vcp_set(adev->dm.dc->ctx, amdgpu_dm_connector->dc_link, sink);
13444 
13445 update:
13446 	if (dm_con_state)
13447 		dm_con_state->freesync_capable = freesync_capable;
13448 
13449 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
13450 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
13451 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
13452 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
13453 	}
13454 
13455 	if (connector->vrr_capable_property)
13456 		drm_connector_set_vrr_capable_property(connector,
13457 						       freesync_capable);
13458 }
13459 
amdgpu_dm_trigger_timing_sync(struct drm_device * dev)13460 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
13461 {
13462 	struct amdgpu_device *adev = drm_to_adev(dev);
13463 	struct dc *dc = adev->dm.dc;
13464 	int i;
13465 
13466 	mutex_lock(&adev->dm.dc_lock);
13467 	if (dc->current_state) {
13468 		for (i = 0; i < dc->current_state->stream_count; ++i)
13469 			dc->current_state->streams[i]
13470 				->triggered_crtc_reset.enabled =
13471 				adev->dm.force_timing_sync;
13472 
13473 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
13474 		dc_trigger_sync(dc, dc->current_state);
13475 	}
13476 	mutex_unlock(&adev->dm.dc_lock);
13477 }
13478 
amdgpu_dm_exit_ips_for_hw_access(struct dc * dc)13479 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
13480 {
13481 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
13482 		dc_exit_ips_for_hw_access(dc);
13483 }
13484 
dm_write_reg_func(const struct dc_context * ctx,uint32_t address,u32 value,const char * func_name)13485 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
13486 		       u32 value, const char *func_name)
13487 {
13488 #ifdef DM_CHECK_ADDR_0
13489 	if (address == 0) {
13490 		drm_err(adev_to_drm(ctx->driver_context),
13491 			"invalid register write. address = 0");
13492 		return;
13493 	}
13494 #endif
13495 
13496 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13497 	cgs_write_register(ctx->cgs_device, address, value);
13498 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
13499 }
13500 
dm_read_reg_func(const struct dc_context * ctx,uint32_t address,const char * func_name)13501 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
13502 			  const char *func_name)
13503 {
13504 	u32 value;
13505 #ifdef DM_CHECK_ADDR_0
13506 	if (address == 0) {
13507 		drm_err(adev_to_drm(ctx->driver_context),
13508 			"invalid register read; address = 0\n");
13509 		return 0;
13510 	}
13511 #endif
13512 
13513 	if (ctx->dmub_srv &&
13514 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
13515 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
13516 		ASSERT(false);
13517 		return 0;
13518 	}
13519 
13520 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13521 
13522 	value = cgs_read_register(ctx->cgs_device, address);
13523 
13524 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
13525 
13526 	return value;
13527 }
13528 
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)13529 int amdgpu_dm_process_dmub_aux_transfer_sync(
13530 		struct dc_context *ctx,
13531 		unsigned int link_index,
13532 		struct aux_payload *payload,
13533 		enum aux_return_code_type *operation_result)
13534 {
13535 	struct amdgpu_device *adev = ctx->driver_context;
13536 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
13537 	int ret = -1;
13538 
13539 	mutex_lock(&adev->dm.dpia_aux_lock);
13540 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
13541 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
13542 		goto out;
13543 	}
13544 
13545 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13546 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13547 		*operation_result = AUX_RET_ERROR_TIMEOUT;
13548 		goto out;
13549 	}
13550 
13551 	if (p_notify->result != AUX_RET_SUCCESS) {
13552 		/*
13553 		 * Transient states before tunneling is enabled could
13554 		 * lead to this error. We can ignore this for now.
13555 		 */
13556 		if (p_notify->result == AUX_RET_ERROR_PROTOCOL_ERROR) {
13557 			drm_warn(adev_to_drm(adev), "DPIA AUX failed on 0x%x(%d), error %d\n",
13558 					payload->address, payload->length,
13559 					p_notify->result);
13560 		}
13561 		*operation_result = p_notify->result;
13562 		goto out;
13563 	}
13564 
13565 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command & 0xF;
13566 	if (adev->dm.dmub_notify->aux_reply.command & 0xF0)
13567 		/* The reply is stored in the top nibble of the command. */
13568 		payload->reply[0] = (adev->dm.dmub_notify->aux_reply.command >> 4) & 0xF;
13569 
13570 	/*write req may receive a byte indicating partially written number as well*/
13571 	if (p_notify->aux_reply.length)
13572 		memcpy(payload->data, p_notify->aux_reply.data,
13573 				p_notify->aux_reply.length);
13574 
13575 	/* success */
13576 	ret = p_notify->aux_reply.length;
13577 	*operation_result = p_notify->result;
13578 out:
13579 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
13580 	mutex_unlock(&adev->dm.dpia_aux_lock);
13581 	return ret;
13582 }
13583 
abort_fused_io(struct dc_context * ctx,const struct dmub_cmd_fused_request * request)13584 static void abort_fused_io(
13585 		struct dc_context *ctx,
13586 		const struct dmub_cmd_fused_request *request
13587 )
13588 {
13589 	union dmub_rb_cmd command = { 0 };
13590 	struct dmub_rb_cmd_fused_io *io = &command.fused_io;
13591 
13592 	io->header.type = DMUB_CMD__FUSED_IO;
13593 	io->header.sub_type = DMUB_CMD__FUSED_IO_ABORT;
13594 	io->header.payload_bytes = sizeof(*io) - sizeof(io->header);
13595 	io->request = *request;
13596 	dm_execute_dmub_cmd(ctx, &command, DM_DMUB_WAIT_TYPE_NO_WAIT);
13597 }
13598 
execute_fused_io(struct amdgpu_device * dev,struct dc_context * ctx,union dmub_rb_cmd * commands,uint8_t count,uint32_t timeout_us)13599 static bool execute_fused_io(
13600 		struct amdgpu_device *dev,
13601 		struct dc_context *ctx,
13602 		union dmub_rb_cmd *commands,
13603 		uint8_t count,
13604 		uint32_t timeout_us
13605 )
13606 {
13607 	const uint8_t ddc_line = commands[0].fused_io.request.u.aux.ddc_line;
13608 
13609 	if (ddc_line >= ARRAY_SIZE(dev->dm.fused_io))
13610 		return false;
13611 
13612 	struct fused_io_sync *sync = &dev->dm.fused_io[ddc_line];
13613 	struct dmub_rb_cmd_fused_io *first = &commands[0].fused_io;
13614 	const bool result = dm_execute_dmub_cmd_list(ctx, count, commands, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY)
13615 			&& first->header.ret_status
13616 			&& first->request.status == FUSED_REQUEST_STATUS_SUCCESS;
13617 
13618 	if (!result)
13619 		return false;
13620 
13621 	while (wait_for_completion_timeout(&sync->replied, usecs_to_jiffies(timeout_us))) {
13622 		reinit_completion(&sync->replied);
13623 
13624 		struct dmub_cmd_fused_request *reply = (struct dmub_cmd_fused_request *) sync->reply_data;
13625 
13626 		static_assert(sizeof(*reply) <= sizeof(sync->reply_data), "Size mismatch");
13627 
13628 		if (reply->identifier == first->request.identifier) {
13629 			first->request = *reply;
13630 			return true;
13631 		}
13632 	}
13633 
13634 	reinit_completion(&sync->replied);
13635 	first->request.status = FUSED_REQUEST_STATUS_TIMEOUT;
13636 	abort_fused_io(ctx, &first->request);
13637 	return false;
13638 }
13639 
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)13640 bool amdgpu_dm_execute_fused_io(
13641 		struct amdgpu_device *dev,
13642 		struct dc_link *link,
13643 		union dmub_rb_cmd *commands,
13644 		uint8_t count,
13645 		uint32_t timeout_us)
13646 {
13647 	struct amdgpu_display_manager *dm = &dev->dm;
13648 
13649 	mutex_lock(&dm->dpia_aux_lock);
13650 
13651 	const bool result = execute_fused_io(dev, link->ctx, commands, count, timeout_us);
13652 
13653 	mutex_unlock(&dm->dpia_aux_lock);
13654 	return result;
13655 }
13656 
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)13657 int amdgpu_dm_process_dmub_set_config_sync(
13658 		struct dc_context *ctx,
13659 		unsigned int link_index,
13660 		struct set_config_cmd_payload *payload,
13661 		enum set_config_status *operation_result)
13662 {
13663 	struct amdgpu_device *adev = ctx->driver_context;
13664 	bool is_cmd_complete;
13665 	int ret;
13666 
13667 	mutex_lock(&adev->dm.dpia_aux_lock);
13668 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
13669 			link_index, payload, adev->dm.dmub_notify);
13670 
13671 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13672 		ret = 0;
13673 		*operation_result = adev->dm.dmub_notify->sc_status;
13674 	} else {
13675 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13676 		ret = -1;
13677 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
13678 	}
13679 
13680 	if (!is_cmd_complete)
13681 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
13682 	mutex_unlock(&adev->dm.dpia_aux_lock);
13683 	return ret;
13684 }
13685 
dm_execute_dmub_cmd(const struct dc_context * ctx,union dmub_rb_cmd * cmd,enum dm_dmub_wait_type wait_type)13686 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
13687 {
13688 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
13689 }
13690 
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)13691 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)
13692 {
13693 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
13694 }
13695 
dm_acpi_process_phy_transition_interlock(const struct dc_context * ctx,struct dm_process_phy_transition_init_params process_phy_transition_init_params)13696 void dm_acpi_process_phy_transition_interlock(
13697 	const struct dc_context *ctx,
13698 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
13699 {
13700 	// Not yet implemented
13701 }
13702