xref: /linux/drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c (revision 8934827db5403eae57d4537114a9ff88b0a8460f)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright 2015 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_utils.h>
95 #include <drm/drm_vblank.h>
96 #include <drm/drm_audio_component.h>
97 #include <drm/drm_gem_atomic_helper.h>
98 
99 #include <media/cec-notifier.h>
100 #include <acpi/video.h>
101 
102 #include "ivsrcid/dcn/irqsrcs_dcn_1_0.h"
103 
104 #include "modules/inc/mod_freesync.h"
105 #include "modules/power/power_helpers.h"
106 
107 static_assert(AMDGPU_DMUB_NOTIFICATION_MAX == DMUB_NOTIFICATION_MAX, "AMDGPU_DMUB_NOTIFICATION_MAX mismatch");
108 
109 #define FIRMWARE_RENOIR_DMUB "amdgpu/renoir_dmcub.bin"
110 MODULE_FIRMWARE(FIRMWARE_RENOIR_DMUB);
111 #define FIRMWARE_SIENNA_CICHLID_DMUB "amdgpu/sienna_cichlid_dmcub.bin"
112 MODULE_FIRMWARE(FIRMWARE_SIENNA_CICHLID_DMUB);
113 #define FIRMWARE_NAVY_FLOUNDER_DMUB "amdgpu/navy_flounder_dmcub.bin"
114 MODULE_FIRMWARE(FIRMWARE_NAVY_FLOUNDER_DMUB);
115 #define FIRMWARE_GREEN_SARDINE_DMUB "amdgpu/green_sardine_dmcub.bin"
116 MODULE_FIRMWARE(FIRMWARE_GREEN_SARDINE_DMUB);
117 #define FIRMWARE_VANGOGH_DMUB "amdgpu/vangogh_dmcub.bin"
118 MODULE_FIRMWARE(FIRMWARE_VANGOGH_DMUB);
119 #define FIRMWARE_DIMGREY_CAVEFISH_DMUB "amdgpu/dimgrey_cavefish_dmcub.bin"
120 MODULE_FIRMWARE(FIRMWARE_DIMGREY_CAVEFISH_DMUB);
121 #define FIRMWARE_BEIGE_GOBY_DMUB "amdgpu/beige_goby_dmcub.bin"
122 MODULE_FIRMWARE(FIRMWARE_BEIGE_GOBY_DMUB);
123 #define FIRMWARE_YELLOW_CARP_DMUB "amdgpu/yellow_carp_dmcub.bin"
124 MODULE_FIRMWARE(FIRMWARE_YELLOW_CARP_DMUB);
125 #define FIRMWARE_DCN_314_DMUB "amdgpu/dcn_3_1_4_dmcub.bin"
126 MODULE_FIRMWARE(FIRMWARE_DCN_314_DMUB);
127 #define FIRMWARE_DCN_315_DMUB "amdgpu/dcn_3_1_5_dmcub.bin"
128 MODULE_FIRMWARE(FIRMWARE_DCN_315_DMUB);
129 #define FIRMWARE_DCN316_DMUB "amdgpu/dcn_3_1_6_dmcub.bin"
130 MODULE_FIRMWARE(FIRMWARE_DCN316_DMUB);
131 
132 #define FIRMWARE_DCN_V3_2_0_DMCUB "amdgpu/dcn_3_2_0_dmcub.bin"
133 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_0_DMCUB);
134 #define FIRMWARE_DCN_V3_2_1_DMCUB "amdgpu/dcn_3_2_1_dmcub.bin"
135 MODULE_FIRMWARE(FIRMWARE_DCN_V3_2_1_DMCUB);
136 
137 #define FIRMWARE_RAVEN_DMCU		"amdgpu/raven_dmcu.bin"
138 MODULE_FIRMWARE(FIRMWARE_RAVEN_DMCU);
139 
140 #define FIRMWARE_NAVI12_DMCU            "amdgpu/navi12_dmcu.bin"
141 MODULE_FIRMWARE(FIRMWARE_NAVI12_DMCU);
142 
143 #define FIRMWARE_DCN_35_DMUB "amdgpu/dcn_3_5_dmcub.bin"
144 MODULE_FIRMWARE(FIRMWARE_DCN_35_DMUB);
145 
146 #define FIRMWARE_DCN_351_DMUB "amdgpu/dcn_3_5_1_dmcub.bin"
147 MODULE_FIRMWARE(FIRMWARE_DCN_351_DMUB);
148 
149 #define FIRMWARE_DCN_36_DMUB "amdgpu/dcn_3_6_dmcub.bin"
150 MODULE_FIRMWARE(FIRMWARE_DCN_36_DMUB);
151 
152 #define FIRMWARE_DCN_401_DMUB "amdgpu/dcn_4_0_1_dmcub.bin"
153 MODULE_FIRMWARE(FIRMWARE_DCN_401_DMUB);
154 
155 /**
156  * DOC: overview
157  *
158  * The AMDgpu display manager, **amdgpu_dm** (or even simpler,
159  * **dm**) sits between DRM and DC. It acts as a liaison, converting DRM
160  * requests into DC requests, and DC responses into DRM responses.
161  *
162  * The root control structure is &struct amdgpu_display_manager.
163  */
164 
165 /* basic init/fini API */
166 static int amdgpu_dm_init(struct amdgpu_device *adev);
167 static void amdgpu_dm_fini(struct amdgpu_device *adev);
168 static bool is_freesync_video_mode(const struct drm_display_mode *mode, struct amdgpu_dm_connector *aconnector);
169 static void reset_freesync_config_for_crtc(struct dm_crtc_state *new_crtc_state);
170 static struct amdgpu_i2c_adapter *
171 create_i2c(struct ddc_service *ddc_service, bool oem);
172 
get_subconnector_type(struct dc_link * link)173 static enum drm_mode_subconnector get_subconnector_type(struct dc_link *link)
174 {
175 	switch (link->dpcd_caps.dongle_type) {
176 	case DISPLAY_DONGLE_NONE:
177 		return DRM_MODE_SUBCONNECTOR_Native;
178 	case DISPLAY_DONGLE_DP_VGA_CONVERTER:
179 		return DRM_MODE_SUBCONNECTOR_VGA;
180 	case DISPLAY_DONGLE_DP_DVI_CONVERTER:
181 	case DISPLAY_DONGLE_DP_DVI_DONGLE:
182 		return DRM_MODE_SUBCONNECTOR_DVID;
183 	case DISPLAY_DONGLE_DP_HDMI_CONVERTER:
184 	case DISPLAY_DONGLE_DP_HDMI_DONGLE:
185 		return DRM_MODE_SUBCONNECTOR_HDMIA;
186 	case DISPLAY_DONGLE_DP_HDMI_MISMATCHED_DONGLE:
187 	default:
188 		return DRM_MODE_SUBCONNECTOR_Unknown;
189 	}
190 }
191 
update_subconnector_property(struct amdgpu_dm_connector * aconnector)192 static void update_subconnector_property(struct amdgpu_dm_connector *aconnector)
193 {
194 	struct dc_link *link = aconnector->dc_link;
195 	struct drm_connector *connector = &aconnector->base;
196 	enum drm_mode_subconnector subconnector = DRM_MODE_SUBCONNECTOR_Unknown;
197 
198 	if (connector->connector_type != DRM_MODE_CONNECTOR_DisplayPort)
199 		return;
200 
201 	if (aconnector->dc_sink)
202 		subconnector = get_subconnector_type(link);
203 
204 	drm_object_property_set_value(&connector->base,
205 			connector->dev->mode_config.dp_subconnector_property,
206 			subconnector);
207 }
208 
209 /*
210  * initializes drm_device display related structures, based on the information
211  * provided by DAL. The drm strcutures are: drm_crtc, drm_connector,
212  * drm_encoder, drm_mode_config
213  *
214  * Returns 0 on success
215  */
216 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev);
217 /* removes and deallocates the drm structures, created by the above function */
218 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm);
219 
220 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
221 				    struct amdgpu_dm_connector *amdgpu_dm_connector,
222 				    u32 link_index,
223 				    struct amdgpu_encoder *amdgpu_encoder);
224 static int amdgpu_dm_encoder_init(struct drm_device *dev,
225 				  struct amdgpu_encoder *aencoder,
226 				  uint32_t link_index);
227 
228 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector);
229 
230 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_state *state);
231 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state);
232 
233 static int amdgpu_dm_atomic_check(struct drm_device *dev,
234 				  struct drm_atomic_state *state);
235 
236 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector);
237 static void handle_hpd_rx_irq(void *param);
238 
239 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
240 					 int bl_idx,
241 					 u32 user_brightness);
242 
243 static bool
244 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
245 				 struct drm_crtc_state *new_crtc_state);
246 /*
247  * dm_vblank_get_counter
248  *
249  * @brief
250  * Get counter for number of vertical blanks
251  *
252  * @param
253  * struct amdgpu_device *adev - [in] desired amdgpu device
254  * int disp_idx - [in] which CRTC to get the counter from
255  *
256  * @return
257  * Counter for vertical blanks
258  */
dm_vblank_get_counter(struct amdgpu_device * adev,int crtc)259 static u32 dm_vblank_get_counter(struct amdgpu_device *adev, int crtc)
260 {
261 	struct amdgpu_crtc *acrtc = NULL;
262 
263 	if (crtc >= adev->mode_info.num_crtc)
264 		return 0;
265 
266 	acrtc = adev->mode_info.crtcs[crtc];
267 
268 	if (!acrtc->dm_irq_params.stream) {
269 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
270 			  crtc);
271 		return 0;
272 	}
273 
274 	return dc_stream_get_vblank_counter(acrtc->dm_irq_params.stream);
275 }
276 
dm_crtc_get_scanoutpos(struct amdgpu_device * adev,int crtc,u32 * vbl,u32 * position)277 static int dm_crtc_get_scanoutpos(struct amdgpu_device *adev, int crtc,
278 				  u32 *vbl, u32 *position)
279 {
280 	u32 v_blank_start = 0, v_blank_end = 0, h_position = 0, v_position = 0;
281 	struct amdgpu_crtc *acrtc = NULL;
282 	struct dc *dc = adev->dm.dc;
283 
284 	if ((crtc < 0) || (crtc >= adev->mode_info.num_crtc))
285 		return -EINVAL;
286 
287 	acrtc = adev->mode_info.crtcs[crtc];
288 
289 	if (!acrtc->dm_irq_params.stream) {
290 		drm_err(adev_to_drm(adev), "dc_stream_state is NULL for crtc '%d'!\n",
291 			  crtc);
292 		return 0;
293 	}
294 
295 	if (dc && dc->caps.ips_support && dc->idle_optimizations_allowed)
296 		dc_allow_idle_optimizations(dc, false);
297 
298 	/*
299 	 * TODO rework base driver to use values directly.
300 	 * for now parse it back into reg-format
301 	 */
302 	dc_stream_get_scanoutpos(acrtc->dm_irq_params.stream,
303 				 &v_blank_start,
304 				 &v_blank_end,
305 				 &h_position,
306 				 &v_position);
307 
308 	*position = v_position | (h_position << 16);
309 	*vbl = v_blank_start | (v_blank_end << 16);
310 
311 	return 0;
312 }
313 
dm_is_idle(struct amdgpu_ip_block * ip_block)314 static bool dm_is_idle(struct amdgpu_ip_block *ip_block)
315 {
316 	/* XXX todo */
317 	return true;
318 }
319 
dm_wait_for_idle(struct amdgpu_ip_block * ip_block)320 static int dm_wait_for_idle(struct amdgpu_ip_block *ip_block)
321 {
322 	/* XXX todo */
323 	return 0;
324 }
325 
dm_check_soft_reset(struct amdgpu_ip_block * ip_block)326 static bool dm_check_soft_reset(struct amdgpu_ip_block *ip_block)
327 {
328 	return false;
329 }
330 
dm_soft_reset(struct amdgpu_ip_block * ip_block)331 static int dm_soft_reset(struct amdgpu_ip_block *ip_block)
332 {
333 	/* XXX todo */
334 	return 0;
335 }
336 
337 static struct amdgpu_crtc *
get_crtc_by_otg_inst(struct amdgpu_device * adev,int otg_inst)338 get_crtc_by_otg_inst(struct amdgpu_device *adev,
339 		     int otg_inst)
340 {
341 	struct drm_device *dev = adev_to_drm(adev);
342 	struct drm_crtc *crtc;
343 	struct amdgpu_crtc *amdgpu_crtc;
344 
345 	if (WARN_ON(otg_inst == -1))
346 		return adev->mode_info.crtcs[0];
347 
348 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
349 		amdgpu_crtc = to_amdgpu_crtc(crtc);
350 
351 		if (amdgpu_crtc->otg_inst == otg_inst)
352 			return amdgpu_crtc;
353 	}
354 
355 	return NULL;
356 }
357 
is_dc_timing_adjust_needed(struct dm_crtc_state * old_state,struct dm_crtc_state * new_state)358 static inline bool is_dc_timing_adjust_needed(struct dm_crtc_state *old_state,
359 					      struct dm_crtc_state *new_state)
360 {
361 	if (new_state->stream->adjust.timing_adjust_pending)
362 		return true;
363 	if (new_state->freesync_config.state ==  VRR_STATE_ACTIVE_FIXED)
364 		return true;
365 	else if (amdgpu_dm_crtc_vrr_active(old_state) != amdgpu_dm_crtc_vrr_active(new_state))
366 		return true;
367 	else
368 		return false;
369 }
370 
371 /*
372  * DC will program planes with their z-order determined by their ordering
373  * in the dc_surface_updates array. This comparator is used to sort them
374  * by descending zpos.
375  */
dm_plane_layer_index_cmp(const void * a,const void * b)376 static int dm_plane_layer_index_cmp(const void *a, const void *b)
377 {
378 	const struct dc_surface_update *sa = (struct dc_surface_update *)a;
379 	const struct dc_surface_update *sb = (struct dc_surface_update *)b;
380 
381 	/* Sort by descending dc_plane layer_index (i.e. normalized_zpos) */
382 	return sb->surface->layer_index - sa->surface->layer_index;
383 }
384 
385 /**
386  * update_planes_and_stream_adapter() - Send planes to be updated in DC
387  *
388  * DC has a generic way to update planes and stream via
389  * dc_update_planes_and_stream function; however, DM might need some
390  * adjustments and preparation before calling it. This function is a wrapper
391  * for the dc_update_planes_and_stream that does any required configuration
392  * before passing control to DC.
393  *
394  * @dc: Display Core control structure
395  * @update_type: specify whether it is FULL/MEDIUM/FAST update
396  * @planes_count: planes count to update
397  * @stream: stream state
398  * @stream_update: stream update
399  * @array_of_surface_update: dc surface update pointer
400  *
401  */
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)402 static inline bool update_planes_and_stream_adapter(struct dc *dc,
403 						    int update_type,
404 						    int planes_count,
405 						    struct dc_stream_state *stream,
406 						    struct dc_stream_update *stream_update,
407 						    struct dc_surface_update *array_of_surface_update)
408 {
409 	sort(array_of_surface_update, planes_count,
410 	     sizeof(*array_of_surface_update), dm_plane_layer_index_cmp, NULL);
411 
412 	/*
413 	 * Previous frame finished and HW is ready for optimization.
414 	 */
415 	dc_post_update_surfaces_to_stream(dc);
416 
417 	return dc_update_planes_and_stream(dc,
418 					   array_of_surface_update,
419 					   planes_count,
420 					   stream,
421 					   stream_update);
422 }
423 
424 /**
425  * dm_pflip_high_irq() - Handle pageflip interrupt
426  * @interrupt_params: ignored
427  *
428  * Handles the pageflip interrupt by notifying all interested parties
429  * that the pageflip has been completed.
430  */
dm_pflip_high_irq(void * interrupt_params)431 static void dm_pflip_high_irq(void *interrupt_params)
432 {
433 	struct amdgpu_crtc *amdgpu_crtc;
434 	struct common_irq_params *irq_params = interrupt_params;
435 	struct amdgpu_device *adev = irq_params->adev;
436 	struct drm_device *dev = adev_to_drm(adev);
437 	unsigned long flags;
438 	struct drm_pending_vblank_event *e;
439 	u32 vpos, hpos, v_blank_start, v_blank_end;
440 	bool vrr_active;
441 
442 	amdgpu_crtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_PFLIP);
443 
444 	/* IRQ could occur when in initial stage */
445 	/* TODO work and BO cleanup */
446 	if (amdgpu_crtc == NULL) {
447 		drm_dbg_state(dev, "CRTC is null, returning.\n");
448 		return;
449 	}
450 
451 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
452 
453 	if (amdgpu_crtc->pflip_status != AMDGPU_FLIP_SUBMITTED) {
454 		drm_dbg_state(dev,
455 			      "amdgpu_crtc->pflip_status = %d != AMDGPU_FLIP_SUBMITTED(%d) on crtc:%d[%p]\n",
456 			      amdgpu_crtc->pflip_status, AMDGPU_FLIP_SUBMITTED,
457 			      amdgpu_crtc->crtc_id, amdgpu_crtc);
458 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
459 		return;
460 	}
461 
462 	/* page flip completed. */
463 	e = amdgpu_crtc->event;
464 	amdgpu_crtc->event = NULL;
465 
466 	WARN_ON(!e);
467 
468 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(amdgpu_crtc);
469 
470 	/* Fixed refresh rate, or VRR scanout position outside front-porch? */
471 	if (!vrr_active ||
472 	    !dc_stream_get_scanoutpos(amdgpu_crtc->dm_irq_params.stream, &v_blank_start,
473 				      &v_blank_end, &hpos, &vpos) ||
474 	    (vpos < v_blank_start)) {
475 		/* Update to correct count and vblank timestamp if racing with
476 		 * vblank irq. This also updates to the correct vblank timestamp
477 		 * even in VRR mode, as scanout is past the front-porch atm.
478 		 */
479 		drm_crtc_accurate_vblank_count(&amdgpu_crtc->base);
480 
481 		/* Wake up userspace by sending the pageflip event with proper
482 		 * count and timestamp of vblank of flip completion.
483 		 */
484 		if (e) {
485 			drm_crtc_send_vblank_event(&amdgpu_crtc->base, e);
486 
487 			/* Event sent, so done with vblank for this flip */
488 			drm_crtc_vblank_put(&amdgpu_crtc->base);
489 		}
490 	} else if (e) {
491 		/* VRR active and inside front-porch: vblank count and
492 		 * timestamp for pageflip event will only be up to date after
493 		 * drm_crtc_handle_vblank() has been executed from late vblank
494 		 * irq handler after start of back-porch (vline 0). We queue the
495 		 * pageflip event for send-out by drm_crtc_handle_vblank() with
496 		 * updated timestamp and count, once it runs after us.
497 		 *
498 		 * We need to open-code this instead of using the helper
499 		 * drm_crtc_arm_vblank_event(), as that helper would
500 		 * call drm_crtc_accurate_vblank_count(), which we must
501 		 * not call in VRR mode while we are in front-porch!
502 		 */
503 
504 		/* sequence will be replaced by real count during send-out. */
505 		e->sequence = drm_crtc_vblank_count(&amdgpu_crtc->base);
506 		e->pipe = amdgpu_crtc->crtc_id;
507 
508 		list_add_tail(&e->base.link, &adev_to_drm(adev)->vblank_event_list);
509 		e = NULL;
510 	}
511 
512 	/* Keep track of vblank of this flip for flip throttling. We use the
513 	 * cooked hw counter, as that one incremented at start of this vblank
514 	 * of pageflip completion, so last_flip_vblank is the forbidden count
515 	 * for queueing new pageflips if vsync + VRR is enabled.
516 	 */
517 	amdgpu_crtc->dm_irq_params.last_flip_vblank =
518 		amdgpu_get_vblank_counter_kms(&amdgpu_crtc->base);
519 
520 	amdgpu_crtc->pflip_status = AMDGPU_FLIP_NONE;
521 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
522 
523 	drm_dbg_state(dev,
524 		      "crtc:%d[%p], pflip_stat:AMDGPU_FLIP_NONE, vrr[%d]-fp %d\n",
525 		      amdgpu_crtc->crtc_id, amdgpu_crtc, vrr_active, (int)!e);
526 }
527 
dm_handle_vmin_vmax_update(struct work_struct * offload_work)528 static void dm_handle_vmin_vmax_update(struct work_struct *offload_work)
529 {
530 	struct vupdate_offload_work *work = container_of(offload_work, struct vupdate_offload_work, work);
531 	struct amdgpu_device *adev = work->adev;
532 	struct dc_stream_state *stream = work->stream;
533 	struct dc_crtc_timing_adjust *adjust = work->adjust;
534 
535 	mutex_lock(&adev->dm.dc_lock);
536 	dc_stream_adjust_vmin_vmax(adev->dm.dc, stream, adjust);
537 	mutex_unlock(&adev->dm.dc_lock);
538 
539 	dc_stream_release(stream);
540 	kfree(work->adjust);
541 	kfree(work);
542 }
543 
schedule_dc_vmin_vmax(struct amdgpu_device * adev,struct dc_stream_state * stream,struct dc_crtc_timing_adjust * adjust)544 static void schedule_dc_vmin_vmax(struct amdgpu_device *adev,
545 	struct dc_stream_state *stream,
546 	struct dc_crtc_timing_adjust *adjust)
547 {
548 	struct vupdate_offload_work *offload_work = kzalloc_obj(*offload_work,
549 								GFP_NOWAIT);
550 	if (!offload_work) {
551 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate vupdate_offload_work\n");
552 		return;
553 	}
554 
555 	struct dc_crtc_timing_adjust *adjust_copy = kzalloc_obj(*adjust_copy,
556 								GFP_NOWAIT);
557 	if (!adjust_copy) {
558 		drm_dbg_driver(adev_to_drm(adev), "Failed to allocate adjust_copy\n");
559 		kfree(offload_work);
560 		return;
561 	}
562 
563 	dc_stream_retain(stream);
564 	memcpy(adjust_copy, adjust, sizeof(*adjust_copy));
565 
566 	INIT_WORK(&offload_work->work, dm_handle_vmin_vmax_update);
567 	offload_work->adev = adev;
568 	offload_work->stream = stream;
569 	offload_work->adjust = adjust_copy;
570 
571 	queue_work(system_wq, &offload_work->work);
572 }
573 
dm_vupdate_high_irq(void * interrupt_params)574 static void dm_vupdate_high_irq(void *interrupt_params)
575 {
576 	struct common_irq_params *irq_params = interrupt_params;
577 	struct amdgpu_device *adev = irq_params->adev;
578 	struct amdgpu_crtc *acrtc;
579 	struct drm_device *drm_dev;
580 	struct drm_vblank_crtc *vblank;
581 	ktime_t frame_duration_ns, previous_timestamp;
582 	unsigned long flags;
583 	int vrr_active;
584 
585 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VUPDATE);
586 
587 	if (acrtc) {
588 		vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
589 		drm_dev = acrtc->base.dev;
590 		vblank = drm_crtc_vblank_crtc(&acrtc->base);
591 		previous_timestamp = atomic64_read(&irq_params->previous_timestamp);
592 		frame_duration_ns = vblank->time - previous_timestamp;
593 
594 		if (frame_duration_ns > 0) {
595 			trace_amdgpu_refresh_rate_track(acrtc->base.index,
596 						frame_duration_ns,
597 						ktime_divns(NSEC_PER_SEC, frame_duration_ns));
598 			atomic64_set(&irq_params->previous_timestamp, vblank->time);
599 		}
600 
601 		drm_dbg_vbl(drm_dev,
602 			    "crtc:%d, vupdate-vrr:%d\n", acrtc->crtc_id,
603 			    vrr_active);
604 
605 		/* Core vblank handling is done here after end of front-porch in
606 		 * vrr mode, as vblank timestamping will give valid results
607 		 * while now done after front-porch. This will also deliver
608 		 * page-flip completion events that have been queued to us
609 		 * if a pageflip happened inside front-porch.
610 		 */
611 		if (vrr_active && acrtc->dm_irq_params.stream) {
612 			bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
613 			bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
614 			bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state
615 				== VRR_STATE_ACTIVE_VARIABLE;
616 
617 			amdgpu_dm_crtc_handle_vblank(acrtc);
618 
619 			/* BTR processing for pre-DCE12 ASICs */
620 			if (adev->family < AMDGPU_FAMILY_AI) {
621 				spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
622 				mod_freesync_handle_v_update(
623 				    adev->dm.freesync_module,
624 				    acrtc->dm_irq_params.stream,
625 				    &acrtc->dm_irq_params.vrr_params);
626 
627 				if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
628 					schedule_dc_vmin_vmax(adev,
629 						acrtc->dm_irq_params.stream,
630 						&acrtc->dm_irq_params.vrr_params.adjust);
631 				}
632 				spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
633 			}
634 		}
635 	}
636 }
637 
638 /**
639  * dm_crtc_high_irq() - Handles CRTC interrupt
640  * @interrupt_params: used for determining the CRTC instance
641  *
642  * Handles the CRTC/VSYNC interrupt by notfying DRM's VBLANK
643  * event handler.
644  */
dm_crtc_high_irq(void * interrupt_params)645 static void dm_crtc_high_irq(void *interrupt_params)
646 {
647 	struct common_irq_params *irq_params = interrupt_params;
648 	struct amdgpu_device *adev = irq_params->adev;
649 	struct drm_writeback_job *job;
650 	struct amdgpu_crtc *acrtc;
651 	unsigned long flags;
652 	int vrr_active;
653 
654 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VBLANK);
655 	if (!acrtc)
656 		return;
657 
658 	if (acrtc->wb_conn) {
659 		spin_lock_irqsave(&acrtc->wb_conn->job_lock, flags);
660 
661 		if (acrtc->wb_pending) {
662 			job = list_first_entry_or_null(&acrtc->wb_conn->job_queue,
663 						       struct drm_writeback_job,
664 						       list_entry);
665 			acrtc->wb_pending = false;
666 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
667 
668 			if (job) {
669 				unsigned int v_total, refresh_hz;
670 				struct dc_stream_state *stream = acrtc->dm_irq_params.stream;
671 
672 				v_total = stream->adjust.v_total_max ?
673 					  stream->adjust.v_total_max : stream->timing.v_total;
674 				refresh_hz = div_u64((uint64_t) stream->timing.pix_clk_100hz *
675 					     100LL, (v_total * stream->timing.h_total));
676 				mdelay(1000 / refresh_hz);
677 
678 				drm_writeback_signal_completion(acrtc->wb_conn, 0);
679 				dc_stream_fc_disable_writeback(adev->dm.dc,
680 							       acrtc->dm_irq_params.stream, 0);
681 			}
682 		} else
683 			spin_unlock_irqrestore(&acrtc->wb_conn->job_lock, flags);
684 	}
685 
686 	vrr_active = amdgpu_dm_crtc_vrr_active_irq(acrtc);
687 
688 	drm_dbg_vbl(adev_to_drm(adev),
689 		    "crtc:%d, vupdate-vrr:%d, planes:%d\n", acrtc->crtc_id,
690 		    vrr_active, acrtc->dm_irq_params.active_planes);
691 
692 	/**
693 	 * Core vblank handling at start of front-porch is only possible
694 	 * in non-vrr mode, as only there vblank timestamping will give
695 	 * valid results while done in front-porch. Otherwise defer it
696 	 * to dm_vupdate_high_irq after end of front-porch.
697 	 */
698 	if (!vrr_active)
699 		amdgpu_dm_crtc_handle_vblank(acrtc);
700 
701 	/**
702 	 * Following stuff must happen at start of vblank, for crc
703 	 * computation and below-the-range btr support in vrr mode.
704 	 */
705 	amdgpu_dm_crtc_handle_crc_irq(&acrtc->base);
706 
707 	/* BTR updates need to happen before VUPDATE on Vega and above. */
708 	if (adev->family < AMDGPU_FAMILY_AI)
709 		return;
710 
711 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
712 
713 	if (acrtc->dm_irq_params.stream &&
714 		acrtc->dm_irq_params.vrr_params.supported) {
715 		bool replay_en = acrtc->dm_irq_params.stream->link->replay_settings.replay_feature_enabled;
716 		bool psr_en = acrtc->dm_irq_params.stream->link->psr_settings.psr_feature_enabled;
717 		bool fs_active_var_en = acrtc->dm_irq_params.freesync_config.state == VRR_STATE_ACTIVE_VARIABLE;
718 
719 		mod_freesync_handle_v_update(adev->dm.freesync_module,
720 					     acrtc->dm_irq_params.stream,
721 					     &acrtc->dm_irq_params.vrr_params);
722 
723 		/* update vmin_vmax only if freesync is enabled, or only if PSR and REPLAY are disabled */
724 		if (fs_active_var_en || (!fs_active_var_en && !replay_en && !psr_en)) {
725 			schedule_dc_vmin_vmax(adev, acrtc->dm_irq_params.stream,
726 					&acrtc->dm_irq_params.vrr_params.adjust);
727 		}
728 	}
729 
730 	/*
731 	 * If there aren't any active_planes then DCH HUBP may be clock-gated.
732 	 * In that case, pageflip completion interrupts won't fire and pageflip
733 	 * completion events won't get delivered. Prevent this by sending
734 	 * pending pageflip events from here if a flip is still pending.
735 	 *
736 	 * If any planes are enabled, use dm_pflip_high_irq() instead, to
737 	 * avoid race conditions between flip programming and completion,
738 	 * which could cause too early flip completion events.
739 	 */
740 	if (adev->family >= AMDGPU_FAMILY_RV &&
741 	    acrtc->pflip_status == AMDGPU_FLIP_SUBMITTED &&
742 	    acrtc->dm_irq_params.active_planes == 0) {
743 		if (acrtc->event) {
744 			drm_crtc_send_vblank_event(&acrtc->base, acrtc->event);
745 			acrtc->event = NULL;
746 			drm_crtc_vblank_put(&acrtc->base);
747 		}
748 		acrtc->pflip_status = AMDGPU_FLIP_NONE;
749 	}
750 
751 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
752 }
753 
754 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
755 /**
756  * dm_dcn_vertical_interrupt0_high_irq() - Handles OTG Vertical interrupt0 for
757  * DCN generation ASICs
758  * @interrupt_params: interrupt parameters
759  *
760  * Used to set crc window/read out crc value at vertical line 0 position
761  */
dm_dcn_vertical_interrupt0_high_irq(void * interrupt_params)762 static void dm_dcn_vertical_interrupt0_high_irq(void *interrupt_params)
763 {
764 	struct common_irq_params *irq_params = interrupt_params;
765 	struct amdgpu_device *adev = irq_params->adev;
766 	struct amdgpu_crtc *acrtc;
767 
768 	acrtc = get_crtc_by_otg_inst(adev, irq_params->irq_src - IRQ_TYPE_VLINE0);
769 
770 	if (!acrtc)
771 		return;
772 
773 	amdgpu_dm_crtc_handle_crc_window_irq(&acrtc->base);
774 }
775 #endif /* CONFIG_DRM_AMD_SECURE_DISPLAY */
776 
777 /**
778  * dmub_aux_setconfig_callback - Callback for AUX or SET_CONFIG command.
779  * @adev: amdgpu_device pointer
780  * @notify: dmub notification structure
781  *
782  * Dmub AUX or SET_CONFIG command completion processing callback
783  * Copies dmub notification to DM which is to be read by AUX command.
784  * issuing thread and also signals the event to wake up the thread.
785  */
dmub_aux_setconfig_callback(struct amdgpu_device * adev,struct dmub_notification * notify)786 static void dmub_aux_setconfig_callback(struct amdgpu_device *adev,
787 					struct dmub_notification *notify)
788 {
789 	if (adev->dm.dmub_notify)
790 		memcpy(adev->dm.dmub_notify, notify, sizeof(struct dmub_notification));
791 	if (notify->type == DMUB_NOTIFICATION_AUX_REPLY)
792 		complete(&adev->dm.dmub_aux_transfer_done);
793 }
794 
dmub_aux_fused_io_callback(struct amdgpu_device * adev,struct dmub_notification * notify)795 static void dmub_aux_fused_io_callback(struct amdgpu_device *adev,
796 					struct dmub_notification *notify)
797 {
798 	if (!adev || !notify) {
799 		ASSERT(false);
800 		return;
801 	}
802 
803 	const struct dmub_cmd_fused_request *req = &notify->fused_request;
804 	const uint8_t ddc_line = req->u.aux.ddc_line;
805 
806 	if (ddc_line >= ARRAY_SIZE(adev->dm.fused_io)) {
807 		ASSERT(false);
808 		return;
809 	}
810 
811 	struct fused_io_sync *sync = &adev->dm.fused_io[ddc_line];
812 
813 	static_assert(sizeof(*req) <= sizeof(sync->reply_data), "Size mismatch");
814 	memcpy(sync->reply_data, req, sizeof(*req));
815 	complete(&sync->replied);
816 }
817 
818 /**
819  * dmub_hpd_callback - DMUB HPD interrupt processing callback.
820  * @adev: amdgpu_device pointer
821  * @notify: dmub notification structure
822  *
823  * Dmub Hpd interrupt processing callback. Gets displayindex through the
824  * ink index and calls helper to do the processing.
825  */
dmub_hpd_callback(struct amdgpu_device * adev,struct dmub_notification * notify)826 static void dmub_hpd_callback(struct amdgpu_device *adev,
827 			      struct dmub_notification *notify)
828 {
829 	struct amdgpu_dm_connector *aconnector;
830 	struct amdgpu_dm_connector *hpd_aconnector = NULL;
831 	struct drm_connector *connector;
832 	struct drm_connector_list_iter iter;
833 	struct dc_link *link;
834 	u8 link_index = 0;
835 	struct drm_device *dev;
836 
837 	if (adev == NULL)
838 		return;
839 
840 	if (notify == NULL) {
841 		drm_err(adev_to_drm(adev), "DMUB HPD callback notification was NULL");
842 		return;
843 	}
844 
845 	if (notify->link_index > adev->dm.dc->link_count) {
846 		drm_err(adev_to_drm(adev), "DMUB HPD index (%u)is abnormal", notify->link_index);
847 		return;
848 	}
849 
850 	/* Skip DMUB HPD IRQ in suspend/resume. We will probe them later. */
851 	if (notify->type == DMUB_NOTIFICATION_HPD && adev->in_suspend) {
852 		drm_info(adev_to_drm(adev), "Skip DMUB HPD IRQ callback in suspend/resume\n");
853 		return;
854 	}
855 
856 	link_index = notify->link_index;
857 	link = adev->dm.dc->links[link_index];
858 	dev = adev->dm.ddev;
859 
860 	drm_connector_list_iter_begin(dev, &iter);
861 	drm_for_each_connector_iter(connector, &iter) {
862 
863 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
864 			continue;
865 
866 		aconnector = to_amdgpu_dm_connector(connector);
867 		if (link && aconnector->dc_link == link) {
868 			if (notify->type == DMUB_NOTIFICATION_HPD)
869 				drm_info(adev_to_drm(adev), "DMUB HPD IRQ callback: link_index=%u\n", link_index);
870 			else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ)
871 				drm_info(adev_to_drm(adev), "DMUB HPD RX IRQ callback: link_index=%u\n", link_index);
872 			else
873 				drm_warn(adev_to_drm(adev), "DMUB Unknown HPD callback type %d, link_index=%u\n",
874 						notify->type, link_index);
875 
876 			hpd_aconnector = aconnector;
877 			break;
878 		}
879 	}
880 	drm_connector_list_iter_end(&iter);
881 
882 	if (hpd_aconnector) {
883 		if (notify->type == DMUB_NOTIFICATION_HPD) {
884 			if (hpd_aconnector->dc_link->hpd_status == (notify->hpd_status == DP_HPD_PLUG))
885 				drm_warn(adev_to_drm(adev), "DMUB reported hpd status unchanged. link_index=%u\n", link_index);
886 			handle_hpd_irq_helper(hpd_aconnector);
887 		} else if (notify->type == DMUB_NOTIFICATION_HPD_IRQ) {
888 			handle_hpd_rx_irq(hpd_aconnector);
889 		}
890 	}
891 }
892 
893 /**
894  * dmub_hpd_sense_callback - DMUB HPD sense processing callback.
895  * @adev: amdgpu_device pointer
896  * @notify: dmub notification structure
897  *
898  * HPD sense changes can occur during low power states and need to be
899  * notified from firmware to driver.
900  */
dmub_hpd_sense_callback(struct amdgpu_device * adev,struct dmub_notification * notify)901 static void dmub_hpd_sense_callback(struct amdgpu_device *adev,
902 			      struct dmub_notification *notify)
903 {
904 	drm_dbg_driver(adev_to_drm(adev), "DMUB HPD SENSE callback.\n");
905 }
906 
907 /**
908  * register_dmub_notify_callback - Sets callback for DMUB notify
909  * @adev: amdgpu_device pointer
910  * @type: Type of dmub notification
911  * @callback: Dmub interrupt callback function
912  * @dmub_int_thread_offload: offload indicator
913  *
914  * API to register a dmub callback handler for a dmub notification
915  * Also sets indicator whether callback processing to be offloaded.
916  * to dmub interrupt handling thread
917  * Return: true if successfully registered, false if there is existing registration
918  */
register_dmub_notify_callback(struct amdgpu_device * adev,enum dmub_notification_type type,dmub_notify_interrupt_callback_t callback,bool dmub_int_thread_offload)919 static bool register_dmub_notify_callback(struct amdgpu_device *adev,
920 					  enum dmub_notification_type type,
921 					  dmub_notify_interrupt_callback_t callback,
922 					  bool dmub_int_thread_offload)
923 {
924 	if (callback != NULL && type < ARRAY_SIZE(adev->dm.dmub_thread_offload)) {
925 		adev->dm.dmub_callback[type] = callback;
926 		adev->dm.dmub_thread_offload[type] = dmub_int_thread_offload;
927 	} else
928 		return false;
929 
930 	return true;
931 }
932 
dm_handle_hpd_work(struct work_struct * work)933 static void dm_handle_hpd_work(struct work_struct *work)
934 {
935 	struct dmub_hpd_work *dmub_hpd_wrk;
936 
937 	dmub_hpd_wrk = container_of(work, struct dmub_hpd_work, handle_hpd_work);
938 
939 	if (!dmub_hpd_wrk->dmub_notify) {
940 		drm_err(adev_to_drm(dmub_hpd_wrk->adev), "dmub_hpd_wrk dmub_notify is NULL");
941 		return;
942 	}
943 
944 	if (dmub_hpd_wrk->dmub_notify->type < ARRAY_SIZE(dmub_hpd_wrk->adev->dm.dmub_callback)) {
945 		dmub_hpd_wrk->adev->dm.dmub_callback[dmub_hpd_wrk->dmub_notify->type](dmub_hpd_wrk->adev,
946 		dmub_hpd_wrk->dmub_notify);
947 	}
948 
949 	kfree(dmub_hpd_wrk->dmub_notify);
950 	kfree(dmub_hpd_wrk);
951 
952 }
953 
dmub_notification_type_str(enum dmub_notification_type e)954 static const char *dmub_notification_type_str(enum dmub_notification_type e)
955 {
956 	switch (e) {
957 	case DMUB_NOTIFICATION_NO_DATA:
958 		return "NO_DATA";
959 	case DMUB_NOTIFICATION_AUX_REPLY:
960 		return "AUX_REPLY";
961 	case DMUB_NOTIFICATION_HPD:
962 		return "HPD";
963 	case DMUB_NOTIFICATION_HPD_IRQ:
964 		return "HPD_IRQ";
965 	case DMUB_NOTIFICATION_SET_CONFIG_REPLY:
966 		return "SET_CONFIG_REPLY";
967 	case DMUB_NOTIFICATION_DPIA_NOTIFICATION:
968 		return "DPIA_NOTIFICATION";
969 	case DMUB_NOTIFICATION_HPD_SENSE_NOTIFY:
970 		return "HPD_SENSE_NOTIFY";
971 	case DMUB_NOTIFICATION_FUSED_IO:
972 		return "FUSED_IO";
973 	default:
974 		return "<unknown>";
975 	}
976 }
977 
978 #define DMUB_TRACE_MAX_READ 64
979 /**
980  * dm_dmub_outbox1_low_irq() - Handles Outbox interrupt
981  * @interrupt_params: used for determining the Outbox instance
982  *
983  * Handles the Outbox Interrupt
984  * event handler.
985  */
dm_dmub_outbox1_low_irq(void * interrupt_params)986 static void dm_dmub_outbox1_low_irq(void *interrupt_params)
987 {
988 	struct dmub_notification notify = {0};
989 	struct common_irq_params *irq_params = interrupt_params;
990 	struct amdgpu_device *adev = irq_params->adev;
991 	struct amdgpu_display_manager *dm = &adev->dm;
992 	struct dmcub_trace_buf_entry entry = { 0 };
993 	u32 count = 0;
994 	struct dmub_hpd_work *dmub_hpd_wrk;
995 
996 	do {
997 		if (dc_dmub_srv_get_dmub_outbox0_msg(dm->dc, &entry)) {
998 			trace_amdgpu_dmub_trace_high_irq(entry.trace_code, entry.tick_count,
999 							entry.param0, entry.param1);
1000 
1001 			drm_dbg_driver(adev_to_drm(adev), "trace_code:%u, tick_count:%u, param0:%u, param1:%u\n",
1002 				 entry.trace_code, entry.tick_count, entry.param0, entry.param1);
1003 		} else
1004 			break;
1005 
1006 		count++;
1007 
1008 	} while (count <= DMUB_TRACE_MAX_READ);
1009 
1010 	if (count > DMUB_TRACE_MAX_READ)
1011 		drm_dbg_driver(adev_to_drm(adev), "Warning : count > DMUB_TRACE_MAX_READ");
1012 
1013 	if (dc_enable_dmub_notifications(adev->dm.dc) &&
1014 		irq_params->irq_src == DC_IRQ_SOURCE_DMCUB_OUTBOX) {
1015 
1016 		do {
1017 			dc_stat_get_dmub_notification(adev->dm.dc, &notify);
1018 			if (notify.type >= ARRAY_SIZE(dm->dmub_thread_offload)) {
1019 				drm_err(adev_to_drm(adev), "DM: notify type %d invalid!", notify.type);
1020 				continue;
1021 			}
1022 			if (!dm->dmub_callback[notify.type]) {
1023 				drm_warn(adev_to_drm(adev), "DMUB notification skipped due to no handler: type=%s\n",
1024 					dmub_notification_type_str(notify.type));
1025 				continue;
1026 			}
1027 			if (dm->dmub_thread_offload[notify.type] == true) {
1028 				dmub_hpd_wrk = kzalloc_obj(*dmub_hpd_wrk,
1029 							   GFP_ATOMIC);
1030 				if (!dmub_hpd_wrk) {
1031 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk");
1032 					return;
1033 				}
1034 				dmub_hpd_wrk->dmub_notify = kmemdup(&notify, sizeof(struct dmub_notification),
1035 								    GFP_ATOMIC);
1036 				if (!dmub_hpd_wrk->dmub_notify) {
1037 					kfree(dmub_hpd_wrk);
1038 					drm_err(adev_to_drm(adev), "Failed to allocate dmub_hpd_wrk->dmub_notify");
1039 					return;
1040 				}
1041 				INIT_WORK(&dmub_hpd_wrk->handle_hpd_work, dm_handle_hpd_work);
1042 				dmub_hpd_wrk->adev = adev;
1043 				queue_work(adev->dm.delayed_hpd_wq, &dmub_hpd_wrk->handle_hpd_work);
1044 			} else {
1045 				dm->dmub_callback[notify.type](adev, &notify);
1046 			}
1047 		} while (notify.pending_notification);
1048 	}
1049 }
1050 
dm_set_clockgating_state(struct amdgpu_ip_block * ip_block,enum amd_clockgating_state state)1051 static int dm_set_clockgating_state(struct amdgpu_ip_block *ip_block,
1052 		  enum amd_clockgating_state state)
1053 {
1054 	return 0;
1055 }
1056 
dm_set_powergating_state(struct amdgpu_ip_block * ip_block,enum amd_powergating_state state)1057 static int dm_set_powergating_state(struct amdgpu_ip_block *ip_block,
1058 		  enum amd_powergating_state state)
1059 {
1060 	return 0;
1061 }
1062 
1063 /* Prototypes of private functions */
1064 static int dm_early_init(struct amdgpu_ip_block *ip_block);
1065 
1066 /* Allocate memory for FBC compressed data  */
amdgpu_dm_fbc_init(struct drm_connector * connector)1067 static void amdgpu_dm_fbc_init(struct drm_connector *connector)
1068 {
1069 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
1070 	struct dm_compressor_info *compressor = &adev->dm.compressor;
1071 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(connector);
1072 	struct drm_display_mode *mode;
1073 	unsigned long max_size = 0;
1074 
1075 	if (adev->dm.dc->fbc_compressor == NULL)
1076 		return;
1077 
1078 	if (aconn->dc_link->connector_signal != SIGNAL_TYPE_EDP)
1079 		return;
1080 
1081 	if (compressor->bo_ptr)
1082 		return;
1083 
1084 
1085 	list_for_each_entry(mode, &connector->modes, head) {
1086 		if (max_size < (unsigned long) mode->htotal * mode->vtotal)
1087 			max_size = (unsigned long) mode->htotal * mode->vtotal;
1088 	}
1089 
1090 	if (max_size) {
1091 		int r = amdgpu_bo_create_kernel(adev, max_size * 4, PAGE_SIZE,
1092 			    AMDGPU_GEM_DOMAIN_GTT, &compressor->bo_ptr,
1093 			    &compressor->gpu_addr, &compressor->cpu_addr);
1094 
1095 		if (r)
1096 			drm_err(adev_to_drm(adev), "DM: Failed to initialize FBC\n");
1097 		else {
1098 			adev->dm.dc->ctx->fbc_gpu_addr = compressor->gpu_addr;
1099 			drm_info(adev_to_drm(adev), "DM: FBC alloc %lu\n", max_size*4);
1100 		}
1101 
1102 	}
1103 
1104 }
1105 
amdgpu_dm_audio_component_get_eld(struct device * kdev,int port,int pipe,bool * enabled,unsigned char * buf,int max_bytes)1106 static int amdgpu_dm_audio_component_get_eld(struct device *kdev, int port,
1107 					  int pipe, bool *enabled,
1108 					  unsigned char *buf, int max_bytes)
1109 {
1110 	struct drm_device *dev = dev_get_drvdata(kdev);
1111 	struct amdgpu_device *adev = drm_to_adev(dev);
1112 	struct drm_connector *connector;
1113 	struct drm_connector_list_iter conn_iter;
1114 	struct amdgpu_dm_connector *aconnector;
1115 	int ret = 0;
1116 
1117 	*enabled = false;
1118 
1119 	mutex_lock(&adev->dm.audio_lock);
1120 
1121 	drm_connector_list_iter_begin(dev, &conn_iter);
1122 	drm_for_each_connector_iter(connector, &conn_iter) {
1123 
1124 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
1125 			continue;
1126 
1127 		aconnector = to_amdgpu_dm_connector(connector);
1128 		if (aconnector->audio_inst != port)
1129 			continue;
1130 
1131 		*enabled = true;
1132 		mutex_lock(&connector->eld_mutex);
1133 		ret = drm_eld_size(connector->eld);
1134 		memcpy(buf, connector->eld, min(max_bytes, ret));
1135 		mutex_unlock(&connector->eld_mutex);
1136 
1137 		break;
1138 	}
1139 	drm_connector_list_iter_end(&conn_iter);
1140 
1141 	mutex_unlock(&adev->dm.audio_lock);
1142 
1143 	drm_dbg_kms(adev_to_drm(adev), "Get ELD : idx=%d ret=%d en=%d\n", port, ret, *enabled);
1144 
1145 	return ret;
1146 }
1147 
1148 static const struct drm_audio_component_ops amdgpu_dm_audio_component_ops = {
1149 	.get_eld = amdgpu_dm_audio_component_get_eld,
1150 };
1151 
amdgpu_dm_audio_component_bind(struct device * kdev,struct device * hda_kdev,void * data)1152 static int amdgpu_dm_audio_component_bind(struct device *kdev,
1153 				       struct device *hda_kdev, void *data)
1154 {
1155 	struct drm_device *dev = dev_get_drvdata(kdev);
1156 	struct amdgpu_device *adev = drm_to_adev(dev);
1157 	struct drm_audio_component *acomp = data;
1158 
1159 	acomp->ops = &amdgpu_dm_audio_component_ops;
1160 	acomp->dev = kdev;
1161 	adev->dm.audio_component = acomp;
1162 
1163 	return 0;
1164 }
1165 
amdgpu_dm_audio_component_unbind(struct device * kdev,struct device * hda_kdev,void * data)1166 static void amdgpu_dm_audio_component_unbind(struct device *kdev,
1167 					  struct device *hda_kdev, void *data)
1168 {
1169 	struct amdgpu_device *adev = drm_to_adev(dev_get_drvdata(kdev));
1170 	struct drm_audio_component *acomp = data;
1171 
1172 	acomp->ops = NULL;
1173 	acomp->dev = NULL;
1174 	adev->dm.audio_component = NULL;
1175 }
1176 
1177 static const struct component_ops amdgpu_dm_audio_component_bind_ops = {
1178 	.bind	= amdgpu_dm_audio_component_bind,
1179 	.unbind	= amdgpu_dm_audio_component_unbind,
1180 };
1181 
amdgpu_dm_audio_init(struct amdgpu_device * adev)1182 static int amdgpu_dm_audio_init(struct amdgpu_device *adev)
1183 {
1184 	int i, ret;
1185 
1186 	if (!amdgpu_audio)
1187 		return 0;
1188 
1189 	adev->mode_info.audio.enabled = true;
1190 
1191 	adev->mode_info.audio.num_pins = adev->dm.dc->res_pool->audio_count;
1192 
1193 	for (i = 0; i < adev->mode_info.audio.num_pins; i++) {
1194 		adev->mode_info.audio.pin[i].channels = -1;
1195 		adev->mode_info.audio.pin[i].rate = -1;
1196 		adev->mode_info.audio.pin[i].bits_per_sample = -1;
1197 		adev->mode_info.audio.pin[i].status_bits = 0;
1198 		adev->mode_info.audio.pin[i].category_code = 0;
1199 		adev->mode_info.audio.pin[i].connected = false;
1200 		adev->mode_info.audio.pin[i].id =
1201 			adev->dm.dc->res_pool->audios[i]->inst;
1202 		adev->mode_info.audio.pin[i].offset = 0;
1203 	}
1204 
1205 	ret = component_add(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1206 	if (ret < 0)
1207 		return ret;
1208 
1209 	adev->dm.audio_registered = true;
1210 
1211 	return 0;
1212 }
1213 
amdgpu_dm_audio_fini(struct amdgpu_device * adev)1214 static void amdgpu_dm_audio_fini(struct amdgpu_device *adev)
1215 {
1216 	if (!amdgpu_audio)
1217 		return;
1218 
1219 	if (!adev->mode_info.audio.enabled)
1220 		return;
1221 
1222 	if (adev->dm.audio_registered) {
1223 		component_del(adev->dev, &amdgpu_dm_audio_component_bind_ops);
1224 		adev->dm.audio_registered = false;
1225 	}
1226 
1227 	/* TODO: Disable audio? */
1228 
1229 	adev->mode_info.audio.enabled = false;
1230 }
1231 
amdgpu_dm_audio_eld_notify(struct amdgpu_device * adev,int pin)1232 static  void amdgpu_dm_audio_eld_notify(struct amdgpu_device *adev, int pin)
1233 {
1234 	struct drm_audio_component *acomp = adev->dm.audio_component;
1235 
1236 	if (acomp && acomp->audio_ops && acomp->audio_ops->pin_eld_notify) {
1237 		drm_dbg_kms(adev_to_drm(adev), "Notify ELD: %d\n", pin);
1238 
1239 		acomp->audio_ops->pin_eld_notify(acomp->audio_ops->audio_ptr,
1240 						 pin, -1);
1241 	}
1242 }
1243 
dm_dmub_hw_init(struct amdgpu_device * adev)1244 static int dm_dmub_hw_init(struct amdgpu_device *adev)
1245 {
1246 	const struct dmcub_firmware_header_v1_0 *hdr;
1247 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1248 	struct dmub_srv_fb_info *fb_info = adev->dm.dmub_fb_info;
1249 	const struct firmware *dmub_fw = adev->dm.dmub_fw;
1250 	struct dc *dc = adev->dm.dc;
1251 	struct dmcu *dmcu = adev->dm.dc->res_pool->dmcu;
1252 	struct abm *abm = adev->dm.dc->res_pool->abm;
1253 	struct dc_context *ctx = adev->dm.dc->ctx;
1254 	struct dmub_srv_hw_params hw_params;
1255 	enum dmub_status status;
1256 	const unsigned char *fw_inst_const, *fw_bss_data;
1257 	u32 i, fw_inst_const_size, fw_bss_data_size;
1258 	bool has_hw_support;
1259 
1260 	if (!dmub_srv)
1261 		/* DMUB isn't supported on the ASIC. */
1262 		return 0;
1263 
1264 	if (!fb_info) {
1265 		drm_err(adev_to_drm(adev), "No framebuffer info for DMUB service.\n");
1266 		return -EINVAL;
1267 	}
1268 
1269 	if (!dmub_fw) {
1270 		/* Firmware required for DMUB support. */
1271 		drm_err(adev_to_drm(adev), "No firmware provided for DMUB.\n");
1272 		return -EINVAL;
1273 	}
1274 
1275 	/* initialize register offsets for ASICs with runtime initialization available */
1276 	if (dmub_srv->hw_funcs.init_reg_offsets)
1277 		dmub_srv->hw_funcs.init_reg_offsets(dmub_srv, ctx);
1278 
1279 	status = dmub_srv_has_hw_support(dmub_srv, &has_hw_support);
1280 	if (status != DMUB_STATUS_OK) {
1281 		drm_err(adev_to_drm(adev), "Error checking HW support for DMUB: %d\n", status);
1282 		return -EINVAL;
1283 	}
1284 
1285 	if (!has_hw_support) {
1286 		drm_info(adev_to_drm(adev), "DMUB unsupported on ASIC\n");
1287 		return 0;
1288 	}
1289 
1290 	/* Reset DMCUB if it was previously running - before we overwrite its memory. */
1291 	status = dmub_srv_hw_reset(dmub_srv);
1292 	if (status != DMUB_STATUS_OK)
1293 		drm_warn(adev_to_drm(adev), "Error resetting DMUB HW: %d\n", status);
1294 
1295 	hdr = (const struct dmcub_firmware_header_v1_0 *)dmub_fw->data;
1296 
1297 	fw_inst_const = dmub_fw->data +
1298 			le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1299 			PSP_HEADER_BYTES_256;
1300 
1301 	fw_bss_data = dmub_fw->data +
1302 		      le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
1303 		      le32_to_cpu(hdr->inst_const_bytes);
1304 
1305 	/* Copy firmware and bios info into FB memory. */
1306 	fw_inst_const_size = adev->dm.fw_inst_size;
1307 
1308 	fw_bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
1309 
1310 	/* if adev->firmware.load_type == AMDGPU_FW_LOAD_PSP,
1311 	 * amdgpu_ucode_init_single_fw will load dmub firmware
1312 	 * fw_inst_const part to cw0; otherwise, the firmware back door load
1313 	 * will be done by dm_dmub_hw_init
1314 	 */
1315 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
1316 		memcpy(fb_info->fb[DMUB_WINDOW_0_INST_CONST].cpu_addr, fw_inst_const,
1317 				fw_inst_const_size);
1318 	}
1319 
1320 	if (fw_bss_data_size)
1321 		memcpy(fb_info->fb[DMUB_WINDOW_2_BSS_DATA].cpu_addr,
1322 		       fw_bss_data, fw_bss_data_size);
1323 
1324 	/* Copy firmware bios info into FB memory. */
1325 	memcpy(fb_info->fb[DMUB_WINDOW_3_VBIOS].cpu_addr, adev->bios,
1326 	       adev->bios_size);
1327 
1328 	/* Reset regions that need to be reset. */
1329 	memset(fb_info->fb[DMUB_WINDOW_4_MAILBOX].cpu_addr, 0,
1330 	fb_info->fb[DMUB_WINDOW_4_MAILBOX].size);
1331 
1332 	memset(fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].cpu_addr, 0,
1333 	       fb_info->fb[DMUB_WINDOW_5_TRACEBUFF].size);
1334 
1335 	memset(fb_info->fb[DMUB_WINDOW_6_FW_STATE].cpu_addr, 0,
1336 	       fb_info->fb[DMUB_WINDOW_6_FW_STATE].size);
1337 
1338 	memset(fb_info->fb[DMUB_WINDOW_SHARED_STATE].cpu_addr, 0,
1339 	       fb_info->fb[DMUB_WINDOW_SHARED_STATE].size);
1340 
1341 	/* Initialize hardware. */
1342 	memset(&hw_params, 0, sizeof(hw_params));
1343 	hw_params.soc_fb_info.fb_base = adev->gmc.fb_start;
1344 	hw_params.soc_fb_info.fb_offset = adev->vm_manager.vram_base_offset;
1345 
1346 	/* backdoor load firmware and trigger dmub running */
1347 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP)
1348 		hw_params.load_inst_const = true;
1349 
1350 	if (dmcu)
1351 		hw_params.psp_version = dmcu->psp_version;
1352 
1353 	for (i = 0; i < fb_info->num_fb; ++i)
1354 		hw_params.fb[i] = &fb_info->fb[i];
1355 
1356 	/* Enable usb4 dpia in the FW APU */
1357 	if (dc->caps.is_apu &&
1358 		dc->res_pool->usb4_dpia_count != 0 &&
1359 		!dc->debug.dpia_debug.bits.disable_dpia) {
1360 		hw_params.dpia_supported = true;
1361 		hw_params.disable_dpia = dc->debug.dpia_debug.bits.disable_dpia;
1362 		hw_params.dpia_hpd_int_enable_supported = false;
1363 		hw_params.enable_non_transparent_setconfig = dc->config.consolidated_dpia_dp_lt;
1364 		hw_params.disable_dpia_bw_allocation = !dc->config.usb4_bw_alloc_support;
1365 	}
1366 
1367 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1368 	case IP_VERSION(3, 5, 0):
1369 	case IP_VERSION(3, 5, 1):
1370 	case IP_VERSION(3, 6, 0):
1371 		hw_params.ips_sequential_ono = adev->external_rev_id > 0x10;
1372 		hw_params.lower_hbr3_phy_ssc = true;
1373 		break;
1374 	default:
1375 		break;
1376 	}
1377 
1378 	status = dmub_srv_hw_init(dmub_srv, &hw_params);
1379 	if (status != DMUB_STATUS_OK) {
1380 		drm_err(adev_to_drm(adev), "Error initializing DMUB HW: %d\n", status);
1381 		return -EINVAL;
1382 	}
1383 
1384 	/* Wait for firmware load to finish. */
1385 	status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1386 	if (status != DMUB_STATUS_OK)
1387 		drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1388 
1389 	/* Init DMCU and ABM if available. */
1390 	if (dmcu && abm) {
1391 		dmcu->funcs->dmcu_init(dmcu);
1392 		abm->dmcu_is_running = dmcu->funcs->is_dmcu_initialized(dmcu);
1393 	}
1394 
1395 	if (!adev->dm.dc->ctx->dmub_srv)
1396 		adev->dm.dc->ctx->dmub_srv = dc_dmub_srv_create(adev->dm.dc, dmub_srv);
1397 	if (!adev->dm.dc->ctx->dmub_srv) {
1398 		drm_err(adev_to_drm(adev), "Couldn't allocate DC DMUB server!\n");
1399 		return -ENOMEM;
1400 	}
1401 
1402 	drm_info(adev_to_drm(adev), "DMUB hardware initialized: version=0x%08X\n",
1403 		 adev->dm.dmcub_fw_version);
1404 
1405 	/* Keeping sanity checks off if
1406 	 * DCN31 >= 4.0.59.0
1407 	 * DCN314 >= 8.0.16.0
1408 	 * Otherwise, turn on sanity checks
1409 	 */
1410 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1411 	case IP_VERSION(3, 1, 2):
1412 	case IP_VERSION(3, 1, 3):
1413 		if (adev->dm.dmcub_fw_version &&
1414 			adev->dm.dmcub_fw_version >= DMUB_FW_VERSION(4, 0, 0) &&
1415 			adev->dm.dmcub_fw_version < DMUB_FW_VERSION(4, 0, 59))
1416 				adev->dm.dc->debug.sanity_checks = true;
1417 		break;
1418 	case IP_VERSION(3, 1, 4):
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(8, 0, 16))
1422 				adev->dm.dc->debug.sanity_checks = true;
1423 		break;
1424 	default:
1425 		break;
1426 	}
1427 
1428 	return 0;
1429 }
1430 
dm_dmub_hw_resume(struct amdgpu_device * adev)1431 static void dm_dmub_hw_resume(struct amdgpu_device *adev)
1432 {
1433 	struct dmub_srv *dmub_srv = adev->dm.dmub_srv;
1434 	enum dmub_status status;
1435 	bool init;
1436 	int r;
1437 
1438 	if (!dmub_srv) {
1439 		/* DMUB isn't supported on the ASIC. */
1440 		return;
1441 	}
1442 
1443 	status = dmub_srv_is_hw_init(dmub_srv, &init);
1444 	if (status != DMUB_STATUS_OK)
1445 		drm_warn(adev_to_drm(adev), "DMUB hardware init check failed: %d\n", status);
1446 
1447 	if (status == DMUB_STATUS_OK && init) {
1448 		/* Wait for firmware load to finish. */
1449 		status = dmub_srv_wait_for_auto_load(dmub_srv, 100000);
1450 		if (status != DMUB_STATUS_OK)
1451 			drm_warn(adev_to_drm(adev), "Wait for DMUB auto-load failed: %d\n", status);
1452 	} else {
1453 		/* Perform the full hardware initialization. */
1454 		r = dm_dmub_hw_init(adev);
1455 		if (r)
1456 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
1457 	}
1458 }
1459 
mmhub_read_system_context(struct amdgpu_device * adev,struct dc_phy_addr_space_config * pa_config)1460 static void mmhub_read_system_context(struct amdgpu_device *adev, struct dc_phy_addr_space_config *pa_config)
1461 {
1462 	u64 pt_base;
1463 	u32 logical_addr_low;
1464 	u32 logical_addr_high;
1465 	u32 agp_base, agp_bot, agp_top;
1466 	PHYSICAL_ADDRESS_LOC page_table_start, page_table_end, page_table_base;
1467 
1468 	memset(pa_config, 0, sizeof(*pa_config));
1469 
1470 	agp_base = 0;
1471 	agp_bot = adev->gmc.agp_start >> 24;
1472 	agp_top = adev->gmc.agp_end >> 24;
1473 
1474 	/* AGP aperture is disabled */
1475 	if (agp_bot > agp_top) {
1476 		logical_addr_low = adev->gmc.fb_start >> 18;
1477 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1478 				       AMD_APU_IS_RENOIR |
1479 				       AMD_APU_IS_GREEN_SARDINE))
1480 			/*
1481 			 * Raven2 has a HW issue that it is unable to use the vram which
1482 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1483 			 * workaround that increase system aperture high address (add 1)
1484 			 * to get rid of the VM fault and hardware hang.
1485 			 */
1486 			logical_addr_high = (adev->gmc.fb_end >> 18) + 0x1;
1487 		else
1488 			logical_addr_high = adev->gmc.fb_end >> 18;
1489 	} else {
1490 		logical_addr_low = min(adev->gmc.fb_start, adev->gmc.agp_start) >> 18;
1491 		if (adev->apu_flags & (AMD_APU_IS_RAVEN2 |
1492 				       AMD_APU_IS_RENOIR |
1493 				       AMD_APU_IS_GREEN_SARDINE))
1494 			/*
1495 			 * Raven2 has a HW issue that it is unable to use the vram which
1496 			 * is out of MC_VM_SYSTEM_APERTURE_HIGH_ADDR. So here is the
1497 			 * workaround that increase system aperture high address (add 1)
1498 			 * to get rid of the VM fault and hardware hang.
1499 			 */
1500 			logical_addr_high = max((adev->gmc.fb_end >> 18) + 0x1, adev->gmc.agp_end >> 18);
1501 		else
1502 			logical_addr_high = max(adev->gmc.fb_end, adev->gmc.agp_end) >> 18;
1503 	}
1504 
1505 	pt_base = amdgpu_gmc_pd_addr(adev->gart.bo);
1506 
1507 	page_table_start.high_part = upper_32_bits(adev->gmc.gart_start >>
1508 						   AMDGPU_GPU_PAGE_SHIFT);
1509 	page_table_start.low_part = lower_32_bits(adev->gmc.gart_start >>
1510 						  AMDGPU_GPU_PAGE_SHIFT);
1511 	page_table_end.high_part = upper_32_bits(adev->gmc.gart_end >>
1512 						 AMDGPU_GPU_PAGE_SHIFT);
1513 	page_table_end.low_part = lower_32_bits(adev->gmc.gart_end >>
1514 						AMDGPU_GPU_PAGE_SHIFT);
1515 	page_table_base.high_part = upper_32_bits(pt_base);
1516 	page_table_base.low_part = lower_32_bits(pt_base);
1517 
1518 	pa_config->system_aperture.start_addr = (uint64_t)logical_addr_low << 18;
1519 	pa_config->system_aperture.end_addr = (uint64_t)logical_addr_high << 18;
1520 
1521 	pa_config->system_aperture.agp_base = (uint64_t)agp_base << 24;
1522 	pa_config->system_aperture.agp_bot = (uint64_t)agp_bot << 24;
1523 	pa_config->system_aperture.agp_top = (uint64_t)agp_top << 24;
1524 
1525 	pa_config->system_aperture.fb_base = adev->gmc.fb_start;
1526 	pa_config->system_aperture.fb_offset = adev->vm_manager.vram_base_offset;
1527 	pa_config->system_aperture.fb_top = adev->gmc.fb_end;
1528 
1529 	pa_config->gart_config.page_table_start_addr = page_table_start.quad_part << 12;
1530 	pa_config->gart_config.page_table_end_addr = page_table_end.quad_part << 12;
1531 	pa_config->gart_config.page_table_base_addr = page_table_base.quad_part;
1532 
1533 	pa_config->is_hvm_enabled = adev->mode_info.gpu_vm_support;
1534 
1535 }
1536 
force_connector_state(struct amdgpu_dm_connector * aconnector,enum drm_connector_force force_state)1537 static void force_connector_state(
1538 	struct amdgpu_dm_connector *aconnector,
1539 	enum drm_connector_force force_state)
1540 {
1541 	struct drm_connector *connector = &aconnector->base;
1542 
1543 	mutex_lock(&connector->dev->mode_config.mutex);
1544 	aconnector->base.force = force_state;
1545 	mutex_unlock(&connector->dev->mode_config.mutex);
1546 
1547 	mutex_lock(&aconnector->hpd_lock);
1548 	drm_kms_helper_connector_hotplug_event(connector);
1549 	mutex_unlock(&aconnector->hpd_lock);
1550 }
1551 
dm_handle_hpd_rx_offload_work(struct work_struct * work)1552 static void dm_handle_hpd_rx_offload_work(struct work_struct *work)
1553 {
1554 	struct hpd_rx_irq_offload_work *offload_work;
1555 	struct amdgpu_dm_connector *aconnector;
1556 	struct dc_link *dc_link;
1557 	struct amdgpu_device *adev;
1558 	enum dc_connection_type new_connection_type = dc_connection_none;
1559 	unsigned long flags;
1560 	union test_response test_response;
1561 
1562 	memset(&test_response, 0, sizeof(test_response));
1563 
1564 	offload_work = container_of(work, struct hpd_rx_irq_offload_work, work);
1565 	aconnector = offload_work->offload_wq->aconnector;
1566 	adev = offload_work->adev;
1567 
1568 	if (!aconnector) {
1569 		drm_err(adev_to_drm(adev), "Can't retrieve aconnector in hpd_rx_irq_offload_work");
1570 		goto skip;
1571 	}
1572 
1573 	dc_link = aconnector->dc_link;
1574 
1575 	mutex_lock(&aconnector->hpd_lock);
1576 	if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
1577 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
1578 	mutex_unlock(&aconnector->hpd_lock);
1579 
1580 	if (new_connection_type == dc_connection_none)
1581 		goto skip;
1582 
1583 	if (amdgpu_in_reset(adev))
1584 		goto skip;
1585 
1586 	if (offload_work->data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
1587 		offload_work->data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
1588 		dm_handle_mst_sideband_msg_ready_event(&aconnector->mst_mgr, DOWN_OR_UP_MSG_RDY_EVENT);
1589 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1590 		offload_work->offload_wq->is_handling_mst_msg_rdy_event = false;
1591 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1592 		goto skip;
1593 	}
1594 
1595 	mutex_lock(&adev->dm.dc_lock);
1596 	if (offload_work->data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
1597 		dc_link_dp_handle_automated_test(dc_link);
1598 
1599 		if (aconnector->timing_changed) {
1600 			/* force connector disconnect and reconnect */
1601 			force_connector_state(aconnector, DRM_FORCE_OFF);
1602 			msleep(100);
1603 			force_connector_state(aconnector, DRM_FORCE_UNSPECIFIED);
1604 		}
1605 
1606 		test_response.bits.ACK = 1;
1607 
1608 		core_link_write_dpcd(
1609 		dc_link,
1610 		DP_TEST_RESPONSE,
1611 		&test_response.raw,
1612 		sizeof(test_response));
1613 	} else if ((dc_link->connector_signal != SIGNAL_TYPE_EDP) &&
1614 			dc_link_check_link_loss_status(dc_link, &offload_work->data) &&
1615 			dc_link_dp_allow_hpd_rx_irq(dc_link)) {
1616 		/* offload_work->data is from handle_hpd_rx_irq->
1617 		 * schedule_hpd_rx_offload_work.this is defer handle
1618 		 * for hpd short pulse. upon here, link status may be
1619 		 * changed, need get latest link status from dpcd
1620 		 * registers. if link status is good, skip run link
1621 		 * training again.
1622 		 */
1623 		union hpd_irq_data irq_data;
1624 
1625 		memset(&irq_data, 0, sizeof(irq_data));
1626 
1627 		/* before dc_link_dp_handle_link_loss, allow new link lost handle
1628 		 * request be added to work queue if link lost at end of dc_link_
1629 		 * dp_handle_link_loss
1630 		 */
1631 		spin_lock_irqsave(&offload_work->offload_wq->offload_lock, flags);
1632 		offload_work->offload_wq->is_handling_link_loss = false;
1633 		spin_unlock_irqrestore(&offload_work->offload_wq->offload_lock, flags);
1634 
1635 		if ((dc_link_dp_read_hpd_rx_irq_data(dc_link, &irq_data) == DC_OK) &&
1636 			dc_link_check_link_loss_status(dc_link, &irq_data))
1637 			dc_link_dp_handle_link_loss(dc_link);
1638 	}
1639 	mutex_unlock(&adev->dm.dc_lock);
1640 
1641 skip:
1642 	kfree(offload_work);
1643 
1644 }
1645 
hpd_rx_irq_create_workqueue(struct amdgpu_device * adev)1646 static struct hpd_rx_irq_offload_work_queue *hpd_rx_irq_create_workqueue(struct amdgpu_device *adev)
1647 {
1648 	struct dc *dc = adev->dm.dc;
1649 	int max_caps = dc->caps.max_links;
1650 	int i = 0;
1651 	struct hpd_rx_irq_offload_work_queue *hpd_rx_offload_wq = NULL;
1652 
1653 	hpd_rx_offload_wq = kzalloc_objs(*hpd_rx_offload_wq, max_caps,
1654 					 GFP_KERNEL);
1655 
1656 	if (!hpd_rx_offload_wq)
1657 		return NULL;
1658 
1659 
1660 	for (i = 0; i < max_caps; i++) {
1661 		hpd_rx_offload_wq[i].wq =
1662 				    create_singlethread_workqueue("amdgpu_dm_hpd_rx_offload_wq");
1663 
1664 		if (hpd_rx_offload_wq[i].wq == NULL) {
1665 			drm_err(adev_to_drm(adev), "create amdgpu_dm_hpd_rx_offload_wq fail!");
1666 			goto out_err;
1667 		}
1668 
1669 		spin_lock_init(&hpd_rx_offload_wq[i].offload_lock);
1670 	}
1671 
1672 	return hpd_rx_offload_wq;
1673 
1674 out_err:
1675 	for (i = 0; i < max_caps; i++) {
1676 		if (hpd_rx_offload_wq[i].wq)
1677 			destroy_workqueue(hpd_rx_offload_wq[i].wq);
1678 	}
1679 	kfree(hpd_rx_offload_wq);
1680 	return NULL;
1681 }
1682 
1683 struct amdgpu_stutter_quirk {
1684 	u16 chip_vendor;
1685 	u16 chip_device;
1686 	u16 subsys_vendor;
1687 	u16 subsys_device;
1688 	u8 revision;
1689 };
1690 
1691 static const struct amdgpu_stutter_quirk amdgpu_stutter_quirk_list[] = {
1692 	/* https://bugzilla.kernel.org/show_bug.cgi?id=214417 */
1693 	{ 0x1002, 0x15dd, 0x1002, 0x15dd, 0xc8 },
1694 	{ 0, 0, 0, 0, 0 },
1695 };
1696 
dm_should_disable_stutter(struct pci_dev * pdev)1697 static bool dm_should_disable_stutter(struct pci_dev *pdev)
1698 {
1699 	const struct amdgpu_stutter_quirk *p = amdgpu_stutter_quirk_list;
1700 
1701 	while (p && p->chip_device != 0) {
1702 		if (pdev->vendor == p->chip_vendor &&
1703 		    pdev->device == p->chip_device &&
1704 		    pdev->subsystem_vendor == p->subsys_vendor &&
1705 		    pdev->subsystem_device == p->subsys_device &&
1706 		    pdev->revision == p->revision) {
1707 			return true;
1708 		}
1709 		++p;
1710 	}
1711 	return false;
1712 }
1713 
1714 
1715 void*
dm_allocate_gpu_mem(struct amdgpu_device * adev,enum dc_gpu_mem_alloc_type type,size_t size,long long * addr)1716 dm_allocate_gpu_mem(
1717 		struct amdgpu_device *adev,
1718 		enum dc_gpu_mem_alloc_type type,
1719 		size_t size,
1720 		long long *addr)
1721 {
1722 	struct dal_allocation *da;
1723 	u32 domain = (type == DC_MEM_ALLOC_TYPE_GART) ?
1724 		AMDGPU_GEM_DOMAIN_GTT : AMDGPU_GEM_DOMAIN_VRAM;
1725 	int ret;
1726 
1727 	da = kzalloc_obj(struct dal_allocation, GFP_KERNEL);
1728 	if (!da)
1729 		return NULL;
1730 
1731 	ret = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
1732 				      domain, &da->bo,
1733 				      &da->gpu_addr, &da->cpu_ptr);
1734 
1735 	*addr = da->gpu_addr;
1736 
1737 	if (ret) {
1738 		kfree(da);
1739 		return NULL;
1740 	}
1741 
1742 	/* add da to list in dm */
1743 	list_add(&da->list, &adev->dm.da_list);
1744 
1745 	return da->cpu_ptr;
1746 }
1747 
1748 void
dm_free_gpu_mem(struct amdgpu_device * adev,enum dc_gpu_mem_alloc_type type,void * pvMem)1749 dm_free_gpu_mem(
1750 		struct amdgpu_device *adev,
1751 		enum dc_gpu_mem_alloc_type type,
1752 		void *pvMem)
1753 {
1754 	struct dal_allocation *da;
1755 
1756 	/* walk the da list in DM */
1757 	list_for_each_entry(da, &adev->dm.da_list, list) {
1758 		if (pvMem == da->cpu_ptr) {
1759 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
1760 			list_del(&da->list);
1761 			kfree(da);
1762 			break;
1763 		}
1764 	}
1765 
1766 }
1767 
1768 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)1769 dm_dmub_send_vbios_gpint_command(struct amdgpu_device *adev,
1770 				 enum dmub_gpint_command command_code,
1771 				 uint16_t param,
1772 				 uint32_t timeout_us)
1773 {
1774 	union dmub_gpint_data_register reg, test;
1775 	uint32_t i;
1776 
1777 	/* Assume that VBIOS DMUB is ready to take commands */
1778 
1779 	reg.bits.status = 1;
1780 	reg.bits.command_code = command_code;
1781 	reg.bits.param = param;
1782 
1783 	cgs_write_register(adev->dm.cgs_device, 0x34c0 + 0x01f8, reg.all);
1784 
1785 	for (i = 0; i < timeout_us; ++i) {
1786 		udelay(1);
1787 
1788 		/* Check if our GPINT got acked */
1789 		reg.bits.status = 0;
1790 		test = (union dmub_gpint_data_register)
1791 			cgs_read_register(adev->dm.cgs_device, 0x34c0 + 0x01f8);
1792 
1793 		if (test.all == reg.all)
1794 			return DMUB_STATUS_OK;
1795 	}
1796 
1797 	return DMUB_STATUS_TIMEOUT;
1798 }
1799 
dm_dmub_get_vbios_bounding_box(struct amdgpu_device * adev)1800 static void *dm_dmub_get_vbios_bounding_box(struct amdgpu_device *adev)
1801 {
1802 	void *bb;
1803 	long long addr;
1804 	unsigned int bb_size;
1805 	int i = 0;
1806 	uint16_t chunk;
1807 	enum dmub_gpint_command send_addrs[] = {
1808 		DMUB_GPINT__SET_BB_ADDR_WORD0,
1809 		DMUB_GPINT__SET_BB_ADDR_WORD1,
1810 		DMUB_GPINT__SET_BB_ADDR_WORD2,
1811 		DMUB_GPINT__SET_BB_ADDR_WORD3,
1812 	};
1813 	enum dmub_status ret;
1814 
1815 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1816 	case IP_VERSION(4, 0, 1):
1817 		bb_size = sizeof(struct dml2_soc_bb);
1818 		break;
1819 	default:
1820 		return NULL;
1821 	}
1822 
1823 	bb =  dm_allocate_gpu_mem(adev,
1824 				  DC_MEM_ALLOC_TYPE_GART,
1825 				  bb_size,
1826 				  &addr);
1827 	if (!bb)
1828 		return NULL;
1829 
1830 	for (i = 0; i < 4; i++) {
1831 		/* Extract 16-bit chunk */
1832 		chunk = ((uint64_t) addr >> (i * 16)) & 0xFFFF;
1833 		/* Send the chunk */
1834 		ret = dm_dmub_send_vbios_gpint_command(adev, send_addrs[i], chunk, 30000);
1835 		if (ret != DMUB_STATUS_OK)
1836 			goto free_bb;
1837 	}
1838 
1839 	/* Now ask DMUB to copy the bb */
1840 	ret = dm_dmub_send_vbios_gpint_command(adev, DMUB_GPINT__BB_COPY, 1, 200000);
1841 	if (ret != DMUB_STATUS_OK)
1842 		goto free_bb;
1843 
1844 	return bb;
1845 
1846 free_bb:
1847 	dm_free_gpu_mem(adev, DC_MEM_ALLOC_TYPE_GART, (void *) bb);
1848 	return NULL;
1849 
1850 }
1851 
dm_get_default_ips_mode(struct amdgpu_device * adev)1852 static enum dmub_ips_disable_type dm_get_default_ips_mode(
1853 	struct amdgpu_device *adev)
1854 {
1855 	enum dmub_ips_disable_type ret = DMUB_IPS_ENABLE;
1856 
1857 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1858 	case IP_VERSION(3, 5, 0):
1859 	case IP_VERSION(3, 6, 0):
1860 	case IP_VERSION(3, 5, 1):
1861 		ret =  DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
1862 		break;
1863 	default:
1864 		/* ASICs older than DCN35 do not have IPSs */
1865 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 5, 0))
1866 			ret = DMUB_IPS_DISABLE_ALL;
1867 		break;
1868 	}
1869 
1870 	return ret;
1871 }
1872 
amdgpu_dm_init(struct amdgpu_device * adev)1873 static int amdgpu_dm_init(struct amdgpu_device *adev)
1874 {
1875 	struct dc_init_data init_data;
1876 	struct dc_callback_init init_params;
1877 	int r;
1878 
1879 	adev->dm.ddev = adev_to_drm(adev);
1880 	adev->dm.adev = adev;
1881 
1882 	/* Zero all the fields */
1883 	memset(&init_data, 0, sizeof(init_data));
1884 	memset(&init_params, 0, sizeof(init_params));
1885 
1886 	mutex_init(&adev->dm.dpia_aux_lock);
1887 	mutex_init(&adev->dm.dc_lock);
1888 	mutex_init(&adev->dm.audio_lock);
1889 
1890 	if (amdgpu_dm_irq_init(adev)) {
1891 		drm_err(adev_to_drm(adev), "failed to initialize DM IRQ support.\n");
1892 		goto error;
1893 	}
1894 
1895 	init_data.asic_id.chip_family = adev->family;
1896 
1897 	init_data.asic_id.pci_revision_id = adev->pdev->revision;
1898 	init_data.asic_id.hw_internal_rev = adev->external_rev_id;
1899 	init_data.asic_id.chip_id = adev->pdev->device;
1900 
1901 	init_data.asic_id.vram_width = adev->gmc.vram_width;
1902 	/* TODO: initialize init_data.asic_id.vram_type here!!!! */
1903 	init_data.asic_id.atombios_base_address =
1904 		adev->mode_info.atom_context->bios;
1905 
1906 	init_data.driver = adev;
1907 
1908 	/* cgs_device was created in dm_sw_init() */
1909 	init_data.cgs_device = adev->dm.cgs_device;
1910 
1911 	init_data.dce_environment = DCE_ENV_PRODUCTION_DRV;
1912 
1913 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
1914 	case IP_VERSION(2, 1, 0):
1915 		switch (adev->dm.dmcub_fw_version) {
1916 		case 0: /* development */
1917 		case 0x1: /* linux-firmware.git hash 6d9f399 */
1918 		case 0x01000000: /* linux-firmware.git hash 9a0b0f4 */
1919 			init_data.flags.disable_dmcu = false;
1920 			break;
1921 		default:
1922 			init_data.flags.disable_dmcu = true;
1923 		}
1924 		break;
1925 	case IP_VERSION(2, 0, 3):
1926 		init_data.flags.disable_dmcu = true;
1927 		break;
1928 	default:
1929 		break;
1930 	}
1931 
1932 	/* APU support S/G display by default except:
1933 	 * ASICs before Carrizo,
1934 	 * RAVEN1 (Users reported stability issue)
1935 	 */
1936 
1937 	if (adev->asic_type < CHIP_CARRIZO) {
1938 		init_data.flags.gpu_vm_support = false;
1939 	} else if (adev->asic_type == CHIP_RAVEN) {
1940 		if (adev->apu_flags & AMD_APU_IS_RAVEN)
1941 			init_data.flags.gpu_vm_support = false;
1942 		else
1943 			init_data.flags.gpu_vm_support = (amdgpu_sg_display != 0);
1944 	} else {
1945 		if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(2, 0, 3))
1946 			init_data.flags.gpu_vm_support = (amdgpu_sg_display == 1);
1947 		else
1948 			init_data.flags.gpu_vm_support =
1949 				(amdgpu_sg_display != 0) && (adev->flags & AMD_IS_APU);
1950 	}
1951 
1952 	adev->mode_info.gpu_vm_support = init_data.flags.gpu_vm_support;
1953 
1954 	if (amdgpu_dc_feature_mask & DC_FBC_MASK)
1955 		init_data.flags.fbc_support = true;
1956 
1957 	if (amdgpu_dc_feature_mask & DC_MULTI_MON_PP_MCLK_SWITCH_MASK)
1958 		init_data.flags.multi_mon_pp_mclk_switch = true;
1959 
1960 	if (amdgpu_dc_feature_mask & DC_DISABLE_FRACTIONAL_PWM_MASK)
1961 		init_data.flags.disable_fractional_pwm = true;
1962 
1963 	if (amdgpu_dc_feature_mask & DC_EDP_NO_POWER_SEQUENCING)
1964 		init_data.flags.edp_no_power_sequencing = true;
1965 
1966 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP1_4A)
1967 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP1_4A = true;
1968 	if (amdgpu_dc_feature_mask & DC_DISABLE_LTTPR_DP2_0)
1969 		init_data.flags.allow_lttpr_non_transparent_mode.bits.DP2_0 = true;
1970 
1971 	init_data.flags.seamless_boot_edp_requested = false;
1972 
1973 	if (amdgpu_device_seamless_boot_supported(adev)) {
1974 		init_data.flags.seamless_boot_edp_requested = true;
1975 		init_data.flags.allow_seamless_boot_optimization = true;
1976 		drm_dbg(adev->dm.ddev, "Seamless boot requested\n");
1977 	}
1978 
1979 	init_data.flags.enable_mipi_converter_optimization = true;
1980 
1981 	init_data.dcn_reg_offsets = adev->reg_offset[DCE_HWIP][0];
1982 	init_data.nbio_reg_offsets = adev->reg_offset[NBIO_HWIP][0];
1983 	init_data.clk_reg_offsets = adev->reg_offset[CLK_HWIP][0];
1984 
1985 	if (amdgpu_dc_debug_mask & DC_DISABLE_IPS)
1986 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_ALL;
1987 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS_DYNAMIC)
1988 		init_data.flags.disable_ips = DMUB_IPS_DISABLE_DYNAMIC;
1989 	else if (amdgpu_dc_debug_mask & DC_DISABLE_IPS2_DYNAMIC)
1990 		init_data.flags.disable_ips = DMUB_IPS_RCG_IN_ACTIVE_IPS2_IN_OFF;
1991 	else if (amdgpu_dc_debug_mask & DC_FORCE_IPS_ENABLE)
1992 		init_data.flags.disable_ips = DMUB_IPS_ENABLE;
1993 	else
1994 		init_data.flags.disable_ips = dm_get_default_ips_mode(adev);
1995 
1996 	init_data.flags.disable_ips_in_vpb = 0;
1997 
1998 	/* DCN35 and above supports dynamic DTBCLK switch */
1999 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 5, 0))
2000 		init_data.flags.allow_0_dtb_clk = true;
2001 
2002 	/* Enable DWB for tested platforms only */
2003 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0))
2004 		init_data.num_virtual_links = 1;
2005 
2006 	retrieve_dmi_info(&adev->dm);
2007 	if (adev->dm.edp0_on_dp1_quirk)
2008 		init_data.flags.support_edp0_on_dp1 = true;
2009 
2010 	if (adev->dm.bb_from_dmub)
2011 		init_data.bb_from_dmub = adev->dm.bb_from_dmub;
2012 	else
2013 		init_data.bb_from_dmub = NULL;
2014 
2015 	/* Display Core create. */
2016 	adev->dm.dc = dc_create(&init_data);
2017 
2018 	if (adev->dm.dc) {
2019 		drm_info(adev_to_drm(adev), "Display Core v%s initialized on %s\n", DC_VER,
2020 			 dce_version_to_string(adev->dm.dc->ctx->dce_version));
2021 	} else {
2022 		drm_info(adev_to_drm(adev), "Display Core failed to initialize with v%s!\n", DC_VER);
2023 		goto error;
2024 	}
2025 
2026 	if (amdgpu_dc_debug_mask & DC_DISABLE_PIPE_SPLIT) {
2027 		adev->dm.dc->debug.force_single_disp_pipe_split = false;
2028 		adev->dm.dc->debug.pipe_split_policy = MPC_SPLIT_AVOID;
2029 	}
2030 
2031 	if (adev->asic_type != CHIP_CARRIZO && adev->asic_type != CHIP_STONEY)
2032 		adev->dm.dc->debug.disable_stutter = amdgpu_pp_feature_mask & PP_STUTTER_MODE ? false : true;
2033 	if (dm_should_disable_stutter(adev->pdev))
2034 		adev->dm.dc->debug.disable_stutter = true;
2035 
2036 	if (amdgpu_dc_debug_mask & DC_DISABLE_STUTTER)
2037 		adev->dm.dc->debug.disable_stutter = true;
2038 
2039 	if (amdgpu_dc_debug_mask & DC_DISABLE_DSC)
2040 		adev->dm.dc->debug.disable_dsc = true;
2041 
2042 	if (amdgpu_dc_debug_mask & DC_DISABLE_CLOCK_GATING)
2043 		adev->dm.dc->debug.disable_clock_gate = true;
2044 
2045 	if (amdgpu_dc_debug_mask & DC_FORCE_SUBVP_MCLK_SWITCH)
2046 		adev->dm.dc->debug.force_subvp_mclk_switch = true;
2047 
2048 	if (amdgpu_dc_debug_mask & DC_DISABLE_SUBVP_FAMS) {
2049 		adev->dm.dc->debug.force_disable_subvp = true;
2050 		adev->dm.dc->debug.fams2_config.bits.enable = false;
2051 	}
2052 
2053 	if (amdgpu_dc_debug_mask & DC_ENABLE_DML2) {
2054 		adev->dm.dc->debug.using_dml2 = true;
2055 		adev->dm.dc->debug.using_dml21 = true;
2056 	}
2057 
2058 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_FORCE_FW_ENABLE)
2059 		adev->dm.dc->debug.hdcp_lc_force_fw_enable = true;
2060 
2061 	if (amdgpu_dc_debug_mask & DC_HDCP_LC_ENABLE_SW_FALLBACK)
2062 		adev->dm.dc->debug.hdcp_lc_enable_sw_fallback = true;
2063 
2064 	if (amdgpu_dc_debug_mask & DC_SKIP_DETECTION_LT)
2065 		adev->dm.dc->debug.skip_detection_link_training = true;
2066 
2067 	adev->dm.dc->debug.visual_confirm = amdgpu_dc_visual_confirm;
2068 
2069 	/* TODO: Remove after DP2 receiver gets proper support of Cable ID feature */
2070 	adev->dm.dc->debug.ignore_cable_id = true;
2071 
2072 	if (adev->dm.dc->caps.dp_hdmi21_pcon_support)
2073 		drm_info(adev_to_drm(adev), "DP-HDMI FRL PCON supported\n");
2074 
2075 	r = dm_dmub_hw_init(adev);
2076 	if (r) {
2077 		drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
2078 		goto error;
2079 	}
2080 
2081 	dc_hardware_init(adev->dm.dc);
2082 
2083 	adev->dm.hpd_rx_offload_wq = hpd_rx_irq_create_workqueue(adev);
2084 	if (!adev->dm.hpd_rx_offload_wq) {
2085 		drm_err(adev_to_drm(adev), "failed to create hpd rx offload workqueue.\n");
2086 		goto error;
2087 	}
2088 
2089 	if ((adev->flags & AMD_IS_APU) && (adev->asic_type >= CHIP_CARRIZO)) {
2090 		struct dc_phy_addr_space_config pa_config;
2091 
2092 		mmhub_read_system_context(adev, &pa_config);
2093 
2094 		// Call the DC init_memory func
2095 		dc_setup_system_context(adev->dm.dc, &pa_config);
2096 	}
2097 
2098 	adev->dm.freesync_module = mod_freesync_create(adev->dm.dc);
2099 	if (!adev->dm.freesync_module) {
2100 		drm_err(adev_to_drm(adev),
2101 		"failed to initialize freesync_module.\n");
2102 	} else
2103 		drm_dbg_driver(adev_to_drm(adev), "freesync_module init done %p.\n",
2104 				adev->dm.freesync_module);
2105 
2106 	amdgpu_dm_init_color_mod();
2107 
2108 	if (adev->dm.dc->caps.max_links > 0) {
2109 		adev->dm.vblank_control_workqueue =
2110 			create_singlethread_workqueue("dm_vblank_control_workqueue");
2111 		if (!adev->dm.vblank_control_workqueue)
2112 			drm_err(adev_to_drm(adev), "failed to initialize vblank_workqueue.\n");
2113 	}
2114 
2115 	if (adev->dm.dc->caps.ips_support &&
2116 	    adev->dm.dc->config.disable_ips != DMUB_IPS_DISABLE_ALL)
2117 		adev->dm.idle_workqueue = idle_create_workqueue(adev);
2118 
2119 	if (adev->dm.dc->caps.max_links > 0 && adev->family >= AMDGPU_FAMILY_RV) {
2120 		adev->dm.hdcp_workqueue = hdcp_create_workqueue(adev, &init_params.cp_psp, adev->dm.dc);
2121 
2122 		if (!adev->dm.hdcp_workqueue)
2123 			drm_err(adev_to_drm(adev), "failed to initialize hdcp_workqueue.\n");
2124 		else
2125 			drm_dbg_driver(adev_to_drm(adev),
2126 				       "hdcp_workqueue init done %p.\n",
2127 				       adev->dm.hdcp_workqueue);
2128 
2129 		dc_init_callbacks(adev->dm.dc, &init_params);
2130 	}
2131 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
2132 		init_completion(&adev->dm.dmub_aux_transfer_done);
2133 		adev->dm.dmub_notify = kzalloc_obj(struct dmub_notification,
2134 						   GFP_KERNEL);
2135 		if (!adev->dm.dmub_notify) {
2136 			drm_info(adev_to_drm(adev), "fail to allocate adev->dm.dmub_notify");
2137 			goto error;
2138 		}
2139 
2140 		adev->dm.delayed_hpd_wq = create_singlethread_workqueue("amdgpu_dm_hpd_wq");
2141 		if (!adev->dm.delayed_hpd_wq) {
2142 			drm_err(adev_to_drm(adev), "failed to create hpd offload workqueue.\n");
2143 			goto error;
2144 		}
2145 
2146 		amdgpu_dm_outbox_init(adev);
2147 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_AUX_REPLY,
2148 			dmub_aux_setconfig_callback, false)) {
2149 			drm_err(adev_to_drm(adev), "fail to register dmub aux callback");
2150 			goto error;
2151 		}
2152 
2153 		for (size_t i = 0; i < ARRAY_SIZE(adev->dm.fused_io); i++)
2154 			init_completion(&adev->dm.fused_io[i].replied);
2155 
2156 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_FUSED_IO,
2157 			dmub_aux_fused_io_callback, false)) {
2158 			drm_err(adev_to_drm(adev), "fail to register dmub fused io callback");
2159 			goto error;
2160 		}
2161 		/* Enable outbox notification only after IRQ handlers are registered and DMUB is alive.
2162 		 * It is expected that DMUB will resend any pending notifications at this point. Note
2163 		 * that hpd and hpd_irq handler registration are deferred to register_hpd_handlers() to
2164 		 * align legacy interface initialization sequence. Connection status will be proactivly
2165 		 * detected once in the amdgpu_dm_initialize_drm_device.
2166 		 */
2167 		dc_enable_dmub_outbox(adev->dm.dc);
2168 
2169 		/* DPIA trace goes to dmesg logs only if outbox is enabled */
2170 		if (amdgpu_dc_debug_mask & DC_ENABLE_DPIA_TRACE)
2171 			dc_dmub_srv_enable_dpia_trace(adev->dm.dc);
2172 	}
2173 
2174 	if (amdgpu_dm_initialize_drm_device(adev)) {
2175 		drm_err(adev_to_drm(adev),
2176 		"failed to initialize sw for display support.\n");
2177 		goto error;
2178 	}
2179 
2180 	/* create fake encoders for MST */
2181 	dm_dp_create_fake_mst_encoders(adev);
2182 
2183 	/* TODO: Add_display_info? */
2184 
2185 	/* TODO use dynamic cursor width */
2186 	adev_to_drm(adev)->mode_config.cursor_width = adev->dm.dc->caps.max_cursor_size;
2187 	adev_to_drm(adev)->mode_config.cursor_height = adev->dm.dc->caps.max_cursor_size;
2188 
2189 	if (drm_vblank_init(adev_to_drm(adev), adev->dm.display_indexes_num)) {
2190 		drm_err(adev_to_drm(adev),
2191 		"failed to initialize vblank for display support.\n");
2192 		goto error;
2193 	}
2194 
2195 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2196 	amdgpu_dm_crtc_secure_display_create_contexts(adev);
2197 	if (!adev->dm.secure_display_ctx.crtc_ctx)
2198 		drm_err(adev_to_drm(adev), "failed to initialize secure display contexts.\n");
2199 
2200 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(4, 0, 1))
2201 		adev->dm.secure_display_ctx.support_mul_roi = true;
2202 
2203 #endif
2204 
2205 	drm_dbg_driver(adev_to_drm(adev), "KMS initialized.\n");
2206 
2207 	return 0;
2208 error:
2209 	amdgpu_dm_fini(adev);
2210 
2211 	return -EINVAL;
2212 }
2213 
amdgpu_dm_early_fini(struct amdgpu_ip_block * ip_block)2214 static int amdgpu_dm_early_fini(struct amdgpu_ip_block *ip_block)
2215 {
2216 	struct amdgpu_device *adev = ip_block->adev;
2217 
2218 	amdgpu_dm_audio_fini(adev);
2219 
2220 	return 0;
2221 }
2222 
amdgpu_dm_fini(struct amdgpu_device * adev)2223 static void amdgpu_dm_fini(struct amdgpu_device *adev)
2224 {
2225 	int i;
2226 
2227 	if (adev->dm.vblank_control_workqueue) {
2228 		destroy_workqueue(adev->dm.vblank_control_workqueue);
2229 		adev->dm.vblank_control_workqueue = NULL;
2230 	}
2231 
2232 	if (adev->dm.idle_workqueue) {
2233 		if (adev->dm.idle_workqueue->running) {
2234 			adev->dm.idle_workqueue->enable = false;
2235 			flush_work(&adev->dm.idle_workqueue->work);
2236 		}
2237 
2238 		kfree(adev->dm.idle_workqueue);
2239 		adev->dm.idle_workqueue = NULL;
2240 	}
2241 
2242 	amdgpu_dm_destroy_drm_device(&adev->dm);
2243 
2244 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
2245 	if (adev->dm.secure_display_ctx.crtc_ctx) {
2246 		for (i = 0; i < adev->mode_info.num_crtc; i++) {
2247 			if (adev->dm.secure_display_ctx.crtc_ctx[i].crtc) {
2248 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].notify_ta_work);
2249 				flush_work(&adev->dm.secure_display_ctx.crtc_ctx[i].forward_roi_work);
2250 			}
2251 		}
2252 		kfree(adev->dm.secure_display_ctx.crtc_ctx);
2253 		adev->dm.secure_display_ctx.crtc_ctx = NULL;
2254 	}
2255 #endif
2256 	if (adev->dm.hdcp_workqueue) {
2257 		hdcp_destroy(&adev->dev->kobj, adev->dm.hdcp_workqueue);
2258 		adev->dm.hdcp_workqueue = NULL;
2259 	}
2260 
2261 	if (adev->dm.dc) {
2262 		dc_deinit_callbacks(adev->dm.dc);
2263 		dc_dmub_srv_destroy(&adev->dm.dc->ctx->dmub_srv);
2264 		if (dc_enable_dmub_notifications(adev->dm.dc)) {
2265 			kfree(adev->dm.dmub_notify);
2266 			adev->dm.dmub_notify = NULL;
2267 			destroy_workqueue(adev->dm.delayed_hpd_wq);
2268 			adev->dm.delayed_hpd_wq = NULL;
2269 		}
2270 	}
2271 
2272 	if (adev->dm.dmub_bo)
2273 		amdgpu_bo_free_kernel(&adev->dm.dmub_bo,
2274 				      &adev->dm.dmub_bo_gpu_addr,
2275 				      &adev->dm.dmub_bo_cpu_addr);
2276 
2277 	if (adev->dm.hpd_rx_offload_wq && adev->dm.dc) {
2278 		for (i = 0; i < adev->dm.dc->caps.max_links; i++) {
2279 			if (adev->dm.hpd_rx_offload_wq[i].wq) {
2280 				destroy_workqueue(adev->dm.hpd_rx_offload_wq[i].wq);
2281 				adev->dm.hpd_rx_offload_wq[i].wq = NULL;
2282 			}
2283 		}
2284 
2285 		kfree(adev->dm.hpd_rx_offload_wq);
2286 		adev->dm.hpd_rx_offload_wq = NULL;
2287 	}
2288 
2289 	/* DC Destroy TODO: Replace destroy DAL */
2290 	if (adev->dm.dc)
2291 		dc_destroy(&adev->dm.dc);
2292 	/*
2293 	 * TODO: pageflip, vlank interrupt
2294 	 *
2295 	 * amdgpu_dm_irq_fini(adev);
2296 	 */
2297 
2298 	if (adev->dm.cgs_device) {
2299 		amdgpu_cgs_destroy_device(adev->dm.cgs_device);
2300 		adev->dm.cgs_device = NULL;
2301 	}
2302 	if (adev->dm.freesync_module) {
2303 		mod_freesync_destroy(adev->dm.freesync_module);
2304 		adev->dm.freesync_module = NULL;
2305 	}
2306 
2307 	mutex_destroy(&adev->dm.audio_lock);
2308 	mutex_destroy(&adev->dm.dc_lock);
2309 	mutex_destroy(&adev->dm.dpia_aux_lock);
2310 }
2311 
load_dmcu_fw(struct amdgpu_device * adev)2312 static int load_dmcu_fw(struct amdgpu_device *adev)
2313 {
2314 	const char *fw_name_dmcu = NULL;
2315 	int r;
2316 	const struct dmcu_firmware_header_v1_0 *hdr;
2317 
2318 	switch (adev->asic_type) {
2319 #if defined(CONFIG_DRM_AMD_DC_SI)
2320 	case CHIP_TAHITI:
2321 	case CHIP_PITCAIRN:
2322 	case CHIP_VERDE:
2323 	case CHIP_OLAND:
2324 #endif
2325 	case CHIP_BONAIRE:
2326 	case CHIP_HAWAII:
2327 	case CHIP_KAVERI:
2328 	case CHIP_KABINI:
2329 	case CHIP_MULLINS:
2330 	case CHIP_TONGA:
2331 	case CHIP_FIJI:
2332 	case CHIP_CARRIZO:
2333 	case CHIP_STONEY:
2334 	case CHIP_POLARIS11:
2335 	case CHIP_POLARIS10:
2336 	case CHIP_POLARIS12:
2337 	case CHIP_VEGAM:
2338 	case CHIP_VEGA10:
2339 	case CHIP_VEGA12:
2340 	case CHIP_VEGA20:
2341 		return 0;
2342 	case CHIP_NAVI12:
2343 		fw_name_dmcu = FIRMWARE_NAVI12_DMCU;
2344 		break;
2345 	case CHIP_RAVEN:
2346 		if (ASICREV_IS_PICASSO(adev->external_rev_id))
2347 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2348 		else if (ASICREV_IS_RAVEN2(adev->external_rev_id))
2349 			fw_name_dmcu = FIRMWARE_RAVEN_DMCU;
2350 		else
2351 			return 0;
2352 		break;
2353 	default:
2354 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2355 		case IP_VERSION(2, 0, 2):
2356 		case IP_VERSION(2, 0, 3):
2357 		case IP_VERSION(2, 0, 0):
2358 		case IP_VERSION(2, 1, 0):
2359 		case IP_VERSION(3, 0, 0):
2360 		case IP_VERSION(3, 0, 2):
2361 		case IP_VERSION(3, 0, 3):
2362 		case IP_VERSION(3, 0, 1):
2363 		case IP_VERSION(3, 1, 2):
2364 		case IP_VERSION(3, 1, 3):
2365 		case IP_VERSION(3, 1, 4):
2366 		case IP_VERSION(3, 1, 5):
2367 		case IP_VERSION(3, 1, 6):
2368 		case IP_VERSION(3, 2, 0):
2369 		case IP_VERSION(3, 2, 1):
2370 		case IP_VERSION(3, 5, 0):
2371 		case IP_VERSION(3, 5, 1):
2372 		case IP_VERSION(3, 6, 0):
2373 		case IP_VERSION(4, 0, 1):
2374 			return 0;
2375 		default:
2376 			break;
2377 		}
2378 		drm_err(adev_to_drm(adev), "Unsupported ASIC type: 0x%X\n", adev->asic_type);
2379 		return -EINVAL;
2380 	}
2381 
2382 	if (adev->firmware.load_type != AMDGPU_FW_LOAD_PSP) {
2383 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not supported on direct or SMU loading\n");
2384 		return 0;
2385 	}
2386 
2387 	r = amdgpu_ucode_request(adev, &adev->dm.fw_dmcu, AMDGPU_UCODE_REQUIRED,
2388 				 "%s", fw_name_dmcu);
2389 	if (r == -ENODEV) {
2390 		/* DMCU firmware is not necessary, so don't raise a fuss if it's missing */
2391 		drm_dbg_kms(adev_to_drm(adev), "dm: DMCU firmware not found\n");
2392 		adev->dm.fw_dmcu = NULL;
2393 		return 0;
2394 	}
2395 	if (r) {
2396 		drm_err(adev_to_drm(adev), "amdgpu_dm: Can't validate firmware \"%s\"\n",
2397 			fw_name_dmcu);
2398 		amdgpu_ucode_release(&adev->dm.fw_dmcu);
2399 		return r;
2400 	}
2401 
2402 	hdr = (const struct dmcu_firmware_header_v1_0 *)adev->dm.fw_dmcu->data;
2403 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].ucode_id = AMDGPU_UCODE_ID_DMCU_ERAM;
2404 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_ERAM].fw = adev->dm.fw_dmcu;
2405 	adev->firmware.fw_size +=
2406 		ALIGN(le32_to_cpu(hdr->header.ucode_size_bytes) - le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2407 
2408 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].ucode_id = AMDGPU_UCODE_ID_DMCU_INTV;
2409 	adev->firmware.ucode[AMDGPU_UCODE_ID_DMCU_INTV].fw = adev->dm.fw_dmcu;
2410 	adev->firmware.fw_size +=
2411 		ALIGN(le32_to_cpu(hdr->intv_size_bytes), PAGE_SIZE);
2412 
2413 	adev->dm.dmcu_fw_version = le32_to_cpu(hdr->header.ucode_version);
2414 
2415 	drm_dbg_kms(adev_to_drm(adev), "PSP loading DMCU firmware\n");
2416 
2417 	return 0;
2418 }
2419 
amdgpu_dm_dmub_reg_read(void * ctx,uint32_t address)2420 static uint32_t amdgpu_dm_dmub_reg_read(void *ctx, uint32_t address)
2421 {
2422 	struct amdgpu_device *adev = ctx;
2423 
2424 	return dm_read_reg(adev->dm.dc->ctx, address);
2425 }
2426 
amdgpu_dm_dmub_reg_write(void * ctx,uint32_t address,uint32_t value)2427 static void amdgpu_dm_dmub_reg_write(void *ctx, uint32_t address,
2428 				     uint32_t value)
2429 {
2430 	struct amdgpu_device *adev = ctx;
2431 
2432 	return dm_write_reg(adev->dm.dc->ctx, address, value);
2433 }
2434 
dm_dmub_sw_init(struct amdgpu_device * adev)2435 static int dm_dmub_sw_init(struct amdgpu_device *adev)
2436 {
2437 	struct dmub_srv_create_params create_params;
2438 	struct dmub_srv_fw_meta_info_params fw_meta_info_params;
2439 	struct dmub_srv_region_params region_params;
2440 	struct dmub_srv_region_info region_info;
2441 	struct dmub_srv_memory_params memory_params;
2442 	struct dmub_fw_meta_info fw_info;
2443 	struct dmub_srv_fb_info *fb_info;
2444 	struct dmub_srv *dmub_srv;
2445 	const struct dmcub_firmware_header_v1_0 *hdr;
2446 	enum dmub_asic dmub_asic;
2447 	enum dmub_status status;
2448 	static enum dmub_window_memory_type window_memory_type[DMUB_WINDOW_TOTAL] = {
2449 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_0_INST_CONST
2450 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_1_STACK
2451 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_2_BSS_DATA
2452 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_3_VBIOS
2453 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_4_MAILBOX
2454 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_5_TRACEBUFF
2455 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_6_FW_STATE
2456 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_7_SCRATCH_MEM
2457 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_IB_MEM
2458 		DMUB_WINDOW_MEMORY_TYPE_FB,		//DMUB_WINDOW_SHARED_STATE
2459 	};
2460 	int r;
2461 
2462 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2463 	case IP_VERSION(2, 1, 0):
2464 		dmub_asic = DMUB_ASIC_DCN21;
2465 		break;
2466 	case IP_VERSION(3, 0, 0):
2467 		dmub_asic = DMUB_ASIC_DCN30;
2468 		break;
2469 	case IP_VERSION(3, 0, 1):
2470 		dmub_asic = DMUB_ASIC_DCN301;
2471 		break;
2472 	case IP_VERSION(3, 0, 2):
2473 		dmub_asic = DMUB_ASIC_DCN302;
2474 		break;
2475 	case IP_VERSION(3, 0, 3):
2476 		dmub_asic = DMUB_ASIC_DCN303;
2477 		break;
2478 	case IP_VERSION(3, 1, 2):
2479 	case IP_VERSION(3, 1, 3):
2480 		dmub_asic = (adev->external_rev_id == YELLOW_CARP_B0) ? DMUB_ASIC_DCN31B : DMUB_ASIC_DCN31;
2481 		break;
2482 	case IP_VERSION(3, 1, 4):
2483 		dmub_asic = DMUB_ASIC_DCN314;
2484 		break;
2485 	case IP_VERSION(3, 1, 5):
2486 		dmub_asic = DMUB_ASIC_DCN315;
2487 		break;
2488 	case IP_VERSION(3, 1, 6):
2489 		dmub_asic = DMUB_ASIC_DCN316;
2490 		break;
2491 	case IP_VERSION(3, 2, 0):
2492 		dmub_asic = DMUB_ASIC_DCN32;
2493 		break;
2494 	case IP_VERSION(3, 2, 1):
2495 		dmub_asic = DMUB_ASIC_DCN321;
2496 		break;
2497 	case IP_VERSION(3, 5, 0):
2498 	case IP_VERSION(3, 5, 1):
2499 		dmub_asic = DMUB_ASIC_DCN35;
2500 		break;
2501 	case IP_VERSION(3, 6, 0):
2502 		dmub_asic = DMUB_ASIC_DCN36;
2503 		break;
2504 	case IP_VERSION(4, 0, 1):
2505 		dmub_asic = DMUB_ASIC_DCN401;
2506 		break;
2507 
2508 	default:
2509 		/* ASIC doesn't support DMUB. */
2510 		return 0;
2511 	}
2512 
2513 	hdr = (const struct dmcub_firmware_header_v1_0 *)adev->dm.dmub_fw->data;
2514 	adev->dm.dmcub_fw_version = le32_to_cpu(hdr->header.ucode_version);
2515 
2516 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
2517 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].ucode_id =
2518 			AMDGPU_UCODE_ID_DMCUB;
2519 		adev->firmware.ucode[AMDGPU_UCODE_ID_DMCUB].fw =
2520 			adev->dm.dmub_fw;
2521 		adev->firmware.fw_size +=
2522 			ALIGN(le32_to_cpu(hdr->inst_const_bytes), PAGE_SIZE);
2523 
2524 		drm_info(adev_to_drm(adev), "Loading DMUB firmware via PSP: version=0x%08X\n",
2525 			 adev->dm.dmcub_fw_version);
2526 	}
2527 
2528 
2529 	adev->dm.dmub_srv = kzalloc_obj(*adev->dm.dmub_srv, GFP_KERNEL);
2530 	dmub_srv = adev->dm.dmub_srv;
2531 
2532 	if (!dmub_srv) {
2533 		drm_err(adev_to_drm(adev), "Failed to allocate DMUB service!\n");
2534 		return -ENOMEM;
2535 	}
2536 
2537 	memset(&create_params, 0, sizeof(create_params));
2538 	create_params.user_ctx = adev;
2539 	create_params.funcs.reg_read = amdgpu_dm_dmub_reg_read;
2540 	create_params.funcs.reg_write = amdgpu_dm_dmub_reg_write;
2541 	create_params.asic = dmub_asic;
2542 
2543 	/* Create the DMUB service. */
2544 	status = dmub_srv_create(dmub_srv, &create_params);
2545 	if (status != DMUB_STATUS_OK) {
2546 		drm_err(adev_to_drm(adev), "Error creating DMUB service: %d\n", status);
2547 		return -EINVAL;
2548 	}
2549 
2550 	/* Extract the FW meta info. */
2551 	memset(&fw_meta_info_params, 0, sizeof(fw_meta_info_params));
2552 
2553 	fw_meta_info_params.inst_const_size = le32_to_cpu(hdr->inst_const_bytes) -
2554 					      PSP_HEADER_BYTES_256;
2555 	fw_meta_info_params.bss_data_size = le32_to_cpu(hdr->bss_data_bytes);
2556 	fw_meta_info_params.fw_inst_const = adev->dm.dmub_fw->data +
2557 					    le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2558 					    PSP_HEADER_BYTES_256;
2559 	fw_meta_info_params.fw_bss_data = region_params.bss_data_size ? adev->dm.dmub_fw->data +
2560 					  le32_to_cpu(hdr->header.ucode_array_offset_bytes) +
2561 					  le32_to_cpu(hdr->inst_const_bytes) : NULL;
2562 	fw_meta_info_params.custom_psp_footer_size = 0;
2563 
2564 	status = dmub_srv_get_fw_meta_info_from_raw_fw(&fw_meta_info_params, &fw_info);
2565 	if (status != DMUB_STATUS_OK) {
2566 		/* Skip returning early, just log the error. */
2567 		drm_err(adev_to_drm(adev), "Error getting DMUB FW meta info: %d\n", status);
2568 		// return -EINVAL;
2569 	}
2570 
2571 	/* Calculate the size of all the regions for the DMUB service. */
2572 	memset(&region_params, 0, sizeof(region_params));
2573 
2574 	region_params.inst_const_size = fw_meta_info_params.inst_const_size;
2575 	region_params.bss_data_size = fw_meta_info_params.bss_data_size;
2576 	region_params.vbios_size = adev->bios_size;
2577 	region_params.fw_bss_data = fw_meta_info_params.fw_bss_data;
2578 	region_params.fw_inst_const = fw_meta_info_params.fw_inst_const;
2579 	region_params.window_memory_type = window_memory_type;
2580 	region_params.fw_info = (status == DMUB_STATUS_OK) ? &fw_info : NULL;
2581 
2582 	status = dmub_srv_calc_region_info(dmub_srv, &region_params,
2583 					   &region_info);
2584 
2585 	if (status != DMUB_STATUS_OK) {
2586 		drm_err(adev_to_drm(adev), "Error calculating DMUB region info: %d\n", status);
2587 		return -EINVAL;
2588 	}
2589 
2590 	/*
2591 	 * Allocate a framebuffer based on the total size of all the regions.
2592 	 * TODO: Move this into GART.
2593 	 */
2594 	r = amdgpu_bo_create_kernel(adev, region_info.fb_size, PAGE_SIZE,
2595 				    AMDGPU_GEM_DOMAIN_VRAM |
2596 				    AMDGPU_GEM_DOMAIN_GTT,
2597 				    &adev->dm.dmub_bo,
2598 				    &adev->dm.dmub_bo_gpu_addr,
2599 				    &adev->dm.dmub_bo_cpu_addr);
2600 	if (r)
2601 		return r;
2602 
2603 	/* Rebase the regions on the framebuffer address. */
2604 	memset(&memory_params, 0, sizeof(memory_params));
2605 	memory_params.cpu_fb_addr = adev->dm.dmub_bo_cpu_addr;
2606 	memory_params.gpu_fb_addr = adev->dm.dmub_bo_gpu_addr;
2607 	memory_params.region_info = &region_info;
2608 	memory_params.window_memory_type = window_memory_type;
2609 
2610 	adev->dm.dmub_fb_info = kzalloc_obj(*adev->dm.dmub_fb_info, GFP_KERNEL);
2611 	fb_info = adev->dm.dmub_fb_info;
2612 
2613 	if (!fb_info) {
2614 		drm_err(adev_to_drm(adev),
2615 			"Failed to allocate framebuffer info for DMUB service!\n");
2616 		return -ENOMEM;
2617 	}
2618 
2619 	status = dmub_srv_calc_mem_info(dmub_srv, &memory_params, fb_info);
2620 	if (status != DMUB_STATUS_OK) {
2621 		drm_err(adev_to_drm(adev), "Error calculating DMUB FB info: %d\n", status);
2622 		return -EINVAL;
2623 	}
2624 
2625 	adev->dm.bb_from_dmub = dm_dmub_get_vbios_bounding_box(adev);
2626 	adev->dm.fw_inst_size = fw_meta_info_params.inst_const_size;
2627 
2628 	return 0;
2629 }
2630 
dm_sw_init(struct amdgpu_ip_block * ip_block)2631 static int dm_sw_init(struct amdgpu_ip_block *ip_block)
2632 {
2633 	struct amdgpu_device *adev = ip_block->adev;
2634 	int r;
2635 
2636 	adev->dm.cgs_device = amdgpu_cgs_create_device(adev);
2637 
2638 	if (!adev->dm.cgs_device) {
2639 		drm_err(adev_to_drm(adev), "failed to create cgs device.\n");
2640 		return -EINVAL;
2641 	}
2642 
2643 	/* Moved from dm init since we need to use allocations for storing bounding box data */
2644 	INIT_LIST_HEAD(&adev->dm.da_list);
2645 
2646 	r = dm_dmub_sw_init(adev);
2647 	if (r)
2648 		return r;
2649 
2650 	return load_dmcu_fw(adev);
2651 }
2652 
dm_sw_fini(struct amdgpu_ip_block * ip_block)2653 static int dm_sw_fini(struct amdgpu_ip_block *ip_block)
2654 {
2655 	struct amdgpu_device *adev = ip_block->adev;
2656 	struct dal_allocation *da;
2657 
2658 	list_for_each_entry(da, &adev->dm.da_list, list) {
2659 		if (adev->dm.bb_from_dmub == (void *) da->cpu_ptr) {
2660 			amdgpu_bo_free_kernel(&da->bo, &da->gpu_addr, &da->cpu_ptr);
2661 			list_del(&da->list);
2662 			kfree(da);
2663 			adev->dm.bb_from_dmub = NULL;
2664 			break;
2665 		}
2666 	}
2667 
2668 
2669 	kfree(adev->dm.dmub_fb_info);
2670 	adev->dm.dmub_fb_info = NULL;
2671 
2672 	if (adev->dm.dmub_srv) {
2673 		dmub_srv_destroy(adev->dm.dmub_srv);
2674 		kfree(adev->dm.dmub_srv);
2675 		adev->dm.dmub_srv = NULL;
2676 	}
2677 
2678 	amdgpu_ucode_release(&adev->dm.dmub_fw);
2679 	amdgpu_ucode_release(&adev->dm.fw_dmcu);
2680 
2681 	return 0;
2682 }
2683 
detect_mst_link_for_all_connectors(struct drm_device * dev)2684 static int detect_mst_link_for_all_connectors(struct drm_device *dev)
2685 {
2686 	struct amdgpu_dm_connector *aconnector;
2687 	struct drm_connector *connector;
2688 	struct drm_connector_list_iter iter;
2689 	int ret = 0;
2690 
2691 	drm_connector_list_iter_begin(dev, &iter);
2692 	drm_for_each_connector_iter(connector, &iter) {
2693 
2694 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2695 			continue;
2696 
2697 		aconnector = to_amdgpu_dm_connector(connector);
2698 		if (aconnector->dc_link->type == dc_connection_mst_branch &&
2699 		    aconnector->mst_mgr.aux) {
2700 			drm_dbg_kms(dev, "DM_MST: starting TM on aconnector: %p [id: %d]\n",
2701 					 aconnector,
2702 					 aconnector->base.base.id);
2703 
2704 			ret = drm_dp_mst_topology_mgr_set_mst(&aconnector->mst_mgr, true);
2705 			if (ret < 0) {
2706 				drm_err(dev, "DM_MST: Failed to start MST\n");
2707 				aconnector->dc_link->type =
2708 					dc_connection_single;
2709 				ret = dm_helpers_dp_mst_stop_top_mgr(aconnector->dc_link->ctx,
2710 								     aconnector->dc_link);
2711 				break;
2712 			}
2713 		}
2714 	}
2715 	drm_connector_list_iter_end(&iter);
2716 
2717 	return ret;
2718 }
2719 
dm_late_init(struct amdgpu_ip_block * ip_block)2720 static int dm_late_init(struct amdgpu_ip_block *ip_block)
2721 {
2722 	struct amdgpu_device *adev = ip_block->adev;
2723 
2724 	struct dmcu_iram_parameters params;
2725 	unsigned int linear_lut[16];
2726 	int i;
2727 	struct dmcu *dmcu = NULL;
2728 
2729 	dmcu = adev->dm.dc->res_pool->dmcu;
2730 
2731 	for (i = 0; i < 16; i++)
2732 		linear_lut[i] = 0xFFFF * i / 15;
2733 
2734 	params.set = 0;
2735 	params.backlight_ramping_override = false;
2736 	params.backlight_ramping_start = 0xCCCC;
2737 	params.backlight_ramping_reduction = 0xCCCCCCCC;
2738 	params.backlight_lut_array_size = 16;
2739 	params.backlight_lut_array = linear_lut;
2740 
2741 	/* Min backlight level after ABM reduction,  Don't allow below 1%
2742 	 * 0xFFFF x 0.01 = 0x28F
2743 	 */
2744 	params.min_abm_backlight = 0x28F;
2745 	/* In the case where abm is implemented on dmcub,
2746 	 * dmcu object will be null.
2747 	 * ABM 2.4 and up are implemented on dmcub.
2748 	 */
2749 	if (dmcu) {
2750 		if (!dmcu_load_iram(dmcu, params))
2751 			return -EINVAL;
2752 	} else if (adev->dm.dc->ctx->dmub_srv) {
2753 		struct dc_link *edp_links[MAX_NUM_EDP];
2754 		int edp_num;
2755 
2756 		dc_get_edp_links(adev->dm.dc, edp_links, &edp_num);
2757 		for (i = 0; i < edp_num; i++) {
2758 			if (!dmub_init_abm_config(adev->dm.dc->res_pool, params, i))
2759 				return -EINVAL;
2760 		}
2761 	}
2762 
2763 	return detect_mst_link_for_all_connectors(adev_to_drm(adev));
2764 }
2765 
resume_mst_branch_status(struct drm_dp_mst_topology_mgr * mgr)2766 static void resume_mst_branch_status(struct drm_dp_mst_topology_mgr *mgr)
2767 {
2768 	u8 buf[UUID_SIZE];
2769 	guid_t guid;
2770 	int ret;
2771 
2772 	mutex_lock(&mgr->lock);
2773 	if (!mgr->mst_primary)
2774 		goto out_fail;
2775 
2776 	if (drm_dp_read_dpcd_caps(mgr->aux, mgr->dpcd) < 0) {
2777 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2778 		goto out_fail;
2779 	}
2780 
2781 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
2782 				 DP_MST_EN |
2783 				 DP_UP_REQ_EN |
2784 				 DP_UPSTREAM_IS_SRC);
2785 	if (ret < 0) {
2786 		drm_dbg_kms(mgr->dev, "mst write failed - undocked during suspend?\n");
2787 		goto out_fail;
2788 	}
2789 
2790 	/* Some hubs forget their guids after they resume */
2791 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, buf, sizeof(buf));
2792 	if (ret != sizeof(buf)) {
2793 		drm_dbg_kms(mgr->dev, "dpcd read failed - undocked during suspend?\n");
2794 		goto out_fail;
2795 	}
2796 
2797 	import_guid(&guid, buf);
2798 
2799 	if (guid_is_null(&guid)) {
2800 		guid_gen(&guid);
2801 		export_guid(buf, &guid);
2802 
2803 		ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, buf, sizeof(buf));
2804 
2805 		if (ret != sizeof(buf)) {
2806 			drm_dbg_kms(mgr->dev, "check mstb guid failed - undocked during suspend?\n");
2807 			goto out_fail;
2808 		}
2809 	}
2810 
2811 	guid_copy(&mgr->mst_primary->guid, &guid);
2812 
2813 out_fail:
2814 	mutex_unlock(&mgr->lock);
2815 }
2816 
hdmi_cec_unset_edid(struct amdgpu_dm_connector * aconnector)2817 void hdmi_cec_unset_edid(struct amdgpu_dm_connector *aconnector)
2818 {
2819 	struct cec_notifier *n = aconnector->notifier;
2820 
2821 	if (!n)
2822 		return;
2823 
2824 	cec_notifier_phys_addr_invalidate(n);
2825 }
2826 
hdmi_cec_set_edid(struct amdgpu_dm_connector * aconnector)2827 void hdmi_cec_set_edid(struct amdgpu_dm_connector *aconnector)
2828 {
2829 	struct drm_connector *connector = &aconnector->base;
2830 	struct cec_notifier *n = aconnector->notifier;
2831 
2832 	if (!n)
2833 		return;
2834 
2835 	cec_notifier_set_phys_addr(n,
2836 				   connector->display_info.source_physical_address);
2837 }
2838 
s3_handle_hdmi_cec(struct drm_device * ddev,bool suspend)2839 static void s3_handle_hdmi_cec(struct drm_device *ddev, bool suspend)
2840 {
2841 	struct amdgpu_dm_connector *aconnector;
2842 	struct drm_connector *connector;
2843 	struct drm_connector_list_iter conn_iter;
2844 
2845 	drm_connector_list_iter_begin(ddev, &conn_iter);
2846 	drm_for_each_connector_iter(connector, &conn_iter) {
2847 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2848 			continue;
2849 
2850 		aconnector = to_amdgpu_dm_connector(connector);
2851 		if (suspend)
2852 			hdmi_cec_unset_edid(aconnector);
2853 		else
2854 			hdmi_cec_set_edid(aconnector);
2855 	}
2856 	drm_connector_list_iter_end(&conn_iter);
2857 }
2858 
s3_handle_mst(struct drm_device * dev,bool suspend)2859 static void s3_handle_mst(struct drm_device *dev, bool suspend)
2860 {
2861 	struct amdgpu_dm_connector *aconnector;
2862 	struct drm_connector *connector;
2863 	struct drm_connector_list_iter iter;
2864 	struct drm_dp_mst_topology_mgr *mgr;
2865 
2866 	drm_connector_list_iter_begin(dev, &iter);
2867 	drm_for_each_connector_iter(connector, &iter) {
2868 
2869 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
2870 			continue;
2871 
2872 		aconnector = to_amdgpu_dm_connector(connector);
2873 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
2874 		    aconnector->mst_root)
2875 			continue;
2876 
2877 		mgr = &aconnector->mst_mgr;
2878 
2879 		if (suspend) {
2880 			drm_dp_mst_topology_mgr_suspend(mgr);
2881 		} else {
2882 			/* if extended timeout is supported in hardware,
2883 			 * default to LTTPR timeout (3.2ms) first as a W/A for DP link layer
2884 			 * CTS 4.2.1.1 regression introduced by CTS specs requirement update.
2885 			 */
2886 			try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_LTTPR_TIMEOUT_PERIOD);
2887 			if (!dp_is_lttpr_present(aconnector->dc_link))
2888 				try_to_configure_aux_timeout(aconnector->dc_link->ddc, LINK_AUX_DEFAULT_TIMEOUT_PERIOD);
2889 
2890 			/* TODO: move resume_mst_branch_status() into drm mst resume again
2891 			 * once topology probing work is pulled out from mst resume into mst
2892 			 * resume 2nd step. mst resume 2nd step should be called after old
2893 			 * state getting restored (i.e. drm_atomic_helper_resume()).
2894 			 */
2895 			resume_mst_branch_status(mgr);
2896 		}
2897 	}
2898 	drm_connector_list_iter_end(&iter);
2899 }
2900 
amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device * adev)2901 static int amdgpu_dm_smu_write_watermarks_table(struct amdgpu_device *adev)
2902 {
2903 	int ret = 0;
2904 
2905 	/* This interface is for dGPU Navi1x.Linux dc-pplib interface depends
2906 	 * on window driver dc implementation.
2907 	 * For Navi1x, clock settings of dcn watermarks are fixed. the settings
2908 	 * should be passed to smu during boot up and resume from s3.
2909 	 * boot up: dc calculate dcn watermark clock settings within dc_create,
2910 	 * dcn20_resource_construct
2911 	 * then call pplib functions below to pass the settings to smu:
2912 	 * smu_set_watermarks_for_clock_ranges
2913 	 * smu_set_watermarks_table
2914 	 * navi10_set_watermarks_table
2915 	 * smu_write_watermarks_table
2916 	 *
2917 	 * For Renoir, clock settings of dcn watermark are also fixed values.
2918 	 * dc has implemented different flow for window driver:
2919 	 * dc_hardware_init / dc_set_power_state
2920 	 * dcn10_init_hw
2921 	 * notify_wm_ranges
2922 	 * set_wm_ranges
2923 	 * -- Linux
2924 	 * smu_set_watermarks_for_clock_ranges
2925 	 * renoir_set_watermarks_table
2926 	 * smu_write_watermarks_table
2927 	 *
2928 	 * For Linux,
2929 	 * dc_hardware_init -> amdgpu_dm_init
2930 	 * dc_set_power_state --> dm_resume
2931 	 *
2932 	 * therefore, this function apply to navi10/12/14 but not Renoir
2933 	 * *
2934 	 */
2935 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
2936 	case IP_VERSION(2, 0, 2):
2937 	case IP_VERSION(2, 0, 0):
2938 		break;
2939 	default:
2940 		return 0;
2941 	}
2942 
2943 	ret = amdgpu_dpm_write_watermarks_table(adev);
2944 	if (ret) {
2945 		drm_err(adev_to_drm(adev), "Failed to update WMTABLE!\n");
2946 		return ret;
2947 	}
2948 
2949 	return 0;
2950 }
2951 
dm_oem_i2c_hw_init(struct amdgpu_device * adev)2952 static int dm_oem_i2c_hw_init(struct amdgpu_device *adev)
2953 {
2954 	struct amdgpu_display_manager *dm = &adev->dm;
2955 	struct amdgpu_i2c_adapter *oem_i2c;
2956 	struct ddc_service *oem_ddc_service;
2957 	int r;
2958 
2959 	oem_ddc_service = dc_get_oem_i2c_device(adev->dm.dc);
2960 	if (oem_ddc_service) {
2961 		oem_i2c = create_i2c(oem_ddc_service, true);
2962 		if (!oem_i2c) {
2963 			drm_info(adev_to_drm(adev), "Failed to create oem i2c adapter data\n");
2964 			return -ENOMEM;
2965 		}
2966 
2967 		r = devm_i2c_add_adapter(adev->dev, &oem_i2c->base);
2968 		if (r) {
2969 			drm_info(adev_to_drm(adev), "Failed to register oem i2c\n");
2970 			kfree(oem_i2c);
2971 			return r;
2972 		}
2973 		dm->oem_i2c = oem_i2c;
2974 	}
2975 
2976 	return 0;
2977 }
2978 
2979 /**
2980  * dm_hw_init() - Initialize DC device
2981  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
2982  *
2983  * Initialize the &struct amdgpu_display_manager device. This involves calling
2984  * the initializers of each DM component, then populating the struct with them.
2985  *
2986  * Although the function implies hardware initialization, both hardware and
2987  * software are initialized here. Splitting them out to their relevant init
2988  * hooks is a future TODO item.
2989  *
2990  * Some notable things that are initialized here:
2991  *
2992  * - Display Core, both software and hardware
2993  * - DC modules that we need (freesync and color management)
2994  * - DRM software states
2995  * - Interrupt sources and handlers
2996  * - Vblank support
2997  * - Debug FS entries, if enabled
2998  */
dm_hw_init(struct amdgpu_ip_block * ip_block)2999 static int dm_hw_init(struct amdgpu_ip_block *ip_block)
3000 {
3001 	struct amdgpu_device *adev = ip_block->adev;
3002 	int r;
3003 
3004 	/* Create DAL display manager */
3005 	r = amdgpu_dm_init(adev);
3006 	if (r)
3007 		return r;
3008 	amdgpu_dm_hpd_init(adev);
3009 
3010 	r = dm_oem_i2c_hw_init(adev);
3011 	if (r)
3012 		drm_info(adev_to_drm(adev), "Failed to add OEM i2c bus\n");
3013 
3014 	return 0;
3015 }
3016 
3017 /**
3018  * dm_hw_fini() - Teardown DC device
3019  * @ip_block: Pointer to the amdgpu_ip_block for this hw instance.
3020  *
3021  * Teardown components within &struct amdgpu_display_manager that require
3022  * cleanup. This involves cleaning up the DRM device, DC, and any modules that
3023  * were loaded. Also flush IRQ workqueues and disable them.
3024  */
dm_hw_fini(struct amdgpu_ip_block * ip_block)3025 static int dm_hw_fini(struct amdgpu_ip_block *ip_block)
3026 {
3027 	struct amdgpu_device *adev = ip_block->adev;
3028 
3029 	amdgpu_dm_hpd_fini(adev);
3030 
3031 	amdgpu_dm_irq_fini(adev);
3032 	amdgpu_dm_fini(adev);
3033 	return 0;
3034 }
3035 
3036 
dm_gpureset_toggle_interrupts(struct amdgpu_device * adev,struct dc_state * state,bool enable)3037 static void dm_gpureset_toggle_interrupts(struct amdgpu_device *adev,
3038 				 struct dc_state *state, bool enable)
3039 {
3040 	enum dc_irq_source irq_source;
3041 	struct amdgpu_crtc *acrtc;
3042 	int rc = -EBUSY;
3043 	int i = 0;
3044 
3045 	for (i = 0; i < state->stream_count; i++) {
3046 		acrtc = get_crtc_by_otg_inst(
3047 				adev, state->stream_status[i].primary_otg_inst);
3048 
3049 		if (acrtc && state->stream_status[i].plane_count != 0) {
3050 			irq_source = IRQ_TYPE_PFLIP + acrtc->otg_inst;
3051 			rc = dc_interrupt_set(adev->dm.dc, irq_source, enable) ? 0 : -EBUSY;
3052 			if (rc)
3053 				drm_warn(adev_to_drm(adev), "Failed to %s pflip interrupts\n",
3054 					 enable ? "enable" : "disable");
3055 
3056 			if (dc_supports_vrr(adev->dm.dc->ctx->dce_version)) {
3057 				if (enable) {
3058 					if (amdgpu_dm_crtc_vrr_active(
3059 							to_dm_crtc_state(acrtc->base.state)))
3060 						rc = amdgpu_dm_crtc_set_vupdate_irq(
3061 							&acrtc->base, true);
3062 				} else
3063 					rc = amdgpu_dm_crtc_set_vupdate_irq(
3064 							&acrtc->base, false);
3065 
3066 				if (rc)
3067 					drm_warn(adev_to_drm(adev), "Failed to %sable vupdate interrupt\n",
3068 						enable ? "en" : "dis");
3069 			}
3070 
3071 			irq_source = IRQ_TYPE_VBLANK + acrtc->otg_inst;
3072 			/* During gpu-reset we disable and then enable vblank irq, so
3073 			 * don't use amdgpu_irq_get/put() to avoid refcount change.
3074 			 */
3075 			if (!dc_interrupt_set(adev->dm.dc, irq_source, enable))
3076 				drm_warn(adev_to_drm(adev), "Failed to %sable vblank interrupt\n", enable ? "en" : "dis");
3077 		}
3078 	}
3079 
3080 }
3081 
DEFINE_FREE(state_release,struct dc_state *,if (_T)dc_state_release (_T))3082 DEFINE_FREE(state_release, struct dc_state *, if (_T) dc_state_release(_T))
3083 
3084 static enum dc_status amdgpu_dm_commit_zero_streams(struct dc *dc)
3085 {
3086 	struct dc_state *context __free(state_release) = NULL;
3087 	int i;
3088 	struct dc_stream_state *del_streams[MAX_PIPES];
3089 	int del_streams_count = 0;
3090 	struct dc_commit_streams_params params = {};
3091 
3092 	memset(del_streams, 0, sizeof(del_streams));
3093 
3094 	context = dc_state_create_current_copy(dc);
3095 	if (context == NULL)
3096 		return DC_ERROR_UNEXPECTED;
3097 
3098 	/* First remove from context all streams */
3099 	for (i = 0; i < context->stream_count; i++) {
3100 		struct dc_stream_state *stream = context->streams[i];
3101 
3102 		del_streams[del_streams_count++] = stream;
3103 	}
3104 
3105 	/* Remove all planes for removed streams and then remove the streams */
3106 	for (i = 0; i < del_streams_count; i++) {
3107 		enum dc_status res;
3108 
3109 		if (!dc_state_rem_all_planes_for_stream(dc, del_streams[i], context))
3110 			return DC_FAIL_DETACH_SURFACES;
3111 
3112 		res = dc_state_remove_stream(dc, context, del_streams[i]);
3113 		if (res != DC_OK)
3114 			return res;
3115 	}
3116 
3117 	params.streams = context->streams;
3118 	params.stream_count = context->stream_count;
3119 
3120 	return dc_commit_streams(dc, &params);
3121 }
3122 
hpd_rx_irq_work_suspend(struct amdgpu_display_manager * dm)3123 static void hpd_rx_irq_work_suspend(struct amdgpu_display_manager *dm)
3124 {
3125 	int i;
3126 
3127 	if (dm->hpd_rx_offload_wq) {
3128 		for (i = 0; i < dm->dc->caps.max_links; i++)
3129 			flush_workqueue(dm->hpd_rx_offload_wq[i].wq);
3130 	}
3131 }
3132 
dm_cache_state(struct amdgpu_device * adev)3133 static int dm_cache_state(struct amdgpu_device *adev)
3134 {
3135 	int r;
3136 
3137 	adev->dm.cached_state = drm_atomic_helper_suspend(adev_to_drm(adev));
3138 	if (IS_ERR(adev->dm.cached_state)) {
3139 		r = PTR_ERR(adev->dm.cached_state);
3140 		adev->dm.cached_state = NULL;
3141 	}
3142 
3143 	return adev->dm.cached_state ? 0 : r;
3144 }
3145 
dm_destroy_cached_state(struct amdgpu_device * adev)3146 static void dm_destroy_cached_state(struct amdgpu_device *adev)
3147 {
3148 	struct amdgpu_display_manager *dm = &adev->dm;
3149 	struct drm_device *ddev = adev_to_drm(adev);
3150 	struct dm_plane_state *dm_new_plane_state;
3151 	struct drm_plane_state *new_plane_state;
3152 	struct dm_crtc_state *dm_new_crtc_state;
3153 	struct drm_crtc_state *new_crtc_state;
3154 	struct drm_plane *plane;
3155 	struct drm_crtc *crtc;
3156 	int i;
3157 
3158 	if (!dm->cached_state)
3159 		return;
3160 
3161 	/* Force mode set in atomic commit */
3162 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3163 		new_crtc_state->active_changed = true;
3164 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3165 		reset_freesync_config_for_crtc(dm_new_crtc_state);
3166 	}
3167 
3168 	/*
3169 	 * atomic_check is expected to create the dc states. We need to release
3170 	 * them here, since they were duplicated as part of the suspend
3171 	 * procedure.
3172 	 */
3173 	for_each_new_crtc_in_state(dm->cached_state, crtc, new_crtc_state, i) {
3174 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
3175 		if (dm_new_crtc_state->stream) {
3176 			WARN_ON(kref_read(&dm_new_crtc_state->stream->refcount) > 1);
3177 			dc_stream_release(dm_new_crtc_state->stream);
3178 			dm_new_crtc_state->stream = NULL;
3179 		}
3180 		dm_new_crtc_state->base.color_mgmt_changed = true;
3181 	}
3182 
3183 	for_each_new_plane_in_state(dm->cached_state, plane, new_plane_state, i) {
3184 		dm_new_plane_state = to_dm_plane_state(new_plane_state);
3185 		if (dm_new_plane_state->dc_state) {
3186 			WARN_ON(kref_read(&dm_new_plane_state->dc_state->refcount) > 1);
3187 			dc_plane_state_release(dm_new_plane_state->dc_state);
3188 			dm_new_plane_state->dc_state = NULL;
3189 		}
3190 	}
3191 
3192 	drm_atomic_helper_resume(ddev, dm->cached_state);
3193 
3194 	dm->cached_state = NULL;
3195 }
3196 
dm_suspend(struct amdgpu_ip_block * ip_block)3197 static int dm_suspend(struct amdgpu_ip_block *ip_block)
3198 {
3199 	struct amdgpu_device *adev = ip_block->adev;
3200 	struct amdgpu_display_manager *dm = &adev->dm;
3201 
3202 	if (amdgpu_in_reset(adev)) {
3203 		enum dc_status res;
3204 
3205 		mutex_lock(&dm->dc_lock);
3206 
3207 		dc_allow_idle_optimizations(adev->dm.dc, false);
3208 
3209 		dm->cached_dc_state = dc_state_create_copy(dm->dc->current_state);
3210 
3211 		if (dm->cached_dc_state)
3212 			dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, false);
3213 
3214 		res = amdgpu_dm_commit_zero_streams(dm->dc);
3215 		if (res != DC_OK) {
3216 			drm_err(adev_to_drm(adev), "Failed to commit zero streams: %d\n", res);
3217 			return -EINVAL;
3218 		}
3219 
3220 		amdgpu_dm_irq_suspend(adev);
3221 
3222 		hpd_rx_irq_work_suspend(dm);
3223 
3224 		return 0;
3225 	}
3226 
3227 	if (!adev->dm.cached_state) {
3228 		int r = dm_cache_state(adev);
3229 
3230 		if (r)
3231 			return r;
3232 	}
3233 
3234 	s3_handle_hdmi_cec(adev_to_drm(adev), true);
3235 
3236 	s3_handle_mst(adev_to_drm(adev), true);
3237 
3238 	amdgpu_dm_irq_suspend(adev);
3239 
3240 	hpd_rx_irq_work_suspend(dm);
3241 
3242 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D3);
3243 
3244 	if (dm->dc->caps.ips_support && adev->in_s0ix)
3245 		dc_allow_idle_optimizations(dm->dc, true);
3246 
3247 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D3);
3248 
3249 	return 0;
3250 }
3251 
3252 struct drm_connector *
amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state * state,struct drm_crtc * crtc)3253 amdgpu_dm_find_first_crtc_matching_connector(struct drm_atomic_state *state,
3254 					     struct drm_crtc *crtc)
3255 {
3256 	u32 i;
3257 	struct drm_connector_state *new_con_state;
3258 	struct drm_connector *connector;
3259 	struct drm_crtc *crtc_from_state;
3260 
3261 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
3262 		crtc_from_state = new_con_state->crtc;
3263 
3264 		if (crtc_from_state == crtc)
3265 			return connector;
3266 	}
3267 
3268 	return NULL;
3269 }
3270 
emulated_link_detect(struct dc_link * link)3271 static void emulated_link_detect(struct dc_link *link)
3272 {
3273 	struct dc_sink_init_data sink_init_data = { 0 };
3274 	struct display_sink_capability sink_caps = { 0 };
3275 	enum dc_edid_status edid_status;
3276 	struct dc_context *dc_ctx = link->ctx;
3277 	struct drm_device *dev = adev_to_drm(dc_ctx->driver_context);
3278 	struct dc_sink *sink = NULL;
3279 	struct dc_sink *prev_sink = NULL;
3280 
3281 	link->type = dc_connection_none;
3282 	prev_sink = link->local_sink;
3283 
3284 	if (prev_sink)
3285 		dc_sink_release(prev_sink);
3286 
3287 	switch (link->connector_signal) {
3288 	case SIGNAL_TYPE_HDMI_TYPE_A: {
3289 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3290 		sink_caps.signal = SIGNAL_TYPE_HDMI_TYPE_A;
3291 		break;
3292 	}
3293 
3294 	case SIGNAL_TYPE_DVI_SINGLE_LINK: {
3295 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3296 		sink_caps.signal = SIGNAL_TYPE_DVI_SINGLE_LINK;
3297 		break;
3298 	}
3299 
3300 	case SIGNAL_TYPE_DVI_DUAL_LINK: {
3301 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3302 		sink_caps.signal = SIGNAL_TYPE_DVI_DUAL_LINK;
3303 		break;
3304 	}
3305 
3306 	case SIGNAL_TYPE_LVDS: {
3307 		sink_caps.transaction_type = DDC_TRANSACTION_TYPE_I2C;
3308 		sink_caps.signal = SIGNAL_TYPE_LVDS;
3309 		break;
3310 	}
3311 
3312 	case SIGNAL_TYPE_EDP: {
3313 		sink_caps.transaction_type =
3314 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3315 		sink_caps.signal = SIGNAL_TYPE_EDP;
3316 		break;
3317 	}
3318 
3319 	case SIGNAL_TYPE_DISPLAY_PORT: {
3320 		sink_caps.transaction_type =
3321 			DDC_TRANSACTION_TYPE_I2C_OVER_AUX;
3322 		sink_caps.signal = SIGNAL_TYPE_VIRTUAL;
3323 		break;
3324 	}
3325 
3326 	default:
3327 		drm_err(dev, "Invalid connector type! signal:%d\n",
3328 			link->connector_signal);
3329 		return;
3330 	}
3331 
3332 	sink_init_data.link = link;
3333 	sink_init_data.sink_signal = sink_caps.signal;
3334 
3335 	sink = dc_sink_create(&sink_init_data);
3336 	if (!sink) {
3337 		drm_err(dev, "Failed to create sink!\n");
3338 		return;
3339 	}
3340 
3341 	/* dc_sink_create returns a new reference */
3342 	link->local_sink = sink;
3343 
3344 	edid_status = dm_helpers_read_local_edid(
3345 			link->ctx,
3346 			link,
3347 			sink);
3348 
3349 	if (edid_status != EDID_OK)
3350 		drm_err(dev, "Failed to read EDID\n");
3351 
3352 }
3353 
dm_gpureset_commit_state(struct dc_state * dc_state,struct amdgpu_display_manager * dm)3354 static void dm_gpureset_commit_state(struct dc_state *dc_state,
3355 				     struct amdgpu_display_manager *dm)
3356 {
3357 	struct {
3358 		struct dc_surface_update surface_updates[MAX_SURFACES];
3359 		struct dc_plane_info plane_infos[MAX_SURFACES];
3360 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
3361 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
3362 		struct dc_stream_update stream_update;
3363 	} *bundle __free(kfree);
3364 	int k, m;
3365 
3366 	bundle = kzalloc_obj(*bundle, GFP_KERNEL);
3367 
3368 	if (!bundle) {
3369 		drm_err(dm->ddev, "Failed to allocate update bundle\n");
3370 		return;
3371 	}
3372 
3373 	for (k = 0; k < dc_state->stream_count; k++) {
3374 		bundle->stream_update.stream = dc_state->streams[k];
3375 
3376 		for (m = 0; m < dc_state->stream_status[k].plane_count; m++) {
3377 			bundle->surface_updates[m].surface =
3378 				dc_state->stream_status[k].plane_states[m];
3379 			bundle->surface_updates[m].surface->force_full_update =
3380 				true;
3381 		}
3382 
3383 		update_planes_and_stream_adapter(dm->dc,
3384 					 UPDATE_TYPE_FULL,
3385 					 dc_state->stream_status[k].plane_count,
3386 					 dc_state->streams[k],
3387 					 &bundle->stream_update,
3388 					 bundle->surface_updates);
3389 	}
3390 }
3391 
apply_delay_after_dpcd_poweroff(struct amdgpu_device * adev,struct dc_sink * sink)3392 static void apply_delay_after_dpcd_poweroff(struct amdgpu_device *adev,
3393 					    struct dc_sink *sink)
3394 {
3395 	struct dc_panel_patch *ppatch = NULL;
3396 
3397 	if (!sink)
3398 		return;
3399 
3400 	ppatch = &sink->edid_caps.panel_patch;
3401 	if (ppatch->wait_after_dpcd_poweroff_ms) {
3402 		msleep(ppatch->wait_after_dpcd_poweroff_ms);
3403 		drm_dbg_driver(adev_to_drm(adev),
3404 			       "%s: adding a %ds delay as w/a for panel\n",
3405 			       __func__,
3406 			       ppatch->wait_after_dpcd_poweroff_ms / 1000);
3407 	}
3408 }
3409 
3410 /**
3411  * amdgpu_dm_dump_links_and_sinks - Debug dump of all DC links and their sinks
3412  * @adev: amdgpu device pointer
3413  *
3414  * Iterates through all DC links and dumps information about local and remote
3415  * (MST) sinks. Should be called after connector detection is complete to see
3416  * the final state of all links.
3417  */
amdgpu_dm_dump_links_and_sinks(struct amdgpu_device * adev)3418 static void amdgpu_dm_dump_links_and_sinks(struct amdgpu_device *adev)
3419 {
3420 	struct dc *dc = adev->dm.dc;
3421 	struct drm_device *dev = adev_to_drm(adev);
3422 	int li;
3423 
3424 	if (!dc)
3425 		return;
3426 
3427 	for (li = 0; li < dc->link_count; li++) {
3428 		struct dc_link *l = dc->links[li];
3429 		const char *name = NULL;
3430 		int rs;
3431 
3432 		if (!l)
3433 			continue;
3434 		if (l->local_sink && l->local_sink->edid_caps.display_name[0])
3435 			name = l->local_sink->edid_caps.display_name;
3436 		else
3437 			name = "n/a";
3438 
3439 		drm_dbg_kms(dev,
3440 			"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",
3441 			li,
3442 			l->local_sink,
3443 			l->type,
3444 			l->local_sink ? l->local_sink->sink_signal : SIGNAL_TYPE_NONE,
3445 			l->sink_count,
3446 			name,
3447 			l->dpcd_caps.is_mst_capable,
3448 			l->mst_stream_alloc_table.stream_count);
3449 
3450 		/* Dump remote (MST) sinks if any */
3451 		for (rs = 0; rs < l->sink_count; rs++) {
3452 			struct dc_sink *rsink = l->remote_sinks[rs];
3453 			const char *rname = NULL;
3454 
3455 			if (!rsink)
3456 				continue;
3457 			if (rsink->edid_caps.display_name[0])
3458 				rname = rsink->edid_caps.display_name;
3459 			else
3460 				rname = "n/a";
3461 			drm_dbg_kms(dev,
3462 				"  REMOTE_SINK[%d:%d]: sink=%p signal=%d edid_name=%s\n",
3463 				li, rs,
3464 				rsink,
3465 				rsink->sink_signal,
3466 				rname);
3467 		}
3468 	}
3469 }
3470 
dm_resume(struct amdgpu_ip_block * ip_block)3471 static int dm_resume(struct amdgpu_ip_block *ip_block)
3472 {
3473 	struct amdgpu_device *adev = ip_block->adev;
3474 	struct drm_device *ddev = adev_to_drm(adev);
3475 	struct amdgpu_display_manager *dm = &adev->dm;
3476 	struct amdgpu_dm_connector *aconnector;
3477 	struct drm_connector *connector;
3478 	struct drm_connector_list_iter iter;
3479 	struct dm_atomic_state *dm_state = to_dm_atomic_state(dm->atomic_obj.state);
3480 	enum dc_connection_type new_connection_type = dc_connection_none;
3481 	struct dc_state *dc_state;
3482 	int i, r, j;
3483 	struct dc_commit_streams_params commit_params = {};
3484 
3485 	if (dm->dc->caps.ips_support) {
3486 		if (!amdgpu_in_reset(adev))
3487 			mutex_lock(&dm->dc_lock);
3488 
3489 		/* Need to set POWER_STATE_D0 first or it will not execute
3490 		 * idle_power_optimizations command to DMUB.
3491 		 */
3492 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3493 		dc_dmub_srv_apply_idle_power_optimizations(dm->dc, false);
3494 
3495 		if (!amdgpu_in_reset(adev))
3496 			mutex_unlock(&dm->dc_lock);
3497 	}
3498 
3499 	if (amdgpu_in_reset(adev)) {
3500 		dc_state = dm->cached_dc_state;
3501 
3502 		/*
3503 		 * The dc->current_state is backed up into dm->cached_dc_state
3504 		 * before we commit 0 streams.
3505 		 *
3506 		 * DC will clear link encoder assignments on the real state
3507 		 * but the changes won't propagate over to the copy we made
3508 		 * before the 0 streams commit.
3509 		 *
3510 		 * DC expects that link encoder assignments are *not* valid
3511 		 * when committing a state, so as a workaround we can copy
3512 		 * off of the current state.
3513 		 *
3514 		 * We lose the previous assignments, but we had already
3515 		 * commit 0 streams anyway.
3516 		 */
3517 		link_enc_cfg_copy(adev->dm.dc->current_state, dc_state);
3518 
3519 		r = dm_dmub_hw_init(adev);
3520 		if (r) {
3521 			drm_err(adev_to_drm(adev), "DMUB interface failed to initialize: status=%d\n", r);
3522 			return r;
3523 		}
3524 
3525 		dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3526 		dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3527 
3528 		dc_resume(dm->dc);
3529 
3530 		amdgpu_dm_irq_resume_early(adev);
3531 
3532 		for (i = 0; i < dc_state->stream_count; i++) {
3533 			dc_state->streams[i]->mode_changed = true;
3534 			for (j = 0; j < dc_state->stream_status[i].plane_count; j++) {
3535 				dc_state->stream_status[i].plane_states[j]->update_flags.raw
3536 					= 0xffffffff;
3537 			}
3538 		}
3539 
3540 		if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3541 			amdgpu_dm_outbox_init(adev);
3542 			dc_enable_dmub_outbox(adev->dm.dc);
3543 		}
3544 
3545 		commit_params.streams = dc_state->streams;
3546 		commit_params.stream_count = dc_state->stream_count;
3547 		dc_exit_ips_for_hw_access(dm->dc);
3548 		WARN_ON(!dc_commit_streams(dm->dc, &commit_params));
3549 
3550 		dm_gpureset_commit_state(dm->cached_dc_state, dm);
3551 
3552 		dm_gpureset_toggle_interrupts(adev, dm->cached_dc_state, true);
3553 
3554 		dc_state_release(dm->cached_dc_state);
3555 		dm->cached_dc_state = NULL;
3556 
3557 		amdgpu_dm_irq_resume_late(adev);
3558 
3559 		mutex_unlock(&dm->dc_lock);
3560 
3561 		/* set the backlight after a reset */
3562 		for (i = 0; i < dm->num_of_edps; i++) {
3563 			if (dm->backlight_dev[i])
3564 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
3565 		}
3566 
3567 		return 0;
3568 	}
3569 	/* Recreate dc_state - DC invalidates it when setting power state to S3. */
3570 	dc_state_release(dm_state->context);
3571 	dm_state->context = dc_state_create(dm->dc, NULL);
3572 	/* TODO: Remove dc_state->dccg, use dc->dccg directly. */
3573 
3574 	/* Before powering on DC we need to re-initialize DMUB. */
3575 	dm_dmub_hw_resume(adev);
3576 
3577 	/* Re-enable outbox interrupts for DPIA. */
3578 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
3579 		amdgpu_dm_outbox_init(adev);
3580 		dc_enable_dmub_outbox(adev->dm.dc);
3581 	}
3582 
3583 	/* power on hardware */
3584 	dc_dmub_srv_set_power_state(dm->dc->ctx->dmub_srv, DC_ACPI_CM_POWER_STATE_D0);
3585 	dc_set_power_state(dm->dc, DC_ACPI_CM_POWER_STATE_D0);
3586 
3587 	/* program HPD filter */
3588 	dc_resume(dm->dc);
3589 
3590 	/*
3591 	 * early enable HPD Rx IRQ, should be done before set mode as short
3592 	 * pulse interrupts are used for MST
3593 	 */
3594 	amdgpu_dm_irq_resume_early(adev);
3595 
3596 	s3_handle_hdmi_cec(ddev, false);
3597 
3598 	/* On resume we need to rewrite the MSTM control bits to enable MST*/
3599 	s3_handle_mst(ddev, false);
3600 
3601 	/* Do detection*/
3602 	drm_connector_list_iter_begin(ddev, &iter);
3603 	drm_for_each_connector_iter(connector, &iter) {
3604 		bool ret;
3605 
3606 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3607 			continue;
3608 
3609 		aconnector = to_amdgpu_dm_connector(connector);
3610 
3611 		if (!aconnector->dc_link)
3612 			continue;
3613 
3614 		/*
3615 		 * this is the case when traversing through already created end sink
3616 		 * MST connectors, should be skipped
3617 		 */
3618 		if (aconnector->mst_root)
3619 			continue;
3620 
3621 		/* Skip eDP detection, when there is no sink present */
3622 		if (aconnector->dc_link->connector_signal == SIGNAL_TYPE_EDP &&
3623 		    !aconnector->dc_link->edp_sink_present)
3624 			continue;
3625 
3626 		guard(mutex)(&aconnector->hpd_lock);
3627 		if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
3628 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
3629 
3630 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
3631 			emulated_link_detect(aconnector->dc_link);
3632 		} else {
3633 			guard(mutex)(&dm->dc_lock);
3634 			dc_exit_ips_for_hw_access(dm->dc);
3635 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_RESUMEFROMS3S4);
3636 			if (ret) {
3637 				/* w/a delay for certain panels */
3638 				apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
3639 			}
3640 		}
3641 
3642 		if (aconnector->fake_enable && aconnector->dc_link->local_sink)
3643 			aconnector->fake_enable = false;
3644 
3645 		if (aconnector->dc_sink)
3646 			dc_sink_release(aconnector->dc_sink);
3647 		aconnector->dc_sink = NULL;
3648 		amdgpu_dm_update_connector_after_detect(aconnector);
3649 	}
3650 	drm_connector_list_iter_end(&iter);
3651 
3652 	dm_destroy_cached_state(adev);
3653 
3654 	/* Do mst topology probing after resuming cached state*/
3655 	drm_connector_list_iter_begin(ddev, &iter);
3656 	drm_for_each_connector_iter(connector, &iter) {
3657 		bool init = false;
3658 
3659 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
3660 			continue;
3661 
3662 		aconnector = to_amdgpu_dm_connector(connector);
3663 		if (aconnector->dc_link->type != dc_connection_mst_branch ||
3664 		    aconnector->mst_root)
3665 			continue;
3666 
3667 		scoped_guard(mutex, &aconnector->mst_mgr.lock) {
3668 			init = !aconnector->mst_mgr.mst_primary;
3669 		}
3670 		if (init)
3671 			dm_helpers_dp_mst_start_top_mgr(aconnector->dc_link->ctx,
3672 				aconnector->dc_link, false);
3673 		else
3674 			drm_dp_mst_topology_queue_probe(&aconnector->mst_mgr);
3675 	}
3676 	drm_connector_list_iter_end(&iter);
3677 
3678 	/* Debug dump: list all DC links and their associated sinks after detection
3679 	 * is complete for all connectors. This provides a comprehensive view of the
3680 	 * final state without repeating the dump for each connector.
3681 	 */
3682 	amdgpu_dm_dump_links_and_sinks(adev);
3683 
3684 	amdgpu_dm_irq_resume_late(adev);
3685 
3686 	amdgpu_dm_smu_write_watermarks_table(adev);
3687 
3688 	drm_kms_helper_hotplug_event(ddev);
3689 
3690 	return 0;
3691 }
3692 
3693 /**
3694  * DOC: DM Lifecycle
3695  *
3696  * DM (and consequently DC) is registered in the amdgpu base driver as a IP
3697  * block. When CONFIG_DRM_AMD_DC is enabled, the DM device IP block is added to
3698  * the base driver's device list to be initialized and torn down accordingly.
3699  *
3700  * The functions to do so are provided as hooks in &struct amd_ip_funcs.
3701  */
3702 
3703 static const struct amd_ip_funcs amdgpu_dm_funcs = {
3704 	.name = "dm",
3705 	.early_init = dm_early_init,
3706 	.late_init = dm_late_init,
3707 	.sw_init = dm_sw_init,
3708 	.sw_fini = dm_sw_fini,
3709 	.early_fini = amdgpu_dm_early_fini,
3710 	.hw_init = dm_hw_init,
3711 	.hw_fini = dm_hw_fini,
3712 	.suspend = dm_suspend,
3713 	.resume = dm_resume,
3714 	.is_idle = dm_is_idle,
3715 	.wait_for_idle = dm_wait_for_idle,
3716 	.check_soft_reset = dm_check_soft_reset,
3717 	.soft_reset = dm_soft_reset,
3718 	.set_clockgating_state = dm_set_clockgating_state,
3719 	.set_powergating_state = dm_set_powergating_state,
3720 };
3721 
3722 const struct amdgpu_ip_block_version dm_ip_block = {
3723 	.type = AMD_IP_BLOCK_TYPE_DCE,
3724 	.major = 1,
3725 	.minor = 0,
3726 	.rev = 0,
3727 	.funcs = &amdgpu_dm_funcs,
3728 };
3729 
3730 
3731 /**
3732  * DOC: atomic
3733  *
3734  * *WIP*
3735  */
3736 
3737 static const struct drm_mode_config_funcs amdgpu_dm_mode_funcs = {
3738 	.fb_create = amdgpu_display_user_framebuffer_create,
3739 	.get_format_info = amdgpu_dm_plane_get_format_info,
3740 	.atomic_check = amdgpu_dm_atomic_check,
3741 	.atomic_commit = drm_atomic_helper_commit,
3742 };
3743 
3744 static struct drm_mode_config_helper_funcs amdgpu_dm_mode_config_helperfuncs = {
3745 	.atomic_commit_tail = amdgpu_dm_atomic_commit_tail,
3746 	.atomic_commit_setup = amdgpu_dm_atomic_setup_commit,
3747 };
3748 
update_connector_ext_caps(struct amdgpu_dm_connector * aconnector)3749 static void update_connector_ext_caps(struct amdgpu_dm_connector *aconnector)
3750 {
3751 	const struct drm_panel_backlight_quirk *panel_backlight_quirk;
3752 	struct amdgpu_dm_backlight_caps *caps;
3753 	struct drm_connector *conn_base;
3754 	struct amdgpu_device *adev;
3755 	struct drm_luminance_range_info *luminance_range;
3756 	struct drm_device *drm;
3757 
3758 	if (aconnector->bl_idx == -1 ||
3759 	    aconnector->dc_link->connector_signal != SIGNAL_TYPE_EDP)
3760 		return;
3761 
3762 	conn_base = &aconnector->base;
3763 	drm = conn_base->dev;
3764 	adev = drm_to_adev(drm);
3765 
3766 	caps = &adev->dm.backlight_caps[aconnector->bl_idx];
3767 	caps->ext_caps = &aconnector->dc_link->dpcd_sink_ext_caps;
3768 	caps->aux_support = false;
3769 
3770 	if (caps->ext_caps->bits.oled == 1
3771 	    /*
3772 	     * ||
3773 	     * caps->ext_caps->bits.sdr_aux_backlight_control == 1 ||
3774 	     * caps->ext_caps->bits.hdr_aux_backlight_control == 1
3775 	     */)
3776 		caps->aux_support = true;
3777 
3778 	if (amdgpu_backlight == 0)
3779 		caps->aux_support = false;
3780 	else if (amdgpu_backlight == 1)
3781 		caps->aux_support = true;
3782 	if (caps->aux_support)
3783 		aconnector->dc_link->backlight_control_type = BACKLIGHT_CONTROL_AMD_AUX;
3784 
3785 	luminance_range = &conn_base->display_info.luminance_range;
3786 
3787 	if (luminance_range->max_luminance)
3788 		caps->aux_max_input_signal = luminance_range->max_luminance;
3789 	else
3790 		caps->aux_max_input_signal = 512;
3791 
3792 	if (luminance_range->min_luminance)
3793 		caps->aux_min_input_signal = luminance_range->min_luminance;
3794 	else
3795 		caps->aux_min_input_signal = 1;
3796 
3797 	panel_backlight_quirk =
3798 		drm_get_panel_backlight_quirk(aconnector->drm_edid);
3799 	if (!IS_ERR_OR_NULL(panel_backlight_quirk)) {
3800 		if (panel_backlight_quirk->min_brightness) {
3801 			caps->min_input_signal =
3802 				panel_backlight_quirk->min_brightness - 1;
3803 			drm_info(drm,
3804 				 "Applying panel backlight quirk, min_brightness: %d\n",
3805 				 caps->min_input_signal);
3806 		}
3807 		if (panel_backlight_quirk->brightness_mask) {
3808 			drm_info(drm,
3809 				 "Applying panel backlight quirk, brightness_mask: 0x%X\n",
3810 				 panel_backlight_quirk->brightness_mask);
3811 			caps->brightness_mask =
3812 				panel_backlight_quirk->brightness_mask;
3813 		}
3814 	}
3815 }
3816 
DEFINE_FREE(sink_release,struct dc_sink *,if (_T)dc_sink_release (_T))3817 DEFINE_FREE(sink_release, struct dc_sink *, if (_T) dc_sink_release(_T))
3818 
3819 void amdgpu_dm_update_connector_after_detect(
3820 		struct amdgpu_dm_connector *aconnector)
3821 {
3822 	struct drm_connector *connector = &aconnector->base;
3823 	struct dc_sink *sink __free(sink_release) = NULL;
3824 	struct drm_device *dev = connector->dev;
3825 
3826 	/* MST handled by drm_mst framework */
3827 	if (aconnector->mst_mgr.mst_state == true)
3828 		return;
3829 
3830 	sink = aconnector->dc_link->local_sink;
3831 	if (sink)
3832 		dc_sink_retain(sink);
3833 
3834 	/*
3835 	 * Edid mgmt connector gets first update only in mode_valid hook and then
3836 	 * the connector sink is set to either fake or physical sink depends on link status.
3837 	 * Skip if already done during boot.
3838 	 */
3839 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED
3840 			&& aconnector->dc_em_sink) {
3841 
3842 		/*
3843 		 * For S3 resume with headless use eml_sink to fake stream
3844 		 * because on resume connector->sink is set to NULL
3845 		 */
3846 		guard(mutex)(&dev->mode_config.mutex);
3847 
3848 		if (sink) {
3849 			if (aconnector->dc_sink) {
3850 				amdgpu_dm_update_freesync_caps(connector, NULL);
3851 				/*
3852 				 * retain and release below are used to
3853 				 * bump up refcount for sink because the link doesn't point
3854 				 * to it anymore after disconnect, so on next crtc to connector
3855 				 * reshuffle by UMD we will get into unwanted dc_sink release
3856 				 */
3857 				dc_sink_release(aconnector->dc_sink);
3858 			}
3859 			aconnector->dc_sink = sink;
3860 			dc_sink_retain(aconnector->dc_sink);
3861 			amdgpu_dm_update_freesync_caps(connector,
3862 					aconnector->drm_edid);
3863 		} else {
3864 			amdgpu_dm_update_freesync_caps(connector, NULL);
3865 			if (!aconnector->dc_sink) {
3866 				aconnector->dc_sink = aconnector->dc_em_sink;
3867 				dc_sink_retain(aconnector->dc_sink);
3868 			}
3869 		}
3870 
3871 		return;
3872 	}
3873 
3874 	/*
3875 	 * TODO: temporary guard to look for proper fix
3876 	 * if this sink is MST sink, we should not do anything
3877 	 */
3878 	if (sink && sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
3879 		return;
3880 
3881 	if (aconnector->dc_sink == sink) {
3882 		/*
3883 		 * We got a DP short pulse (Link Loss, DP CTS, etc...).
3884 		 * Do nothing!!
3885 		 */
3886 		drm_dbg_kms(dev, "DCHPD: connector_id=%d: dc_sink didn't change.\n",
3887 				 aconnector->connector_id);
3888 		return;
3889 	}
3890 
3891 	drm_dbg_kms(dev, "DCHPD: connector_id=%d: Old sink=%p New sink=%p\n",
3892 		    aconnector->connector_id, aconnector->dc_sink, sink);
3893 
3894 	/* When polling, DRM has already locked the mutex for us. */
3895 	if (!drm_kms_helper_is_poll_worker())
3896 		mutex_lock(&dev->mode_config.mutex);
3897 
3898 	/*
3899 	 * 1. Update status of the drm connector
3900 	 * 2. Send an event and let userspace tell us what to do
3901 	 */
3902 	if (sink) {
3903 		/*
3904 		 * TODO: check if we still need the S3 mode update workaround.
3905 		 * If yes, put it here.
3906 		 */
3907 		if (aconnector->dc_sink) {
3908 			amdgpu_dm_update_freesync_caps(connector, NULL);
3909 			dc_sink_release(aconnector->dc_sink);
3910 		}
3911 
3912 		aconnector->dc_sink = sink;
3913 		dc_sink_retain(aconnector->dc_sink);
3914 		if (sink->dc_edid.length == 0) {
3915 			aconnector->drm_edid = NULL;
3916 			hdmi_cec_unset_edid(aconnector);
3917 			if (aconnector->dc_link->aux_mode) {
3918 				drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
3919 			}
3920 		} else {
3921 			const struct edid *edid = (const struct edid *)sink->dc_edid.raw_edid;
3922 
3923 			aconnector->drm_edid = drm_edid_alloc(edid, sink->dc_edid.length);
3924 			drm_edid_connector_update(connector, aconnector->drm_edid);
3925 
3926 			hdmi_cec_set_edid(aconnector);
3927 			if (aconnector->dc_link->aux_mode)
3928 				drm_dp_cec_attach(&aconnector->dm_dp_aux.aux,
3929 						  connector->display_info.source_physical_address);
3930 		}
3931 
3932 		if (!aconnector->timing_requested) {
3933 			aconnector->timing_requested =
3934 				kzalloc_obj(struct dc_crtc_timing, GFP_KERNEL);
3935 			if (!aconnector->timing_requested)
3936 				drm_err(dev,
3937 					"failed to create aconnector->requested_timing\n");
3938 		}
3939 
3940 		amdgpu_dm_update_freesync_caps(connector, aconnector->drm_edid);
3941 		update_connector_ext_caps(aconnector);
3942 	} else {
3943 		hdmi_cec_unset_edid(aconnector);
3944 		drm_dp_cec_unset_edid(&aconnector->dm_dp_aux.aux);
3945 		amdgpu_dm_update_freesync_caps(connector, NULL);
3946 		aconnector->num_modes = 0;
3947 		dc_sink_release(aconnector->dc_sink);
3948 		aconnector->dc_sink = NULL;
3949 		drm_edid_free(aconnector->drm_edid);
3950 		aconnector->drm_edid = NULL;
3951 		kfree(aconnector->timing_requested);
3952 		aconnector->timing_requested = NULL;
3953 		/* Set CP to DESIRED if it was ENABLED, so we can re-enable it again on hotplug */
3954 		if (connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
3955 			connector->state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
3956 	}
3957 
3958 	update_subconnector_property(aconnector);
3959 
3960 	/* When polling, the mutex will be unlocked for us by DRM. */
3961 	if (!drm_kms_helper_is_poll_worker())
3962 		mutex_unlock(&dev->mode_config.mutex);
3963 }
3964 
are_sinks_equal(const struct dc_sink * sink1,const struct dc_sink * sink2)3965 static bool are_sinks_equal(const struct dc_sink *sink1, const struct dc_sink *sink2)
3966 {
3967 	if (!sink1 || !sink2)
3968 		return false;
3969 	if (sink1->sink_signal != sink2->sink_signal)
3970 		return false;
3971 
3972 	if (sink1->dc_edid.length != sink2->dc_edid.length)
3973 		return false;
3974 
3975 	if (memcmp(sink1->dc_edid.raw_edid, sink2->dc_edid.raw_edid,
3976 		   sink1->dc_edid.length) != 0)
3977 		return false;
3978 	return true;
3979 }
3980 
3981 
3982 /**
3983  * DOC: hdmi_hpd_debounce_work
3984  *
3985  * HDMI HPD debounce delay in milliseconds. When an HDMI display toggles HPD
3986  * (such as during power save transitions), this delay determines how long to
3987  * wait before processing the HPD event. This allows distinguishing between a
3988  * physical unplug (>hdmi_hpd_debounce_delay)
3989  * and a spontaneous RX HPD toggle (<hdmi_hpd_debounce_delay).
3990  *
3991  * If the toggle is less than this delay, the driver compares sink capabilities
3992  * and permits a hotplug event if they changed.
3993  *
3994  * The default value of 1500ms was chosen based on experimental testing with
3995  * various monitors that exhibit spontaneous HPD toggling behavior.
3996  */
hdmi_hpd_debounce_work(struct work_struct * work)3997 static void hdmi_hpd_debounce_work(struct work_struct *work)
3998 {
3999 	struct amdgpu_dm_connector *aconnector =
4000 		container_of(to_delayed_work(work), struct amdgpu_dm_connector,
4001 			     hdmi_hpd_debounce_work);
4002 	struct drm_connector *connector = &aconnector->base;
4003 	struct drm_device *dev = connector->dev;
4004 	struct amdgpu_device *adev = drm_to_adev(dev);
4005 	struct dc *dc = aconnector->dc_link->ctx->dc;
4006 	bool fake_reconnect = false;
4007 	bool reallow_idle = false;
4008 	bool ret = false;
4009 	guard(mutex)(&aconnector->hpd_lock);
4010 
4011 	/* Re-detect the display */
4012 	scoped_guard(mutex, &adev->dm.dc_lock) {
4013 		if (dc->caps.ips_support && dc->ctx->dmub_srv->idle_allowed) {
4014 			dc_allow_idle_optimizations(dc, false);
4015 			reallow_idle = true;
4016 		}
4017 		ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4018 	}
4019 
4020 	if (ret) {
4021 		/* Apply workaround delay for certain panels */
4022 		apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4023 		/* Compare sinks to determine if this was a spontaneous HPD toggle */
4024 		if (are_sinks_equal(aconnector->dc_link->local_sink, aconnector->hdmi_prev_sink)) {
4025 			/*
4026 			* Sinks match - this was a spontaneous HDMI HPD toggle.
4027 			*/
4028 			drm_dbg_kms(dev, "HDMI HPD: Sink unchanged after debounce, internal re-enable\n");
4029 			fake_reconnect = true;
4030 		}
4031 
4032 		/* Update connector state */
4033 		amdgpu_dm_update_connector_after_detect(aconnector);
4034 
4035 		drm_modeset_lock_all(dev);
4036 		dm_restore_drm_connector_state(dev, connector);
4037 		drm_modeset_unlock_all(dev);
4038 
4039 		/* Only notify OS if sink actually changed */
4040 		if (!fake_reconnect && aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4041 			drm_kms_helper_hotplug_event(dev);
4042 	}
4043 
4044 	/* Release the cached sink reference */
4045 	if (aconnector->hdmi_prev_sink) {
4046 		dc_sink_release(aconnector->hdmi_prev_sink);
4047 		aconnector->hdmi_prev_sink = NULL;
4048 	}
4049 
4050 	scoped_guard(mutex, &adev->dm.dc_lock) {
4051 		if (reallow_idle && dc->caps.ips_support)
4052 			dc_allow_idle_optimizations(dc, true);
4053 	}
4054 }
4055 
handle_hpd_irq_helper(struct amdgpu_dm_connector * aconnector)4056 static void handle_hpd_irq_helper(struct amdgpu_dm_connector *aconnector)
4057 {
4058 	struct drm_connector *connector = &aconnector->base;
4059 	struct drm_device *dev = connector->dev;
4060 	enum dc_connection_type new_connection_type = dc_connection_none;
4061 	struct amdgpu_device *adev = drm_to_adev(dev);
4062 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
4063 	struct dc *dc = aconnector->dc_link->ctx->dc;
4064 	bool ret = false;
4065 	bool debounce_required = false;
4066 
4067 	if (adev->dm.disable_hpd_irq)
4068 		return;
4069 
4070 	/*
4071 	 * In case of failure or MST no need to update connector status or notify the OS
4072 	 * since (for MST case) MST does this in its own context.
4073 	 */
4074 	guard(mutex)(&aconnector->hpd_lock);
4075 
4076 	if (adev->dm.hdcp_workqueue) {
4077 		hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
4078 		dm_con_state->update_hdcp = true;
4079 	}
4080 	if (aconnector->fake_enable)
4081 		aconnector->fake_enable = false;
4082 
4083 	aconnector->timing_changed = false;
4084 
4085 	if (!dc_link_detect_connection_type(aconnector->dc_link, &new_connection_type))
4086 		drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4087 
4088 	/*
4089 	 * Check for HDMI disconnect with debounce enabled.
4090 	 */
4091 	debounce_required = (aconnector->hdmi_hpd_debounce_delay_ms > 0 &&
4092 			      dc_is_hdmi_signal(aconnector->dc_link->connector_signal) &&
4093 			      new_connection_type == dc_connection_none &&
4094 			      aconnector->dc_link->local_sink != NULL);
4095 
4096 	if (aconnector->base.force && new_connection_type == dc_connection_none) {
4097 		emulated_link_detect(aconnector->dc_link);
4098 
4099 		drm_modeset_lock_all(dev);
4100 		dm_restore_drm_connector_state(dev, connector);
4101 		drm_modeset_unlock_all(dev);
4102 
4103 		if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4104 			drm_kms_helper_connector_hotplug_event(connector);
4105 	} else if (debounce_required) {
4106 		/*
4107 		 * HDMI disconnect detected - schedule delayed work instead of
4108 		 * processing immediately. This allows us to coalesce spurious
4109 		 * HDMI signals from physical unplugs.
4110 		 */
4111 		drm_dbg_kms(dev, "HDMI HPD: Disconnect detected, scheduling debounce work (%u ms)\n",
4112 			    aconnector->hdmi_hpd_debounce_delay_ms);
4113 
4114 		/* Cache the current sink for later comparison */
4115 		if (aconnector->hdmi_prev_sink)
4116 			dc_sink_release(aconnector->hdmi_prev_sink);
4117 		aconnector->hdmi_prev_sink = aconnector->dc_link->local_sink;
4118 		if (aconnector->hdmi_prev_sink)
4119 			dc_sink_retain(aconnector->hdmi_prev_sink);
4120 
4121 		/* Schedule delayed detection. */
4122 		if (mod_delayed_work(system_wq,
4123 				 &aconnector->hdmi_hpd_debounce_work,
4124 				 msecs_to_jiffies(aconnector->hdmi_hpd_debounce_delay_ms)))
4125 			drm_dbg_kms(dev, "HDMI HPD: Re-scheduled debounce work\n");
4126 
4127 	} else {
4128 
4129 		/* If the aconnector->hdmi_hpd_debounce_work is scheduled, exit early */
4130 		if (delayed_work_pending(&aconnector->hdmi_hpd_debounce_work))
4131 			return;
4132 
4133 		scoped_guard(mutex, &adev->dm.dc_lock) {
4134 			dc_exit_ips_for_hw_access(dc);
4135 			ret = dc_link_detect(aconnector->dc_link, DETECT_REASON_HPD);
4136 		}
4137 		if (ret) {
4138 			/* w/a delay for certain panels */
4139 			apply_delay_after_dpcd_poweroff(adev, aconnector->dc_sink);
4140 			amdgpu_dm_update_connector_after_detect(aconnector);
4141 
4142 			drm_modeset_lock_all(dev);
4143 			dm_restore_drm_connector_state(dev, connector);
4144 			drm_modeset_unlock_all(dev);
4145 
4146 			if (aconnector->base.force == DRM_FORCE_UNSPECIFIED)
4147 				drm_kms_helper_connector_hotplug_event(connector);
4148 		}
4149 	}
4150 }
4151 
handle_hpd_irq(void * param)4152 static void handle_hpd_irq(void *param)
4153 {
4154 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4155 
4156 	handle_hpd_irq_helper(aconnector);
4157 
4158 }
4159 
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)4160 static void schedule_hpd_rx_offload_work(struct amdgpu_device *adev, struct hpd_rx_irq_offload_work_queue *offload_wq,
4161 							union hpd_irq_data hpd_irq_data)
4162 {
4163 	struct hpd_rx_irq_offload_work *offload_work = kzalloc_obj(*offload_work,
4164 								   GFP_KERNEL);
4165 
4166 	if (!offload_work) {
4167 		drm_err(adev_to_drm(adev), "Failed to allocate hpd_rx_irq_offload_work.\n");
4168 		return;
4169 	}
4170 
4171 	INIT_WORK(&offload_work->work, dm_handle_hpd_rx_offload_work);
4172 	offload_work->data = hpd_irq_data;
4173 	offload_work->offload_wq = offload_wq;
4174 	offload_work->adev = adev;
4175 
4176 	queue_work(offload_wq->wq, &offload_work->work);
4177 	drm_dbg_kms(adev_to_drm(adev), "queue work to handle hpd_rx offload work");
4178 }
4179 
handle_hpd_rx_irq(void * param)4180 static void handle_hpd_rx_irq(void *param)
4181 {
4182 	struct amdgpu_dm_connector *aconnector = (struct amdgpu_dm_connector *)param;
4183 	struct drm_connector *connector = &aconnector->base;
4184 	struct drm_device *dev = connector->dev;
4185 	struct dc_link *dc_link = aconnector->dc_link;
4186 	bool is_mst_root_connector = aconnector->mst_mgr.mst_state;
4187 	bool result = false;
4188 	enum dc_connection_type new_connection_type = dc_connection_none;
4189 	struct amdgpu_device *adev = drm_to_adev(dev);
4190 	union hpd_irq_data hpd_irq_data;
4191 	bool link_loss = false;
4192 	bool has_left_work = false;
4193 	int idx = dc_link->link_index;
4194 	struct hpd_rx_irq_offload_work_queue *offload_wq = &adev->dm.hpd_rx_offload_wq[idx];
4195 	struct dc *dc = aconnector->dc_link->ctx->dc;
4196 
4197 	memset(&hpd_irq_data, 0, sizeof(hpd_irq_data));
4198 
4199 	if (adev->dm.disable_hpd_irq)
4200 		return;
4201 
4202 	/*
4203 	 * TODO:Temporary add mutex to protect hpd interrupt not have a gpio
4204 	 * conflict, after implement i2c helper, this mutex should be
4205 	 * retired.
4206 	 */
4207 	mutex_lock(&aconnector->hpd_lock);
4208 
4209 	result = dc_link_handle_hpd_rx_irq(dc_link, &hpd_irq_data,
4210 						&link_loss, true, &has_left_work);
4211 
4212 	if (!has_left_work)
4213 		goto out;
4214 
4215 	if (hpd_irq_data.bytes.device_service_irq.bits.AUTOMATED_TEST) {
4216 		schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4217 		goto out;
4218 	}
4219 
4220 	if (dc_link_dp_allow_hpd_rx_irq(dc_link)) {
4221 		if (hpd_irq_data.bytes.device_service_irq.bits.UP_REQ_MSG_RDY ||
4222 			hpd_irq_data.bytes.device_service_irq.bits.DOWN_REP_MSG_RDY) {
4223 			bool skip = false;
4224 
4225 			/*
4226 			 * DOWN_REP_MSG_RDY is also handled by polling method
4227 			 * mgr->cbs->poll_hpd_irq()
4228 			 */
4229 			spin_lock(&offload_wq->offload_lock);
4230 			skip = offload_wq->is_handling_mst_msg_rdy_event;
4231 
4232 			if (!skip)
4233 				offload_wq->is_handling_mst_msg_rdy_event = true;
4234 
4235 			spin_unlock(&offload_wq->offload_lock);
4236 
4237 			if (!skip)
4238 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4239 
4240 			goto out;
4241 		}
4242 
4243 		if (link_loss) {
4244 			bool skip = false;
4245 
4246 			spin_lock(&offload_wq->offload_lock);
4247 			skip = offload_wq->is_handling_link_loss;
4248 
4249 			if (!skip)
4250 				offload_wq->is_handling_link_loss = true;
4251 
4252 			spin_unlock(&offload_wq->offload_lock);
4253 
4254 			if (!skip)
4255 				schedule_hpd_rx_offload_work(adev, offload_wq, hpd_irq_data);
4256 
4257 			goto out;
4258 		}
4259 	}
4260 
4261 out:
4262 	if (result && !is_mst_root_connector) {
4263 		/* Downstream Port status changed. */
4264 		if (!dc_link_detect_connection_type(dc_link, &new_connection_type))
4265 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
4266 
4267 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
4268 			emulated_link_detect(dc_link);
4269 
4270 			if (aconnector->fake_enable)
4271 				aconnector->fake_enable = false;
4272 
4273 			amdgpu_dm_update_connector_after_detect(aconnector);
4274 
4275 
4276 			drm_modeset_lock_all(dev);
4277 			dm_restore_drm_connector_state(dev, connector);
4278 			drm_modeset_unlock_all(dev);
4279 
4280 			drm_kms_helper_connector_hotplug_event(connector);
4281 		} else {
4282 			bool ret = false;
4283 
4284 			mutex_lock(&adev->dm.dc_lock);
4285 			dc_exit_ips_for_hw_access(dc);
4286 			ret = dc_link_detect(dc_link, DETECT_REASON_HPDRX);
4287 			mutex_unlock(&adev->dm.dc_lock);
4288 
4289 			if (ret) {
4290 				if (aconnector->fake_enable)
4291 					aconnector->fake_enable = false;
4292 
4293 				amdgpu_dm_update_connector_after_detect(aconnector);
4294 
4295 				drm_modeset_lock_all(dev);
4296 				dm_restore_drm_connector_state(dev, connector);
4297 				drm_modeset_unlock_all(dev);
4298 
4299 				drm_kms_helper_connector_hotplug_event(connector);
4300 			}
4301 		}
4302 	}
4303 	if (hpd_irq_data.bytes.device_service_irq.bits.CP_IRQ) {
4304 		if (adev->dm.hdcp_workqueue)
4305 			hdcp_handle_cpirq(adev->dm.hdcp_workqueue,  aconnector->base.index);
4306 	}
4307 
4308 	if (dc_link->type != dc_connection_mst_branch)
4309 		drm_dp_cec_irq(&aconnector->dm_dp_aux.aux);
4310 
4311 	mutex_unlock(&aconnector->hpd_lock);
4312 }
4313 
register_hpd_handlers(struct amdgpu_device * adev)4314 static int register_hpd_handlers(struct amdgpu_device *adev)
4315 {
4316 	struct drm_device *dev = adev_to_drm(adev);
4317 	struct drm_connector *connector;
4318 	struct amdgpu_dm_connector *aconnector;
4319 	const struct dc_link *dc_link;
4320 	struct dc_interrupt_params int_params = {0};
4321 
4322 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4323 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4324 
4325 	if (dc_is_dmub_outbox_supported(adev->dm.dc)) {
4326 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD,
4327 			dmub_hpd_callback, true)) {
4328 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4329 			return -EINVAL;
4330 		}
4331 
4332 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_IRQ,
4333 			dmub_hpd_callback, true)) {
4334 			drm_err(adev_to_drm(adev), "fail to register dmub hpd callback");
4335 			return -EINVAL;
4336 		}
4337 
4338 		if (!register_dmub_notify_callback(adev, DMUB_NOTIFICATION_HPD_SENSE_NOTIFY,
4339 			dmub_hpd_sense_callback, true)) {
4340 			drm_err(adev_to_drm(adev), "fail to register dmub hpd sense callback");
4341 			return -EINVAL;
4342 		}
4343 	}
4344 
4345 	list_for_each_entry(connector,
4346 			&dev->mode_config.connector_list, head)	{
4347 
4348 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
4349 			continue;
4350 
4351 		aconnector = to_amdgpu_dm_connector(connector);
4352 		dc_link = aconnector->dc_link;
4353 
4354 		if (dc_link->irq_source_hpd != DC_IRQ_SOURCE_INVALID) {
4355 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4356 			int_params.irq_source = dc_link->irq_source_hpd;
4357 
4358 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4359 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1 ||
4360 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6) {
4361 				drm_err(adev_to_drm(adev), "Failed to register hpd irq!\n");
4362 				return -EINVAL;
4363 			}
4364 
4365 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4366 				handle_hpd_irq, (void *) aconnector))
4367 				return -ENOMEM;
4368 		}
4369 
4370 		if (dc_link->irq_source_hpd_rx != DC_IRQ_SOURCE_INVALID) {
4371 
4372 			/* Also register for DP short pulse (hpd_rx). */
4373 			int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4374 			int_params.irq_source =	dc_link->irq_source_hpd_rx;
4375 
4376 			if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4377 				int_params.irq_source  < DC_IRQ_SOURCE_HPD1RX ||
4378 				int_params.irq_source  > DC_IRQ_SOURCE_HPD6RX) {
4379 				drm_err(adev_to_drm(adev), "Failed to register hpd rx irq!\n");
4380 				return -EINVAL;
4381 			}
4382 
4383 			if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4384 				handle_hpd_rx_irq, (void *) aconnector))
4385 				return -ENOMEM;
4386 		}
4387 	}
4388 	return 0;
4389 }
4390 
4391 #if defined(CONFIG_DRM_AMD_DC_SI)
4392 /* Register IRQ sources and initialize IRQ callbacks */
dce60_register_irq_handlers(struct amdgpu_device * adev)4393 static int dce60_register_irq_handlers(struct amdgpu_device *adev)
4394 {
4395 	struct dc *dc = adev->dm.dc;
4396 	struct common_irq_params *c_irq_params;
4397 	struct dc_interrupt_params int_params = {0};
4398 	int r;
4399 	int i;
4400 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4401 
4402 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4403 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4404 
4405 	/*
4406 	 * Actions of amdgpu_irq_add_id():
4407 	 * 1. Register a set() function with base driver.
4408 	 *    Base driver will call set() function to enable/disable an
4409 	 *    interrupt in DC hardware.
4410 	 * 2. Register amdgpu_dm_irq_handler().
4411 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4412 	 *    coming from DC hardware.
4413 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4414 	 *    for acknowledging and handling.
4415 	 */
4416 
4417 	/* Use VBLANK interrupt */
4418 	for (i = 0; i < adev->mode_info.num_crtc; i++) {
4419 		r = amdgpu_irq_add_id(adev, client_id, i + 1, &adev->crtc_irq);
4420 		if (r) {
4421 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4422 			return r;
4423 		}
4424 
4425 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4426 		int_params.irq_source =
4427 			dc_interrupt_to_irq_source(dc, i + 1, 0);
4428 
4429 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4430 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4431 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4432 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4433 			return -EINVAL;
4434 		}
4435 
4436 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4437 
4438 		c_irq_params->adev = adev;
4439 		c_irq_params->irq_src = int_params.irq_source;
4440 
4441 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4442 			dm_crtc_high_irq, c_irq_params))
4443 			return -ENOMEM;
4444 	}
4445 
4446 	/* Use GRPH_PFLIP interrupt */
4447 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4448 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4449 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4450 		if (r) {
4451 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4452 			return r;
4453 		}
4454 
4455 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4456 		int_params.irq_source =
4457 			dc_interrupt_to_irq_source(dc, i, 0);
4458 
4459 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4460 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4461 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4462 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4463 			return -EINVAL;
4464 		}
4465 
4466 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4467 
4468 		c_irq_params->adev = adev;
4469 		c_irq_params->irq_src = int_params.irq_source;
4470 
4471 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4472 			dm_pflip_high_irq, c_irq_params))
4473 			return -ENOMEM;
4474 	}
4475 
4476 	/* HPD */
4477 	r = amdgpu_irq_add_id(adev, client_id,
4478 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4479 	if (r) {
4480 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4481 		return r;
4482 	}
4483 
4484 	r = register_hpd_handlers(adev);
4485 
4486 	return r;
4487 }
4488 #endif
4489 
4490 /* Register IRQ sources and initialize IRQ callbacks */
dce110_register_irq_handlers(struct amdgpu_device * adev)4491 static int dce110_register_irq_handlers(struct amdgpu_device *adev)
4492 {
4493 	struct dc *dc = adev->dm.dc;
4494 	struct common_irq_params *c_irq_params;
4495 	struct dc_interrupt_params int_params = {0};
4496 	int r;
4497 	int i;
4498 	unsigned int client_id = AMDGPU_IRQ_CLIENTID_LEGACY;
4499 
4500 	if (adev->family >= AMDGPU_FAMILY_AI)
4501 		client_id = SOC15_IH_CLIENTID_DCE;
4502 
4503 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4504 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4505 
4506 	/*
4507 	 * Actions of amdgpu_irq_add_id():
4508 	 * 1. Register a set() function with base driver.
4509 	 *    Base driver will call set() function to enable/disable an
4510 	 *    interrupt in DC hardware.
4511 	 * 2. Register amdgpu_dm_irq_handler().
4512 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4513 	 *    coming from DC hardware.
4514 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4515 	 *    for acknowledging and handling.
4516 	 */
4517 
4518 	/* Use VBLANK interrupt */
4519 	for (i = VISLANDS30_IV_SRCID_D1_VERTICAL_INTERRUPT0; i <= VISLANDS30_IV_SRCID_D6_VERTICAL_INTERRUPT0; i++) {
4520 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->crtc_irq);
4521 		if (r) {
4522 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4523 			return r;
4524 		}
4525 
4526 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4527 		int_params.irq_source =
4528 			dc_interrupt_to_irq_source(dc, i, 0);
4529 
4530 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4531 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4532 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4533 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4534 			return -EINVAL;
4535 		}
4536 
4537 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4538 
4539 		c_irq_params->adev = adev;
4540 		c_irq_params->irq_src = int_params.irq_source;
4541 
4542 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4543 			dm_crtc_high_irq, c_irq_params))
4544 			return -ENOMEM;
4545 	}
4546 
4547 	/* Use VUPDATE interrupt */
4548 	for (i = VISLANDS30_IV_SRCID_D1_V_UPDATE_INT; i <= VISLANDS30_IV_SRCID_D6_V_UPDATE_INT; i += 2) {
4549 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->vupdate_irq);
4550 		if (r) {
4551 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4552 			return r;
4553 		}
4554 
4555 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4556 		int_params.irq_source =
4557 			dc_interrupt_to_irq_source(dc, i, 0);
4558 
4559 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4560 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4561 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4562 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4563 			return -EINVAL;
4564 		}
4565 
4566 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4567 
4568 		c_irq_params->adev = adev;
4569 		c_irq_params->irq_src = int_params.irq_source;
4570 
4571 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4572 			dm_vupdate_high_irq, c_irq_params))
4573 			return -ENOMEM;
4574 	}
4575 
4576 	/* Use GRPH_PFLIP interrupt */
4577 	for (i = VISLANDS30_IV_SRCID_D1_GRPH_PFLIP;
4578 			i <= VISLANDS30_IV_SRCID_D6_GRPH_PFLIP; i += 2) {
4579 		r = amdgpu_irq_add_id(adev, client_id, i, &adev->pageflip_irq);
4580 		if (r) {
4581 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4582 			return r;
4583 		}
4584 
4585 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4586 		int_params.irq_source =
4587 			dc_interrupt_to_irq_source(dc, i, 0);
4588 
4589 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4590 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4591 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4592 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4593 			return -EINVAL;
4594 		}
4595 
4596 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4597 
4598 		c_irq_params->adev = adev;
4599 		c_irq_params->irq_src = int_params.irq_source;
4600 
4601 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4602 			dm_pflip_high_irq, c_irq_params))
4603 			return -ENOMEM;
4604 	}
4605 
4606 	/* HPD */
4607 	r = amdgpu_irq_add_id(adev, client_id,
4608 			VISLANDS30_IV_SRCID_HOTPLUG_DETECT_A, &adev->hpd_irq);
4609 	if (r) {
4610 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4611 		return r;
4612 	}
4613 
4614 	r = register_hpd_handlers(adev);
4615 
4616 	return r;
4617 }
4618 
4619 /* Register IRQ sources and initialize IRQ callbacks */
dcn10_register_irq_handlers(struct amdgpu_device * adev)4620 static int dcn10_register_irq_handlers(struct amdgpu_device *adev)
4621 {
4622 	struct dc *dc = adev->dm.dc;
4623 	struct common_irq_params *c_irq_params;
4624 	struct dc_interrupt_params int_params = {0};
4625 	int r;
4626 	int i;
4627 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4628 	static const unsigned int vrtl_int_srcid[] = {
4629 		DCN_1_0__SRCID__OTG1_VERTICAL_INTERRUPT0_CONTROL,
4630 		DCN_1_0__SRCID__OTG2_VERTICAL_INTERRUPT0_CONTROL,
4631 		DCN_1_0__SRCID__OTG3_VERTICAL_INTERRUPT0_CONTROL,
4632 		DCN_1_0__SRCID__OTG4_VERTICAL_INTERRUPT0_CONTROL,
4633 		DCN_1_0__SRCID__OTG5_VERTICAL_INTERRUPT0_CONTROL,
4634 		DCN_1_0__SRCID__OTG6_VERTICAL_INTERRUPT0_CONTROL
4635 	};
4636 #endif
4637 
4638 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4639 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4640 
4641 	/*
4642 	 * Actions of amdgpu_irq_add_id():
4643 	 * 1. Register a set() function with base driver.
4644 	 *    Base driver will call set() function to enable/disable an
4645 	 *    interrupt in DC hardware.
4646 	 * 2. Register amdgpu_dm_irq_handler().
4647 	 *    Base driver will call amdgpu_dm_irq_handler() for ALL interrupts
4648 	 *    coming from DC hardware.
4649 	 *    amdgpu_dm_irq_handler() will re-direct the interrupt to DC
4650 	 *    for acknowledging and handling.
4651 	 */
4652 
4653 	/* Use VSTARTUP interrupt */
4654 	for (i = DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP;
4655 			i <= DCN_1_0__SRCID__DC_D1_OTG_VSTARTUP + adev->mode_info.num_crtc - 1;
4656 			i++) {
4657 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->crtc_irq);
4658 
4659 		if (r) {
4660 			drm_err(adev_to_drm(adev), "Failed to add crtc irq id!\n");
4661 			return r;
4662 		}
4663 
4664 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4665 		int_params.irq_source =
4666 			dc_interrupt_to_irq_source(dc, i, 0);
4667 
4668 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4669 			int_params.irq_source  < DC_IRQ_SOURCE_VBLANK1 ||
4670 			int_params.irq_source  > DC_IRQ_SOURCE_VBLANK6) {
4671 			drm_err(adev_to_drm(adev), "Failed to register vblank irq!\n");
4672 			return -EINVAL;
4673 		}
4674 
4675 		c_irq_params = &adev->dm.vblank_params[int_params.irq_source - DC_IRQ_SOURCE_VBLANK1];
4676 
4677 		c_irq_params->adev = adev;
4678 		c_irq_params->irq_src = int_params.irq_source;
4679 
4680 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4681 			dm_crtc_high_irq, c_irq_params))
4682 			return -ENOMEM;
4683 	}
4684 
4685 	/* Use otg vertical line interrupt */
4686 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
4687 	for (i = 0; i <= adev->mode_info.num_crtc - 1; i++) {
4688 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE,
4689 				vrtl_int_srcid[i], &adev->vline0_irq);
4690 
4691 		if (r) {
4692 			drm_err(adev_to_drm(adev), "Failed to add vline0 irq id!\n");
4693 			return r;
4694 		}
4695 
4696 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4697 		int_params.irq_source =
4698 			dc_interrupt_to_irq_source(dc, vrtl_int_srcid[i], 0);
4699 
4700 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4701 			int_params.irq_source < DC_IRQ_SOURCE_DC1_VLINE0 ||
4702 			int_params.irq_source > DC_IRQ_SOURCE_DC6_VLINE0) {
4703 			drm_err(adev_to_drm(adev), "Failed to register vline0 irq!\n");
4704 			return -EINVAL;
4705 		}
4706 
4707 		c_irq_params = &adev->dm.vline0_params[int_params.irq_source
4708 					- DC_IRQ_SOURCE_DC1_VLINE0];
4709 
4710 		c_irq_params->adev = adev;
4711 		c_irq_params->irq_src = int_params.irq_source;
4712 
4713 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4714 			dm_dcn_vertical_interrupt0_high_irq,
4715 			c_irq_params))
4716 			return -ENOMEM;
4717 	}
4718 #endif
4719 
4720 	/* Use VUPDATE_NO_LOCK interrupt on DCN, which seems to correspond to
4721 	 * the regular VUPDATE interrupt on DCE. We want DC_IRQ_SOURCE_VUPDATEx
4722 	 * to trigger at end of each vblank, regardless of state of the lock,
4723 	 * matching DCE behaviour.
4724 	 */
4725 	for (i = DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT;
4726 	     i <= DCN_1_0__SRCID__OTG0_IHC_V_UPDATE_NO_LOCK_INTERRUPT + adev->mode_info.num_crtc - 1;
4727 	     i++) {
4728 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->vupdate_irq);
4729 
4730 		if (r) {
4731 			drm_err(adev_to_drm(adev), "Failed to add vupdate irq id!\n");
4732 			return r;
4733 		}
4734 
4735 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4736 		int_params.irq_source =
4737 			dc_interrupt_to_irq_source(dc, i, 0);
4738 
4739 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4740 			int_params.irq_source  < DC_IRQ_SOURCE_VUPDATE1 ||
4741 			int_params.irq_source  > DC_IRQ_SOURCE_VUPDATE6) {
4742 			drm_err(adev_to_drm(adev), "Failed to register vupdate irq!\n");
4743 			return -EINVAL;
4744 		}
4745 
4746 		c_irq_params = &adev->dm.vupdate_params[int_params.irq_source - DC_IRQ_SOURCE_VUPDATE1];
4747 
4748 		c_irq_params->adev = adev;
4749 		c_irq_params->irq_src = int_params.irq_source;
4750 
4751 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4752 			dm_vupdate_high_irq, c_irq_params))
4753 			return -ENOMEM;
4754 	}
4755 
4756 	/* Use GRPH_PFLIP interrupt */
4757 	for (i = DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT;
4758 			i <= DCN_1_0__SRCID__HUBP0_FLIP_INTERRUPT + dc->caps.max_otg_num - 1;
4759 			i++) {
4760 		r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, i, &adev->pageflip_irq);
4761 		if (r) {
4762 			drm_err(adev_to_drm(adev), "Failed to add page flip irq id!\n");
4763 			return r;
4764 		}
4765 
4766 		int_params.int_context = INTERRUPT_HIGH_IRQ_CONTEXT;
4767 		int_params.irq_source =
4768 			dc_interrupt_to_irq_source(dc, i, 0);
4769 
4770 		if (int_params.irq_source == DC_IRQ_SOURCE_INVALID ||
4771 			int_params.irq_source  < DC_IRQ_SOURCE_PFLIP_FIRST ||
4772 			int_params.irq_source  > DC_IRQ_SOURCE_PFLIP_LAST) {
4773 			drm_err(adev_to_drm(adev), "Failed to register pflip irq!\n");
4774 			return -EINVAL;
4775 		}
4776 
4777 		c_irq_params = &adev->dm.pflip_params[int_params.irq_source - DC_IRQ_SOURCE_PFLIP_FIRST];
4778 
4779 		c_irq_params->adev = adev;
4780 		c_irq_params->irq_src = int_params.irq_source;
4781 
4782 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4783 			dm_pflip_high_irq, c_irq_params))
4784 			return -ENOMEM;
4785 	}
4786 
4787 	/* HPD */
4788 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DC_HPD1_INT,
4789 			&adev->hpd_irq);
4790 	if (r) {
4791 		drm_err(adev_to_drm(adev), "Failed to add hpd irq id!\n");
4792 		return r;
4793 	}
4794 
4795 	r = register_hpd_handlers(adev);
4796 
4797 	return r;
4798 }
4799 /* Register Outbox IRQ sources and initialize IRQ callbacks */
register_outbox_irq_handlers(struct amdgpu_device * adev)4800 static int register_outbox_irq_handlers(struct amdgpu_device *adev)
4801 {
4802 	struct dc *dc = adev->dm.dc;
4803 	struct common_irq_params *c_irq_params;
4804 	struct dc_interrupt_params int_params = {0};
4805 	int r, i;
4806 
4807 	int_params.requested_polarity = INTERRUPT_POLARITY_DEFAULT;
4808 	int_params.current_polarity = INTERRUPT_POLARITY_DEFAULT;
4809 
4810 	r = amdgpu_irq_add_id(adev, SOC15_IH_CLIENTID_DCE, DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT,
4811 			&adev->dmub_outbox_irq);
4812 	if (r) {
4813 		drm_err(adev_to_drm(adev), "Failed to add outbox irq id!\n");
4814 		return r;
4815 	}
4816 
4817 	if (dc->ctx->dmub_srv) {
4818 		i = DCN_1_0__SRCID__DMCUB_OUTBOX_LOW_PRIORITY_READY_INT;
4819 		int_params.int_context = INTERRUPT_LOW_IRQ_CONTEXT;
4820 		int_params.irq_source =
4821 		dc_interrupt_to_irq_source(dc, i, 0);
4822 
4823 		c_irq_params = &adev->dm.dmub_outbox_params[0];
4824 
4825 		c_irq_params->adev = adev;
4826 		c_irq_params->irq_src = int_params.irq_source;
4827 
4828 		if (!amdgpu_dm_irq_register_interrupt(adev, &int_params,
4829 			dm_dmub_outbox1_low_irq, c_irq_params))
4830 			return -ENOMEM;
4831 	}
4832 
4833 	return 0;
4834 }
4835 
4836 /*
4837  * Acquires the lock for the atomic state object and returns
4838  * the new atomic state.
4839  *
4840  * This should only be called during atomic check.
4841  */
dm_atomic_get_state(struct drm_atomic_state * state,struct dm_atomic_state ** dm_state)4842 int dm_atomic_get_state(struct drm_atomic_state *state,
4843 			struct dm_atomic_state **dm_state)
4844 {
4845 	struct drm_device *dev = state->dev;
4846 	struct amdgpu_device *adev = drm_to_adev(dev);
4847 	struct amdgpu_display_manager *dm = &adev->dm;
4848 	struct drm_private_state *priv_state;
4849 
4850 	if (*dm_state)
4851 		return 0;
4852 
4853 	priv_state = drm_atomic_get_private_obj_state(state, &dm->atomic_obj);
4854 	if (IS_ERR(priv_state))
4855 		return PTR_ERR(priv_state);
4856 
4857 	*dm_state = to_dm_atomic_state(priv_state);
4858 
4859 	return 0;
4860 }
4861 
4862 static struct dm_atomic_state *
dm_atomic_get_new_state(struct drm_atomic_state * state)4863 dm_atomic_get_new_state(struct drm_atomic_state *state)
4864 {
4865 	struct drm_device *dev = state->dev;
4866 	struct amdgpu_device *adev = drm_to_adev(dev);
4867 	struct amdgpu_display_manager *dm = &adev->dm;
4868 	struct drm_private_obj *obj;
4869 	struct drm_private_state *new_obj_state;
4870 	int i;
4871 
4872 	for_each_new_private_obj_in_state(state, obj, new_obj_state, i) {
4873 		if (obj->funcs == dm->atomic_obj.funcs)
4874 			return to_dm_atomic_state(new_obj_state);
4875 	}
4876 
4877 	return NULL;
4878 }
4879 
4880 static struct drm_private_state *
dm_atomic_duplicate_state(struct drm_private_obj * obj)4881 dm_atomic_duplicate_state(struct drm_private_obj *obj)
4882 {
4883 	struct dm_atomic_state *old_state, *new_state;
4884 
4885 	new_state = kzalloc_obj(*new_state, GFP_KERNEL);
4886 	if (!new_state)
4887 		return NULL;
4888 
4889 	__drm_atomic_helper_private_obj_duplicate_state(obj, &new_state->base);
4890 
4891 	old_state = to_dm_atomic_state(obj->state);
4892 
4893 	if (old_state && old_state->context)
4894 		new_state->context = dc_state_create_copy(old_state->context);
4895 
4896 	if (!new_state->context) {
4897 		kfree(new_state);
4898 		return NULL;
4899 	}
4900 
4901 	return &new_state->base;
4902 }
4903 
dm_atomic_destroy_state(struct drm_private_obj * obj,struct drm_private_state * state)4904 static void dm_atomic_destroy_state(struct drm_private_obj *obj,
4905 				    struct drm_private_state *state)
4906 {
4907 	struct dm_atomic_state *dm_state = to_dm_atomic_state(state);
4908 
4909 	if (dm_state && dm_state->context)
4910 		dc_state_release(dm_state->context);
4911 
4912 	kfree(dm_state);
4913 }
4914 
4915 static struct drm_private_state_funcs dm_atomic_state_funcs = {
4916 	.atomic_duplicate_state = dm_atomic_duplicate_state,
4917 	.atomic_destroy_state = dm_atomic_destroy_state,
4918 };
4919 
amdgpu_dm_mode_config_init(struct amdgpu_device * adev)4920 static int amdgpu_dm_mode_config_init(struct amdgpu_device *adev)
4921 {
4922 	struct dm_atomic_state *state;
4923 	int r;
4924 
4925 	adev->mode_info.mode_config_initialized = true;
4926 
4927 	adev_to_drm(adev)->mode_config.funcs = (void *)&amdgpu_dm_mode_funcs;
4928 	adev_to_drm(adev)->mode_config.helper_private = &amdgpu_dm_mode_config_helperfuncs;
4929 
4930 	adev_to_drm(adev)->mode_config.max_width = 16384;
4931 	adev_to_drm(adev)->mode_config.max_height = 16384;
4932 
4933 	adev_to_drm(adev)->mode_config.preferred_depth = 24;
4934 	if (adev->asic_type == CHIP_HAWAII)
4935 		/* disable prefer shadow for now due to hibernation issues */
4936 		adev_to_drm(adev)->mode_config.prefer_shadow = 0;
4937 	else
4938 		adev_to_drm(adev)->mode_config.prefer_shadow = 1;
4939 	/* indicates support for immediate flip */
4940 	adev_to_drm(adev)->mode_config.async_page_flip = true;
4941 
4942 	state = kzalloc_obj(*state, GFP_KERNEL);
4943 	if (!state)
4944 		return -ENOMEM;
4945 
4946 	state->context = dc_state_create_current_copy(adev->dm.dc);
4947 	if (!state->context) {
4948 		kfree(state);
4949 		return -ENOMEM;
4950 	}
4951 
4952 	drm_atomic_private_obj_init(adev_to_drm(adev),
4953 				    &adev->dm.atomic_obj,
4954 				    &state->base,
4955 				    &dm_atomic_state_funcs);
4956 
4957 	r = amdgpu_display_modeset_create_props(adev);
4958 	if (r) {
4959 		dc_state_release(state->context);
4960 		kfree(state);
4961 		return r;
4962 	}
4963 
4964 #ifdef AMD_PRIVATE_COLOR
4965 	if (amdgpu_dm_create_color_properties(adev)) {
4966 		dc_state_release(state->context);
4967 		kfree(state);
4968 		return -ENOMEM;
4969 	}
4970 #endif
4971 
4972 	r = amdgpu_dm_audio_init(adev);
4973 	if (r) {
4974 		dc_state_release(state->context);
4975 		kfree(state);
4976 		return r;
4977 	}
4978 
4979 	return 0;
4980 }
4981 
4982 #define AMDGPU_DM_DEFAULT_MIN_BACKLIGHT 12
4983 #define AMDGPU_DM_DEFAULT_MAX_BACKLIGHT 255
4984 #define AMDGPU_DM_MIN_SPREAD ((AMDGPU_DM_DEFAULT_MAX_BACKLIGHT - AMDGPU_DM_DEFAULT_MIN_BACKLIGHT) / 2)
4985 #define AUX_BL_DEFAULT_TRANSITION_TIME_MS 50
4986 
amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager * dm,int bl_idx)4987 static void amdgpu_dm_update_backlight_caps(struct amdgpu_display_manager *dm,
4988 					    int bl_idx)
4989 {
4990 	struct amdgpu_dm_backlight_caps *caps = &dm->backlight_caps[bl_idx];
4991 
4992 	if (caps->caps_valid)
4993 		return;
4994 
4995 #if defined(CONFIG_ACPI)
4996 	amdgpu_acpi_get_backlight_caps(caps);
4997 
4998 	/* validate the firmware value is sane */
4999 	if (caps->caps_valid) {
5000 		int spread = caps->max_input_signal - caps->min_input_signal;
5001 
5002 		if (caps->max_input_signal > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5003 		    caps->min_input_signal < 0 ||
5004 		    spread > AMDGPU_DM_DEFAULT_MAX_BACKLIGHT ||
5005 		    spread < AMDGPU_DM_MIN_SPREAD) {
5006 			drm_dbg_kms(adev_to_drm(dm->adev), "DM: Invalid backlight caps: min=%d, max=%d\n",
5007 				      caps->min_input_signal, caps->max_input_signal);
5008 			caps->caps_valid = false;
5009 		}
5010 	}
5011 
5012 	if (!caps->caps_valid) {
5013 		caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5014 		caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5015 		caps->caps_valid = true;
5016 	}
5017 #else
5018 	if (caps->aux_support)
5019 		return;
5020 
5021 	caps->min_input_signal = AMDGPU_DM_DEFAULT_MIN_BACKLIGHT;
5022 	caps->max_input_signal = AMDGPU_DM_DEFAULT_MAX_BACKLIGHT;
5023 	caps->caps_valid = true;
5024 #endif
5025 }
5026 
get_brightness_range(const struct amdgpu_dm_backlight_caps * caps,unsigned int * min,unsigned int * max)5027 static int get_brightness_range(const struct amdgpu_dm_backlight_caps *caps,
5028 				unsigned int *min, unsigned int *max)
5029 {
5030 	if (!caps)
5031 		return 0;
5032 
5033 	if (caps->aux_support) {
5034 		// Firmware limits are in nits, DC API wants millinits.
5035 		*max = 1000 * caps->aux_max_input_signal;
5036 		*min = 1000 * caps->aux_min_input_signal;
5037 	} else {
5038 		// Firmware limits are 8-bit, PWM control is 16-bit.
5039 		*max = 0x101 * caps->max_input_signal;
5040 		*min = 0x101 * caps->min_input_signal;
5041 	}
5042 	return 1;
5043 }
5044 
5045 /* Rescale from [min..max] to [0..AMDGPU_MAX_BL_LEVEL] */
scale_input_to_fw(int min,int max,u64 input)5046 static inline u32 scale_input_to_fw(int min, int max, u64 input)
5047 {
5048 	return DIV_ROUND_CLOSEST_ULL(input * AMDGPU_MAX_BL_LEVEL, max - min);
5049 }
5050 
5051 /* Rescale from [0..AMDGPU_MAX_BL_LEVEL] to [min..max] */
scale_fw_to_input(int min,int max,u64 input)5052 static inline u32 scale_fw_to_input(int min, int max, u64 input)
5053 {
5054 	return min + DIV_ROUND_CLOSEST_ULL(input * (max - min), AMDGPU_MAX_BL_LEVEL);
5055 }
5056 
convert_custom_brightness(const struct amdgpu_dm_backlight_caps * caps,unsigned int min,unsigned int max,uint32_t * user_brightness)5057 static void convert_custom_brightness(const struct amdgpu_dm_backlight_caps *caps,
5058 				      unsigned int min, unsigned int max,
5059 				      uint32_t *user_brightness)
5060 {
5061 	u32 brightness = scale_input_to_fw(min, max, *user_brightness);
5062 	u8 lower_signal, upper_signal, upper_lum, lower_lum, lum;
5063 	int left, right;
5064 
5065 	if (amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)
5066 		return;
5067 
5068 	if (!caps->data_points)
5069 		return;
5070 
5071 	/*
5072 	 * Handle the case where brightness is below the first data point
5073 	 * Interpolate between (0,0) and (first_signal, first_lum)
5074 	 */
5075 	if (brightness < caps->luminance_data[0].input_signal) {
5076 		lum = DIV_ROUND_CLOSEST(caps->luminance_data[0].luminance * brightness,
5077 					caps->luminance_data[0].input_signal);
5078 		goto scale;
5079 	}
5080 
5081 	left = 0;
5082 	right = caps->data_points - 1;
5083 	while (left <= right) {
5084 		int mid = left + (right - left) / 2;
5085 		u8 signal = caps->luminance_data[mid].input_signal;
5086 
5087 		/* Exact match found */
5088 		if (signal == brightness) {
5089 			lum = caps->luminance_data[mid].luminance;
5090 			goto scale;
5091 		}
5092 
5093 		if (signal < brightness)
5094 			left = mid + 1;
5095 		else
5096 			right = mid - 1;
5097 	}
5098 
5099 	/* verify bound */
5100 	if (left >= caps->data_points)
5101 		left = caps->data_points - 1;
5102 
5103 	/* At this point, left > right */
5104 	lower_signal = caps->luminance_data[right].input_signal;
5105 	upper_signal = caps->luminance_data[left].input_signal;
5106 	lower_lum = caps->luminance_data[right].luminance;
5107 	upper_lum = caps->luminance_data[left].luminance;
5108 
5109 	/* interpolate */
5110 	if (right == left || !lower_lum)
5111 		lum = upper_lum;
5112 	else
5113 		lum = lower_lum + DIV_ROUND_CLOSEST((upper_lum - lower_lum) *
5114 						    (brightness - lower_signal),
5115 						    upper_signal - lower_signal);
5116 scale:
5117 	*user_brightness = scale_fw_to_input(min, max,
5118 					     DIV_ROUND_CLOSEST(lum * brightness, 101));
5119 }
5120 
convert_brightness_from_user(const struct amdgpu_dm_backlight_caps * caps,uint32_t brightness)5121 static u32 convert_brightness_from_user(const struct amdgpu_dm_backlight_caps *caps,
5122 					uint32_t brightness)
5123 {
5124 	unsigned int min, max;
5125 
5126 	if (!get_brightness_range(caps, &min, &max))
5127 		return brightness;
5128 
5129 	convert_custom_brightness(caps, min, max, &brightness);
5130 
5131 	// Rescale 0..max to min..max
5132 	return min + DIV_ROUND_CLOSEST_ULL((u64)(max - min) * brightness, max);
5133 }
5134 
convert_brightness_to_user(const struct amdgpu_dm_backlight_caps * caps,uint32_t brightness)5135 static u32 convert_brightness_to_user(const struct amdgpu_dm_backlight_caps *caps,
5136 				      uint32_t brightness)
5137 {
5138 	unsigned int min, max;
5139 
5140 	if (!get_brightness_range(caps, &min, &max))
5141 		return brightness;
5142 
5143 	if (brightness < min)
5144 		return 0;
5145 	// Rescale min..max to 0..max
5146 	return DIV_ROUND_CLOSEST_ULL((u64)max * (brightness - min),
5147 				 max - min);
5148 }
5149 
amdgpu_dm_backlight_set_level(struct amdgpu_display_manager * dm,int bl_idx,u32 user_brightness)5150 static void amdgpu_dm_backlight_set_level(struct amdgpu_display_manager *dm,
5151 					 int bl_idx,
5152 					 u32 user_brightness)
5153 {
5154 	struct amdgpu_dm_backlight_caps *caps;
5155 	struct dc_link *link;
5156 	u32 brightness;
5157 	bool rc, reallow_idle = false;
5158 	struct drm_connector *connector;
5159 
5160 	list_for_each_entry(connector, &dm->ddev->mode_config.connector_list, head) {
5161 		struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
5162 
5163 		if (aconnector->bl_idx != bl_idx)
5164 			continue;
5165 
5166 		/* if connector is off, save the brightness for next time it's on */
5167 		if (!aconnector->base.encoder) {
5168 			dm->brightness[bl_idx] = user_brightness;
5169 			dm->actual_brightness[bl_idx] = 0;
5170 			return;
5171 		}
5172 	}
5173 
5174 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5175 	caps = &dm->backlight_caps[bl_idx];
5176 
5177 	dm->brightness[bl_idx] = user_brightness;
5178 	/* update scratch register */
5179 	if (bl_idx == 0)
5180 		amdgpu_atombios_scratch_regs_set_backlight_level(dm->adev, dm->brightness[bl_idx]);
5181 	brightness = convert_brightness_from_user(caps, dm->brightness[bl_idx]);
5182 	link = (struct dc_link *)dm->backlight_link[bl_idx];
5183 
5184 	/* Apply brightness quirk */
5185 	if (caps->brightness_mask)
5186 		brightness |= caps->brightness_mask;
5187 
5188 	/* Change brightness based on AUX property */
5189 	mutex_lock(&dm->dc_lock);
5190 	if (dm->dc->caps.ips_support && dm->dc->ctx->dmub_srv->idle_allowed) {
5191 		dc_allow_idle_optimizations(dm->dc, false);
5192 		reallow_idle = true;
5193 	}
5194 
5195 	if (trace_amdgpu_dm_brightness_enabled()) {
5196 		trace_amdgpu_dm_brightness(__builtin_return_address(0),
5197 					   user_brightness,
5198 					   brightness,
5199 					   caps->aux_support,
5200 					   power_supply_is_system_supplied() > 0);
5201 	}
5202 
5203 	if (caps->aux_support) {
5204 		rc = dc_link_set_backlight_level_nits(link, true, brightness,
5205 						      AUX_BL_DEFAULT_TRANSITION_TIME_MS);
5206 		if (!rc)
5207 			DRM_DEBUG("DM: Failed to update backlight via AUX on eDP[%d]\n", bl_idx);
5208 	} else {
5209 		struct set_backlight_level_params backlight_level_params = { 0 };
5210 
5211 		backlight_level_params.backlight_pwm_u16_16 = brightness;
5212 		backlight_level_params.transition_time_in_ms = 0;
5213 
5214 		rc = dc_link_set_backlight_level(link, &backlight_level_params);
5215 		if (!rc)
5216 			DRM_DEBUG("DM: Failed to update backlight on eDP[%d]\n", bl_idx);
5217 	}
5218 
5219 	if (dm->dc->caps.ips_support && reallow_idle)
5220 		dc_allow_idle_optimizations(dm->dc, true);
5221 
5222 	mutex_unlock(&dm->dc_lock);
5223 
5224 	if (rc)
5225 		dm->actual_brightness[bl_idx] = user_brightness;
5226 }
5227 
amdgpu_dm_backlight_update_status(struct backlight_device * bd)5228 static int amdgpu_dm_backlight_update_status(struct backlight_device *bd)
5229 {
5230 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5231 	int i;
5232 
5233 	for (i = 0; i < dm->num_of_edps; i++) {
5234 		if (bd == dm->backlight_dev[i])
5235 			break;
5236 	}
5237 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5238 		i = 0;
5239 	amdgpu_dm_backlight_set_level(dm, i, bd->props.brightness);
5240 
5241 	return 0;
5242 }
5243 
amdgpu_dm_backlight_get_level(struct amdgpu_display_manager * dm,int bl_idx)5244 static u32 amdgpu_dm_backlight_get_level(struct amdgpu_display_manager *dm,
5245 					 int bl_idx)
5246 {
5247 	int ret;
5248 	struct amdgpu_dm_backlight_caps caps;
5249 	struct dc_link *link = (struct dc_link *)dm->backlight_link[bl_idx];
5250 
5251 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5252 	caps = dm->backlight_caps[bl_idx];
5253 
5254 	if (caps.aux_support) {
5255 		u32 avg, peak;
5256 
5257 		if (!dc_link_get_backlight_level_nits(link, &avg, &peak))
5258 			return dm->brightness[bl_idx];
5259 		return convert_brightness_to_user(&caps, avg);
5260 	}
5261 
5262 	ret = dc_link_get_backlight_level(link);
5263 
5264 	if (ret == DC_ERROR_UNEXPECTED)
5265 		return dm->brightness[bl_idx];
5266 
5267 	return convert_brightness_to_user(&caps, ret);
5268 }
5269 
amdgpu_dm_backlight_get_brightness(struct backlight_device * bd)5270 static int amdgpu_dm_backlight_get_brightness(struct backlight_device *bd)
5271 {
5272 	struct amdgpu_display_manager *dm = bl_get_data(bd);
5273 	int i;
5274 
5275 	for (i = 0; i < dm->num_of_edps; i++) {
5276 		if (bd == dm->backlight_dev[i])
5277 			break;
5278 	}
5279 	if (i >= AMDGPU_DM_MAX_NUM_EDP)
5280 		i = 0;
5281 	return amdgpu_dm_backlight_get_level(dm, i);
5282 }
5283 
5284 static const struct backlight_ops amdgpu_dm_backlight_ops = {
5285 	.options = BL_CORE_SUSPENDRESUME,
5286 	.get_brightness = amdgpu_dm_backlight_get_brightness,
5287 	.update_status	= amdgpu_dm_backlight_update_status,
5288 };
5289 
5290 static void
amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector * aconnector)5291 amdgpu_dm_register_backlight_device(struct amdgpu_dm_connector *aconnector)
5292 {
5293 	struct drm_device *drm = aconnector->base.dev;
5294 	struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
5295 	struct backlight_properties props = { 0 };
5296 	struct amdgpu_dm_backlight_caps *caps;
5297 	char bl_name[16];
5298 	int min, max;
5299 	int real_brightness;
5300 	int init_brightness;
5301 
5302 	if (aconnector->bl_idx == -1)
5303 		return;
5304 
5305 	if (!acpi_video_backlight_use_native()) {
5306 		drm_info(drm, "Skipping amdgpu DM backlight registration\n");
5307 		/* Try registering an ACPI video backlight device instead. */
5308 		acpi_video_register_backlight();
5309 		return;
5310 	}
5311 
5312 	caps = &dm->backlight_caps[aconnector->bl_idx];
5313 	if (get_brightness_range(caps, &min, &max)) {
5314 		if (power_supply_is_system_supplied() > 0)
5315 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->ac_level, 100);
5316 		else
5317 			props.brightness = DIV_ROUND_CLOSEST((max - min) * caps->dc_level, 100);
5318 		/* min is zero, so max needs to be adjusted */
5319 		props.max_brightness = max - min;
5320 		drm_dbg(drm, "Backlight caps: min: %d, max: %d, ac %d, dc %d\n", min, max,
5321 			caps->ac_level, caps->dc_level);
5322 	} else
5323 		props.brightness = props.max_brightness = MAX_BACKLIGHT_LEVEL;
5324 
5325 	init_brightness = props.brightness;
5326 
5327 	if (caps->data_points && !(amdgpu_dc_debug_mask & DC_DISABLE_CUSTOM_BRIGHTNESS_CURVE)) {
5328 		drm_info(drm, "Using custom brightness curve\n");
5329 		props.scale = BACKLIGHT_SCALE_NON_LINEAR;
5330 	} else
5331 		props.scale = BACKLIGHT_SCALE_LINEAR;
5332 	props.type = BACKLIGHT_RAW;
5333 
5334 	snprintf(bl_name, sizeof(bl_name), "amdgpu_bl%d",
5335 		 drm->primary->index + aconnector->bl_idx);
5336 
5337 	dm->backlight_dev[aconnector->bl_idx] =
5338 		backlight_device_register(bl_name, aconnector->base.kdev, dm,
5339 					  &amdgpu_dm_backlight_ops, &props);
5340 	dm->brightness[aconnector->bl_idx] = props.brightness;
5341 
5342 	if (IS_ERR(dm->backlight_dev[aconnector->bl_idx])) {
5343 		drm_err(drm, "DM: Backlight registration failed!\n");
5344 		dm->backlight_dev[aconnector->bl_idx] = NULL;
5345 	} else {
5346 		/*
5347 		 * dm->brightness[x] can be inconsistent just after startup until
5348 		 * ops.get_brightness is called.
5349 		 */
5350 		real_brightness =
5351 			amdgpu_dm_backlight_ops.get_brightness(dm->backlight_dev[aconnector->bl_idx]);
5352 
5353 		if (real_brightness != init_brightness) {
5354 			dm->actual_brightness[aconnector->bl_idx] = real_brightness;
5355 			dm->brightness[aconnector->bl_idx] = real_brightness;
5356 		}
5357 		drm_dbg_driver(drm, "DM: Registered Backlight device: %s\n", bl_name);
5358 	}
5359 }
5360 
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)5361 static int initialize_plane(struct amdgpu_display_manager *dm,
5362 			    struct amdgpu_mode_info *mode_info, int plane_id,
5363 			    enum drm_plane_type plane_type,
5364 			    const struct dc_plane_cap *plane_cap)
5365 {
5366 	struct drm_plane *plane;
5367 	unsigned long possible_crtcs;
5368 	int ret = 0;
5369 
5370 	plane = kzalloc_obj(struct drm_plane, GFP_KERNEL);
5371 	if (!plane) {
5372 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to allocate plane\n");
5373 		return -ENOMEM;
5374 	}
5375 	plane->type = plane_type;
5376 
5377 	/*
5378 	 * HACK: IGT tests expect that the primary plane for a CRTC
5379 	 * can only have one possible CRTC. Only expose support for
5380 	 * any CRTC if they're not going to be used as a primary plane
5381 	 * for a CRTC - like overlay or underlay planes.
5382 	 */
5383 	possible_crtcs = 1 << plane_id;
5384 	if (plane_id >= dm->dc->caps.max_streams)
5385 		possible_crtcs = 0xff;
5386 
5387 	ret = amdgpu_dm_plane_init(dm, plane, possible_crtcs, plane_cap);
5388 
5389 	if (ret) {
5390 		drm_err(adev_to_drm(dm->adev), "KMS: Failed to initialize plane\n");
5391 		kfree(plane);
5392 		return ret;
5393 	}
5394 
5395 	if (mode_info)
5396 		mode_info->planes[plane_id] = plane;
5397 
5398 	return ret;
5399 }
5400 
5401 
setup_backlight_device(struct amdgpu_display_manager * dm,struct amdgpu_dm_connector * aconnector)5402 static void setup_backlight_device(struct amdgpu_display_manager *dm,
5403 				   struct amdgpu_dm_connector *aconnector)
5404 {
5405 	struct amdgpu_dm_backlight_caps *caps;
5406 	struct dc_link *link = aconnector->dc_link;
5407 	int bl_idx = dm->num_of_edps;
5408 
5409 	if (!(link->connector_signal & (SIGNAL_TYPE_EDP | SIGNAL_TYPE_LVDS)) ||
5410 	    link->type == dc_connection_none)
5411 		return;
5412 
5413 	if (dm->num_of_edps >= AMDGPU_DM_MAX_NUM_EDP) {
5414 		drm_warn(adev_to_drm(dm->adev), "Too much eDP connections, skipping backlight setup for additional eDPs\n");
5415 		return;
5416 	}
5417 
5418 	aconnector->bl_idx = bl_idx;
5419 
5420 	amdgpu_dm_update_backlight_caps(dm, bl_idx);
5421 	dm->backlight_link[bl_idx] = link;
5422 	dm->num_of_edps++;
5423 
5424 	update_connector_ext_caps(aconnector);
5425 	caps = &dm->backlight_caps[aconnector->bl_idx];
5426 
5427 	/* Only offer ABM property when non-OLED and user didn't turn off by module parameter */
5428 	if (!caps->ext_caps->bits.oled && amdgpu_dm_abm_level < 0)
5429 		drm_object_attach_property(&aconnector->base.base,
5430 					   dm->adev->mode_info.abm_level_property,
5431 					   ABM_SYSFS_CONTROL);
5432 }
5433 
5434 static void amdgpu_set_panel_orientation(struct drm_connector *connector);
5435 
5436 /*
5437  * In this architecture, the association
5438  * connector -> encoder -> crtc
5439  * id not really requried. The crtc and connector will hold the
5440  * display_index as an abstraction to use with DAL component
5441  *
5442  * Returns 0 on success
5443  */
amdgpu_dm_initialize_drm_device(struct amdgpu_device * adev)5444 static int amdgpu_dm_initialize_drm_device(struct amdgpu_device *adev)
5445 {
5446 	struct amdgpu_display_manager *dm = &adev->dm;
5447 	s32 i;
5448 	struct amdgpu_dm_connector *aconnector = NULL;
5449 	struct amdgpu_encoder *aencoder = NULL;
5450 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5451 	u32 link_cnt;
5452 	s32 primary_planes;
5453 	enum dc_connection_type new_connection_type = dc_connection_none;
5454 	const struct dc_plane_cap *plane;
5455 	bool psr_feature_enabled = false;
5456 	bool replay_feature_enabled = false;
5457 	int max_overlay = dm->dc->caps.max_slave_planes;
5458 
5459 	dm->display_indexes_num = dm->dc->caps.max_streams;
5460 	/* Update the actual used number of crtc */
5461 	adev->mode_info.num_crtc = adev->dm.display_indexes_num;
5462 
5463 	amdgpu_dm_set_irq_funcs(adev);
5464 
5465 	link_cnt = dm->dc->caps.max_links;
5466 	if (amdgpu_dm_mode_config_init(dm->adev)) {
5467 		drm_err(adev_to_drm(adev), "DM: Failed to initialize mode config\n");
5468 		return -EINVAL;
5469 	}
5470 
5471 	/* There is one primary plane per CRTC */
5472 	primary_planes = dm->dc->caps.max_streams;
5473 	if (primary_planes > AMDGPU_MAX_PLANES) {
5474 		drm_err(adev_to_drm(adev), "DM: Plane nums out of 6 planes\n");
5475 		return -EINVAL;
5476 	}
5477 
5478 	/*
5479 	 * Initialize primary planes, implicit planes for legacy IOCTLS.
5480 	 * Order is reversed to match iteration order in atomic check.
5481 	 */
5482 	for (i = (primary_planes - 1); i >= 0; i--) {
5483 		plane = &dm->dc->caps.planes[i];
5484 
5485 		if (initialize_plane(dm, mode_info, i,
5486 				     DRM_PLANE_TYPE_PRIMARY, plane)) {
5487 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize primary plane\n");
5488 			goto fail;
5489 		}
5490 	}
5491 
5492 	/*
5493 	 * Initialize overlay planes, index starting after primary planes.
5494 	 * These planes have a higher DRM index than the primary planes since
5495 	 * they should be considered as having a higher z-order.
5496 	 * Order is reversed to match iteration order in atomic check.
5497 	 *
5498 	 * Only support DCN for now, and only expose one so we don't encourage
5499 	 * userspace to use up all the pipes.
5500 	 */
5501 	for (i = 0; i < dm->dc->caps.max_planes; ++i) {
5502 		struct dc_plane_cap *plane = &dm->dc->caps.planes[i];
5503 
5504 		/* Do not create overlay if MPO disabled */
5505 		if (amdgpu_dc_debug_mask & DC_DISABLE_MPO)
5506 			break;
5507 
5508 		if (plane->type != DC_PLANE_TYPE_DCN_UNIVERSAL)
5509 			continue;
5510 
5511 		if (!plane->pixel_format_support.argb8888)
5512 			continue;
5513 
5514 		if (max_overlay-- == 0)
5515 			break;
5516 
5517 		if (initialize_plane(dm, NULL, primary_planes + i,
5518 				     DRM_PLANE_TYPE_OVERLAY, plane)) {
5519 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize overlay plane\n");
5520 			goto fail;
5521 		}
5522 	}
5523 
5524 	for (i = 0; i < dm->dc->caps.max_streams; i++)
5525 		if (amdgpu_dm_crtc_init(dm, mode_info->planes[i], i)) {
5526 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize crtc\n");
5527 			goto fail;
5528 		}
5529 
5530 	/* Use Outbox interrupt */
5531 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5532 	case IP_VERSION(3, 0, 0):
5533 	case IP_VERSION(3, 1, 2):
5534 	case IP_VERSION(3, 1, 3):
5535 	case IP_VERSION(3, 1, 4):
5536 	case IP_VERSION(3, 1, 5):
5537 	case IP_VERSION(3, 1, 6):
5538 	case IP_VERSION(3, 2, 0):
5539 	case IP_VERSION(3, 2, 1):
5540 	case IP_VERSION(2, 1, 0):
5541 	case IP_VERSION(3, 5, 0):
5542 	case IP_VERSION(3, 5, 1):
5543 	case IP_VERSION(3, 6, 0):
5544 	case IP_VERSION(4, 0, 1):
5545 		if (register_outbox_irq_handlers(dm->adev)) {
5546 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5547 			goto fail;
5548 		}
5549 		break;
5550 	default:
5551 		drm_dbg_kms(adev_to_drm(adev), "Unsupported DCN IP version for outbox: 0x%X\n",
5552 			      amdgpu_ip_version(adev, DCE_HWIP, 0));
5553 	}
5554 
5555 	/* Determine whether to enable PSR support by default. */
5556 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_PSR)) {
5557 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5558 		case IP_VERSION(3, 1, 2):
5559 		case IP_VERSION(3, 1, 3):
5560 		case IP_VERSION(3, 1, 4):
5561 		case IP_VERSION(3, 1, 5):
5562 		case IP_VERSION(3, 1, 6):
5563 		case IP_VERSION(3, 2, 0):
5564 		case IP_VERSION(3, 2, 1):
5565 		case IP_VERSION(3, 5, 0):
5566 		case IP_VERSION(3, 5, 1):
5567 		case IP_VERSION(3, 6, 0):
5568 		case IP_VERSION(4, 0, 1):
5569 			psr_feature_enabled = true;
5570 			break;
5571 		default:
5572 			psr_feature_enabled = amdgpu_dc_feature_mask & DC_PSR_MASK;
5573 			break;
5574 		}
5575 	}
5576 
5577 	/* Determine whether to enable Replay support by default. */
5578 	if (!(amdgpu_dc_debug_mask & DC_DISABLE_REPLAY)) {
5579 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5580 		case IP_VERSION(3, 1, 4):
5581 		case IP_VERSION(3, 2, 0):
5582 		case IP_VERSION(3, 2, 1):
5583 		case IP_VERSION(3, 5, 0):
5584 		case IP_VERSION(3, 5, 1):
5585 		case IP_VERSION(3, 6, 0):
5586 			replay_feature_enabled = true;
5587 			break;
5588 
5589 		default:
5590 			replay_feature_enabled = amdgpu_dc_feature_mask & DC_REPLAY_MASK;
5591 			break;
5592 		}
5593 	}
5594 
5595 	if (link_cnt > MAX_LINKS) {
5596 		drm_err(adev_to_drm(adev),
5597 			"KMS: Cannot support more than %d display indexes\n",
5598 				MAX_LINKS);
5599 		goto fail;
5600 	}
5601 
5602 	/* loops over all connectors on the board */
5603 	for (i = 0; i < link_cnt; i++) {
5604 		struct dc_link *link = NULL;
5605 
5606 		link = dc_get_link_at_index(dm->dc, i);
5607 
5608 		if (link->connector_signal == SIGNAL_TYPE_VIRTUAL) {
5609 			struct amdgpu_dm_wb_connector *wbcon = kzalloc_obj(*wbcon,
5610 									   GFP_KERNEL);
5611 
5612 			if (!wbcon) {
5613 				drm_err(adev_to_drm(adev), "KMS: Failed to allocate writeback connector\n");
5614 				continue;
5615 			}
5616 
5617 			if (amdgpu_dm_wb_connector_init(dm, wbcon, i)) {
5618 				drm_err(adev_to_drm(adev), "KMS: Failed to initialize writeback connector\n");
5619 				kfree(wbcon);
5620 				continue;
5621 			}
5622 
5623 			link->psr_settings.psr_feature_enabled = false;
5624 			link->psr_settings.psr_version = DC_PSR_VERSION_UNSUPPORTED;
5625 
5626 			continue;
5627 		}
5628 
5629 		aconnector = kzalloc_obj(*aconnector, GFP_KERNEL);
5630 		if (!aconnector)
5631 			goto fail;
5632 
5633 		aencoder = kzalloc_obj(*aencoder, GFP_KERNEL);
5634 		if (!aencoder)
5635 			goto fail;
5636 
5637 		if (amdgpu_dm_encoder_init(dm->ddev, aencoder, i)) {
5638 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize encoder\n");
5639 			goto fail;
5640 		}
5641 
5642 		if (amdgpu_dm_connector_init(dm, aconnector, i, aencoder)) {
5643 			drm_err(adev_to_drm(adev), "KMS: Failed to initialize connector\n");
5644 			goto fail;
5645 		}
5646 
5647 		if (dm->hpd_rx_offload_wq)
5648 			dm->hpd_rx_offload_wq[aconnector->base.index].aconnector =
5649 				aconnector;
5650 
5651 		if (!dc_link_detect_connection_type(link, &new_connection_type))
5652 			drm_err(adev_to_drm(adev), "KMS: Failed to detect connector\n");
5653 
5654 		if (aconnector->base.force && new_connection_type == dc_connection_none) {
5655 			emulated_link_detect(link);
5656 			amdgpu_dm_update_connector_after_detect(aconnector);
5657 		} else {
5658 			bool ret = false;
5659 
5660 			mutex_lock(&dm->dc_lock);
5661 			dc_exit_ips_for_hw_access(dm->dc);
5662 			ret = dc_link_detect(link, DETECT_REASON_BOOT);
5663 			mutex_unlock(&dm->dc_lock);
5664 
5665 			if (ret) {
5666 				amdgpu_dm_update_connector_after_detect(aconnector);
5667 				setup_backlight_device(dm, aconnector);
5668 
5669 				/* Disable PSR if Replay can be enabled */
5670 				if (replay_feature_enabled)
5671 					if (amdgpu_dm_set_replay_caps(link, aconnector))
5672 						psr_feature_enabled = false;
5673 
5674 				if (psr_feature_enabled) {
5675 					amdgpu_dm_set_psr_caps(link);
5676 					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",
5677 						 aconnector->base.name,
5678 						 link->psr_settings.psr_feature_enabled,
5679 						 link->psr_settings.psr_version,
5680 						 link->dpcd_caps.psr_info.psr_version,
5681 						 link->dpcd_caps.psr_info.psr_dpcd_caps.raw,
5682 						 link->dpcd_caps.psr_info.psr2_su_y_granularity_cap);
5683 				}
5684 			}
5685 		}
5686 		amdgpu_set_panel_orientation(&aconnector->base);
5687 	}
5688 
5689 	/* Debug dump: list all DC links and their associated sinks after detection
5690 	 * is complete for all connectors. This provides a comprehensive view of the
5691 	 * final state without repeating the dump for each connector.
5692 	 */
5693 	amdgpu_dm_dump_links_and_sinks(adev);
5694 
5695 	/* Software is initialized. Now we can register interrupt handlers. */
5696 	switch (adev->asic_type) {
5697 #if defined(CONFIG_DRM_AMD_DC_SI)
5698 	case CHIP_TAHITI:
5699 	case CHIP_PITCAIRN:
5700 	case CHIP_VERDE:
5701 	case CHIP_OLAND:
5702 		if (dce60_register_irq_handlers(dm->adev)) {
5703 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5704 			goto fail;
5705 		}
5706 		break;
5707 #endif
5708 	case CHIP_BONAIRE:
5709 	case CHIP_HAWAII:
5710 	case CHIP_KAVERI:
5711 	case CHIP_KABINI:
5712 	case CHIP_MULLINS:
5713 	case CHIP_TONGA:
5714 	case CHIP_FIJI:
5715 	case CHIP_CARRIZO:
5716 	case CHIP_STONEY:
5717 	case CHIP_POLARIS11:
5718 	case CHIP_POLARIS10:
5719 	case CHIP_POLARIS12:
5720 	case CHIP_VEGAM:
5721 	case CHIP_VEGA10:
5722 	case CHIP_VEGA12:
5723 	case CHIP_VEGA20:
5724 		if (dce110_register_irq_handlers(dm->adev)) {
5725 			drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5726 			goto fail;
5727 		}
5728 		break;
5729 	default:
5730 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5731 		case IP_VERSION(1, 0, 0):
5732 		case IP_VERSION(1, 0, 1):
5733 		case IP_VERSION(2, 0, 2):
5734 		case IP_VERSION(2, 0, 3):
5735 		case IP_VERSION(2, 0, 0):
5736 		case IP_VERSION(2, 1, 0):
5737 		case IP_VERSION(3, 0, 0):
5738 		case IP_VERSION(3, 0, 2):
5739 		case IP_VERSION(3, 0, 3):
5740 		case IP_VERSION(3, 0, 1):
5741 		case IP_VERSION(3, 1, 2):
5742 		case IP_VERSION(3, 1, 3):
5743 		case IP_VERSION(3, 1, 4):
5744 		case IP_VERSION(3, 1, 5):
5745 		case IP_VERSION(3, 1, 6):
5746 		case IP_VERSION(3, 2, 0):
5747 		case IP_VERSION(3, 2, 1):
5748 		case IP_VERSION(3, 5, 0):
5749 		case IP_VERSION(3, 5, 1):
5750 		case IP_VERSION(3, 6, 0):
5751 		case IP_VERSION(4, 0, 1):
5752 			if (dcn10_register_irq_handlers(dm->adev)) {
5753 				drm_err(adev_to_drm(adev), "DM: Failed to initialize IRQ\n");
5754 				goto fail;
5755 			}
5756 			break;
5757 		default:
5758 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%X\n",
5759 					amdgpu_ip_version(adev, DCE_HWIP, 0));
5760 			goto fail;
5761 		}
5762 		break;
5763 	}
5764 
5765 	return 0;
5766 fail:
5767 	kfree(aencoder);
5768 	kfree(aconnector);
5769 
5770 	return -EINVAL;
5771 }
5772 
amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager * dm)5773 static void amdgpu_dm_destroy_drm_device(struct amdgpu_display_manager *dm)
5774 {
5775 	if (dm->atomic_obj.state)
5776 		drm_atomic_private_obj_fini(&dm->atomic_obj);
5777 }
5778 
5779 /******************************************************************************
5780  * amdgpu_display_funcs functions
5781  *****************************************************************************/
5782 
5783 /*
5784  * dm_bandwidth_update - program display watermarks
5785  *
5786  * @adev: amdgpu_device pointer
5787  *
5788  * Calculate and program the display watermarks and line buffer allocation.
5789  */
dm_bandwidth_update(struct amdgpu_device * adev)5790 static void dm_bandwidth_update(struct amdgpu_device *adev)
5791 {
5792 	/* TODO: implement later */
5793 }
5794 
5795 static const struct amdgpu_display_funcs dm_display_funcs = {
5796 	.bandwidth_update = dm_bandwidth_update, /* called unconditionally */
5797 	.vblank_get_counter = dm_vblank_get_counter,/* called unconditionally */
5798 	.backlight_set_level = NULL, /* never called for DC */
5799 	.backlight_get_level = NULL, /* never called for DC */
5800 	.hpd_sense = NULL,/* called unconditionally */
5801 	.hpd_set_polarity = NULL, /* called unconditionally */
5802 	.hpd_get_gpio_reg = NULL, /* VBIOS parsing. DAL does it. */
5803 	.page_flip_get_scanoutpos =
5804 		dm_crtc_get_scanoutpos,/* called unconditionally */
5805 	.add_encoder = NULL, /* VBIOS parsing. DAL does it. */
5806 	.add_connector = NULL, /* VBIOS parsing. DAL does it. */
5807 };
5808 
5809 #if defined(CONFIG_DEBUG_KERNEL_DC)
5810 
s3_debug_store(struct device * device,struct device_attribute * attr,const char * buf,size_t count)5811 static ssize_t s3_debug_store(struct device *device,
5812 			      struct device_attribute *attr,
5813 			      const char *buf,
5814 			      size_t count)
5815 {
5816 	int ret;
5817 	int s3_state;
5818 	struct drm_device *drm_dev = dev_get_drvdata(device);
5819 	struct amdgpu_device *adev = drm_to_adev(drm_dev);
5820 	struct amdgpu_ip_block *ip_block;
5821 
5822 	ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_DCE);
5823 	if (!ip_block)
5824 		return -EINVAL;
5825 
5826 	ret = kstrtoint(buf, 0, &s3_state);
5827 
5828 	if (ret == 0) {
5829 		if (s3_state) {
5830 			dm_resume(ip_block);
5831 			drm_kms_helper_hotplug_event(adev_to_drm(adev));
5832 		} else
5833 			dm_suspend(ip_block);
5834 	}
5835 
5836 	return ret == 0 ? count : 0;
5837 }
5838 
5839 DEVICE_ATTR_WO(s3_debug);
5840 
5841 #endif
5842 
dm_init_microcode(struct amdgpu_device * adev)5843 static int dm_init_microcode(struct amdgpu_device *adev)
5844 {
5845 	char *fw_name_dmub;
5846 	int r;
5847 
5848 	switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5849 	case IP_VERSION(2, 1, 0):
5850 		fw_name_dmub = FIRMWARE_RENOIR_DMUB;
5851 		if (ASICREV_IS_GREEN_SARDINE(adev->external_rev_id))
5852 			fw_name_dmub = FIRMWARE_GREEN_SARDINE_DMUB;
5853 		break;
5854 	case IP_VERSION(3, 0, 0):
5855 		if (amdgpu_ip_version(adev, GC_HWIP, 0) == IP_VERSION(10, 3, 0))
5856 			fw_name_dmub = FIRMWARE_SIENNA_CICHLID_DMUB;
5857 		else
5858 			fw_name_dmub = FIRMWARE_NAVY_FLOUNDER_DMUB;
5859 		break;
5860 	case IP_VERSION(3, 0, 1):
5861 		fw_name_dmub = FIRMWARE_VANGOGH_DMUB;
5862 		break;
5863 	case IP_VERSION(3, 0, 2):
5864 		fw_name_dmub = FIRMWARE_DIMGREY_CAVEFISH_DMUB;
5865 		break;
5866 	case IP_VERSION(3, 0, 3):
5867 		fw_name_dmub = FIRMWARE_BEIGE_GOBY_DMUB;
5868 		break;
5869 	case IP_VERSION(3, 1, 2):
5870 	case IP_VERSION(3, 1, 3):
5871 		fw_name_dmub = FIRMWARE_YELLOW_CARP_DMUB;
5872 		break;
5873 	case IP_VERSION(3, 1, 4):
5874 		fw_name_dmub = FIRMWARE_DCN_314_DMUB;
5875 		break;
5876 	case IP_VERSION(3, 1, 5):
5877 		fw_name_dmub = FIRMWARE_DCN_315_DMUB;
5878 		break;
5879 	case IP_VERSION(3, 1, 6):
5880 		fw_name_dmub = FIRMWARE_DCN316_DMUB;
5881 		break;
5882 	case IP_VERSION(3, 2, 0):
5883 		fw_name_dmub = FIRMWARE_DCN_V3_2_0_DMCUB;
5884 		break;
5885 	case IP_VERSION(3, 2, 1):
5886 		fw_name_dmub = FIRMWARE_DCN_V3_2_1_DMCUB;
5887 		break;
5888 	case IP_VERSION(3, 5, 0):
5889 		fw_name_dmub = FIRMWARE_DCN_35_DMUB;
5890 		break;
5891 	case IP_VERSION(3, 5, 1):
5892 		fw_name_dmub = FIRMWARE_DCN_351_DMUB;
5893 		break;
5894 	case IP_VERSION(3, 6, 0):
5895 		fw_name_dmub = FIRMWARE_DCN_36_DMUB;
5896 		break;
5897 	case IP_VERSION(4, 0, 1):
5898 		fw_name_dmub = FIRMWARE_DCN_401_DMUB;
5899 		break;
5900 	default:
5901 		/* ASIC doesn't support DMUB. */
5902 		return 0;
5903 	}
5904 	r = amdgpu_ucode_request(adev, &adev->dm.dmub_fw, AMDGPU_UCODE_REQUIRED,
5905 				 "%s", fw_name_dmub);
5906 	return r;
5907 }
5908 
dm_early_init(struct amdgpu_ip_block * ip_block)5909 static int dm_early_init(struct amdgpu_ip_block *ip_block)
5910 {
5911 	struct amdgpu_device *adev = ip_block->adev;
5912 	struct amdgpu_mode_info *mode_info = &adev->mode_info;
5913 	struct atom_context *ctx = mode_info->atom_context;
5914 	int index = GetIndexIntoMasterTable(DATA, Object_Header);
5915 	u16 data_offset;
5916 
5917 	/* if there is no object header, skip DM */
5918 	if (!amdgpu_atom_parse_data_header(ctx, index, NULL, NULL, NULL, &data_offset)) {
5919 		adev->harvest_ip_mask |= AMD_HARVEST_IP_DMU_MASK;
5920 		drm_info(adev_to_drm(adev), "No object header, skipping DM\n");
5921 		return -ENOENT;
5922 	}
5923 
5924 	switch (adev->asic_type) {
5925 #if defined(CONFIG_DRM_AMD_DC_SI)
5926 	case CHIP_TAHITI:
5927 	case CHIP_PITCAIRN:
5928 	case CHIP_VERDE:
5929 		adev->mode_info.num_crtc = 6;
5930 		adev->mode_info.num_hpd = 6;
5931 		adev->mode_info.num_dig = 6;
5932 		break;
5933 	case CHIP_OLAND:
5934 		adev->mode_info.num_crtc = 2;
5935 		adev->mode_info.num_hpd = 2;
5936 		adev->mode_info.num_dig = 2;
5937 		break;
5938 #endif
5939 	case CHIP_BONAIRE:
5940 	case CHIP_HAWAII:
5941 		adev->mode_info.num_crtc = 6;
5942 		adev->mode_info.num_hpd = 6;
5943 		adev->mode_info.num_dig = 6;
5944 		break;
5945 	case CHIP_KAVERI:
5946 		adev->mode_info.num_crtc = 4;
5947 		adev->mode_info.num_hpd = 6;
5948 		adev->mode_info.num_dig = 7;
5949 		break;
5950 	case CHIP_KABINI:
5951 	case CHIP_MULLINS:
5952 		adev->mode_info.num_crtc = 2;
5953 		adev->mode_info.num_hpd = 6;
5954 		adev->mode_info.num_dig = 6;
5955 		break;
5956 	case CHIP_FIJI:
5957 	case CHIP_TONGA:
5958 		adev->mode_info.num_crtc = 6;
5959 		adev->mode_info.num_hpd = 6;
5960 		adev->mode_info.num_dig = 7;
5961 		break;
5962 	case CHIP_CARRIZO:
5963 		adev->mode_info.num_crtc = 3;
5964 		adev->mode_info.num_hpd = 6;
5965 		adev->mode_info.num_dig = 9;
5966 		break;
5967 	case CHIP_STONEY:
5968 		adev->mode_info.num_crtc = 2;
5969 		adev->mode_info.num_hpd = 6;
5970 		adev->mode_info.num_dig = 9;
5971 		break;
5972 	case CHIP_POLARIS11:
5973 	case CHIP_POLARIS12:
5974 		adev->mode_info.num_crtc = 5;
5975 		adev->mode_info.num_hpd = 5;
5976 		adev->mode_info.num_dig = 5;
5977 		break;
5978 	case CHIP_POLARIS10:
5979 	case CHIP_VEGAM:
5980 		adev->mode_info.num_crtc = 6;
5981 		adev->mode_info.num_hpd = 6;
5982 		adev->mode_info.num_dig = 6;
5983 		break;
5984 	case CHIP_VEGA10:
5985 	case CHIP_VEGA12:
5986 	case CHIP_VEGA20:
5987 		adev->mode_info.num_crtc = 6;
5988 		adev->mode_info.num_hpd = 6;
5989 		adev->mode_info.num_dig = 6;
5990 		break;
5991 	default:
5992 
5993 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
5994 		case IP_VERSION(2, 0, 2):
5995 		case IP_VERSION(3, 0, 0):
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 IP_VERSION(2, 0, 0):
6001 		case IP_VERSION(3, 0, 2):
6002 			adev->mode_info.num_crtc = 5;
6003 			adev->mode_info.num_hpd = 5;
6004 			adev->mode_info.num_dig = 5;
6005 			break;
6006 		case IP_VERSION(2, 0, 3):
6007 		case IP_VERSION(3, 0, 3):
6008 			adev->mode_info.num_crtc = 2;
6009 			adev->mode_info.num_hpd = 2;
6010 			adev->mode_info.num_dig = 2;
6011 			break;
6012 		case IP_VERSION(1, 0, 0):
6013 		case IP_VERSION(1, 0, 1):
6014 		case IP_VERSION(3, 0, 1):
6015 		case IP_VERSION(2, 1, 0):
6016 		case IP_VERSION(3, 1, 2):
6017 		case IP_VERSION(3, 1, 3):
6018 		case IP_VERSION(3, 1, 4):
6019 		case IP_VERSION(3, 1, 5):
6020 		case IP_VERSION(3, 1, 6):
6021 		case IP_VERSION(3, 2, 0):
6022 		case IP_VERSION(3, 2, 1):
6023 		case IP_VERSION(3, 5, 0):
6024 		case IP_VERSION(3, 5, 1):
6025 		case IP_VERSION(3, 6, 0):
6026 		case IP_VERSION(4, 0, 1):
6027 			adev->mode_info.num_crtc = 4;
6028 			adev->mode_info.num_hpd = 4;
6029 			adev->mode_info.num_dig = 4;
6030 			break;
6031 		default:
6032 			drm_err(adev_to_drm(adev), "Unsupported DCE IP versions: 0x%x\n",
6033 					amdgpu_ip_version(adev, DCE_HWIP, 0));
6034 			return -EINVAL;
6035 		}
6036 		break;
6037 	}
6038 
6039 	if (adev->mode_info.funcs == NULL)
6040 		adev->mode_info.funcs = &dm_display_funcs;
6041 
6042 	/*
6043 	 * Note: Do NOT change adev->audio_endpt_rreg and
6044 	 * adev->audio_endpt_wreg because they are initialised in
6045 	 * amdgpu_device_init()
6046 	 */
6047 #if defined(CONFIG_DEBUG_KERNEL_DC)
6048 	device_create_file(
6049 		adev_to_drm(adev)->dev,
6050 		&dev_attr_s3_debug);
6051 #endif
6052 	adev->dc_enabled = true;
6053 
6054 	return dm_init_microcode(adev);
6055 }
6056 
modereset_required(struct drm_crtc_state * crtc_state)6057 static bool modereset_required(struct drm_crtc_state *crtc_state)
6058 {
6059 	return !crtc_state->active && drm_atomic_crtc_needs_modeset(crtc_state);
6060 }
6061 
amdgpu_dm_encoder_destroy(struct drm_encoder * encoder)6062 static void amdgpu_dm_encoder_destroy(struct drm_encoder *encoder)
6063 {
6064 	drm_encoder_cleanup(encoder);
6065 	kfree(encoder);
6066 }
6067 
6068 static const struct drm_encoder_funcs amdgpu_dm_encoder_funcs = {
6069 	.destroy = amdgpu_dm_encoder_destroy,
6070 };
6071 
6072 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)6073 fill_plane_color_attributes(const struct drm_plane_state *plane_state,
6074 			    const enum surface_pixel_format format,
6075 			    enum dc_color_space *color_space)
6076 {
6077 	bool full_range;
6078 
6079 	*color_space = COLOR_SPACE_SRGB;
6080 
6081 	/* Ignore properties when DRM_CLIENT_CAP_PLANE_COLOR_PIPELINE is set */
6082 	if (plane_state->state && plane_state->state->plane_color_pipeline)
6083 		return 0;
6084 
6085 	/* DRM color properties only affect non-RGB formats. */
6086 	if (format < SURFACE_PIXEL_FORMAT_VIDEO_BEGIN)
6087 		return 0;
6088 
6089 	full_range = (plane_state->color_range == DRM_COLOR_YCBCR_FULL_RANGE);
6090 
6091 	switch (plane_state->color_encoding) {
6092 	case DRM_COLOR_YCBCR_BT601:
6093 		if (full_range)
6094 			*color_space = COLOR_SPACE_YCBCR601;
6095 		else
6096 			*color_space = COLOR_SPACE_YCBCR601_LIMITED;
6097 		break;
6098 
6099 	case DRM_COLOR_YCBCR_BT709:
6100 		if (full_range)
6101 			*color_space = COLOR_SPACE_YCBCR709;
6102 		else
6103 			*color_space = COLOR_SPACE_YCBCR709_LIMITED;
6104 		break;
6105 
6106 	case DRM_COLOR_YCBCR_BT2020:
6107 		if (full_range)
6108 			*color_space = COLOR_SPACE_2020_YCBCR_FULL;
6109 		else
6110 			*color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6111 		break;
6112 
6113 	default:
6114 		return -EINVAL;
6115 	}
6116 
6117 	return 0;
6118 }
6119 
6120 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)6121 fill_dc_plane_info_and_addr(struct amdgpu_device *adev,
6122 			    const struct drm_plane_state *plane_state,
6123 			    const u64 tiling_flags,
6124 			    struct dc_plane_info *plane_info,
6125 			    struct dc_plane_address *address,
6126 			    bool tmz_surface)
6127 {
6128 	const struct drm_framebuffer *fb = plane_state->fb;
6129 	const struct amdgpu_framebuffer *afb =
6130 		to_amdgpu_framebuffer(plane_state->fb);
6131 	int ret;
6132 
6133 	memset(plane_info, 0, sizeof(*plane_info));
6134 
6135 	switch (fb->format->format) {
6136 	case DRM_FORMAT_C8:
6137 		plane_info->format =
6138 			SURFACE_PIXEL_FORMAT_GRPH_PALETA_256_COLORS;
6139 		break;
6140 	case DRM_FORMAT_RGB565:
6141 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_RGB565;
6142 		break;
6143 	case DRM_FORMAT_XRGB8888:
6144 	case DRM_FORMAT_ARGB8888:
6145 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
6146 		break;
6147 	case DRM_FORMAT_XRGB2101010:
6148 	case DRM_FORMAT_ARGB2101010:
6149 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB2101010;
6150 		break;
6151 	case DRM_FORMAT_XBGR2101010:
6152 	case DRM_FORMAT_ABGR2101010:
6153 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR2101010;
6154 		break;
6155 	case DRM_FORMAT_XBGR8888:
6156 	case DRM_FORMAT_ABGR8888:
6157 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR8888;
6158 		break;
6159 	case DRM_FORMAT_NV21:
6160 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCbCr;
6161 		break;
6162 	case DRM_FORMAT_NV12:
6163 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_YCrCb;
6164 		break;
6165 	case DRM_FORMAT_P010:
6166 		plane_info->format = SURFACE_PIXEL_FORMAT_VIDEO_420_10bpc_YCrCb;
6167 		break;
6168 	case DRM_FORMAT_XRGB16161616F:
6169 	case DRM_FORMAT_ARGB16161616F:
6170 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616F;
6171 		break;
6172 	case DRM_FORMAT_XBGR16161616F:
6173 	case DRM_FORMAT_ABGR16161616F:
6174 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616F;
6175 		break;
6176 	case DRM_FORMAT_XRGB16161616:
6177 	case DRM_FORMAT_ARGB16161616:
6178 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB16161616;
6179 		break;
6180 	case DRM_FORMAT_XBGR16161616:
6181 	case DRM_FORMAT_ABGR16161616:
6182 		plane_info->format = SURFACE_PIXEL_FORMAT_GRPH_ABGR16161616;
6183 		break;
6184 	default:
6185 		drm_err(adev_to_drm(adev),
6186 			"Unsupported screen format %p4cc\n",
6187 			&fb->format->format);
6188 		return -EINVAL;
6189 	}
6190 
6191 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
6192 	case DRM_MODE_ROTATE_0:
6193 		plane_info->rotation = ROTATION_ANGLE_0;
6194 		break;
6195 	case DRM_MODE_ROTATE_90:
6196 		plane_info->rotation = ROTATION_ANGLE_90;
6197 		break;
6198 	case DRM_MODE_ROTATE_180:
6199 		plane_info->rotation = ROTATION_ANGLE_180;
6200 		break;
6201 	case DRM_MODE_ROTATE_270:
6202 		plane_info->rotation = ROTATION_ANGLE_270;
6203 		break;
6204 	default:
6205 		plane_info->rotation = ROTATION_ANGLE_0;
6206 		break;
6207 	}
6208 
6209 
6210 	plane_info->visible = true;
6211 	plane_info->stereo_format = PLANE_STEREO_FORMAT_NONE;
6212 
6213 	plane_info->layer_index = plane_state->normalized_zpos;
6214 
6215 	ret = fill_plane_color_attributes(plane_state, plane_info->format,
6216 					  &plane_info->color_space);
6217 	if (ret)
6218 		return ret;
6219 
6220 	ret = amdgpu_dm_plane_fill_plane_buffer_attributes(adev, afb, plane_info->format,
6221 					   plane_info->rotation, tiling_flags,
6222 					   &plane_info->tiling_info,
6223 					   &plane_info->plane_size,
6224 					   &plane_info->dcc, address,
6225 					   tmz_surface);
6226 	if (ret)
6227 		return ret;
6228 
6229 	amdgpu_dm_plane_fill_blending_from_plane_state(
6230 		plane_state, &plane_info->per_pixel_alpha, &plane_info->pre_multiplied_alpha,
6231 		&plane_info->global_alpha, &plane_info->global_alpha_value);
6232 
6233 	return 0;
6234 }
6235 
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)6236 static int fill_dc_plane_attributes(struct amdgpu_device *adev,
6237 				    struct dc_plane_state *dc_plane_state,
6238 				    struct drm_plane_state *plane_state,
6239 				    struct drm_crtc_state *crtc_state)
6240 {
6241 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6242 	struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)plane_state->fb;
6243 	struct dc_scaling_info scaling_info;
6244 	struct dc_plane_info plane_info;
6245 	int ret;
6246 
6247 	ret = amdgpu_dm_plane_fill_dc_scaling_info(adev, plane_state, &scaling_info);
6248 	if (ret)
6249 		return ret;
6250 
6251 	dc_plane_state->src_rect = scaling_info.src_rect;
6252 	dc_plane_state->dst_rect = scaling_info.dst_rect;
6253 	dc_plane_state->clip_rect = scaling_info.clip_rect;
6254 	dc_plane_state->scaling_quality = scaling_info.scaling_quality;
6255 
6256 	ret = fill_dc_plane_info_and_addr(adev, plane_state,
6257 					  afb->tiling_flags,
6258 					  &plane_info,
6259 					  &dc_plane_state->address,
6260 					  afb->tmz_surface);
6261 	if (ret)
6262 		return ret;
6263 
6264 	dc_plane_state->format = plane_info.format;
6265 	dc_plane_state->color_space = plane_info.color_space;
6266 	dc_plane_state->format = plane_info.format;
6267 	dc_plane_state->plane_size = plane_info.plane_size;
6268 	dc_plane_state->rotation = plane_info.rotation;
6269 	dc_plane_state->horizontal_mirror = plane_info.horizontal_mirror;
6270 	dc_plane_state->stereo_format = plane_info.stereo_format;
6271 	dc_plane_state->tiling_info = plane_info.tiling_info;
6272 	dc_plane_state->visible = plane_info.visible;
6273 	dc_plane_state->per_pixel_alpha = plane_info.per_pixel_alpha;
6274 	dc_plane_state->pre_multiplied_alpha = plane_info.pre_multiplied_alpha;
6275 	dc_plane_state->global_alpha = plane_info.global_alpha;
6276 	dc_plane_state->global_alpha_value = plane_info.global_alpha_value;
6277 	dc_plane_state->dcc = plane_info.dcc;
6278 	dc_plane_state->layer_index = plane_info.layer_index;
6279 	dc_plane_state->flip_int_enabled = true;
6280 
6281 	/*
6282 	 * Always set input transfer function, since plane state is refreshed
6283 	 * every time.
6284 	 */
6285 	ret = amdgpu_dm_update_plane_color_mgmt(dm_crtc_state,
6286 						plane_state,
6287 						dc_plane_state);
6288 	if (ret)
6289 		return ret;
6290 
6291 	return 0;
6292 }
6293 
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)6294 static inline void fill_dc_dirty_rect(struct drm_plane *plane,
6295 				      struct rect *dirty_rect, int32_t x,
6296 				      s32 y, s32 width, s32 height,
6297 				      int *i, bool ffu)
6298 {
6299 	WARN_ON(*i >= DC_MAX_DIRTY_RECTS);
6300 
6301 	dirty_rect->x = x;
6302 	dirty_rect->y = y;
6303 	dirty_rect->width = width;
6304 	dirty_rect->height = height;
6305 
6306 	if (ffu)
6307 		drm_dbg(plane->dev,
6308 			"[PLANE:%d] PSR FFU dirty rect size (%d, %d)\n",
6309 			plane->base.id, width, height);
6310 	else
6311 		drm_dbg(plane->dev,
6312 			"[PLANE:%d] PSR SU dirty rect at (%d, %d) size (%d, %d)",
6313 			plane->base.id, x, y, width, height);
6314 
6315 	(*i)++;
6316 }
6317 
6318 /**
6319  * fill_dc_dirty_rects() - Fill DC dirty regions for PSR selective updates
6320  *
6321  * @plane: DRM plane containing dirty regions that need to be flushed to the eDP
6322  *         remote fb
6323  * @old_plane_state: Old state of @plane
6324  * @new_plane_state: New state of @plane
6325  * @crtc_state: New state of CRTC connected to the @plane
6326  * @flip_addrs: DC flip tracking struct, which also tracts dirty rects
6327  * @is_psr_su: Flag indicating whether Panel Self Refresh Selective Update (PSR SU) is enabled.
6328  *             If PSR SU is enabled and damage clips are available, only the regions of the screen
6329  *             that have changed will be updated. If PSR SU is not enabled,
6330  *             or if damage clips are not available, the entire screen will be updated.
6331  * @dirty_regions_changed: dirty regions changed
6332  *
6333  * For PSR SU, DC informs the DMUB uController of dirty rectangle regions
6334  * (referred to as "damage clips" in DRM nomenclature) that require updating on
6335  * the eDP remote buffer. The responsibility of specifying the dirty regions is
6336  * amdgpu_dm's.
6337  *
6338  * A damage-aware DRM client should fill the FB_DAMAGE_CLIPS property on the
6339  * plane with regions that require flushing to the eDP remote buffer. In
6340  * addition, certain use cases - such as cursor and multi-plane overlay (MPO) -
6341  * implicitly provide damage clips without any client support via the plane
6342  * bounds.
6343  */
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)6344 static void fill_dc_dirty_rects(struct drm_plane *plane,
6345 				struct drm_plane_state *old_plane_state,
6346 				struct drm_plane_state *new_plane_state,
6347 				struct drm_crtc_state *crtc_state,
6348 				struct dc_flip_addrs *flip_addrs,
6349 				bool is_psr_su,
6350 				bool *dirty_regions_changed)
6351 {
6352 	struct dm_crtc_state *dm_crtc_state = to_dm_crtc_state(crtc_state);
6353 	struct rect *dirty_rects = flip_addrs->dirty_rects;
6354 	u32 num_clips;
6355 	struct drm_mode_rect *clips;
6356 	bool bb_changed;
6357 	bool fb_changed;
6358 	u32 i = 0;
6359 	*dirty_regions_changed = false;
6360 
6361 	/*
6362 	 * Cursor plane has it's own dirty rect update interface. See
6363 	 * dcn10_dmub_update_cursor_data and dmub_cmd_update_cursor_info_data
6364 	 */
6365 	if (plane->type == DRM_PLANE_TYPE_CURSOR)
6366 		return;
6367 
6368 	if (new_plane_state->rotation != DRM_MODE_ROTATE_0)
6369 		goto ffu;
6370 
6371 	num_clips = drm_plane_get_damage_clips_count(new_plane_state);
6372 	clips = drm_plane_get_damage_clips(new_plane_state);
6373 
6374 	if (num_clips && (!amdgpu_damage_clips || (amdgpu_damage_clips < 0 &&
6375 						   is_psr_su)))
6376 		goto ffu;
6377 
6378 	if (!dm_crtc_state->mpo_requested) {
6379 		if (!num_clips || num_clips > DC_MAX_DIRTY_RECTS)
6380 			goto ffu;
6381 
6382 		for (; flip_addrs->dirty_rect_count < num_clips; clips++)
6383 			fill_dc_dirty_rect(new_plane_state->plane,
6384 					   &dirty_rects[flip_addrs->dirty_rect_count],
6385 					   clips->x1, clips->y1,
6386 					   clips->x2 - clips->x1, clips->y2 - clips->y1,
6387 					   &flip_addrs->dirty_rect_count,
6388 					   false);
6389 		return;
6390 	}
6391 
6392 	/*
6393 	 * MPO is requested. Add entire plane bounding box to dirty rects if
6394 	 * flipped to or damaged.
6395 	 *
6396 	 * If plane is moved or resized, also add old bounding box to dirty
6397 	 * rects.
6398 	 */
6399 	fb_changed = old_plane_state->fb->base.id !=
6400 		     new_plane_state->fb->base.id;
6401 	bb_changed = (old_plane_state->crtc_x != new_plane_state->crtc_x ||
6402 		      old_plane_state->crtc_y != new_plane_state->crtc_y ||
6403 		      old_plane_state->crtc_w != new_plane_state->crtc_w ||
6404 		      old_plane_state->crtc_h != new_plane_state->crtc_h);
6405 
6406 	drm_dbg(plane->dev,
6407 		"[PLANE:%d] PSR bb_changed:%d fb_changed:%d num_clips:%d\n",
6408 		new_plane_state->plane->base.id,
6409 		bb_changed, fb_changed, num_clips);
6410 
6411 	*dirty_regions_changed = bb_changed;
6412 
6413 	if ((num_clips + (bb_changed ? 2 : 0)) > DC_MAX_DIRTY_RECTS)
6414 		goto ffu;
6415 
6416 	if (bb_changed) {
6417 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6418 				   new_plane_state->crtc_x,
6419 				   new_plane_state->crtc_y,
6420 				   new_plane_state->crtc_w,
6421 				   new_plane_state->crtc_h, &i, false);
6422 
6423 		/* Add old plane bounding-box if plane is moved or resized */
6424 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6425 				   old_plane_state->crtc_x,
6426 				   old_plane_state->crtc_y,
6427 				   old_plane_state->crtc_w,
6428 				   old_plane_state->crtc_h, &i, false);
6429 	}
6430 
6431 	if (num_clips) {
6432 		for (; i < num_clips; clips++)
6433 			fill_dc_dirty_rect(new_plane_state->plane,
6434 					   &dirty_rects[i], clips->x1,
6435 					   clips->y1, clips->x2 - clips->x1,
6436 					   clips->y2 - clips->y1, &i, false);
6437 	} else if (fb_changed && !bb_changed) {
6438 		fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[i],
6439 				   new_plane_state->crtc_x,
6440 				   new_plane_state->crtc_y,
6441 				   new_plane_state->crtc_w,
6442 				   new_plane_state->crtc_h, &i, false);
6443 	}
6444 
6445 	flip_addrs->dirty_rect_count = i;
6446 	return;
6447 
6448 ffu:
6449 	fill_dc_dirty_rect(new_plane_state->plane, &dirty_rects[0], 0, 0,
6450 			   dm_crtc_state->base.mode.crtc_hdisplay,
6451 			   dm_crtc_state->base.mode.crtc_vdisplay,
6452 			   &flip_addrs->dirty_rect_count, true);
6453 }
6454 
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)6455 static void update_stream_scaling_settings(struct drm_device *dev,
6456 					   const struct drm_display_mode *mode,
6457 					   const struct dm_connector_state *dm_state,
6458 					   struct dc_stream_state *stream)
6459 {
6460 	enum amdgpu_rmx_type rmx_type;
6461 
6462 	struct rect src = { 0 }; /* viewport in composition space*/
6463 	struct rect dst = { 0 }; /* stream addressable area */
6464 
6465 	/* no mode. nothing to be done */
6466 	if (!mode)
6467 		return;
6468 
6469 	/* Full screen scaling by default */
6470 	src.width = mode->hdisplay;
6471 	src.height = mode->vdisplay;
6472 	dst.width = stream->timing.h_addressable;
6473 	dst.height = stream->timing.v_addressable;
6474 
6475 	if (dm_state) {
6476 		rmx_type = dm_state->scaling;
6477 		if (rmx_type == RMX_ASPECT || rmx_type == RMX_OFF) {
6478 			if (src.width * dst.height <
6479 					src.height * dst.width) {
6480 				/* height needs less upscaling/more downscaling */
6481 				dst.width = src.width *
6482 						dst.height / src.height;
6483 			} else {
6484 				/* width needs less upscaling/more downscaling */
6485 				dst.height = src.height *
6486 						dst.width / src.width;
6487 			}
6488 		} else if (rmx_type == RMX_CENTER) {
6489 			dst = src;
6490 		}
6491 
6492 		dst.x = (stream->timing.h_addressable - dst.width) / 2;
6493 		dst.y = (stream->timing.v_addressable - dst.height) / 2;
6494 
6495 		if (dm_state->underscan_enable) {
6496 			dst.x += dm_state->underscan_hborder / 2;
6497 			dst.y += dm_state->underscan_vborder / 2;
6498 			dst.width -= dm_state->underscan_hborder;
6499 			dst.height -= dm_state->underscan_vborder;
6500 		}
6501 	}
6502 
6503 	stream->src = src;
6504 	stream->dst = dst;
6505 
6506 	drm_dbg_kms(dev, "Destination Rectangle x:%d  y:%d  width:%d  height:%d\n",
6507 		    dst.x, dst.y, dst.width, dst.height);
6508 
6509 }
6510 
6511 static enum dc_color_depth
convert_color_depth_from_display_info(const struct drm_connector * connector,bool is_y420,int requested_bpc)6512 convert_color_depth_from_display_info(const struct drm_connector *connector,
6513 				      bool is_y420, int requested_bpc)
6514 {
6515 	u8 bpc;
6516 
6517 	if (is_y420) {
6518 		bpc = 8;
6519 
6520 		/* Cap display bpc based on HDMI 2.0 HF-VSDB */
6521 		if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_48)
6522 			bpc = 16;
6523 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_36)
6524 			bpc = 12;
6525 		else if (connector->display_info.hdmi.y420_dc_modes & DRM_EDID_YCBCR420_DC_30)
6526 			bpc = 10;
6527 	} else {
6528 		bpc = (uint8_t)connector->display_info.bpc;
6529 		/* Assume 8 bpc by default if no bpc is specified. */
6530 		bpc = bpc ? bpc : 8;
6531 	}
6532 
6533 	if (requested_bpc > 0) {
6534 		/*
6535 		 * Cap display bpc based on the user requested value.
6536 		 *
6537 		 * The value for state->max_bpc may not correctly updated
6538 		 * depending on when the connector gets added to the state
6539 		 * or if this was called outside of atomic check, so it
6540 		 * can't be used directly.
6541 		 */
6542 		bpc = min_t(u8, bpc, requested_bpc);
6543 
6544 		/* Round down to the nearest even number. */
6545 		bpc = bpc - (bpc & 1);
6546 	}
6547 
6548 	switch (bpc) {
6549 	case 0:
6550 		/*
6551 		 * Temporary Work around, DRM doesn't parse color depth for
6552 		 * EDID revision before 1.4
6553 		 * TODO: Fix edid parsing
6554 		 */
6555 		return COLOR_DEPTH_888;
6556 	case 6:
6557 		return COLOR_DEPTH_666;
6558 	case 8:
6559 		return COLOR_DEPTH_888;
6560 	case 10:
6561 		return COLOR_DEPTH_101010;
6562 	case 12:
6563 		return COLOR_DEPTH_121212;
6564 	case 14:
6565 		return COLOR_DEPTH_141414;
6566 	case 16:
6567 		return COLOR_DEPTH_161616;
6568 	default:
6569 		return COLOR_DEPTH_UNDEFINED;
6570 	}
6571 }
6572 
6573 static enum dc_aspect_ratio
get_aspect_ratio(const struct drm_display_mode * mode_in)6574 get_aspect_ratio(const struct drm_display_mode *mode_in)
6575 {
6576 	/* 1-1 mapping, since both enums follow the HDMI spec. */
6577 	return (enum dc_aspect_ratio) mode_in->picture_aspect_ratio;
6578 }
6579 
6580 static enum dc_color_space
get_output_color_space(const struct dc_crtc_timing * dc_crtc_timing,const struct drm_connector_state * connector_state)6581 get_output_color_space(const struct dc_crtc_timing *dc_crtc_timing,
6582 		       const struct drm_connector_state *connector_state)
6583 {
6584 	enum dc_color_space color_space = COLOR_SPACE_SRGB;
6585 
6586 	switch (connector_state->colorspace) {
6587 	case DRM_MODE_COLORIMETRY_BT601_YCC:
6588 		if (dc_crtc_timing->flags.Y_ONLY)
6589 			color_space = COLOR_SPACE_YCBCR601_LIMITED;
6590 		else
6591 			color_space = COLOR_SPACE_YCBCR601;
6592 		break;
6593 	case DRM_MODE_COLORIMETRY_BT709_YCC:
6594 		if (dc_crtc_timing->flags.Y_ONLY)
6595 			color_space = COLOR_SPACE_YCBCR709_LIMITED;
6596 		else
6597 			color_space = COLOR_SPACE_YCBCR709;
6598 		break;
6599 	case DRM_MODE_COLORIMETRY_OPRGB:
6600 		color_space = COLOR_SPACE_ADOBERGB;
6601 		break;
6602 	case DRM_MODE_COLORIMETRY_BT2020_RGB:
6603 	case DRM_MODE_COLORIMETRY_BT2020_YCC:
6604 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB)
6605 			color_space = COLOR_SPACE_2020_RGB_FULLRANGE;
6606 		else
6607 			color_space = COLOR_SPACE_2020_YCBCR_LIMITED;
6608 		break;
6609 	case DRM_MODE_COLORIMETRY_DEFAULT: // ITU601
6610 	default:
6611 		if (dc_crtc_timing->pixel_encoding == PIXEL_ENCODING_RGB) {
6612 			color_space = COLOR_SPACE_SRGB;
6613 			if (connector_state->hdmi.broadcast_rgb == DRM_HDMI_BROADCAST_RGB_LIMITED)
6614 				color_space = COLOR_SPACE_SRGB_LIMITED;
6615 		/*
6616 		 * 27030khz is the separation point between HDTV and SDTV
6617 		 * according to HDMI spec, we use YCbCr709 and YCbCr601
6618 		 * respectively
6619 		 */
6620 		} else if (dc_crtc_timing->pix_clk_100hz > 270300) {
6621 			if (dc_crtc_timing->flags.Y_ONLY)
6622 				color_space =
6623 					COLOR_SPACE_YCBCR709_LIMITED;
6624 			else
6625 				color_space = COLOR_SPACE_YCBCR709;
6626 		} else {
6627 			if (dc_crtc_timing->flags.Y_ONLY)
6628 				color_space =
6629 					COLOR_SPACE_YCBCR601_LIMITED;
6630 			else
6631 				color_space = COLOR_SPACE_YCBCR601;
6632 		}
6633 		break;
6634 	}
6635 
6636 	return color_space;
6637 }
6638 
6639 static enum display_content_type
get_output_content_type(const struct drm_connector_state * connector_state)6640 get_output_content_type(const struct drm_connector_state *connector_state)
6641 {
6642 	switch (connector_state->content_type) {
6643 	default:
6644 	case DRM_MODE_CONTENT_TYPE_NO_DATA:
6645 		return DISPLAY_CONTENT_TYPE_NO_DATA;
6646 	case DRM_MODE_CONTENT_TYPE_GRAPHICS:
6647 		return DISPLAY_CONTENT_TYPE_GRAPHICS;
6648 	case DRM_MODE_CONTENT_TYPE_PHOTO:
6649 		return DISPLAY_CONTENT_TYPE_PHOTO;
6650 	case DRM_MODE_CONTENT_TYPE_CINEMA:
6651 		return DISPLAY_CONTENT_TYPE_CINEMA;
6652 	case DRM_MODE_CONTENT_TYPE_GAME:
6653 		return DISPLAY_CONTENT_TYPE_GAME;
6654 	}
6655 }
6656 
adjust_colour_depth_from_display_info(struct dc_crtc_timing * timing_out,const struct drm_display_info * info)6657 static bool adjust_colour_depth_from_display_info(
6658 	struct dc_crtc_timing *timing_out,
6659 	const struct drm_display_info *info)
6660 {
6661 	enum dc_color_depth depth = timing_out->display_color_depth;
6662 	int normalized_clk;
6663 
6664 	do {
6665 		normalized_clk = timing_out->pix_clk_100hz / 10;
6666 		/* YCbCr 4:2:0 requires additional adjustment of 1/2 */
6667 		if (timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420)
6668 			normalized_clk /= 2;
6669 		/* Adjusting pix clock following on HDMI spec based on colour depth */
6670 		switch (depth) {
6671 		case COLOR_DEPTH_888:
6672 			break;
6673 		case COLOR_DEPTH_101010:
6674 			normalized_clk = (normalized_clk * 30) / 24;
6675 			break;
6676 		case COLOR_DEPTH_121212:
6677 			normalized_clk = (normalized_clk * 36) / 24;
6678 			break;
6679 		case COLOR_DEPTH_161616:
6680 			normalized_clk = (normalized_clk * 48) / 24;
6681 			break;
6682 		default:
6683 			/* The above depths are the only ones valid for HDMI. */
6684 			return false;
6685 		}
6686 		if (normalized_clk <= info->max_tmds_clock) {
6687 			timing_out->display_color_depth = depth;
6688 			return true;
6689 		}
6690 	} while (--depth > COLOR_DEPTH_666);
6691 	return false;
6692 }
6693 
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)6694 static void fill_stream_properties_from_drm_display_mode(
6695 	struct dc_stream_state *stream,
6696 	const struct drm_display_mode *mode_in,
6697 	const struct drm_connector *connector,
6698 	const struct drm_connector_state *connector_state,
6699 	const struct dc_stream_state *old_stream,
6700 	int requested_bpc)
6701 {
6702 	struct dc_crtc_timing *timing_out = &stream->timing;
6703 	const struct drm_display_info *info = &connector->display_info;
6704 	struct amdgpu_dm_connector *aconnector = NULL;
6705 	struct hdmi_vendor_infoframe hv_frame;
6706 	struct hdmi_avi_infoframe avi_frame;
6707 	ssize_t err;
6708 
6709 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
6710 		aconnector = to_amdgpu_dm_connector(connector);
6711 
6712 	memset(&hv_frame, 0, sizeof(hv_frame));
6713 	memset(&avi_frame, 0, sizeof(avi_frame));
6714 
6715 	timing_out->h_border_left = 0;
6716 	timing_out->h_border_right = 0;
6717 	timing_out->v_border_top = 0;
6718 	timing_out->v_border_bottom = 0;
6719 	/* TODO: un-hardcode */
6720 	if (drm_mode_is_420_only(info, mode_in)
6721 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6722 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6723 	else if (drm_mode_is_420_also(info, mode_in)
6724 			&& aconnector
6725 			&& aconnector->force_yuv420_output)
6726 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6727 	else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCBCR422)
6728 			&& aconnector
6729 			&& aconnector->force_yuv422_output)
6730 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR422;
6731 	else if ((connector->display_info.color_formats & DRM_COLOR_FORMAT_YCBCR444)
6732 			&& stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
6733 		timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR444;
6734 	else
6735 		timing_out->pixel_encoding = PIXEL_ENCODING_RGB;
6736 
6737 	timing_out->timing_3d_format = TIMING_3D_FORMAT_NONE;
6738 	timing_out->display_color_depth = convert_color_depth_from_display_info(
6739 		connector,
6740 		(timing_out->pixel_encoding == PIXEL_ENCODING_YCBCR420),
6741 		requested_bpc);
6742 	timing_out->scan_type = SCANNING_TYPE_NODATA;
6743 	timing_out->hdmi_vic = 0;
6744 
6745 	if (old_stream) {
6746 		timing_out->vic = old_stream->timing.vic;
6747 		timing_out->flags.HSYNC_POSITIVE_POLARITY = old_stream->timing.flags.HSYNC_POSITIVE_POLARITY;
6748 		timing_out->flags.VSYNC_POSITIVE_POLARITY = old_stream->timing.flags.VSYNC_POSITIVE_POLARITY;
6749 	} else {
6750 		timing_out->vic = drm_match_cea_mode(mode_in);
6751 		if (mode_in->flags & DRM_MODE_FLAG_PHSYNC)
6752 			timing_out->flags.HSYNC_POSITIVE_POLARITY = 1;
6753 		if (mode_in->flags & DRM_MODE_FLAG_PVSYNC)
6754 			timing_out->flags.VSYNC_POSITIVE_POLARITY = 1;
6755 	}
6756 
6757 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
6758 		err = drm_hdmi_avi_infoframe_from_display_mode(&avi_frame,
6759 							       (struct drm_connector *)connector,
6760 							       mode_in);
6761 		if (err < 0)
6762 			drm_warn_once(connector->dev, "Failed to setup avi infoframe on connector %s: %zd\n",
6763 				      connector->name, err);
6764 		timing_out->vic = avi_frame.video_code;
6765 		err = drm_hdmi_vendor_infoframe_from_display_mode(&hv_frame,
6766 								  (struct drm_connector *)connector,
6767 								  mode_in);
6768 		if (err < 0)
6769 			drm_warn_once(connector->dev, "Failed to setup vendor infoframe on connector %s: %zd\n",
6770 				      connector->name, err);
6771 		timing_out->hdmi_vic = hv_frame.vic;
6772 	}
6773 
6774 	if (aconnector && is_freesync_video_mode(mode_in, aconnector)) {
6775 		timing_out->h_addressable = mode_in->hdisplay;
6776 		timing_out->h_total = mode_in->htotal;
6777 		timing_out->h_sync_width = mode_in->hsync_end - mode_in->hsync_start;
6778 		timing_out->h_front_porch = mode_in->hsync_start - mode_in->hdisplay;
6779 		timing_out->v_total = mode_in->vtotal;
6780 		timing_out->v_addressable = mode_in->vdisplay;
6781 		timing_out->v_front_porch = mode_in->vsync_start - mode_in->vdisplay;
6782 		timing_out->v_sync_width = mode_in->vsync_end - mode_in->vsync_start;
6783 		timing_out->pix_clk_100hz = mode_in->clock * 10;
6784 	} else {
6785 		timing_out->h_addressable = mode_in->crtc_hdisplay;
6786 		timing_out->h_total = mode_in->crtc_htotal;
6787 		timing_out->h_sync_width = mode_in->crtc_hsync_end - mode_in->crtc_hsync_start;
6788 		timing_out->h_front_porch = mode_in->crtc_hsync_start - mode_in->crtc_hdisplay;
6789 		timing_out->v_total = mode_in->crtc_vtotal;
6790 		timing_out->v_addressable = mode_in->crtc_vdisplay;
6791 		timing_out->v_front_porch = mode_in->crtc_vsync_start - mode_in->crtc_vdisplay;
6792 		timing_out->v_sync_width = mode_in->crtc_vsync_end - mode_in->crtc_vsync_start;
6793 		timing_out->pix_clk_100hz = mode_in->crtc_clock * 10;
6794 	}
6795 
6796 	timing_out->aspect_ratio = get_aspect_ratio(mode_in);
6797 
6798 	stream->out_transfer_func.type = TF_TYPE_PREDEFINED;
6799 	stream->out_transfer_func.tf = TRANSFER_FUNCTION_SRGB;
6800 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A) {
6801 		if (!adjust_colour_depth_from_display_info(timing_out, info) &&
6802 		    drm_mode_is_420_also(info, mode_in) &&
6803 		    timing_out->pixel_encoding != PIXEL_ENCODING_YCBCR420) {
6804 			timing_out->pixel_encoding = PIXEL_ENCODING_YCBCR420;
6805 			adjust_colour_depth_from_display_info(timing_out, info);
6806 		}
6807 	}
6808 
6809 	stream->output_color_space = get_output_color_space(timing_out, connector_state);
6810 	stream->content_type = get_output_content_type(connector_state);
6811 }
6812 
fill_audio_info(struct audio_info * audio_info,const struct drm_connector * drm_connector,const struct dc_sink * dc_sink)6813 static void fill_audio_info(struct audio_info *audio_info,
6814 			    const struct drm_connector *drm_connector,
6815 			    const struct dc_sink *dc_sink)
6816 {
6817 	int i = 0;
6818 	int cea_revision = 0;
6819 	const struct dc_edid_caps *edid_caps = &dc_sink->edid_caps;
6820 
6821 	audio_info->manufacture_id = edid_caps->manufacturer_id;
6822 	audio_info->product_id = edid_caps->product_id;
6823 
6824 	cea_revision = drm_connector->display_info.cea_rev;
6825 
6826 	strscpy(audio_info->display_name,
6827 		edid_caps->display_name,
6828 		AUDIO_INFO_DISPLAY_NAME_SIZE_IN_CHARS);
6829 
6830 	if (cea_revision >= 3) {
6831 		audio_info->mode_count = edid_caps->audio_mode_count;
6832 
6833 		for (i = 0; i < audio_info->mode_count; ++i) {
6834 			audio_info->modes[i].format_code =
6835 					(enum audio_format_code)
6836 					(edid_caps->audio_modes[i].format_code);
6837 			audio_info->modes[i].channel_count =
6838 					edid_caps->audio_modes[i].channel_count;
6839 			audio_info->modes[i].sample_rates.all =
6840 					edid_caps->audio_modes[i].sample_rate;
6841 			audio_info->modes[i].sample_size =
6842 					edid_caps->audio_modes[i].sample_size;
6843 		}
6844 	}
6845 
6846 	audio_info->flags.all = edid_caps->speaker_flags;
6847 
6848 	/* TODO: We only check for the progressive mode, check for interlace mode too */
6849 	if (drm_connector->latency_present[0]) {
6850 		audio_info->video_latency = drm_connector->video_latency[0];
6851 		audio_info->audio_latency = drm_connector->audio_latency[0];
6852 	}
6853 
6854 	/* TODO: For DP, video and audio latency should be calculated from DPCD caps */
6855 
6856 }
6857 
6858 static void
copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode * src_mode,struct drm_display_mode * dst_mode)6859 copy_crtc_timing_for_drm_display_mode(const struct drm_display_mode *src_mode,
6860 				      struct drm_display_mode *dst_mode)
6861 {
6862 	dst_mode->crtc_hdisplay = src_mode->crtc_hdisplay;
6863 	dst_mode->crtc_vdisplay = src_mode->crtc_vdisplay;
6864 	dst_mode->crtc_clock = src_mode->crtc_clock;
6865 	dst_mode->crtc_hblank_start = src_mode->crtc_hblank_start;
6866 	dst_mode->crtc_hblank_end = src_mode->crtc_hblank_end;
6867 	dst_mode->crtc_hsync_start =  src_mode->crtc_hsync_start;
6868 	dst_mode->crtc_hsync_end = src_mode->crtc_hsync_end;
6869 	dst_mode->crtc_htotal = src_mode->crtc_htotal;
6870 	dst_mode->crtc_hskew = src_mode->crtc_hskew;
6871 	dst_mode->crtc_vblank_start = src_mode->crtc_vblank_start;
6872 	dst_mode->crtc_vblank_end = src_mode->crtc_vblank_end;
6873 	dst_mode->crtc_vsync_start = src_mode->crtc_vsync_start;
6874 	dst_mode->crtc_vsync_end = src_mode->crtc_vsync_end;
6875 	dst_mode->crtc_vtotal = src_mode->crtc_vtotal;
6876 }
6877 
6878 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)6879 decide_crtc_timing_for_drm_display_mode(struct drm_display_mode *drm_mode,
6880 					const struct drm_display_mode *native_mode,
6881 					bool scale_enabled)
6882 {
6883 	if (scale_enabled || (
6884 	    native_mode->clock == drm_mode->clock &&
6885 	    native_mode->htotal == drm_mode->htotal &&
6886 	    native_mode->vtotal == drm_mode->vtotal)) {
6887 		if (native_mode->crtc_clock)
6888 			copy_crtc_timing_for_drm_display_mode(native_mode, drm_mode);
6889 	} else {
6890 		/* no scaling nor amdgpu inserted, no need to patch */
6891 	}
6892 }
6893 
6894 static struct dc_sink *
create_fake_sink(struct drm_device * dev,struct dc_link * link)6895 create_fake_sink(struct drm_device *dev, struct dc_link *link)
6896 {
6897 	struct dc_sink_init_data sink_init_data = { 0 };
6898 	struct dc_sink *sink = NULL;
6899 
6900 	sink_init_data.link = link;
6901 	sink_init_data.sink_signal = link->connector_signal;
6902 
6903 	sink = dc_sink_create(&sink_init_data);
6904 	if (!sink) {
6905 		drm_err(dev, "Failed to create sink!\n");
6906 		return NULL;
6907 	}
6908 	sink->sink_signal = SIGNAL_TYPE_VIRTUAL;
6909 
6910 	return sink;
6911 }
6912 
set_multisync_trigger_params(struct dc_stream_state * stream)6913 static void set_multisync_trigger_params(
6914 		struct dc_stream_state *stream)
6915 {
6916 	struct dc_stream_state *master = NULL;
6917 
6918 	if (stream->triggered_crtc_reset.enabled) {
6919 		master = stream->triggered_crtc_reset.event_source;
6920 		stream->triggered_crtc_reset.event =
6921 			master->timing.flags.VSYNC_POSITIVE_POLARITY ?
6922 			CRTC_EVENT_VSYNC_RISING : CRTC_EVENT_VSYNC_FALLING;
6923 		stream->triggered_crtc_reset.delay = TRIGGER_DELAY_NEXT_PIXEL;
6924 	}
6925 }
6926 
set_master_stream(struct dc_stream_state * stream_set[],int stream_count)6927 static void set_master_stream(struct dc_stream_state *stream_set[],
6928 			      int stream_count)
6929 {
6930 	int j, highest_rfr = 0, master_stream = 0;
6931 
6932 	for (j = 0;  j < stream_count; j++) {
6933 		if (stream_set[j] && stream_set[j]->triggered_crtc_reset.enabled) {
6934 			int refresh_rate = 0;
6935 
6936 			refresh_rate = (stream_set[j]->timing.pix_clk_100hz*100)/
6937 				(stream_set[j]->timing.h_total*stream_set[j]->timing.v_total);
6938 			if (refresh_rate > highest_rfr) {
6939 				highest_rfr = refresh_rate;
6940 				master_stream = j;
6941 			}
6942 		}
6943 	}
6944 	for (j = 0;  j < stream_count; j++) {
6945 		if (stream_set[j])
6946 			stream_set[j]->triggered_crtc_reset.event_source = stream_set[master_stream];
6947 	}
6948 }
6949 
dm_enable_per_frame_crtc_master_sync(struct dc_state * context)6950 static void dm_enable_per_frame_crtc_master_sync(struct dc_state *context)
6951 {
6952 	int i = 0;
6953 	struct dc_stream_state *stream;
6954 
6955 	if (context->stream_count < 2)
6956 		return;
6957 	for (i = 0; i < context->stream_count ; i++) {
6958 		if (!context->streams[i])
6959 			continue;
6960 		/*
6961 		 * TODO: add a function to read AMD VSDB bits and set
6962 		 * crtc_sync_master.multi_sync_enabled flag
6963 		 * For now it's set to false
6964 		 */
6965 	}
6966 
6967 	set_master_stream(context->streams, context->stream_count);
6968 
6969 	for (i = 0; i < context->stream_count ; i++) {
6970 		stream = context->streams[i];
6971 
6972 		if (!stream)
6973 			continue;
6974 
6975 		set_multisync_trigger_params(stream);
6976 	}
6977 }
6978 
6979 /**
6980  * DOC: FreeSync Video
6981  *
6982  * When a userspace application wants to play a video, the content follows a
6983  * standard format definition that usually specifies the FPS for that format.
6984  * The below list illustrates some video format and the expected FPS,
6985  * respectively:
6986  *
6987  * - TV/NTSC (23.976 FPS)
6988  * - Cinema (24 FPS)
6989  * - TV/PAL (25 FPS)
6990  * - TV/NTSC (29.97 FPS)
6991  * - TV/NTSC (30 FPS)
6992  * - Cinema HFR (48 FPS)
6993  * - TV/PAL (50 FPS)
6994  * - Commonly used (60 FPS)
6995  * - Multiples of 24 (48,72,96 FPS)
6996  *
6997  * The list of standards video format is not huge and can be added to the
6998  * connector modeset list beforehand. With that, userspace can leverage
6999  * FreeSync to extends the front porch in order to attain the target refresh
7000  * rate. Such a switch will happen seamlessly, without screen blanking or
7001  * reprogramming of the output in any other way. If the userspace requests a
7002  * modesetting change compatible with FreeSync modes that only differ in the
7003  * refresh rate, DC will skip the full update and avoid blink during the
7004  * transition. For example, the video player can change the modesetting from
7005  * 60Hz to 30Hz for playing TV/NTSC content when it goes full screen without
7006  * causing any display blink. This same concept can be applied to a mode
7007  * setting change.
7008  */
7009 static struct drm_display_mode *
get_highest_refresh_rate_mode(struct amdgpu_dm_connector * aconnector,bool use_probed_modes)7010 get_highest_refresh_rate_mode(struct amdgpu_dm_connector *aconnector,
7011 		bool use_probed_modes)
7012 {
7013 	struct drm_display_mode *m, *m_pref = NULL;
7014 	u16 current_refresh, highest_refresh;
7015 	struct list_head *list_head = use_probed_modes ?
7016 		&aconnector->base.probed_modes :
7017 		&aconnector->base.modes;
7018 
7019 	if (aconnector->base.connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
7020 		return NULL;
7021 
7022 	if (aconnector->freesync_vid_base.clock != 0)
7023 		return &aconnector->freesync_vid_base;
7024 
7025 	/* Find the preferred mode */
7026 	list_for_each_entry(m, list_head, head) {
7027 		if (m->type & DRM_MODE_TYPE_PREFERRED) {
7028 			m_pref = m;
7029 			break;
7030 		}
7031 	}
7032 
7033 	if (!m_pref) {
7034 		/* Probably an EDID with no preferred mode. Fallback to first entry */
7035 		m_pref = list_first_entry_or_null(
7036 				&aconnector->base.modes, struct drm_display_mode, head);
7037 		if (!m_pref) {
7038 			drm_dbg_driver(aconnector->base.dev, "No preferred mode found in EDID\n");
7039 			return NULL;
7040 		}
7041 	}
7042 
7043 	highest_refresh = drm_mode_vrefresh(m_pref);
7044 
7045 	/*
7046 	 * Find the mode with highest refresh rate with same resolution.
7047 	 * For some monitors, preferred mode is not the mode with highest
7048 	 * supported refresh rate.
7049 	 */
7050 	list_for_each_entry(m, list_head, head) {
7051 		current_refresh  = drm_mode_vrefresh(m);
7052 
7053 		if (m->hdisplay == m_pref->hdisplay &&
7054 		    m->vdisplay == m_pref->vdisplay &&
7055 		    highest_refresh < current_refresh) {
7056 			highest_refresh = current_refresh;
7057 			m_pref = m;
7058 		}
7059 	}
7060 
7061 	drm_mode_copy(&aconnector->freesync_vid_base, m_pref);
7062 	return m_pref;
7063 }
7064 
is_freesync_video_mode(const struct drm_display_mode * mode,struct amdgpu_dm_connector * aconnector)7065 static bool is_freesync_video_mode(const struct drm_display_mode *mode,
7066 		struct amdgpu_dm_connector *aconnector)
7067 {
7068 	struct drm_display_mode *high_mode;
7069 	int timing_diff;
7070 
7071 	high_mode = get_highest_refresh_rate_mode(aconnector, false);
7072 	if (!high_mode || !mode)
7073 		return false;
7074 
7075 	timing_diff = high_mode->vtotal - mode->vtotal;
7076 
7077 	if (high_mode->clock == 0 || high_mode->clock != mode->clock ||
7078 	    high_mode->hdisplay != mode->hdisplay ||
7079 	    high_mode->vdisplay != mode->vdisplay ||
7080 	    high_mode->hsync_start != mode->hsync_start ||
7081 	    high_mode->hsync_end != mode->hsync_end ||
7082 	    high_mode->htotal != mode->htotal ||
7083 	    high_mode->hskew != mode->hskew ||
7084 	    high_mode->vscan != mode->vscan ||
7085 	    high_mode->vsync_start - mode->vsync_start != timing_diff ||
7086 	    high_mode->vsync_end - mode->vsync_end != timing_diff)
7087 		return false;
7088 	else
7089 		return true;
7090 }
7091 
7092 #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)7093 static void update_dsc_caps(struct amdgpu_dm_connector *aconnector,
7094 			    struct dc_sink *sink, struct dc_stream_state *stream,
7095 			    struct dsc_dec_dpcd_caps *dsc_caps)
7096 {
7097 	stream->timing.flags.DSC = 0;
7098 	dsc_caps->is_dsc_supported = false;
7099 
7100 	if (aconnector->dc_link && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
7101 	    sink->sink_signal == SIGNAL_TYPE_EDP)) {
7102 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE ||
7103 			sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER)
7104 			dc_dsc_parse_dsc_dpcd(aconnector->dc_link->ctx->dc,
7105 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_basic_caps.raw,
7106 				aconnector->dc_link->dpcd_caps.dsc_caps.dsc_branch_decoder_caps.raw,
7107 				dsc_caps);
7108 	}
7109 }
7110 
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)7111 static void apply_dsc_policy_for_edp(struct amdgpu_dm_connector *aconnector,
7112 				    struct dc_sink *sink, struct dc_stream_state *stream,
7113 				    struct dsc_dec_dpcd_caps *dsc_caps,
7114 				    uint32_t max_dsc_target_bpp_limit_override)
7115 {
7116 	const struct dc_link_settings *verified_link_cap = NULL;
7117 	u32 link_bw_in_kbps;
7118 	u32 edp_min_bpp_x16, edp_max_bpp_x16;
7119 	struct dc *dc = sink->ctx->dc;
7120 	struct dc_dsc_bw_range bw_range = {0};
7121 	struct dc_dsc_config dsc_cfg = {0};
7122 	struct dc_dsc_config_options dsc_options = {0};
7123 
7124 	dc_dsc_get_default_config_option(dc, &dsc_options);
7125 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7126 
7127 	verified_link_cap = dc_link_get_link_cap(stream->link);
7128 	link_bw_in_kbps = dc_link_bandwidth_kbps(stream->link, verified_link_cap);
7129 	edp_min_bpp_x16 = 8 * 16;
7130 	edp_max_bpp_x16 = 8 * 16;
7131 
7132 	if (edp_max_bpp_x16 > dsc_caps->edp_max_bits_per_pixel)
7133 		edp_max_bpp_x16 = dsc_caps->edp_max_bits_per_pixel;
7134 
7135 	if (edp_max_bpp_x16 < edp_min_bpp_x16)
7136 		edp_min_bpp_x16 = edp_max_bpp_x16;
7137 
7138 	if (dc_dsc_compute_bandwidth_range(dc->res_pool->dscs[0],
7139 				dc->debug.dsc_min_slice_height_override,
7140 				edp_min_bpp_x16, edp_max_bpp_x16,
7141 				dsc_caps,
7142 				&stream->timing,
7143 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7144 				&bw_range)) {
7145 
7146 		if (bw_range.max_kbps < link_bw_in_kbps) {
7147 			if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7148 					dsc_caps,
7149 					&dsc_options,
7150 					0,
7151 					&stream->timing,
7152 					dc_link_get_highest_encoding_format(aconnector->dc_link),
7153 					&dsc_cfg)) {
7154 				stream->timing.dsc_cfg = dsc_cfg;
7155 				stream->timing.flags.DSC = 1;
7156 				stream->timing.dsc_cfg.bits_per_pixel = edp_max_bpp_x16;
7157 			}
7158 			return;
7159 		}
7160 	}
7161 
7162 	if (dc_dsc_compute_config(dc->res_pool->dscs[0],
7163 				dsc_caps,
7164 				&dsc_options,
7165 				link_bw_in_kbps,
7166 				&stream->timing,
7167 				dc_link_get_highest_encoding_format(aconnector->dc_link),
7168 				&dsc_cfg)) {
7169 		stream->timing.dsc_cfg = dsc_cfg;
7170 		stream->timing.flags.DSC = 1;
7171 	}
7172 }
7173 
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)7174 static void apply_dsc_policy_for_stream(struct amdgpu_dm_connector *aconnector,
7175 					struct dc_sink *sink, struct dc_stream_state *stream,
7176 					struct dsc_dec_dpcd_caps *dsc_caps)
7177 {
7178 	struct drm_connector *drm_connector = &aconnector->base;
7179 	u32 link_bandwidth_kbps;
7180 	struct dc *dc = sink->ctx->dc;
7181 	u32 max_supported_bw_in_kbps, timing_bw_in_kbps;
7182 	u32 dsc_max_supported_bw_in_kbps;
7183 	u32 max_dsc_target_bpp_limit_override =
7184 		drm_connector->display_info.max_dsc_bpp;
7185 	struct dc_dsc_config_options dsc_options = {0};
7186 
7187 	dc_dsc_get_default_config_option(dc, &dsc_options);
7188 	dsc_options.max_target_bpp_limit_override_x16 = max_dsc_target_bpp_limit_override * 16;
7189 
7190 	link_bandwidth_kbps = dc_link_bandwidth_kbps(aconnector->dc_link,
7191 							dc_link_get_link_cap(aconnector->dc_link));
7192 
7193 	/* Set DSC policy according to dsc_clock_en */
7194 	dc_dsc_policy_set_enable_dsc_when_not_needed(
7195 		aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE);
7196 
7197 	if (sink->sink_signal == SIGNAL_TYPE_EDP &&
7198 	    !aconnector->dc_link->panel_config.dsc.disable_dsc_edp &&
7199 	    dc->caps.edp_dsc_support && aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE) {
7200 
7201 		apply_dsc_policy_for_edp(aconnector, sink, stream, dsc_caps, max_dsc_target_bpp_limit_override);
7202 
7203 	} else if (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT) {
7204 		if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_NONE) {
7205 			if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7206 						dsc_caps,
7207 						&dsc_options,
7208 						link_bandwidth_kbps,
7209 						&stream->timing,
7210 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7211 						&stream->timing.dsc_cfg)) {
7212 				stream->timing.flags.DSC = 1;
7213 				drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from SST RX\n",
7214 							__func__, drm_connector->name);
7215 			}
7216 		} else if (sink->link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER) {
7217 			timing_bw_in_kbps = dc_bandwidth_in_kbps_from_timing(&stream->timing,
7218 					dc_link_get_highest_encoding_format(aconnector->dc_link));
7219 			max_supported_bw_in_kbps = link_bandwidth_kbps;
7220 			dsc_max_supported_bw_in_kbps = link_bandwidth_kbps;
7221 
7222 			if (timing_bw_in_kbps > max_supported_bw_in_kbps &&
7223 					max_supported_bw_in_kbps > 0 &&
7224 					dsc_max_supported_bw_in_kbps > 0)
7225 				if (dc_dsc_compute_config(aconnector->dc_link->ctx->dc->res_pool->dscs[0],
7226 						dsc_caps,
7227 						&dsc_options,
7228 						dsc_max_supported_bw_in_kbps,
7229 						&stream->timing,
7230 						dc_link_get_highest_encoding_format(aconnector->dc_link),
7231 						&stream->timing.dsc_cfg)) {
7232 					stream->timing.flags.DSC = 1;
7233 					drm_dbg_driver(drm_connector->dev, "%s: SST_DSC [%s] DSC is selected from DP-HDMI PCON\n",
7234 									 __func__, drm_connector->name);
7235 				}
7236 		}
7237 	}
7238 
7239 	/* Overwrite the stream flag if DSC is enabled through debugfs */
7240 	if (aconnector->dsc_settings.dsc_force_enable == DSC_CLK_FORCE_ENABLE)
7241 		stream->timing.flags.DSC = 1;
7242 
7243 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_h)
7244 		stream->timing.dsc_cfg.num_slices_h = aconnector->dsc_settings.dsc_num_slices_h;
7245 
7246 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_num_slices_v)
7247 		stream->timing.dsc_cfg.num_slices_v = aconnector->dsc_settings.dsc_num_slices_v;
7248 
7249 	if (stream->timing.flags.DSC && aconnector->dsc_settings.dsc_bits_per_pixel)
7250 		stream->timing.dsc_cfg.bits_per_pixel = aconnector->dsc_settings.dsc_bits_per_pixel;
7251 }
7252 #endif
7253 
7254 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)7255 create_stream_for_sink(struct drm_connector *connector,
7256 		       const struct drm_display_mode *drm_mode,
7257 		       const struct dm_connector_state *dm_state,
7258 		       const struct dc_stream_state *old_stream,
7259 		       int requested_bpc)
7260 {
7261 	struct drm_device *dev = connector->dev;
7262 	struct amdgpu_dm_connector *aconnector = NULL;
7263 	struct drm_display_mode *preferred_mode = NULL;
7264 	const struct drm_connector_state *con_state = &dm_state->base;
7265 	struct dc_stream_state *stream = NULL;
7266 	struct drm_display_mode mode;
7267 	struct drm_display_mode saved_mode;
7268 	struct drm_display_mode *freesync_mode = NULL;
7269 	bool native_mode_found = false;
7270 	bool recalculate_timing = false;
7271 	bool scale = dm_state->scaling != RMX_OFF;
7272 	int mode_refresh;
7273 	int preferred_refresh = 0;
7274 	enum color_transfer_func tf = TRANSFER_FUNC_UNKNOWN;
7275 #if defined(CONFIG_DRM_AMD_DC_FP)
7276 	struct dsc_dec_dpcd_caps dsc_caps;
7277 #endif
7278 	struct dc_link *link = NULL;
7279 	struct dc_sink *sink = NULL;
7280 
7281 	drm_mode_init(&mode, drm_mode);
7282 	memset(&saved_mode, 0, sizeof(saved_mode));
7283 
7284 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK) {
7285 		aconnector = NULL;
7286 		aconnector = to_amdgpu_dm_connector(connector);
7287 		link = aconnector->dc_link;
7288 	} else {
7289 		struct drm_writeback_connector *wbcon = NULL;
7290 		struct amdgpu_dm_wb_connector *dm_wbcon = NULL;
7291 
7292 		wbcon = drm_connector_to_writeback(connector);
7293 		dm_wbcon = to_amdgpu_dm_wb_connector(wbcon);
7294 		link = dm_wbcon->link;
7295 	}
7296 
7297 	if (!aconnector || !aconnector->dc_sink) {
7298 		sink = create_fake_sink(dev, link);
7299 		if (!sink)
7300 			return stream;
7301 
7302 	} else {
7303 		sink = aconnector->dc_sink;
7304 		dc_sink_retain(sink);
7305 	}
7306 
7307 	stream = dc_create_stream_for_sink(sink);
7308 
7309 	if (stream == NULL) {
7310 		drm_err(dev, "Failed to create stream for sink!\n");
7311 		goto finish;
7312 	}
7313 
7314 	/* We leave this NULL for writeback connectors */
7315 	stream->dm_stream_context = aconnector;
7316 
7317 	stream->timing.flags.LTE_340MCSC_SCRAMBLE =
7318 		connector->display_info.hdmi.scdc.scrambling.low_rates;
7319 
7320 	list_for_each_entry(preferred_mode, &connector->modes, head) {
7321 		/* Search for preferred mode */
7322 		if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED) {
7323 			native_mode_found = true;
7324 			break;
7325 		}
7326 	}
7327 	if (!native_mode_found)
7328 		preferred_mode = list_first_entry_or_null(
7329 				&connector->modes,
7330 				struct drm_display_mode,
7331 				head);
7332 
7333 	mode_refresh = drm_mode_vrefresh(&mode);
7334 
7335 	if (preferred_mode == NULL) {
7336 		/*
7337 		 * This may not be an error, the use case is when we have no
7338 		 * usermode calls to reset and set mode upon hotplug. In this
7339 		 * case, we call set mode ourselves to restore the previous mode
7340 		 * and the modelist may not be filled in time.
7341 		 */
7342 		drm_dbg_driver(dev, "No preferred mode found\n");
7343 	} else if (aconnector) {
7344 		recalculate_timing = amdgpu_freesync_vid_mode &&
7345 				 is_freesync_video_mode(&mode, aconnector);
7346 		if (recalculate_timing) {
7347 			freesync_mode = get_highest_refresh_rate_mode(aconnector, false);
7348 			drm_mode_copy(&saved_mode, &mode);
7349 			saved_mode.picture_aspect_ratio = mode.picture_aspect_ratio;
7350 			drm_mode_copy(&mode, freesync_mode);
7351 			mode.picture_aspect_ratio = saved_mode.picture_aspect_ratio;
7352 		} else {
7353 			decide_crtc_timing_for_drm_display_mode(
7354 					&mode, preferred_mode, scale);
7355 
7356 			preferred_refresh = drm_mode_vrefresh(preferred_mode);
7357 		}
7358 	}
7359 
7360 	if (recalculate_timing)
7361 		drm_mode_set_crtcinfo(&saved_mode, 0);
7362 
7363 	/*
7364 	 * If scaling is enabled and refresh rate didn't change
7365 	 * we copy the vic and polarities of the old timings
7366 	 */
7367 	if (!scale || mode_refresh != preferred_refresh)
7368 		fill_stream_properties_from_drm_display_mode(
7369 			stream, &mode, connector, con_state, NULL,
7370 			requested_bpc);
7371 	else
7372 		fill_stream_properties_from_drm_display_mode(
7373 			stream, &mode, connector, con_state, old_stream,
7374 			requested_bpc);
7375 
7376 	/* The rest isn't needed for writeback connectors */
7377 	if (!aconnector)
7378 		goto finish;
7379 
7380 	if (aconnector->timing_changed) {
7381 		drm_dbg(aconnector->base.dev,
7382 			"overriding timing for automated test, bpc %d, changing to %d\n",
7383 			stream->timing.display_color_depth,
7384 			aconnector->timing_requested->display_color_depth);
7385 		stream->timing = *aconnector->timing_requested;
7386 	}
7387 
7388 #if defined(CONFIG_DRM_AMD_DC_FP)
7389 	/* SST DSC determination policy */
7390 	update_dsc_caps(aconnector, sink, stream, &dsc_caps);
7391 	if (aconnector->dsc_settings.dsc_force_enable != DSC_CLK_FORCE_DISABLE && dsc_caps.is_dsc_supported)
7392 		apply_dsc_policy_for_stream(aconnector, sink, stream, &dsc_caps);
7393 #endif
7394 
7395 	update_stream_scaling_settings(dev, &mode, dm_state, stream);
7396 
7397 	fill_audio_info(
7398 		&stream->audio_info,
7399 		connector,
7400 		sink);
7401 
7402 	update_stream_signal(stream, sink);
7403 
7404 	if (stream->signal == SIGNAL_TYPE_HDMI_TYPE_A)
7405 		mod_build_hf_vsif_infopacket(stream, &stream->vsp_infopacket);
7406 
7407 	if (stream->signal == SIGNAL_TYPE_DISPLAY_PORT ||
7408 	    stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST ||
7409 	    stream->signal == SIGNAL_TYPE_EDP) {
7410 		const struct dc_edid_caps *edid_caps;
7411 		unsigned int disable_colorimetry = 0;
7412 
7413 		if (aconnector->dc_sink) {
7414 			edid_caps = &aconnector->dc_sink->edid_caps;
7415 			disable_colorimetry = edid_caps->panel_patch.disable_colorimetry;
7416 		}
7417 
7418 		//
7419 		// should decide stream support vsc sdp colorimetry capability
7420 		// before building vsc info packet
7421 		//
7422 		stream->use_vsc_sdp_for_colorimetry = stream->link->dpcd_caps.dpcd_rev.raw >= 0x14 &&
7423 						      stream->link->dpcd_caps.dprx_feature.bits.VSC_SDP_COLORIMETRY_SUPPORTED &&
7424 						      !disable_colorimetry;
7425 
7426 		if (stream->out_transfer_func.tf == TRANSFER_FUNCTION_GAMMA22)
7427 			tf = TRANSFER_FUNC_GAMMA_22;
7428 		mod_build_vsc_infopacket(stream, &stream->vsc_infopacket, stream->output_color_space, tf);
7429 		aconnector->sr_skip_count = AMDGPU_DM_PSR_ENTRY_DELAY;
7430 
7431 	}
7432 finish:
7433 	dc_sink_release(sink);
7434 
7435 	return stream;
7436 }
7437 
7438 /**
7439  * amdgpu_dm_connector_poll - Poll a connector to see if it's connected to a display
7440  * @aconnector: DM connector to poll (owns @base drm_connector and @dc_link)
7441  * @force: if true, force polling even when DAC load detection was used
7442  *
7443  * Used for connectors that don't support HPD (hotplug detection) to
7444  * periodically check whether the connector is connected to a display.
7445  *
7446  * When connection was determined via DAC load detection, we avoid
7447  * re-running it on normal polls to prevent visible glitches, unless
7448  * @force is set.
7449  *
7450  * Return: The probed connector status (connected/disconnected/unknown).
7451  */
7452 static enum drm_connector_status
amdgpu_dm_connector_poll(struct amdgpu_dm_connector * aconnector,bool force)7453 amdgpu_dm_connector_poll(struct amdgpu_dm_connector *aconnector, bool force)
7454 {
7455 	struct drm_connector *connector = &aconnector->base;
7456 	struct drm_device *dev = connector->dev;
7457 	struct amdgpu_device *adev = drm_to_adev(dev);
7458 	struct dc_link *link = aconnector->dc_link;
7459 	enum dc_connection_type conn_type = dc_connection_none;
7460 	enum drm_connector_status status = connector_status_disconnected;
7461 
7462 	/* When we determined the connection using DAC load detection,
7463 	 * do NOT poll the connector do detect disconnect because
7464 	 * that would run DAC load detection again which can cause
7465 	 * visible visual glitches.
7466 	 *
7467 	 * Only allow to poll such a connector again when forcing.
7468 	 */
7469 	if (!force && link->local_sink && link->type == dc_connection_analog_load)
7470 		return connector->status;
7471 
7472 	mutex_lock(&aconnector->hpd_lock);
7473 
7474 	if (dc_link_detect_connection_type(aconnector->dc_link, &conn_type) &&
7475 	    conn_type != dc_connection_none) {
7476 		mutex_lock(&adev->dm.dc_lock);
7477 
7478 		/* Only call full link detection when a sink isn't created yet,
7479 		 * ie. just when the display is plugged in, otherwise we risk flickering.
7480 		 */
7481 		if (link->local_sink ||
7482 			dc_link_detect(link, DETECT_REASON_HPD))
7483 			status = connector_status_connected;
7484 
7485 		mutex_unlock(&adev->dm.dc_lock);
7486 	}
7487 
7488 	if (connector->status != status) {
7489 		if (status == connector_status_disconnected) {
7490 			if (link->local_sink)
7491 				dc_sink_release(link->local_sink);
7492 
7493 			link->local_sink = NULL;
7494 			link->dpcd_sink_count = 0;
7495 			link->type = dc_connection_none;
7496 		}
7497 
7498 		amdgpu_dm_update_connector_after_detect(aconnector);
7499 	}
7500 
7501 	mutex_unlock(&aconnector->hpd_lock);
7502 	return status;
7503 }
7504 
7505 /**
7506  * amdgpu_dm_connector_detect() - Detect whether a DRM connector is connected to a display
7507  *
7508  * A connector is considered connected when it has a sink that is not NULL.
7509  * For connectors that support HPD (hotplug detection), the connection is
7510  * handled in the HPD interrupt.
7511  * For connectors that may not support HPD, such as analog connectors,
7512  * DRM will call this function repeatedly to poll them.
7513  *
7514  * Notes:
7515  * 1. This interface is NOT called in context of HPD irq.
7516  * 2. This interface *is called* in context of user-mode ioctl. Which
7517  *    makes it a bad place for *any* MST-related activity.
7518  *
7519  * @connector: The DRM connector we are checking. We convert it to
7520  *             amdgpu_dm_connector so we can read the DC link and state.
7521  * @force:     If true, do a full detect again. This is used even when
7522  *             a lighter check would normally be used to avoid flicker.
7523  *
7524  * Return: The connector status (connected, disconnected, or unknown).
7525  *
7526  */
7527 static enum drm_connector_status
amdgpu_dm_connector_detect(struct drm_connector * connector,bool force)7528 amdgpu_dm_connector_detect(struct drm_connector *connector, bool force)
7529 {
7530 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7531 
7532 	update_subconnector_property(aconnector);
7533 
7534 	if (aconnector->base.force == DRM_FORCE_ON ||
7535 		aconnector->base.force == DRM_FORCE_ON_DIGITAL)
7536 		return connector_status_connected;
7537 	else if (aconnector->base.force == DRM_FORCE_OFF)
7538 		return connector_status_disconnected;
7539 
7540 	/* Poll analog connectors and only when either
7541 	 * disconnected or connected to an analog display.
7542 	 */
7543 	if (drm_kms_helper_is_poll_worker() &&
7544 		dc_connector_supports_analog(aconnector->dc_link->link_id.id) &&
7545 		(!aconnector->dc_sink || aconnector->dc_sink->edid_caps.analog))
7546 		return amdgpu_dm_connector_poll(aconnector, force);
7547 
7548 	return (aconnector->dc_sink ? connector_status_connected :
7549 			connector_status_disconnected);
7550 }
7551 
amdgpu_dm_connector_atomic_set_property(struct drm_connector * connector,struct drm_connector_state * connector_state,struct drm_property * property,uint64_t val)7552 int amdgpu_dm_connector_atomic_set_property(struct drm_connector *connector,
7553 					    struct drm_connector_state *connector_state,
7554 					    struct drm_property *property,
7555 					    uint64_t val)
7556 {
7557 	struct drm_device *dev = connector->dev;
7558 	struct amdgpu_device *adev = drm_to_adev(dev);
7559 	struct dm_connector_state *dm_old_state =
7560 		to_dm_connector_state(connector->state);
7561 	struct dm_connector_state *dm_new_state =
7562 		to_dm_connector_state(connector_state);
7563 
7564 	int ret = -EINVAL;
7565 
7566 	if (property == dev->mode_config.scaling_mode_property) {
7567 		enum amdgpu_rmx_type rmx_type;
7568 
7569 		switch (val) {
7570 		case DRM_MODE_SCALE_CENTER:
7571 			rmx_type = RMX_CENTER;
7572 			break;
7573 		case DRM_MODE_SCALE_ASPECT:
7574 			rmx_type = RMX_ASPECT;
7575 			break;
7576 		case DRM_MODE_SCALE_FULLSCREEN:
7577 			rmx_type = RMX_FULL;
7578 			break;
7579 		case DRM_MODE_SCALE_NONE:
7580 		default:
7581 			rmx_type = RMX_OFF;
7582 			break;
7583 		}
7584 
7585 		if (dm_old_state->scaling == rmx_type)
7586 			return 0;
7587 
7588 		dm_new_state->scaling = rmx_type;
7589 		ret = 0;
7590 	} else if (property == adev->mode_info.underscan_hborder_property) {
7591 		dm_new_state->underscan_hborder = val;
7592 		ret = 0;
7593 	} else if (property == adev->mode_info.underscan_vborder_property) {
7594 		dm_new_state->underscan_vborder = val;
7595 		ret = 0;
7596 	} else if (property == adev->mode_info.underscan_property) {
7597 		dm_new_state->underscan_enable = val;
7598 		ret = 0;
7599 	} else if (property == adev->mode_info.abm_level_property) {
7600 		switch (val) {
7601 		case ABM_SYSFS_CONTROL:
7602 			dm_new_state->abm_sysfs_forbidden = false;
7603 			break;
7604 		case ABM_LEVEL_OFF:
7605 			dm_new_state->abm_sysfs_forbidden = true;
7606 			dm_new_state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7607 			break;
7608 		default:
7609 			dm_new_state->abm_sysfs_forbidden = true;
7610 			dm_new_state->abm_level = val;
7611 		}
7612 		ret = 0;
7613 	}
7614 
7615 	return ret;
7616 }
7617 
amdgpu_dm_connector_atomic_get_property(struct drm_connector * connector,const struct drm_connector_state * state,struct drm_property * property,uint64_t * val)7618 int amdgpu_dm_connector_atomic_get_property(struct drm_connector *connector,
7619 					    const struct drm_connector_state *state,
7620 					    struct drm_property *property,
7621 					    uint64_t *val)
7622 {
7623 	struct drm_device *dev = connector->dev;
7624 	struct amdgpu_device *adev = drm_to_adev(dev);
7625 	struct dm_connector_state *dm_state =
7626 		to_dm_connector_state(state);
7627 	int ret = -EINVAL;
7628 
7629 	if (property == dev->mode_config.scaling_mode_property) {
7630 		switch (dm_state->scaling) {
7631 		case RMX_CENTER:
7632 			*val = DRM_MODE_SCALE_CENTER;
7633 			break;
7634 		case RMX_ASPECT:
7635 			*val = DRM_MODE_SCALE_ASPECT;
7636 			break;
7637 		case RMX_FULL:
7638 			*val = DRM_MODE_SCALE_FULLSCREEN;
7639 			break;
7640 		case RMX_OFF:
7641 		default:
7642 			*val = DRM_MODE_SCALE_NONE;
7643 			break;
7644 		}
7645 		ret = 0;
7646 	} else if (property == adev->mode_info.underscan_hborder_property) {
7647 		*val = dm_state->underscan_hborder;
7648 		ret = 0;
7649 	} else if (property == adev->mode_info.underscan_vborder_property) {
7650 		*val = dm_state->underscan_vborder;
7651 		ret = 0;
7652 	} else if (property == adev->mode_info.underscan_property) {
7653 		*val = dm_state->underscan_enable;
7654 		ret = 0;
7655 	} else if (property == adev->mode_info.abm_level_property) {
7656 		if (!dm_state->abm_sysfs_forbidden)
7657 			*val = ABM_SYSFS_CONTROL;
7658 		else
7659 			*val = (dm_state->abm_level != ABM_LEVEL_IMMEDIATE_DISABLE) ?
7660 				dm_state->abm_level : 0;
7661 		ret = 0;
7662 	}
7663 
7664 	return ret;
7665 }
7666 
7667 /**
7668  * DOC: panel power savings
7669  *
7670  * The display manager allows you to set your desired **panel power savings**
7671  * level (between 0-4, with 0 representing off), e.g. using the following::
7672  *
7673  *   # echo 3 > /sys/class/drm/card0-eDP-1/amdgpu/panel_power_savings
7674  *
7675  * Modifying this value can have implications on color accuracy, so tread
7676  * carefully.
7677  */
7678 
panel_power_savings_show(struct device * device,struct device_attribute * attr,char * buf)7679 static ssize_t panel_power_savings_show(struct device *device,
7680 					struct device_attribute *attr,
7681 					char *buf)
7682 {
7683 	struct drm_connector *connector = dev_get_drvdata(device);
7684 	struct drm_device *dev = connector->dev;
7685 	u8 val;
7686 
7687 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
7688 	val = to_dm_connector_state(connector->state)->abm_level ==
7689 		ABM_LEVEL_IMMEDIATE_DISABLE ? 0 :
7690 		to_dm_connector_state(connector->state)->abm_level;
7691 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
7692 
7693 	return sysfs_emit(buf, "%u\n", val);
7694 }
7695 
panel_power_savings_store(struct device * device,struct device_attribute * attr,const char * buf,size_t count)7696 static ssize_t panel_power_savings_store(struct device *device,
7697 					 struct device_attribute *attr,
7698 					 const char *buf, size_t count)
7699 {
7700 	struct drm_connector *connector = dev_get_drvdata(device);
7701 	struct drm_device *dev = connector->dev;
7702 	long val;
7703 	int ret;
7704 
7705 	ret = kstrtol(buf, 0, &val);
7706 
7707 	if (ret)
7708 		return ret;
7709 
7710 	if (val < 0 || val > 4)
7711 		return -EINVAL;
7712 
7713 	drm_modeset_lock(&dev->mode_config.connection_mutex, NULL);
7714 	if (to_dm_connector_state(connector->state)->abm_sysfs_forbidden)
7715 		ret = -EBUSY;
7716 	else
7717 		to_dm_connector_state(connector->state)->abm_level = val ?:
7718 			ABM_LEVEL_IMMEDIATE_DISABLE;
7719 	drm_modeset_unlock(&dev->mode_config.connection_mutex);
7720 
7721 	if (ret)
7722 		return ret;
7723 
7724 	drm_kms_helper_hotplug_event(dev);
7725 
7726 	return count;
7727 }
7728 
7729 static DEVICE_ATTR_RW(panel_power_savings);
7730 
7731 static struct attribute *amdgpu_attrs[] = {
7732 	&dev_attr_panel_power_savings.attr,
7733 	NULL
7734 };
7735 
7736 static const struct attribute_group amdgpu_group = {
7737 	.name = "amdgpu",
7738 	.attrs = amdgpu_attrs
7739 };
7740 
7741 static bool
amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector * amdgpu_dm_connector)7742 amdgpu_dm_should_create_sysfs(struct amdgpu_dm_connector *amdgpu_dm_connector)
7743 {
7744 	if (amdgpu_dm_abm_level >= 0)
7745 		return false;
7746 
7747 	if (amdgpu_dm_connector->base.connector_type != DRM_MODE_CONNECTOR_eDP)
7748 		return false;
7749 
7750 	/* check for OLED panels */
7751 	if (amdgpu_dm_connector->bl_idx >= 0) {
7752 		struct drm_device *drm = amdgpu_dm_connector->base.dev;
7753 		struct amdgpu_display_manager *dm = &drm_to_adev(drm)->dm;
7754 		struct amdgpu_dm_backlight_caps *caps;
7755 
7756 		caps = &dm->backlight_caps[amdgpu_dm_connector->bl_idx];
7757 		if (caps->aux_support)
7758 			return false;
7759 	}
7760 
7761 	return true;
7762 }
7763 
amdgpu_dm_connector_unregister(struct drm_connector * connector)7764 static void amdgpu_dm_connector_unregister(struct drm_connector *connector)
7765 {
7766 	struct amdgpu_dm_connector *amdgpu_dm_connector = to_amdgpu_dm_connector(connector);
7767 
7768 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector))
7769 		sysfs_remove_group(&connector->kdev->kobj, &amdgpu_group);
7770 
7771 	cec_notifier_conn_unregister(amdgpu_dm_connector->notifier);
7772 	drm_dp_aux_unregister(&amdgpu_dm_connector->dm_dp_aux.aux);
7773 }
7774 
amdgpu_dm_connector_destroy(struct drm_connector * connector)7775 static void amdgpu_dm_connector_destroy(struct drm_connector *connector)
7776 {
7777 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7778 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
7779 	struct amdgpu_display_manager *dm = &adev->dm;
7780 
7781 	/*
7782 	 * Call only if mst_mgr was initialized before since it's not done
7783 	 * for all connector types.
7784 	 */
7785 	if (aconnector->mst_mgr.dev)
7786 		drm_dp_mst_topology_mgr_destroy(&aconnector->mst_mgr);
7787 
7788 	/* Cancel and flush any pending HDMI HPD debounce work */
7789 	if (aconnector->hdmi_hpd_debounce_delay_ms) {
7790 		cancel_delayed_work_sync(&aconnector->hdmi_hpd_debounce_work);
7791 		if (aconnector->hdmi_prev_sink) {
7792 			dc_sink_release(aconnector->hdmi_prev_sink);
7793 			aconnector->hdmi_prev_sink = NULL;
7794 		}
7795 	}
7796 
7797 	if (aconnector->bl_idx != -1) {
7798 		backlight_device_unregister(dm->backlight_dev[aconnector->bl_idx]);
7799 		dm->backlight_dev[aconnector->bl_idx] = NULL;
7800 	}
7801 
7802 	if (aconnector->dc_em_sink)
7803 		dc_sink_release(aconnector->dc_em_sink);
7804 	aconnector->dc_em_sink = NULL;
7805 	if (aconnector->dc_sink)
7806 		dc_sink_release(aconnector->dc_sink);
7807 	aconnector->dc_sink = NULL;
7808 
7809 	drm_dp_cec_unregister_connector(&aconnector->dm_dp_aux.aux);
7810 	drm_connector_unregister(connector);
7811 	drm_connector_cleanup(connector);
7812 	kfree(aconnector->dm_dp_aux.aux.name);
7813 
7814 	kfree(connector);
7815 }
7816 
amdgpu_dm_connector_funcs_reset(struct drm_connector * connector)7817 void amdgpu_dm_connector_funcs_reset(struct drm_connector *connector)
7818 {
7819 	struct dm_connector_state *state =
7820 		to_dm_connector_state(connector->state);
7821 
7822 	if (connector->state)
7823 		__drm_atomic_helper_connector_destroy_state(connector->state);
7824 
7825 	kfree(state);
7826 
7827 	state = kzalloc_obj(*state, GFP_KERNEL);
7828 
7829 	if (state) {
7830 		state->scaling = RMX_OFF;
7831 		state->underscan_enable = false;
7832 		state->underscan_hborder = 0;
7833 		state->underscan_vborder = 0;
7834 		state->base.max_requested_bpc = 8;
7835 		state->vcpi_slots = 0;
7836 		state->pbn = 0;
7837 
7838 		if (connector->connector_type == DRM_MODE_CONNECTOR_eDP) {
7839 			if (amdgpu_dm_abm_level <= 0)
7840 				state->abm_level = ABM_LEVEL_IMMEDIATE_DISABLE;
7841 			else
7842 				state->abm_level = amdgpu_dm_abm_level;
7843 		}
7844 
7845 		__drm_atomic_helper_connector_reset(connector, &state->base);
7846 	}
7847 }
7848 
7849 struct drm_connector_state *
amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector * connector)7850 amdgpu_dm_connector_atomic_duplicate_state(struct drm_connector *connector)
7851 {
7852 	struct dm_connector_state *state =
7853 		to_dm_connector_state(connector->state);
7854 
7855 	struct dm_connector_state *new_state =
7856 			kmemdup(state, sizeof(*state), GFP_KERNEL);
7857 
7858 	if (!new_state)
7859 		return NULL;
7860 
7861 	__drm_atomic_helper_connector_duplicate_state(connector, &new_state->base);
7862 
7863 	new_state->freesync_capable = state->freesync_capable;
7864 	new_state->abm_level = state->abm_level;
7865 	new_state->scaling = state->scaling;
7866 	new_state->underscan_enable = state->underscan_enable;
7867 	new_state->underscan_hborder = state->underscan_hborder;
7868 	new_state->underscan_vborder = state->underscan_vborder;
7869 	new_state->vcpi_slots = state->vcpi_slots;
7870 	new_state->pbn = state->pbn;
7871 	return &new_state->base;
7872 }
7873 
7874 static int
amdgpu_dm_connector_late_register(struct drm_connector * connector)7875 amdgpu_dm_connector_late_register(struct drm_connector *connector)
7876 {
7877 	struct amdgpu_dm_connector *amdgpu_dm_connector =
7878 		to_amdgpu_dm_connector(connector);
7879 	int r;
7880 
7881 	if (amdgpu_dm_should_create_sysfs(amdgpu_dm_connector)) {
7882 		r = sysfs_create_group(&connector->kdev->kobj,
7883 				       &amdgpu_group);
7884 		if (r)
7885 			return r;
7886 	}
7887 
7888 	amdgpu_dm_register_backlight_device(amdgpu_dm_connector);
7889 
7890 	if ((connector->connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
7891 	    (connector->connector_type == DRM_MODE_CONNECTOR_eDP)) {
7892 		amdgpu_dm_connector->dm_dp_aux.aux.dev = connector->kdev;
7893 		r = drm_dp_aux_register(&amdgpu_dm_connector->dm_dp_aux.aux);
7894 		if (r)
7895 			return r;
7896 	}
7897 
7898 #if defined(CONFIG_DEBUG_FS)
7899 	connector_debugfs_init(amdgpu_dm_connector);
7900 #endif
7901 
7902 	return 0;
7903 }
7904 
amdgpu_dm_connector_funcs_force(struct drm_connector * connector)7905 static void amdgpu_dm_connector_funcs_force(struct drm_connector *connector)
7906 {
7907 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
7908 	struct dc_link *dc_link = aconnector->dc_link;
7909 	struct dc_sink *dc_em_sink = aconnector->dc_em_sink;
7910 	const struct drm_edid *drm_edid;
7911 	struct i2c_adapter *ddc;
7912 	struct drm_device *dev = connector->dev;
7913 
7914 	if (dc_link && dc_link->aux_mode)
7915 		ddc = &aconnector->dm_dp_aux.aux.ddc;
7916 	else
7917 		ddc = &aconnector->i2c->base;
7918 
7919 	drm_edid = drm_edid_read_ddc(connector, ddc);
7920 	drm_edid_connector_update(connector, drm_edid);
7921 	if (!drm_edid) {
7922 		drm_err(dev, "No EDID found on connector: %s.\n", connector->name);
7923 		return;
7924 	}
7925 
7926 	aconnector->drm_edid = drm_edid;
7927 	/* Update emulated (virtual) sink's EDID */
7928 	if (dc_em_sink && dc_link) {
7929 		// FIXME: Get rid of drm_edid_raw()
7930 		const struct edid *edid = drm_edid_raw(drm_edid);
7931 
7932 		memset(&dc_em_sink->edid_caps, 0, sizeof(struct dc_edid_caps));
7933 		memmove(dc_em_sink->dc_edid.raw_edid, edid,
7934 			(edid->extensions + 1) * EDID_LENGTH);
7935 		dm_helpers_parse_edid_caps(
7936 			dc_link,
7937 			&dc_em_sink->dc_edid,
7938 			&dc_em_sink->edid_caps);
7939 	}
7940 }
7941 
7942 static const struct drm_connector_funcs amdgpu_dm_connector_funcs = {
7943 	.reset = amdgpu_dm_connector_funcs_reset,
7944 	.detect = amdgpu_dm_connector_detect,
7945 	.fill_modes = drm_helper_probe_single_connector_modes,
7946 	.destroy = amdgpu_dm_connector_destroy,
7947 	.atomic_duplicate_state = amdgpu_dm_connector_atomic_duplicate_state,
7948 	.atomic_destroy_state = drm_atomic_helper_connector_destroy_state,
7949 	.atomic_set_property = amdgpu_dm_connector_atomic_set_property,
7950 	.atomic_get_property = amdgpu_dm_connector_atomic_get_property,
7951 	.late_register = amdgpu_dm_connector_late_register,
7952 	.early_unregister = amdgpu_dm_connector_unregister,
7953 	.force = amdgpu_dm_connector_funcs_force
7954 };
7955 
get_modes(struct drm_connector * connector)7956 static int get_modes(struct drm_connector *connector)
7957 {
7958 	return amdgpu_dm_connector_get_modes(connector);
7959 }
7960 
create_eml_sink(struct amdgpu_dm_connector * aconnector)7961 static void create_eml_sink(struct amdgpu_dm_connector *aconnector)
7962 {
7963 	struct drm_connector *connector = &aconnector->base;
7964 	struct dc_link *dc_link = aconnector->dc_link;
7965 	struct dc_sink_init_data init_params = {
7966 			.link = aconnector->dc_link,
7967 			.sink_signal = SIGNAL_TYPE_VIRTUAL
7968 	};
7969 	const struct drm_edid *drm_edid;
7970 	const struct edid *edid;
7971 	struct i2c_adapter *ddc;
7972 
7973 	if (dc_link && dc_link->aux_mode)
7974 		ddc = &aconnector->dm_dp_aux.aux.ddc;
7975 	else
7976 		ddc = &aconnector->i2c->base;
7977 
7978 	drm_edid = drm_edid_read_ddc(connector, ddc);
7979 	drm_edid_connector_update(connector, drm_edid);
7980 	if (!drm_edid) {
7981 		drm_err(connector->dev, "No EDID found on connector: %s.\n", connector->name);
7982 		return;
7983 	}
7984 
7985 	if (connector->display_info.is_hdmi)
7986 		init_params.sink_signal = SIGNAL_TYPE_HDMI_TYPE_A;
7987 
7988 	aconnector->drm_edid = drm_edid;
7989 
7990 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
7991 	aconnector->dc_em_sink = dc_link_add_remote_sink(
7992 		aconnector->dc_link,
7993 		(uint8_t *)edid,
7994 		(edid->extensions + 1) * EDID_LENGTH,
7995 		&init_params);
7996 
7997 	if (aconnector->base.force == DRM_FORCE_ON) {
7998 		aconnector->dc_sink = aconnector->dc_link->local_sink ?
7999 		aconnector->dc_link->local_sink :
8000 		aconnector->dc_em_sink;
8001 		if (aconnector->dc_sink)
8002 			dc_sink_retain(aconnector->dc_sink);
8003 	}
8004 }
8005 
handle_edid_mgmt(struct amdgpu_dm_connector * aconnector)8006 static void handle_edid_mgmt(struct amdgpu_dm_connector *aconnector)
8007 {
8008 	struct dc_link *link = (struct dc_link *)aconnector->dc_link;
8009 
8010 	/*
8011 	 * In case of headless boot with force on for DP managed connector
8012 	 * Those settings have to be != 0 to get initial modeset
8013 	 */
8014 	if (link->connector_signal == SIGNAL_TYPE_DISPLAY_PORT) {
8015 		link->verified_link_cap.lane_count = LANE_COUNT_FOUR;
8016 		link->verified_link_cap.link_rate = LINK_RATE_HIGH2;
8017 	}
8018 
8019 	create_eml_sink(aconnector);
8020 }
8021 
dm_validate_stream_and_context(struct dc * dc,struct dc_stream_state * stream)8022 static enum dc_status dm_validate_stream_and_context(struct dc *dc,
8023 						struct dc_stream_state *stream)
8024 {
8025 	enum dc_status dc_result = DC_ERROR_UNEXPECTED;
8026 	struct dc_plane_state *dc_plane_state = NULL;
8027 	struct dc_state *dc_state = NULL;
8028 
8029 	if (!stream)
8030 		goto cleanup;
8031 
8032 	dc_plane_state = dc_create_plane_state(dc);
8033 	if (!dc_plane_state)
8034 		goto cleanup;
8035 
8036 	dc_state = dc_state_create(dc, NULL);
8037 	if (!dc_state)
8038 		goto cleanup;
8039 
8040 	/* populate stream to plane */
8041 	dc_plane_state->src_rect.height  = stream->src.height;
8042 	dc_plane_state->src_rect.width   = stream->src.width;
8043 	dc_plane_state->dst_rect.height  = stream->src.height;
8044 	dc_plane_state->dst_rect.width   = stream->src.width;
8045 	dc_plane_state->clip_rect.height = stream->src.height;
8046 	dc_plane_state->clip_rect.width  = stream->src.width;
8047 	dc_plane_state->plane_size.surface_pitch = ((stream->src.width + 255) / 256) * 256;
8048 	dc_plane_state->plane_size.surface_size.height = stream->src.height;
8049 	dc_plane_state->plane_size.surface_size.width  = stream->src.width;
8050 	dc_plane_state->plane_size.chroma_size.height  = stream->src.height;
8051 	dc_plane_state->plane_size.chroma_size.width   = stream->src.width;
8052 	dc_plane_state->format = SURFACE_PIXEL_FORMAT_GRPH_ARGB8888;
8053 	dc_plane_state->tiling_info.gfx9.swizzle = DC_SW_UNKNOWN;
8054 	dc_plane_state->rotation = ROTATION_ANGLE_0;
8055 	dc_plane_state->is_tiling_rotated = false;
8056 	dc_plane_state->tiling_info.gfx8.array_mode = DC_ARRAY_LINEAR_GENERAL;
8057 
8058 	dc_result = dc_validate_stream(dc, stream);
8059 	if (dc_result == DC_OK)
8060 		dc_result = dc_validate_plane(dc, dc_plane_state);
8061 
8062 	if (dc_result == DC_OK)
8063 		dc_result = dc_state_add_stream(dc, dc_state, stream);
8064 
8065 	if (dc_result == DC_OK && !dc_state_add_plane(
8066 						dc,
8067 						stream,
8068 						dc_plane_state,
8069 						dc_state))
8070 		dc_result = DC_FAIL_ATTACH_SURFACES;
8071 
8072 	if (dc_result == DC_OK)
8073 		dc_result = dc_validate_global_state(dc, dc_state, DC_VALIDATE_MODE_ONLY);
8074 
8075 cleanup:
8076 	if (dc_state)
8077 		dc_state_release(dc_state);
8078 
8079 	if (dc_plane_state)
8080 		dc_plane_state_release(dc_plane_state);
8081 
8082 	return dc_result;
8083 }
8084 
8085 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)8086 create_validate_stream_for_sink(struct drm_connector *connector,
8087 				const struct drm_display_mode *drm_mode,
8088 				const struct dm_connector_state *dm_state,
8089 				const struct dc_stream_state *old_stream)
8090 {
8091 	struct amdgpu_dm_connector *aconnector = NULL;
8092 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
8093 	struct dc_stream_state *stream;
8094 	const struct drm_connector_state *drm_state = dm_state ? &dm_state->base : NULL;
8095 	int requested_bpc = drm_state ? drm_state->max_requested_bpc : 8;
8096 	enum dc_status dc_result = DC_OK;
8097 	uint8_t bpc_limit = 6;
8098 
8099 	if (!dm_state)
8100 		return NULL;
8101 
8102 	if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
8103 		aconnector = to_amdgpu_dm_connector(connector);
8104 
8105 	if (aconnector &&
8106 	    (aconnector->dc_link->connector_signal == SIGNAL_TYPE_HDMI_TYPE_A ||
8107 	     aconnector->dc_link->dpcd_caps.dongle_type == DISPLAY_DONGLE_DP_HDMI_CONVERTER))
8108 		bpc_limit = 8;
8109 
8110 	do {
8111 		drm_dbg_kms(connector->dev, "Trying with %d bpc\n", requested_bpc);
8112 		stream = create_stream_for_sink(connector, drm_mode,
8113 						dm_state, old_stream,
8114 						requested_bpc);
8115 		if (stream == NULL) {
8116 			drm_err(adev_to_drm(adev), "Failed to create stream for sink!\n");
8117 			break;
8118 		}
8119 
8120 		dc_result = dc_validate_stream(adev->dm.dc, stream);
8121 
8122 		if (!aconnector) /* writeback connector */
8123 			return stream;
8124 
8125 		if (dc_result == DC_OK && stream->signal == SIGNAL_TYPE_DISPLAY_PORT_MST)
8126 			dc_result = dm_dp_mst_is_port_support_mode(aconnector, stream);
8127 
8128 		if (dc_result == DC_OK)
8129 			dc_result = dm_validate_stream_and_context(adev->dm.dc, stream);
8130 
8131 		if (dc_result != DC_OK) {
8132 			drm_dbg_kms(connector->dev, "Pruned mode %d x %d (clk %d) %s %s -- %s\n",
8133 				      drm_mode->hdisplay,
8134 				      drm_mode->vdisplay,
8135 				      drm_mode->clock,
8136 				      dc_pixel_encoding_to_str(stream->timing.pixel_encoding),
8137 				      dc_color_depth_to_str(stream->timing.display_color_depth),
8138 				      dc_status_to_str(dc_result));
8139 
8140 			dc_stream_release(stream);
8141 			stream = NULL;
8142 			requested_bpc -= 2; /* lower bpc to retry validation */
8143 		}
8144 
8145 	} while (stream == NULL && requested_bpc >= bpc_limit);
8146 
8147 	switch (dc_result) {
8148 	/*
8149 	 * If we failed to validate DP bandwidth stream with the requested RGB color depth,
8150 	 * we try to fallback and configure in order:
8151 	 * YUV422 (8bpc, 6bpc)
8152 	 * YUV420 (8bpc, 6bpc)
8153 	 */
8154 	case DC_FAIL_ENC_VALIDATE:
8155 	case DC_EXCEED_DONGLE_CAP:
8156 	case DC_NO_DP_LINK_BANDWIDTH:
8157 		/* recursively entered twice and already tried both YUV422 and YUV420 */
8158 		if (aconnector->force_yuv422_output && aconnector->force_yuv420_output)
8159 			break;
8160 		/* first failure; try YUV422 */
8161 		if (!aconnector->force_yuv422_output) {
8162 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV422\n",
8163 				    __func__, __LINE__, dc_result);
8164 			aconnector->force_yuv422_output = true;
8165 		/* recursively entered and YUV422 failed, try YUV420 */
8166 		} else if (!aconnector->force_yuv420_output) {
8167 			drm_dbg_kms(connector->dev, "%s:%d Validation failed with %d, retrying w/ YUV420\n",
8168 				    __func__, __LINE__, dc_result);
8169 			aconnector->force_yuv420_output = true;
8170 		}
8171 		stream = create_validate_stream_for_sink(connector, drm_mode,
8172 							 dm_state, old_stream);
8173 		aconnector->force_yuv422_output = false;
8174 		aconnector->force_yuv420_output = false;
8175 		break;
8176 	case DC_OK:
8177 		break;
8178 	default:
8179 		drm_dbg_kms(connector->dev, "%s:%d Unhandled validation failure %d\n",
8180 			    __func__, __LINE__, dc_result);
8181 		break;
8182 	}
8183 
8184 	return stream;
8185 }
8186 
amdgpu_dm_connector_mode_valid(struct drm_connector * connector,const struct drm_display_mode * mode)8187 enum drm_mode_status amdgpu_dm_connector_mode_valid(struct drm_connector *connector,
8188 				   const struct drm_display_mode *mode)
8189 {
8190 	int result = MODE_ERROR;
8191 	struct dc_sink *dc_sink;
8192 	struct drm_display_mode *test_mode;
8193 	/* TODO: Unhardcode stream count */
8194 	struct dc_stream_state *stream;
8195 	/* we always have an amdgpu_dm_connector here since we got
8196 	 * here via the amdgpu_dm_connector_helper_funcs
8197 	 */
8198 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8199 
8200 	if ((mode->flags & DRM_MODE_FLAG_INTERLACE) ||
8201 			(mode->flags & DRM_MODE_FLAG_DBLSCAN))
8202 		return result;
8203 
8204 	/*
8205 	 * Only run this the first time mode_valid is called to initilialize
8206 	 * EDID mgmt
8207 	 */
8208 	if (aconnector->base.force != DRM_FORCE_UNSPECIFIED &&
8209 		!aconnector->dc_em_sink)
8210 		handle_edid_mgmt(aconnector);
8211 
8212 	dc_sink = to_amdgpu_dm_connector(connector)->dc_sink;
8213 
8214 	if (dc_sink == NULL && aconnector->base.force != DRM_FORCE_ON_DIGITAL &&
8215 				aconnector->base.force != DRM_FORCE_ON) {
8216 		drm_err(connector->dev, "dc_sink is NULL!\n");
8217 		goto fail;
8218 	}
8219 
8220 	test_mode = drm_mode_duplicate(connector->dev, mode);
8221 	if (!test_mode)
8222 		goto fail;
8223 
8224 	drm_mode_set_crtcinfo(test_mode, 0);
8225 
8226 	stream = create_validate_stream_for_sink(connector, test_mode,
8227 						 to_dm_connector_state(connector->state),
8228 						 NULL);
8229 	drm_mode_destroy(connector->dev, test_mode);
8230 	if (stream) {
8231 		dc_stream_release(stream);
8232 		result = MODE_OK;
8233 	}
8234 
8235 fail:
8236 	/* TODO: error handling*/
8237 	return result;
8238 }
8239 
fill_hdr_info_packet(const struct drm_connector_state * state,struct dc_info_packet * out)8240 static int fill_hdr_info_packet(const struct drm_connector_state *state,
8241 				struct dc_info_packet *out)
8242 {
8243 	struct hdmi_drm_infoframe frame;
8244 	unsigned char buf[30]; /* 26 + 4 */
8245 	ssize_t len;
8246 	int ret, i;
8247 
8248 	memset(out, 0, sizeof(*out));
8249 
8250 	if (!state->hdr_output_metadata)
8251 		return 0;
8252 
8253 	ret = drm_hdmi_infoframe_set_hdr_metadata(&frame, state);
8254 	if (ret)
8255 		return ret;
8256 
8257 	len = hdmi_drm_infoframe_pack_only(&frame, buf, sizeof(buf));
8258 	if (len < 0)
8259 		return (int)len;
8260 
8261 	/* Static metadata is a fixed 26 bytes + 4 byte header. */
8262 	if (len != 30)
8263 		return -EINVAL;
8264 
8265 	/* Prepare the infopacket for DC. */
8266 	switch (state->connector->connector_type) {
8267 	case DRM_MODE_CONNECTOR_HDMIA:
8268 		out->hb0 = 0x87; /* type */
8269 		out->hb1 = 0x01; /* version */
8270 		out->hb2 = 0x1A; /* length */
8271 		out->sb[0] = buf[3]; /* checksum */
8272 		i = 1;
8273 		break;
8274 
8275 	case DRM_MODE_CONNECTOR_DisplayPort:
8276 	case DRM_MODE_CONNECTOR_eDP:
8277 		out->hb0 = 0x00; /* sdp id, zero */
8278 		out->hb1 = 0x87; /* type */
8279 		out->hb2 = 0x1D; /* payload len - 1 */
8280 		out->hb3 = (0x13 << 2); /* sdp version */
8281 		out->sb[0] = 0x01; /* version */
8282 		out->sb[1] = 0x1A; /* length */
8283 		i = 2;
8284 		break;
8285 
8286 	default:
8287 		return -EINVAL;
8288 	}
8289 
8290 	memcpy(&out->sb[i], &buf[4], 26);
8291 	out->valid = true;
8292 
8293 	print_hex_dump(KERN_DEBUG, "HDR SB:", DUMP_PREFIX_NONE, 16, 1, out->sb,
8294 		       sizeof(out->sb), false);
8295 
8296 	return 0;
8297 }
8298 
8299 static int
amdgpu_dm_connector_atomic_check(struct drm_connector * conn,struct drm_atomic_state * state)8300 amdgpu_dm_connector_atomic_check(struct drm_connector *conn,
8301 				 struct drm_atomic_state *state)
8302 {
8303 	struct drm_connector_state *new_con_state =
8304 		drm_atomic_get_new_connector_state(state, conn);
8305 	struct drm_connector_state *old_con_state =
8306 		drm_atomic_get_old_connector_state(state, conn);
8307 	struct drm_crtc *crtc = new_con_state->crtc;
8308 	struct drm_crtc_state *new_crtc_state;
8309 	struct amdgpu_dm_connector *aconn = to_amdgpu_dm_connector(conn);
8310 	int ret;
8311 
8312 	if (WARN_ON(unlikely(!old_con_state || !new_con_state)))
8313 		return -EINVAL;
8314 
8315 	trace_amdgpu_dm_connector_atomic_check(new_con_state);
8316 
8317 	if (conn->connector_type == DRM_MODE_CONNECTOR_DisplayPort) {
8318 		ret = drm_dp_mst_root_conn_atomic_check(new_con_state, &aconn->mst_mgr);
8319 		if (ret < 0)
8320 			return ret;
8321 	}
8322 
8323 	if (!crtc)
8324 		return 0;
8325 
8326 	if (new_con_state->privacy_screen_sw_state != old_con_state->privacy_screen_sw_state) {
8327 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8328 		if (IS_ERR(new_crtc_state))
8329 			return PTR_ERR(new_crtc_state);
8330 
8331 		new_crtc_state->mode_changed = true;
8332 	}
8333 
8334 	if (new_con_state->colorspace != old_con_state->colorspace) {
8335 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8336 		if (IS_ERR(new_crtc_state))
8337 			return PTR_ERR(new_crtc_state);
8338 
8339 		new_crtc_state->mode_changed = true;
8340 	}
8341 
8342 	if (new_con_state->content_type != old_con_state->content_type) {
8343 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8344 		if (IS_ERR(new_crtc_state))
8345 			return PTR_ERR(new_crtc_state);
8346 
8347 		new_crtc_state->mode_changed = true;
8348 	}
8349 
8350 	if (!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state)) {
8351 		struct dc_info_packet hdr_infopacket;
8352 
8353 		ret = fill_hdr_info_packet(new_con_state, &hdr_infopacket);
8354 		if (ret)
8355 			return ret;
8356 
8357 		new_crtc_state = drm_atomic_get_crtc_state(state, crtc);
8358 		if (IS_ERR(new_crtc_state))
8359 			return PTR_ERR(new_crtc_state);
8360 
8361 		/*
8362 		 * DC considers the stream backends changed if the
8363 		 * static metadata changes. Forcing the modeset also
8364 		 * gives a simple way for userspace to switch from
8365 		 * 8bpc to 10bpc when setting the metadata to enter
8366 		 * or exit HDR.
8367 		 *
8368 		 * Changing the static metadata after it's been
8369 		 * set is permissible, however. So only force a
8370 		 * modeset if we're entering or exiting HDR.
8371 		 */
8372 		new_crtc_state->mode_changed = new_crtc_state->mode_changed ||
8373 			!old_con_state->hdr_output_metadata ||
8374 			!new_con_state->hdr_output_metadata;
8375 	}
8376 
8377 	return 0;
8378 }
8379 
8380 static const struct drm_connector_helper_funcs
8381 amdgpu_dm_connector_helper_funcs = {
8382 	/*
8383 	 * If hotplugging a second bigger display in FB Con mode, bigger resolution
8384 	 * modes will be filtered by drm_mode_validate_size(), and those modes
8385 	 * are missing after user start lightdm. So we need to renew modes list.
8386 	 * in get_modes call back, not just return the modes count
8387 	 */
8388 	.get_modes = get_modes,
8389 	.mode_valid = amdgpu_dm_connector_mode_valid,
8390 	.atomic_check = amdgpu_dm_connector_atomic_check,
8391 };
8392 
dm_encoder_helper_disable(struct drm_encoder * encoder)8393 static void dm_encoder_helper_disable(struct drm_encoder *encoder)
8394 {
8395 
8396 }
8397 
convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)8398 int convert_dc_color_depth_into_bpc(enum dc_color_depth display_color_depth)
8399 {
8400 	switch (display_color_depth) {
8401 	case COLOR_DEPTH_666:
8402 		return 6;
8403 	case COLOR_DEPTH_888:
8404 		return 8;
8405 	case COLOR_DEPTH_101010:
8406 		return 10;
8407 	case COLOR_DEPTH_121212:
8408 		return 12;
8409 	case COLOR_DEPTH_141414:
8410 		return 14;
8411 	case COLOR_DEPTH_161616:
8412 		return 16;
8413 	default:
8414 		break;
8415 	}
8416 	return 0;
8417 }
8418 
dm_encoder_helper_atomic_check(struct drm_encoder * encoder,struct drm_crtc_state * crtc_state,struct drm_connector_state * conn_state)8419 static int dm_encoder_helper_atomic_check(struct drm_encoder *encoder,
8420 					  struct drm_crtc_state *crtc_state,
8421 					  struct drm_connector_state *conn_state)
8422 {
8423 	struct drm_atomic_state *state = crtc_state->state;
8424 	struct drm_connector *connector = conn_state->connector;
8425 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
8426 	struct dm_connector_state *dm_new_connector_state = to_dm_connector_state(conn_state);
8427 	const struct drm_display_mode *adjusted_mode = &crtc_state->adjusted_mode;
8428 	struct drm_dp_mst_topology_mgr *mst_mgr;
8429 	struct drm_dp_mst_port *mst_port;
8430 	struct drm_dp_mst_topology_state *mst_state;
8431 	enum dc_color_depth color_depth;
8432 	int clock, bpp = 0;
8433 	bool is_y420 = false;
8434 
8435 	if ((connector->connector_type == DRM_MODE_CONNECTOR_eDP) ||
8436 	    (connector->connector_type == DRM_MODE_CONNECTOR_LVDS)) {
8437 		struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8438 		struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8439 		enum drm_mode_status result;
8440 
8441 		result = drm_crtc_helper_mode_valid_fixed(encoder->crtc, adjusted_mode, native_mode);
8442 		if (result != MODE_OK && dm_new_connector_state->scaling == RMX_OFF) {
8443 			drm_dbg_driver(encoder->dev,
8444 				       "mode %dx%d@%dHz is not native, enabling scaling\n",
8445 				       adjusted_mode->hdisplay, adjusted_mode->vdisplay,
8446 				       drm_mode_vrefresh(adjusted_mode));
8447 			dm_new_connector_state->scaling = RMX_ASPECT;
8448 		}
8449 		return 0;
8450 	}
8451 
8452 	if (!aconnector->mst_output_port)
8453 		return 0;
8454 
8455 	mst_port = aconnector->mst_output_port;
8456 	mst_mgr = &aconnector->mst_root->mst_mgr;
8457 
8458 	if (!crtc_state->connectors_changed && !crtc_state->mode_changed)
8459 		return 0;
8460 
8461 	mst_state = drm_atomic_get_mst_topology_state(state, mst_mgr);
8462 	if (IS_ERR(mst_state))
8463 		return PTR_ERR(mst_state);
8464 
8465 	mst_state->pbn_div.full = dm_mst_get_pbn_divider(aconnector->mst_root->dc_link);
8466 
8467 	if (!state->duplicated) {
8468 		int max_bpc = conn_state->max_requested_bpc;
8469 
8470 		is_y420 = drm_mode_is_420_also(&connector->display_info, adjusted_mode) &&
8471 			  aconnector->force_yuv420_output;
8472 		color_depth = convert_color_depth_from_display_info(connector,
8473 								    is_y420,
8474 								    max_bpc);
8475 		bpp = convert_dc_color_depth_into_bpc(color_depth) * 3;
8476 		clock = adjusted_mode->clock;
8477 		dm_new_connector_state->pbn = drm_dp_calc_pbn_mode(clock, bpp << 4);
8478 	}
8479 
8480 	dm_new_connector_state->vcpi_slots =
8481 		drm_dp_atomic_find_time_slots(state, mst_mgr, mst_port,
8482 					      dm_new_connector_state->pbn);
8483 	if (dm_new_connector_state->vcpi_slots < 0) {
8484 		drm_dbg_atomic(connector->dev, "failed finding vcpi slots: %d\n", (int)dm_new_connector_state->vcpi_slots);
8485 		return dm_new_connector_state->vcpi_slots;
8486 	}
8487 	return 0;
8488 }
8489 
8490 const struct drm_encoder_helper_funcs amdgpu_dm_encoder_helper_funcs = {
8491 	.disable = dm_encoder_helper_disable,
8492 	.atomic_check = dm_encoder_helper_atomic_check
8493 };
8494 
dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state * state,struct dc_state * dc_state,struct dsc_mst_fairness_vars * vars)8495 static int dm_update_mst_vcpi_slots_for_dsc(struct drm_atomic_state *state,
8496 					    struct dc_state *dc_state,
8497 					    struct dsc_mst_fairness_vars *vars)
8498 {
8499 	struct dc_stream_state *stream = NULL;
8500 	struct drm_connector *connector;
8501 	struct drm_connector_state *new_con_state;
8502 	struct amdgpu_dm_connector *aconnector;
8503 	struct dm_connector_state *dm_conn_state;
8504 	int i, j, ret;
8505 	int vcpi, pbn_div, pbn = 0, slot_num = 0;
8506 
8507 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
8508 
8509 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
8510 			continue;
8511 
8512 		aconnector = to_amdgpu_dm_connector(connector);
8513 
8514 		if (!aconnector->mst_output_port)
8515 			continue;
8516 
8517 		if (!new_con_state || !new_con_state->crtc)
8518 			continue;
8519 
8520 		dm_conn_state = to_dm_connector_state(new_con_state);
8521 
8522 		for (j = 0; j < dc_state->stream_count; j++) {
8523 			stream = dc_state->streams[j];
8524 			if (!stream)
8525 				continue;
8526 
8527 			if ((struct amdgpu_dm_connector *)stream->dm_stream_context == aconnector)
8528 				break;
8529 
8530 			stream = NULL;
8531 		}
8532 
8533 		if (!stream)
8534 			continue;
8535 
8536 		pbn_div = dm_mst_get_pbn_divider(stream->link);
8537 		/* pbn is calculated by compute_mst_dsc_configs_for_state*/
8538 		for (j = 0; j < dc_state->stream_count; j++) {
8539 			if (vars[j].aconnector == aconnector) {
8540 				pbn = vars[j].pbn;
8541 				break;
8542 			}
8543 		}
8544 
8545 		if (j == dc_state->stream_count || pbn_div == 0)
8546 			continue;
8547 
8548 		slot_num = DIV_ROUND_UP(pbn, pbn_div);
8549 
8550 		if (stream->timing.flags.DSC != 1) {
8551 			dm_conn_state->pbn = pbn;
8552 			dm_conn_state->vcpi_slots = slot_num;
8553 
8554 			ret = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port,
8555 							   dm_conn_state->pbn, false);
8556 			if (ret < 0)
8557 				return ret;
8558 
8559 			continue;
8560 		}
8561 
8562 		vcpi = drm_dp_mst_atomic_enable_dsc(state, aconnector->mst_output_port, pbn, true);
8563 		if (vcpi < 0)
8564 			return vcpi;
8565 
8566 		dm_conn_state->pbn = pbn;
8567 		dm_conn_state->vcpi_slots = vcpi;
8568 	}
8569 	return 0;
8570 }
8571 
to_drm_connector_type(enum signal_type st,uint32_t connector_id)8572 static int to_drm_connector_type(enum signal_type st, uint32_t connector_id)
8573 {
8574 	switch (st) {
8575 	case SIGNAL_TYPE_HDMI_TYPE_A:
8576 		return DRM_MODE_CONNECTOR_HDMIA;
8577 	case SIGNAL_TYPE_EDP:
8578 		return DRM_MODE_CONNECTOR_eDP;
8579 	case SIGNAL_TYPE_LVDS:
8580 		return DRM_MODE_CONNECTOR_LVDS;
8581 	case SIGNAL_TYPE_RGB:
8582 		return DRM_MODE_CONNECTOR_VGA;
8583 	case SIGNAL_TYPE_DISPLAY_PORT:
8584 	case SIGNAL_TYPE_DISPLAY_PORT_MST:
8585 		return DRM_MODE_CONNECTOR_DisplayPort;
8586 	case SIGNAL_TYPE_DVI_DUAL_LINK:
8587 	case SIGNAL_TYPE_DVI_SINGLE_LINK:
8588 		if (connector_id == CONNECTOR_ID_SINGLE_LINK_DVII ||
8589 			connector_id == CONNECTOR_ID_DUAL_LINK_DVII)
8590 			return DRM_MODE_CONNECTOR_DVII;
8591 
8592 		return DRM_MODE_CONNECTOR_DVID;
8593 	case SIGNAL_TYPE_VIRTUAL:
8594 		return DRM_MODE_CONNECTOR_VIRTUAL;
8595 
8596 	default:
8597 		return DRM_MODE_CONNECTOR_Unknown;
8598 	}
8599 }
8600 
amdgpu_dm_connector_to_encoder(struct drm_connector * connector)8601 static struct drm_encoder *amdgpu_dm_connector_to_encoder(struct drm_connector *connector)
8602 {
8603 	struct drm_encoder *encoder;
8604 
8605 	/* There is only one encoder per connector */
8606 	drm_connector_for_each_possible_encoder(connector, encoder)
8607 		return encoder;
8608 
8609 	return NULL;
8610 }
8611 
amdgpu_dm_get_native_mode(struct drm_connector * connector)8612 static void amdgpu_dm_get_native_mode(struct drm_connector *connector)
8613 {
8614 	struct drm_encoder *encoder;
8615 	struct amdgpu_encoder *amdgpu_encoder;
8616 
8617 	encoder = amdgpu_dm_connector_to_encoder(connector);
8618 
8619 	if (encoder == NULL)
8620 		return;
8621 
8622 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8623 
8624 	amdgpu_encoder->native_mode.clock = 0;
8625 
8626 	if (!list_empty(&connector->probed_modes)) {
8627 		struct drm_display_mode *preferred_mode = NULL;
8628 
8629 		list_for_each_entry(preferred_mode,
8630 				    &connector->probed_modes,
8631 				    head) {
8632 			if (preferred_mode->type & DRM_MODE_TYPE_PREFERRED)
8633 				amdgpu_encoder->native_mode = *preferred_mode;
8634 
8635 			break;
8636 		}
8637 
8638 	}
8639 }
8640 
8641 static struct drm_display_mode *
amdgpu_dm_create_common_mode(struct drm_encoder * encoder,const char * name,int hdisplay,int vdisplay)8642 amdgpu_dm_create_common_mode(struct drm_encoder *encoder,
8643 			     const char *name,
8644 			     int hdisplay, int vdisplay)
8645 {
8646 	struct drm_device *dev = encoder->dev;
8647 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8648 	struct drm_display_mode *mode = NULL;
8649 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8650 
8651 	mode = drm_mode_duplicate(dev, native_mode);
8652 
8653 	if (mode == NULL)
8654 		return NULL;
8655 
8656 	mode->hdisplay = hdisplay;
8657 	mode->vdisplay = vdisplay;
8658 	mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8659 	strscpy(mode->name, name, DRM_DISPLAY_MODE_LEN);
8660 
8661 	return mode;
8662 
8663 }
8664 
8665 static const struct amdgpu_dm_mode_size {
8666 	char name[DRM_DISPLAY_MODE_LEN];
8667 	int w;
8668 	int h;
8669 } common_modes[] = {
8670 	{  "640x480",  640,  480},
8671 	{  "800x600",  800,  600},
8672 	{ "1024x768", 1024,  768},
8673 	{ "1280x720", 1280,  720},
8674 	{ "1280x800", 1280,  800},
8675 	{"1280x1024", 1280, 1024},
8676 	{ "1440x900", 1440,  900},
8677 	{"1680x1050", 1680, 1050},
8678 	{"1600x1200", 1600, 1200},
8679 	{"1920x1080", 1920, 1080},
8680 	{"1920x1200", 1920, 1200}
8681 };
8682 
amdgpu_dm_connector_add_common_modes(struct drm_encoder * encoder,struct drm_connector * connector)8683 static void amdgpu_dm_connector_add_common_modes(struct drm_encoder *encoder,
8684 						 struct drm_connector *connector)
8685 {
8686 	struct amdgpu_encoder *amdgpu_encoder = to_amdgpu_encoder(encoder);
8687 	struct drm_display_mode *mode = NULL;
8688 	struct drm_display_mode *native_mode = &amdgpu_encoder->native_mode;
8689 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8690 				to_amdgpu_dm_connector(connector);
8691 	int i;
8692 	int n;
8693 
8694 	if ((connector->connector_type != DRM_MODE_CONNECTOR_eDP) &&
8695 	    (connector->connector_type != DRM_MODE_CONNECTOR_LVDS))
8696 		return;
8697 
8698 	n = ARRAY_SIZE(common_modes);
8699 
8700 	for (i = 0; i < n; i++) {
8701 		struct drm_display_mode *curmode = NULL;
8702 		bool mode_existed = false;
8703 
8704 		if (common_modes[i].w > native_mode->hdisplay ||
8705 		    common_modes[i].h > native_mode->vdisplay ||
8706 		   (common_modes[i].w == native_mode->hdisplay &&
8707 		    common_modes[i].h == native_mode->vdisplay))
8708 			continue;
8709 
8710 		list_for_each_entry(curmode, &connector->probed_modes, head) {
8711 			if (common_modes[i].w == curmode->hdisplay &&
8712 			    common_modes[i].h == curmode->vdisplay) {
8713 				mode_existed = true;
8714 				break;
8715 			}
8716 		}
8717 
8718 		if (mode_existed)
8719 			continue;
8720 
8721 		mode = amdgpu_dm_create_common_mode(encoder,
8722 				common_modes[i].name, common_modes[i].w,
8723 				common_modes[i].h);
8724 		if (!mode)
8725 			continue;
8726 
8727 		drm_mode_probed_add(connector, mode);
8728 		amdgpu_dm_connector->num_modes++;
8729 	}
8730 }
8731 
amdgpu_set_panel_orientation(struct drm_connector * connector)8732 static void amdgpu_set_panel_orientation(struct drm_connector *connector)
8733 {
8734 	struct drm_encoder *encoder;
8735 	struct amdgpu_encoder *amdgpu_encoder;
8736 	const struct drm_display_mode *native_mode;
8737 
8738 	if (connector->connector_type != DRM_MODE_CONNECTOR_eDP &&
8739 	    connector->connector_type != DRM_MODE_CONNECTOR_LVDS)
8740 		return;
8741 
8742 	mutex_lock(&connector->dev->mode_config.mutex);
8743 	amdgpu_dm_connector_get_modes(connector);
8744 	mutex_unlock(&connector->dev->mode_config.mutex);
8745 
8746 	encoder = amdgpu_dm_connector_to_encoder(connector);
8747 	if (!encoder)
8748 		return;
8749 
8750 	amdgpu_encoder = to_amdgpu_encoder(encoder);
8751 
8752 	native_mode = &amdgpu_encoder->native_mode;
8753 	if (native_mode->hdisplay == 0 || native_mode->vdisplay == 0)
8754 		return;
8755 
8756 	drm_connector_set_panel_orientation_with_quirk(connector,
8757 						       DRM_MODE_PANEL_ORIENTATION_UNKNOWN,
8758 						       native_mode->hdisplay,
8759 						       native_mode->vdisplay);
8760 }
8761 
amdgpu_dm_connector_ddc_get_modes(struct drm_connector * connector,const struct drm_edid * drm_edid)8762 static void amdgpu_dm_connector_ddc_get_modes(struct drm_connector *connector,
8763 					      const struct drm_edid *drm_edid)
8764 {
8765 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8766 			to_amdgpu_dm_connector(connector);
8767 
8768 	if (drm_edid) {
8769 		/* empty probed_modes */
8770 		INIT_LIST_HEAD(&connector->probed_modes);
8771 		amdgpu_dm_connector->num_modes =
8772 				drm_edid_connector_add_modes(connector);
8773 
8774 		/* sorting the probed modes before calling function
8775 		 * amdgpu_dm_get_native_mode() since EDID can have
8776 		 * more than one preferred mode. The modes that are
8777 		 * later in the probed mode list could be of higher
8778 		 * and preferred resolution. For example, 3840x2160
8779 		 * resolution in base EDID preferred timing and 4096x2160
8780 		 * preferred resolution in DID extension block later.
8781 		 */
8782 		drm_mode_sort(&connector->probed_modes);
8783 		amdgpu_dm_get_native_mode(connector);
8784 
8785 		/* Freesync capabilities are reset by calling
8786 		 * drm_edid_connector_add_modes() and need to be
8787 		 * restored here.
8788 		 */
8789 		amdgpu_dm_update_freesync_caps(connector, drm_edid);
8790 	} else {
8791 		amdgpu_dm_connector->num_modes = 0;
8792 	}
8793 }
8794 
is_duplicate_mode(struct amdgpu_dm_connector * aconnector,struct drm_display_mode * mode)8795 static bool is_duplicate_mode(struct amdgpu_dm_connector *aconnector,
8796 			      struct drm_display_mode *mode)
8797 {
8798 	struct drm_display_mode *m;
8799 
8800 	list_for_each_entry(m, &aconnector->base.probed_modes, head) {
8801 		if (drm_mode_equal(m, mode))
8802 			return true;
8803 	}
8804 
8805 	return false;
8806 }
8807 
add_fs_modes(struct amdgpu_dm_connector * aconnector)8808 static uint add_fs_modes(struct amdgpu_dm_connector *aconnector)
8809 {
8810 	const struct drm_display_mode *m;
8811 	struct drm_display_mode *new_mode;
8812 	uint i;
8813 	u32 new_modes_count = 0;
8814 
8815 	/* Standard FPS values
8816 	 *
8817 	 * 23.976       - TV/NTSC
8818 	 * 24           - Cinema
8819 	 * 25           - TV/PAL
8820 	 * 29.97        - TV/NTSC
8821 	 * 30           - TV/NTSC
8822 	 * 48           - Cinema HFR
8823 	 * 50           - TV/PAL
8824 	 * 60           - Commonly used
8825 	 * 48,72,96,120 - Multiples of 24
8826 	 */
8827 	static const u32 common_rates[] = {
8828 		23976, 24000, 25000, 29970, 30000,
8829 		48000, 50000, 60000, 72000, 96000, 120000
8830 	};
8831 
8832 	/*
8833 	 * Find mode with highest refresh rate with the same resolution
8834 	 * as the preferred mode. Some monitors report a preferred mode
8835 	 * with lower resolution than the highest refresh rate supported.
8836 	 */
8837 
8838 	m = get_highest_refresh_rate_mode(aconnector, true);
8839 	if (!m)
8840 		return 0;
8841 
8842 	for (i = 0; i < ARRAY_SIZE(common_rates); i++) {
8843 		u64 target_vtotal, target_vtotal_diff;
8844 		u64 num, den;
8845 
8846 		if (drm_mode_vrefresh(m) * 1000 < common_rates[i])
8847 			continue;
8848 
8849 		if (common_rates[i] < aconnector->min_vfreq * 1000 ||
8850 		    common_rates[i] > aconnector->max_vfreq * 1000)
8851 			continue;
8852 
8853 		num = (unsigned long long)m->clock * 1000 * 1000;
8854 		den = common_rates[i] * (unsigned long long)m->htotal;
8855 		target_vtotal = div_u64(num, den);
8856 		target_vtotal_diff = target_vtotal - m->vtotal;
8857 
8858 		/* Check for illegal modes */
8859 		if (m->vsync_start + target_vtotal_diff < m->vdisplay ||
8860 		    m->vsync_end + target_vtotal_diff < m->vsync_start ||
8861 		    m->vtotal + target_vtotal_diff < m->vsync_end)
8862 			continue;
8863 
8864 		new_mode = drm_mode_duplicate(aconnector->base.dev, m);
8865 		if (!new_mode)
8866 			goto out;
8867 
8868 		new_mode->vtotal += (u16)target_vtotal_diff;
8869 		new_mode->vsync_start += (u16)target_vtotal_diff;
8870 		new_mode->vsync_end += (u16)target_vtotal_diff;
8871 		new_mode->type &= ~DRM_MODE_TYPE_PREFERRED;
8872 		new_mode->type |= DRM_MODE_TYPE_DRIVER;
8873 
8874 		if (!is_duplicate_mode(aconnector, new_mode)) {
8875 			drm_mode_probed_add(&aconnector->base, new_mode);
8876 			new_modes_count += 1;
8877 		} else
8878 			drm_mode_destroy(aconnector->base.dev, new_mode);
8879 	}
8880  out:
8881 	return new_modes_count;
8882 }
8883 
amdgpu_dm_connector_add_freesync_modes(struct drm_connector * connector,const struct drm_edid * drm_edid)8884 static void amdgpu_dm_connector_add_freesync_modes(struct drm_connector *connector,
8885 						   const struct drm_edid *drm_edid)
8886 {
8887 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8888 		to_amdgpu_dm_connector(connector);
8889 
8890 	if (!(amdgpu_freesync_vid_mode && drm_edid))
8891 		return;
8892 
8893 	if (!amdgpu_dm_connector->dc_sink || !amdgpu_dm_connector->dc_link)
8894 		return;
8895 
8896 	if (!dc_supports_vrr(amdgpu_dm_connector->dc_sink->ctx->dce_version))
8897 		return;
8898 
8899 	if (dc_connector_supports_analog(amdgpu_dm_connector->dc_link->link_id.id) &&
8900 	    amdgpu_dm_connector->dc_sink->edid_caps.analog)
8901 		return;
8902 
8903 	if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
8904 		amdgpu_dm_connector->num_modes +=
8905 			add_fs_modes(amdgpu_dm_connector);
8906 }
8907 
amdgpu_dm_connector_get_modes(struct drm_connector * connector)8908 static int amdgpu_dm_connector_get_modes(struct drm_connector *connector)
8909 {
8910 	struct amdgpu_dm_connector *amdgpu_dm_connector =
8911 			to_amdgpu_dm_connector(connector);
8912 	struct dc_link *dc_link = amdgpu_dm_connector->dc_link;
8913 	struct drm_encoder *encoder;
8914 	const struct drm_edid *drm_edid = amdgpu_dm_connector->drm_edid;
8915 	struct dc_link_settings *verified_link_cap = &dc_link->verified_link_cap;
8916 	const struct dc *dc = dc_link->dc;
8917 
8918 	encoder = amdgpu_dm_connector_to_encoder(connector);
8919 
8920 	if (!drm_edid) {
8921 		amdgpu_dm_connector->num_modes =
8922 				drm_add_modes_noedid(connector, 640, 480);
8923 		if (dc->link_srv->dp_get_encoding_format(verified_link_cap) == DP_128b_132b_ENCODING)
8924 			amdgpu_dm_connector->num_modes +=
8925 				drm_add_modes_noedid(connector, 1920, 1080);
8926 
8927 		if (amdgpu_dm_connector->dc_sink &&
8928 		    amdgpu_dm_connector->dc_sink->edid_caps.analog &&
8929 		    dc_connector_supports_analog(dc_link->link_id.id)) {
8930 			/* Analog monitor connected by DAC load detection.
8931 			 * Add common modes. It will be up to the user to select one that works.
8932 			 */
8933 			for (int i = 0; i < ARRAY_SIZE(common_modes); i++)
8934 				amdgpu_dm_connector->num_modes += drm_add_modes_noedid(
8935 					connector, common_modes[i].w, common_modes[i].h);
8936 		}
8937 	} else {
8938 		amdgpu_dm_connector_ddc_get_modes(connector, drm_edid);
8939 		if (encoder)
8940 			amdgpu_dm_connector_add_common_modes(encoder, connector);
8941 		amdgpu_dm_connector_add_freesync_modes(connector, drm_edid);
8942 	}
8943 	amdgpu_dm_fbc_init(connector);
8944 
8945 	return amdgpu_dm_connector->num_modes;
8946 }
8947 
8948 static const u32 supported_colorspaces =
8949 	BIT(DRM_MODE_COLORIMETRY_BT709_YCC) |
8950 	BIT(DRM_MODE_COLORIMETRY_OPRGB) |
8951 	BIT(DRM_MODE_COLORIMETRY_BT2020_RGB) |
8952 	BIT(DRM_MODE_COLORIMETRY_BT2020_YCC);
8953 
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)8954 void amdgpu_dm_connector_init_helper(struct amdgpu_display_manager *dm,
8955 				     struct amdgpu_dm_connector *aconnector,
8956 				     int connector_type,
8957 				     struct dc_link *link,
8958 				     int link_index)
8959 {
8960 	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
8961 
8962 	/*
8963 	 * Some of the properties below require access to state, like bpc.
8964 	 * Allocate some default initial connector state with our reset helper.
8965 	 */
8966 	if (aconnector->base.funcs->reset)
8967 		aconnector->base.funcs->reset(&aconnector->base);
8968 
8969 	aconnector->connector_id = link_index;
8970 	aconnector->bl_idx = -1;
8971 	aconnector->dc_link = link;
8972 	aconnector->base.interlace_allowed = false;
8973 	aconnector->base.doublescan_allowed = false;
8974 	aconnector->base.stereo_allowed = false;
8975 	aconnector->base.dpms = DRM_MODE_DPMS_OFF;
8976 	aconnector->hpd.hpd = AMDGPU_HPD_NONE; /* not used */
8977 	aconnector->audio_inst = -1;
8978 	aconnector->pack_sdp_v1_3 = false;
8979 	aconnector->as_type = ADAPTIVE_SYNC_TYPE_NONE;
8980 	memset(&aconnector->vsdb_info, 0, sizeof(aconnector->vsdb_info));
8981 	mutex_init(&aconnector->hpd_lock);
8982 	mutex_init(&aconnector->handle_mst_msg_ready);
8983 
8984 	/*
8985 	 * If HDMI HPD debounce delay is set, use the minimum between selected
8986 	 * value and AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS
8987 	 */
8988 	if (amdgpu_hdmi_hpd_debounce_delay_ms) {
8989 		aconnector->hdmi_hpd_debounce_delay_ms = min(amdgpu_hdmi_hpd_debounce_delay_ms,
8990 							     AMDGPU_DM_MAX_HDMI_HPD_DEBOUNCE_MS);
8991 		INIT_DELAYED_WORK(&aconnector->hdmi_hpd_debounce_work, hdmi_hpd_debounce_work);
8992 		aconnector->hdmi_prev_sink = NULL;
8993 	} else {
8994 		aconnector->hdmi_hpd_debounce_delay_ms = 0;
8995 	}
8996 
8997 	/*
8998 	 * configure support HPD hot plug connector_>polled default value is 0
8999 	 * which means HPD hot plug not supported
9000 	 */
9001 	switch (connector_type) {
9002 	case DRM_MODE_CONNECTOR_HDMIA:
9003 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9004 		aconnector->base.ycbcr_420_allowed =
9005 			link->link_enc->features.hdmi_ycbcr420_supported ? true : false;
9006 		break;
9007 	case DRM_MODE_CONNECTOR_DisplayPort:
9008 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9009 		link->link_enc = link_enc_cfg_get_link_enc(link);
9010 		ASSERT(link->link_enc);
9011 		if (link->link_enc)
9012 			aconnector->base.ycbcr_420_allowed =
9013 			link->link_enc->features.dp_ycbcr420_supported ? true : false;
9014 		break;
9015 	case DRM_MODE_CONNECTOR_DVID:
9016 		aconnector->base.polled = DRM_CONNECTOR_POLL_HPD;
9017 		break;
9018 	case DRM_MODE_CONNECTOR_DVII:
9019 	case DRM_MODE_CONNECTOR_VGA:
9020 		aconnector->base.polled =
9021 			DRM_CONNECTOR_POLL_CONNECT | DRM_CONNECTOR_POLL_DISCONNECT;
9022 		break;
9023 	default:
9024 		break;
9025 	}
9026 
9027 	drm_object_attach_property(&aconnector->base.base,
9028 				dm->ddev->mode_config.scaling_mode_property,
9029 				DRM_MODE_SCALE_NONE);
9030 
9031 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA
9032 		|| (connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root))
9033 		drm_connector_attach_broadcast_rgb_property(&aconnector->base);
9034 
9035 	drm_object_attach_property(&aconnector->base.base,
9036 				adev->mode_info.underscan_property,
9037 				UNDERSCAN_OFF);
9038 	drm_object_attach_property(&aconnector->base.base,
9039 				adev->mode_info.underscan_hborder_property,
9040 				0);
9041 	drm_object_attach_property(&aconnector->base.base,
9042 				adev->mode_info.underscan_vborder_property,
9043 				0);
9044 
9045 	if (!aconnector->mst_root)
9046 		drm_connector_attach_max_bpc_property(&aconnector->base, 8, 16);
9047 
9048 	aconnector->base.state->max_bpc = 16;
9049 	aconnector->base.state->max_requested_bpc = aconnector->base.state->max_bpc;
9050 
9051 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9052 		/* Content Type is currently only implemented for HDMI. */
9053 		drm_connector_attach_content_type_property(&aconnector->base);
9054 	}
9055 
9056 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA) {
9057 		if (!drm_mode_create_hdmi_colorspace_property(&aconnector->base, supported_colorspaces))
9058 			drm_connector_attach_colorspace_property(&aconnector->base);
9059 	} else if ((connector_type == DRM_MODE_CONNECTOR_DisplayPort && !aconnector->mst_root) ||
9060 		   connector_type == DRM_MODE_CONNECTOR_eDP) {
9061 		if (!drm_mode_create_dp_colorspace_property(&aconnector->base, supported_colorspaces))
9062 			drm_connector_attach_colorspace_property(&aconnector->base);
9063 	}
9064 
9065 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9066 	    connector_type == DRM_MODE_CONNECTOR_DisplayPort ||
9067 	    connector_type == DRM_MODE_CONNECTOR_eDP) {
9068 		drm_connector_attach_hdr_output_metadata_property(&aconnector->base);
9069 
9070 		if (!aconnector->mst_root)
9071 			drm_connector_attach_vrr_capable_property(&aconnector->base);
9072 
9073 		if (adev->dm.hdcp_workqueue)
9074 			drm_connector_attach_content_protection_property(&aconnector->base, true);
9075 	}
9076 
9077 	if (connector_type == DRM_MODE_CONNECTOR_eDP) {
9078 		struct drm_privacy_screen *privacy_screen;
9079 
9080 		privacy_screen = drm_privacy_screen_get(adev_to_drm(adev)->dev, NULL);
9081 		if (!IS_ERR(privacy_screen)) {
9082 			drm_connector_attach_privacy_screen_provider(&aconnector->base,
9083 								     privacy_screen);
9084 		} else if (PTR_ERR(privacy_screen) != -ENODEV) {
9085 			drm_warn(adev_to_drm(adev), "Error getting privacy-screen\n");
9086 		}
9087 	}
9088 }
9089 
amdgpu_dm_i2c_xfer(struct i2c_adapter * i2c_adap,struct i2c_msg * msgs,int num)9090 static int amdgpu_dm_i2c_xfer(struct i2c_adapter *i2c_adap,
9091 			      struct i2c_msg *msgs, int num)
9092 {
9093 	struct amdgpu_i2c_adapter *i2c = i2c_get_adapdata(i2c_adap);
9094 	struct ddc_service *ddc_service = i2c->ddc_service;
9095 	struct i2c_command cmd;
9096 	int i;
9097 	int result = -EIO;
9098 
9099 	if (!ddc_service->ddc_pin)
9100 		return result;
9101 
9102 	cmd.payloads = kzalloc_objs(struct i2c_payload, num, GFP_KERNEL);
9103 
9104 	if (!cmd.payloads)
9105 		return result;
9106 
9107 	cmd.number_of_payloads = num;
9108 	cmd.engine = I2C_COMMAND_ENGINE_DEFAULT;
9109 	cmd.speed = 100;
9110 
9111 	for (i = 0; i < num; i++) {
9112 		cmd.payloads[i].write = !(msgs[i].flags & I2C_M_RD);
9113 		cmd.payloads[i].address = msgs[i].addr;
9114 		cmd.payloads[i].length = msgs[i].len;
9115 		cmd.payloads[i].data = msgs[i].buf;
9116 	}
9117 
9118 	if (i2c->oem) {
9119 		if (dc_submit_i2c_oem(
9120 			    ddc_service->ctx->dc,
9121 			    &cmd))
9122 			result = num;
9123 	} else {
9124 		if (dc_submit_i2c(
9125 			    ddc_service->ctx->dc,
9126 			    ddc_service->link->link_index,
9127 			    &cmd))
9128 			result = num;
9129 	}
9130 
9131 	kfree(cmd.payloads);
9132 	return result;
9133 }
9134 
amdgpu_dm_i2c_func(struct i2c_adapter * adap)9135 static u32 amdgpu_dm_i2c_func(struct i2c_adapter *adap)
9136 {
9137 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL;
9138 }
9139 
9140 static const struct i2c_algorithm amdgpu_dm_i2c_algo = {
9141 	.master_xfer = amdgpu_dm_i2c_xfer,
9142 	.functionality = amdgpu_dm_i2c_func,
9143 };
9144 
9145 static struct amdgpu_i2c_adapter *
create_i2c(struct ddc_service * ddc_service,bool oem)9146 create_i2c(struct ddc_service *ddc_service, bool oem)
9147 {
9148 	struct amdgpu_device *adev = ddc_service->ctx->driver_context;
9149 	struct amdgpu_i2c_adapter *i2c;
9150 
9151 	i2c = kzalloc_obj(struct amdgpu_i2c_adapter, GFP_KERNEL);
9152 	if (!i2c)
9153 		return NULL;
9154 	i2c->base.owner = THIS_MODULE;
9155 	i2c->base.dev.parent = &adev->pdev->dev;
9156 	i2c->base.algo = &amdgpu_dm_i2c_algo;
9157 	if (oem)
9158 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c OEM bus");
9159 	else
9160 		snprintf(i2c->base.name, sizeof(i2c->base.name), "AMDGPU DM i2c hw bus %d",
9161 			 ddc_service->link->link_index);
9162 	i2c_set_adapdata(&i2c->base, i2c);
9163 	i2c->ddc_service = ddc_service;
9164 	i2c->oem = oem;
9165 
9166 	return i2c;
9167 }
9168 
amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector * aconnector)9169 int amdgpu_dm_initialize_hdmi_connector(struct amdgpu_dm_connector *aconnector)
9170 {
9171 	struct cec_connector_info conn_info;
9172 	struct drm_device *ddev = aconnector->base.dev;
9173 	struct device *hdmi_dev = ddev->dev;
9174 
9175 	if (amdgpu_dc_debug_mask & DC_DISABLE_HDMI_CEC) {
9176 		drm_info(ddev, "HDMI-CEC feature masked\n");
9177 		return -EINVAL;
9178 	}
9179 
9180 	cec_fill_conn_info_from_drm(&conn_info, &aconnector->base);
9181 	aconnector->notifier =
9182 		cec_notifier_conn_register(hdmi_dev, NULL, &conn_info);
9183 	if (!aconnector->notifier) {
9184 		drm_err(ddev, "Failed to create cec notifier\n");
9185 		return -ENOMEM;
9186 	}
9187 
9188 	return 0;
9189 }
9190 
9191 /*
9192  * Note: this function assumes that dc_link_detect() was called for the
9193  * dc_link which will be represented by this aconnector.
9194  */
amdgpu_dm_connector_init(struct amdgpu_display_manager * dm,struct amdgpu_dm_connector * aconnector,u32 link_index,struct amdgpu_encoder * aencoder)9195 static int amdgpu_dm_connector_init(struct amdgpu_display_manager *dm,
9196 				    struct amdgpu_dm_connector *aconnector,
9197 				    u32 link_index,
9198 				    struct amdgpu_encoder *aencoder)
9199 {
9200 	int res = 0;
9201 	int connector_type;
9202 	struct dc *dc = dm->dc;
9203 	struct dc_link *link = dc_get_link_at_index(dc, link_index);
9204 	struct amdgpu_i2c_adapter *i2c;
9205 
9206 	/* Not needed for writeback connector */
9207 	link->priv = aconnector;
9208 
9209 
9210 	i2c = create_i2c(link->ddc, false);
9211 	if (!i2c) {
9212 		drm_err(adev_to_drm(dm->adev), "Failed to create i2c adapter data\n");
9213 		return -ENOMEM;
9214 	}
9215 
9216 	aconnector->i2c = i2c;
9217 	res = devm_i2c_add_adapter(dm->adev->dev, &i2c->base);
9218 
9219 	if (res) {
9220 		drm_err(adev_to_drm(dm->adev), "Failed to register hw i2c %d\n", link->link_index);
9221 		goto out_free;
9222 	}
9223 
9224 	connector_type = to_drm_connector_type(link->connector_signal, link->link_id.id);
9225 
9226 	res = drm_connector_init_with_ddc(
9227 			dm->ddev,
9228 			&aconnector->base,
9229 			&amdgpu_dm_connector_funcs,
9230 			connector_type,
9231 			&i2c->base);
9232 
9233 	if (res) {
9234 		drm_err(adev_to_drm(dm->adev), "connector_init failed\n");
9235 		aconnector->connector_id = -1;
9236 		goto out_free;
9237 	}
9238 
9239 	drm_connector_helper_add(
9240 			&aconnector->base,
9241 			&amdgpu_dm_connector_helper_funcs);
9242 
9243 	amdgpu_dm_connector_init_helper(
9244 		dm,
9245 		aconnector,
9246 		connector_type,
9247 		link,
9248 		link_index);
9249 
9250 	drm_connector_attach_encoder(
9251 		&aconnector->base, &aencoder->base);
9252 
9253 	if (connector_type == DRM_MODE_CONNECTOR_HDMIA ||
9254 	    connector_type == DRM_MODE_CONNECTOR_HDMIB)
9255 		amdgpu_dm_initialize_hdmi_connector(aconnector);
9256 
9257 	if (connector_type == DRM_MODE_CONNECTOR_DisplayPort
9258 		|| connector_type == DRM_MODE_CONNECTOR_eDP)
9259 		amdgpu_dm_initialize_dp_connector(dm, aconnector, link->link_index);
9260 
9261 out_free:
9262 	if (res) {
9263 		kfree(i2c);
9264 		aconnector->i2c = NULL;
9265 	}
9266 	return res;
9267 }
9268 
amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device * adev)9269 int amdgpu_dm_get_encoder_crtc_mask(struct amdgpu_device *adev)
9270 {
9271 	switch (adev->mode_info.num_crtc) {
9272 	case 1:
9273 		return 0x1;
9274 	case 2:
9275 		return 0x3;
9276 	case 3:
9277 		return 0x7;
9278 	case 4:
9279 		return 0xf;
9280 	case 5:
9281 		return 0x1f;
9282 	case 6:
9283 	default:
9284 		return 0x3f;
9285 	}
9286 }
9287 
amdgpu_dm_encoder_init(struct drm_device * dev,struct amdgpu_encoder * aencoder,uint32_t link_index)9288 static int amdgpu_dm_encoder_init(struct drm_device *dev,
9289 				  struct amdgpu_encoder *aencoder,
9290 				  uint32_t link_index)
9291 {
9292 	struct amdgpu_device *adev = drm_to_adev(dev);
9293 
9294 	int res = drm_encoder_init(dev,
9295 				   &aencoder->base,
9296 				   &amdgpu_dm_encoder_funcs,
9297 				   DRM_MODE_ENCODER_TMDS,
9298 				   NULL);
9299 
9300 	aencoder->base.possible_crtcs = amdgpu_dm_get_encoder_crtc_mask(adev);
9301 
9302 	if (!res)
9303 		aencoder->encoder_id = link_index;
9304 	else
9305 		aencoder->encoder_id = -1;
9306 
9307 	drm_encoder_helper_add(&aencoder->base, &amdgpu_dm_encoder_helper_funcs);
9308 
9309 	return res;
9310 }
9311 
manage_dm_interrupts(struct amdgpu_device * adev,struct amdgpu_crtc * acrtc,struct dm_crtc_state * acrtc_state)9312 static void manage_dm_interrupts(struct amdgpu_device *adev,
9313 				 struct amdgpu_crtc *acrtc,
9314 				 struct dm_crtc_state *acrtc_state)
9315 {	/*
9316 	 * We cannot be sure that the frontend index maps to the same
9317 	 * backend index - some even map to more than one.
9318 	 * So we have to go through the CRTC to find the right IRQ.
9319 	 */
9320 	int irq_type = amdgpu_display_crtc_idx_to_irq_type(
9321 			adev,
9322 			acrtc->crtc_id);
9323 	struct drm_device *dev = adev_to_drm(adev);
9324 
9325 	struct drm_vblank_crtc_config config = {0};
9326 	struct dc_crtc_timing *timing;
9327 	int offdelay;
9328 
9329 	if (acrtc_state) {
9330 		timing = &acrtc_state->stream->timing;
9331 
9332 		/*
9333 		 * Depending on when the HW latching event of double-buffered
9334 		 * registers happen relative to the PSR SDP deadline, and how
9335 		 * bad the Panel clock has drifted since the last ALPM off
9336 		 * event, there can be up to 3 frames of delay between sending
9337 		 * the PSR exit cmd to DMUB fw, and when the panel starts
9338 		 * displaying live frames.
9339 		 *
9340 		 * We can set:
9341 		 *
9342 		 * 20/100 * offdelay_ms = 3_frames_ms
9343 		 * => offdelay_ms = 5 * 3_frames_ms
9344 		 *
9345 		 * This ensures that `3_frames_ms` will only be experienced as a
9346 		 * 20% delay on top how long the display has been static, and
9347 		 * thus make the delay less perceivable.
9348 		 */
9349 		if (acrtc_state->stream->link->psr_settings.psr_version <
9350 		    DC_PSR_VERSION_UNSUPPORTED) {
9351 			offdelay = DIV64_U64_ROUND_UP((u64)5 * 3 * 10 *
9352 						      timing->v_total *
9353 						      timing->h_total,
9354 						      timing->pix_clk_100hz);
9355 			config.offdelay_ms = offdelay ?: 30;
9356 		} else if (amdgpu_ip_version(adev, DCE_HWIP, 0) <
9357 			   IP_VERSION(3, 5, 0) ||
9358 			   !(adev->flags & AMD_IS_APU)) {
9359 			/*
9360 			 * Older HW and DGPU have issues with instant off;
9361 			 * use a 2 frame offdelay.
9362 			 */
9363 			offdelay = DIV64_U64_ROUND_UP((u64)20 *
9364 						      timing->v_total *
9365 						      timing->h_total,
9366 						      timing->pix_clk_100hz);
9367 
9368 			config.offdelay_ms = offdelay ?: 30;
9369 		} else {
9370 			/* offdelay_ms = 0 will never disable vblank */
9371 			config.offdelay_ms = 1;
9372 			config.disable_immediate = true;
9373 		}
9374 
9375 		drm_crtc_vblank_on_config(&acrtc->base,
9376 					  &config);
9377 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_get.*/
9378 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9379 		case IP_VERSION(3, 0, 0):
9380 		case IP_VERSION(3, 0, 2):
9381 		case IP_VERSION(3, 0, 3):
9382 		case IP_VERSION(3, 2, 0):
9383 			if (amdgpu_irq_get(adev, &adev->pageflip_irq, irq_type))
9384 				drm_err(dev, "DM_IRQ: Cannot get pageflip irq!\n");
9385 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9386 			if (amdgpu_irq_get(adev, &adev->vline0_irq, irq_type))
9387 				drm_err(dev, "DM_IRQ: Cannot get vline0 irq!\n");
9388 #endif
9389 		}
9390 
9391 	} else {
9392 		/* Allow RX6xxx, RX7700, RX7800 GPUs to call amdgpu_irq_put.*/
9393 		switch (amdgpu_ip_version(adev, DCE_HWIP, 0)) {
9394 		case IP_VERSION(3, 0, 0):
9395 		case IP_VERSION(3, 0, 2):
9396 		case IP_VERSION(3, 0, 3):
9397 		case IP_VERSION(3, 2, 0):
9398 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
9399 			if (amdgpu_irq_put(adev, &adev->vline0_irq, irq_type))
9400 				drm_err(dev, "DM_IRQ: Cannot put vline0 irq!\n");
9401 #endif
9402 			if (amdgpu_irq_put(adev, &adev->pageflip_irq, irq_type))
9403 				drm_err(dev, "DM_IRQ: Cannot put pageflip irq!\n");
9404 		}
9405 
9406 		drm_crtc_vblank_off(&acrtc->base);
9407 	}
9408 }
9409 
dm_update_pflip_irq_state(struct amdgpu_device * adev,struct amdgpu_crtc * acrtc)9410 static void dm_update_pflip_irq_state(struct amdgpu_device *adev,
9411 				      struct amdgpu_crtc *acrtc)
9412 {
9413 	int irq_type =
9414 		amdgpu_display_crtc_idx_to_irq_type(adev, acrtc->crtc_id);
9415 
9416 	/**
9417 	 * This reads the current state for the IRQ and force reapplies
9418 	 * the setting to hardware.
9419 	 */
9420 	amdgpu_irq_update(adev, &adev->pageflip_irq, irq_type);
9421 }
9422 
9423 static bool
is_scaling_state_different(const struct dm_connector_state * dm_state,const struct dm_connector_state * old_dm_state)9424 is_scaling_state_different(const struct dm_connector_state *dm_state,
9425 			   const struct dm_connector_state *old_dm_state)
9426 {
9427 	if (dm_state->scaling != old_dm_state->scaling)
9428 		return true;
9429 	if (!dm_state->underscan_enable && old_dm_state->underscan_enable) {
9430 		if (old_dm_state->underscan_hborder != 0 && old_dm_state->underscan_vborder != 0)
9431 			return true;
9432 	} else  if (dm_state->underscan_enable && !old_dm_state->underscan_enable) {
9433 		if (dm_state->underscan_hborder != 0 && dm_state->underscan_vborder != 0)
9434 			return true;
9435 	} else if (dm_state->underscan_hborder != old_dm_state->underscan_hborder ||
9436 		   dm_state->underscan_vborder != old_dm_state->underscan_vborder)
9437 		return true;
9438 	return false;
9439 }
9440 
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)9441 static bool is_content_protection_different(struct drm_crtc_state *new_crtc_state,
9442 					    struct drm_crtc_state *old_crtc_state,
9443 					    struct drm_connector_state *new_conn_state,
9444 					    struct drm_connector_state *old_conn_state,
9445 					    const struct drm_connector *connector,
9446 					    struct hdcp_workqueue *hdcp_w)
9447 {
9448 	struct amdgpu_dm_connector *aconnector = to_amdgpu_dm_connector(connector);
9449 	struct dm_connector_state *dm_con_state = to_dm_connector_state(connector->state);
9450 
9451 	pr_debug("[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
9452 		connector->index, connector->status, connector->dpms);
9453 	pr_debug("[HDCP_DM] state protection old: %x new: %x\n",
9454 		old_conn_state->content_protection, new_conn_state->content_protection);
9455 
9456 	if (old_crtc_state)
9457 		pr_debug("[HDCP_DM] old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9458 		old_crtc_state->enable,
9459 		old_crtc_state->active,
9460 		old_crtc_state->mode_changed,
9461 		old_crtc_state->active_changed,
9462 		old_crtc_state->connectors_changed);
9463 
9464 	if (new_crtc_state)
9465 		pr_debug("[HDCP_DM] NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
9466 		new_crtc_state->enable,
9467 		new_crtc_state->active,
9468 		new_crtc_state->mode_changed,
9469 		new_crtc_state->active_changed,
9470 		new_crtc_state->connectors_changed);
9471 
9472 	/* hdcp content type change */
9473 	if (old_conn_state->hdcp_content_type != new_conn_state->hdcp_content_type &&
9474 	    new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_UNDESIRED) {
9475 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9476 		pr_debug("[HDCP_DM] Type0/1 change %s :true\n", __func__);
9477 		return true;
9478 	}
9479 
9480 	/* CP is being re enabled, ignore this */
9481 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED &&
9482 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9483 		if (new_crtc_state && new_crtc_state->mode_changed) {
9484 			new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9485 			pr_debug("[HDCP_DM] ENABLED->DESIRED & mode_changed %s :true\n", __func__);
9486 			return true;
9487 		}
9488 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_ENABLED;
9489 		pr_debug("[HDCP_DM] ENABLED -> DESIRED %s :false\n", __func__);
9490 		return false;
9491 	}
9492 
9493 	/* S3 resume case, since old state will always be 0 (UNDESIRED) and the restored state will be ENABLED
9494 	 *
9495 	 * Handles:	UNDESIRED -> ENABLED
9496 	 */
9497 	if (old_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_UNDESIRED &&
9498 	    new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED)
9499 		new_conn_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
9500 
9501 	/* Stream removed and re-enabled
9502 	 *
9503 	 * Can sometimes overlap with the HPD case,
9504 	 * thus set update_hdcp to false to avoid
9505 	 * setting HDCP multiple times.
9506 	 *
9507 	 * Handles:	DESIRED -> DESIRED (Special case)
9508 	 */
9509 	if (!(old_conn_state->crtc && old_conn_state->crtc->enabled) &&
9510 		new_conn_state->crtc && new_conn_state->crtc->enabled &&
9511 		connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9512 		dm_con_state->update_hdcp = false;
9513 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Stream removed and re-enabled) %s :true\n",
9514 			__func__);
9515 		return true;
9516 	}
9517 
9518 	/* Hot-plug, headless s3, dpms
9519 	 *
9520 	 * Only start HDCP if the display is connected/enabled.
9521 	 * update_hdcp flag will be set to false until the next
9522 	 * HPD comes in.
9523 	 *
9524 	 * Handles:	DESIRED -> DESIRED (Special case)
9525 	 */
9526 	if (dm_con_state->update_hdcp &&
9527 	new_conn_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED &&
9528 	connector->dpms == DRM_MODE_DPMS_ON && aconnector->dc_sink != NULL) {
9529 		dm_con_state->update_hdcp = false;
9530 		pr_debug("[HDCP_DM] DESIRED->DESIRED (Hot-plug, headless s3, dpms) %s :true\n",
9531 			__func__);
9532 		return true;
9533 	}
9534 
9535 	if (old_conn_state->content_protection == new_conn_state->content_protection) {
9536 		if (new_conn_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED) {
9537 			if (new_crtc_state && new_crtc_state->mode_changed) {
9538 				pr_debug("[HDCP_DM] DESIRED->DESIRED or ENABLE->ENABLE mode_change %s :true\n",
9539 					__func__);
9540 				return true;
9541 			}
9542 			pr_debug("[HDCP_DM] DESIRED->DESIRED & ENABLE->ENABLE %s :false\n",
9543 				__func__);
9544 			return false;
9545 		}
9546 
9547 		pr_debug("[HDCP_DM] UNDESIRED->UNDESIRED %s :false\n", __func__);
9548 		return false;
9549 	}
9550 
9551 	if (new_conn_state->content_protection != DRM_MODE_CONTENT_PROTECTION_ENABLED) {
9552 		pr_debug("[HDCP_DM] UNDESIRED->DESIRED or DESIRED->UNDESIRED or ENABLED->UNDESIRED %s :true\n",
9553 			__func__);
9554 		return true;
9555 	}
9556 
9557 	pr_debug("[HDCP_DM] DESIRED->ENABLED %s :false\n", __func__);
9558 	return false;
9559 }
9560 
remove_stream(struct amdgpu_device * adev,struct amdgpu_crtc * acrtc,struct dc_stream_state * stream)9561 static void remove_stream(struct amdgpu_device *adev,
9562 			  struct amdgpu_crtc *acrtc,
9563 			  struct dc_stream_state *stream)
9564 {
9565 	/* this is the update mode case */
9566 
9567 	acrtc->otg_inst = -1;
9568 	acrtc->enabled = false;
9569 }
9570 
prepare_flip_isr(struct amdgpu_crtc * acrtc)9571 static void prepare_flip_isr(struct amdgpu_crtc *acrtc)
9572 {
9573 
9574 	assert_spin_locked(&acrtc->base.dev->event_lock);
9575 	WARN_ON(acrtc->event);
9576 
9577 	acrtc->event = acrtc->base.state->event;
9578 
9579 	/* Set the flip status */
9580 	acrtc->pflip_status = AMDGPU_FLIP_SUBMITTED;
9581 
9582 	/* Mark this event as consumed */
9583 	acrtc->base.state->event = NULL;
9584 
9585 	drm_dbg_state(acrtc->base.dev,
9586 		      "crtc:%d, pflip_stat:AMDGPU_FLIP_SUBMITTED\n",
9587 		      acrtc->crtc_id);
9588 }
9589 
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)9590 static void update_freesync_state_on_stream(
9591 	struct amdgpu_display_manager *dm,
9592 	struct dm_crtc_state *new_crtc_state,
9593 	struct dc_stream_state *new_stream,
9594 	struct dc_plane_state *surface,
9595 	u32 flip_timestamp_in_us)
9596 {
9597 	struct mod_vrr_params vrr_params;
9598 	struct dc_info_packet vrr_infopacket = {0};
9599 	struct amdgpu_device *adev = dm->adev;
9600 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9601 	unsigned long flags;
9602 	bool pack_sdp_v1_3 = false;
9603 	struct amdgpu_dm_connector *aconn;
9604 	enum vrr_packet_type packet_type = PACKET_TYPE_VRR;
9605 
9606 	if (!new_stream)
9607 		return;
9608 
9609 	/*
9610 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9611 	 * For now it's sufficient to just guard against these conditions.
9612 	 */
9613 
9614 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9615 		return;
9616 
9617 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9618 	vrr_params = acrtc->dm_irq_params.vrr_params;
9619 
9620 	if (surface) {
9621 		mod_freesync_handle_preflip(
9622 			dm->freesync_module,
9623 			surface,
9624 			new_stream,
9625 			flip_timestamp_in_us,
9626 			&vrr_params);
9627 
9628 		if (adev->family < AMDGPU_FAMILY_AI &&
9629 		    amdgpu_dm_crtc_vrr_active(new_crtc_state)) {
9630 			mod_freesync_handle_v_update(dm->freesync_module,
9631 						     new_stream, &vrr_params);
9632 
9633 			/* Need to call this before the frame ends. */
9634 			dc_stream_adjust_vmin_vmax(dm->dc,
9635 						   new_crtc_state->stream,
9636 						   &vrr_params.adjust);
9637 		}
9638 	}
9639 
9640 	aconn = (struct amdgpu_dm_connector *)new_stream->dm_stream_context;
9641 
9642 	if (aconn && (aconn->as_type == FREESYNC_TYPE_PCON_IN_WHITELIST || aconn->vsdb_info.replay_mode)) {
9643 		pack_sdp_v1_3 = aconn->pack_sdp_v1_3;
9644 
9645 		if (aconn->vsdb_info.amd_vsdb_version == 1)
9646 			packet_type = PACKET_TYPE_FS_V1;
9647 		else if (aconn->vsdb_info.amd_vsdb_version == 2)
9648 			packet_type = PACKET_TYPE_FS_V2;
9649 		else if (aconn->vsdb_info.amd_vsdb_version == 3)
9650 			packet_type = PACKET_TYPE_FS_V3;
9651 
9652 		mod_build_adaptive_sync_infopacket(new_stream, aconn->as_type, NULL,
9653 					&new_stream->adaptive_sync_infopacket);
9654 	}
9655 
9656 	mod_freesync_build_vrr_infopacket(
9657 		dm->freesync_module,
9658 		new_stream,
9659 		&vrr_params,
9660 		packet_type,
9661 		TRANSFER_FUNC_UNKNOWN,
9662 		&vrr_infopacket,
9663 		pack_sdp_v1_3);
9664 
9665 	new_crtc_state->freesync_vrr_info_changed |=
9666 		(memcmp(&new_crtc_state->vrr_infopacket,
9667 			&vrr_infopacket,
9668 			sizeof(vrr_infopacket)) != 0);
9669 
9670 	acrtc->dm_irq_params.vrr_params = vrr_params;
9671 	new_crtc_state->vrr_infopacket = vrr_infopacket;
9672 
9673 	new_stream->vrr_infopacket = vrr_infopacket;
9674 	new_stream->allow_freesync = mod_freesync_get_freesync_enabled(&vrr_params);
9675 
9676 	if (new_crtc_state->freesync_vrr_info_changed)
9677 		drm_dbg_kms(adev_to_drm(adev), "VRR packet update: crtc=%u enabled=%d state=%d",
9678 			      new_crtc_state->base.crtc->base.id,
9679 			      (int)new_crtc_state->base.vrr_enabled,
9680 			      (int)vrr_params.state);
9681 
9682 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9683 }
9684 
update_stream_irq_parameters(struct amdgpu_display_manager * dm,struct dm_crtc_state * new_crtc_state)9685 static void update_stream_irq_parameters(
9686 	struct amdgpu_display_manager *dm,
9687 	struct dm_crtc_state *new_crtc_state)
9688 {
9689 	struct dc_stream_state *new_stream = new_crtc_state->stream;
9690 	struct mod_vrr_params vrr_params;
9691 	struct mod_freesync_config config = new_crtc_state->freesync_config;
9692 	struct amdgpu_device *adev = dm->adev;
9693 	struct amdgpu_crtc *acrtc = to_amdgpu_crtc(new_crtc_state->base.crtc);
9694 	unsigned long flags;
9695 
9696 	if (!new_stream)
9697 		return;
9698 
9699 	/*
9700 	 * TODO: Determine why min/max totals and vrefresh can be 0 here.
9701 	 * For now it's sufficient to just guard against these conditions.
9702 	 */
9703 	if (!new_stream->timing.h_total || !new_stream->timing.v_total)
9704 		return;
9705 
9706 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
9707 	vrr_params = acrtc->dm_irq_params.vrr_params;
9708 
9709 	if (new_crtc_state->vrr_supported &&
9710 	    config.min_refresh_in_uhz &&
9711 	    config.max_refresh_in_uhz) {
9712 		/*
9713 		 * if freesync compatible mode was set, config.state will be set
9714 		 * in atomic check
9715 		 */
9716 		if (config.state == VRR_STATE_ACTIVE_FIXED && config.fixed_refresh_in_uhz &&
9717 		    (!drm_atomic_crtc_needs_modeset(&new_crtc_state->base) ||
9718 		     new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED)) {
9719 			vrr_params.max_refresh_in_uhz = config.max_refresh_in_uhz;
9720 			vrr_params.min_refresh_in_uhz = config.min_refresh_in_uhz;
9721 			vrr_params.fixed_refresh_in_uhz = config.fixed_refresh_in_uhz;
9722 			vrr_params.state = VRR_STATE_ACTIVE_FIXED;
9723 		} else {
9724 			config.state = new_crtc_state->base.vrr_enabled ?
9725 						     VRR_STATE_ACTIVE_VARIABLE :
9726 						     VRR_STATE_INACTIVE;
9727 		}
9728 	} else {
9729 		config.state = VRR_STATE_UNSUPPORTED;
9730 	}
9731 
9732 	mod_freesync_build_vrr_params(dm->freesync_module,
9733 				      new_stream,
9734 				      &config, &vrr_params);
9735 
9736 	new_crtc_state->freesync_config = config;
9737 	/* Copy state for access from DM IRQ handler */
9738 	acrtc->dm_irq_params.freesync_config = config;
9739 	acrtc->dm_irq_params.active_planes = new_crtc_state->active_planes;
9740 	acrtc->dm_irq_params.vrr_params = vrr_params;
9741 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
9742 }
9743 
amdgpu_dm_handle_vrr_transition(struct dm_crtc_state * old_state,struct dm_crtc_state * new_state)9744 static void amdgpu_dm_handle_vrr_transition(struct dm_crtc_state *old_state,
9745 					    struct dm_crtc_state *new_state)
9746 {
9747 	bool old_vrr_active = amdgpu_dm_crtc_vrr_active(old_state);
9748 	bool new_vrr_active = amdgpu_dm_crtc_vrr_active(new_state);
9749 
9750 	if (!old_vrr_active && new_vrr_active) {
9751 		/* Transition VRR inactive -> active:
9752 		 * While VRR is active, we must not disable vblank irq, as a
9753 		 * reenable after disable would compute bogus vblank/pflip
9754 		 * timestamps if it likely happened inside display front-porch.
9755 		 *
9756 		 * We also need vupdate irq for the actual core vblank handling
9757 		 * at end of vblank.
9758 		 */
9759 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, true) != 0);
9760 		WARN_ON(drm_crtc_vblank_get(new_state->base.crtc) != 0);
9761 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR off->on: Get vblank ref\n",
9762 				 __func__, new_state->base.crtc->base.id);
9763 	} else if (old_vrr_active && !new_vrr_active) {
9764 		/* Transition VRR active -> inactive:
9765 		 * Allow vblank irq disable again for fixed refresh rate.
9766 		 */
9767 		WARN_ON(amdgpu_dm_crtc_set_vupdate_irq(new_state->base.crtc, false) != 0);
9768 		drm_crtc_vblank_put(new_state->base.crtc);
9769 		drm_dbg_driver(new_state->base.crtc->dev, "%s: crtc=%u VRR on->off: Drop vblank ref\n",
9770 				 __func__, new_state->base.crtc->base.id);
9771 	}
9772 }
9773 
amdgpu_dm_commit_cursors(struct drm_atomic_state * state)9774 static void amdgpu_dm_commit_cursors(struct drm_atomic_state *state)
9775 {
9776 	struct drm_plane *plane;
9777 	struct drm_plane_state *old_plane_state;
9778 	int i;
9779 
9780 	/*
9781 	 * TODO: Make this per-stream so we don't issue redundant updates for
9782 	 * commits with multiple streams.
9783 	 */
9784 	for_each_old_plane_in_state(state, plane, old_plane_state, i)
9785 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
9786 			amdgpu_dm_plane_handle_cursor_update(plane, old_plane_state);
9787 }
9788 
get_mem_type(struct drm_framebuffer * fb)9789 static inline uint32_t get_mem_type(struct drm_framebuffer *fb)
9790 {
9791 	struct amdgpu_bo *abo = gem_to_amdgpu_bo(fb->obj[0]);
9792 
9793 	return abo->tbo.resource ? abo->tbo.resource->mem_type : 0;
9794 }
9795 
amdgpu_dm_update_cursor(struct drm_plane * plane,struct drm_plane_state * old_plane_state,struct dc_stream_update * update)9796 static void amdgpu_dm_update_cursor(struct drm_plane *plane,
9797 				    struct drm_plane_state *old_plane_state,
9798 				    struct dc_stream_update *update)
9799 {
9800 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
9801 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(plane->state->fb);
9802 	struct drm_crtc *crtc = afb ? plane->state->crtc : old_plane_state->crtc;
9803 	struct dm_crtc_state *crtc_state = crtc ? to_dm_crtc_state(crtc->state) : NULL;
9804 	struct amdgpu_crtc *amdgpu_crtc = to_amdgpu_crtc(crtc);
9805 	uint64_t address = afb ? afb->address : 0;
9806 	struct dc_cursor_position position = {0};
9807 	struct dc_cursor_attributes attributes;
9808 	int ret;
9809 
9810 	if (!plane->state->fb && !old_plane_state->fb)
9811 		return;
9812 
9813 	drm_dbg_atomic(plane->dev, "crtc_id=%d with size %d to %d\n",
9814 		       amdgpu_crtc->crtc_id, plane->state->crtc_w,
9815 		       plane->state->crtc_h);
9816 
9817 	ret = amdgpu_dm_plane_get_cursor_position(plane, crtc, &position);
9818 	if (ret)
9819 		return;
9820 
9821 	if (!position.enable) {
9822 		/* turn off cursor */
9823 		if (crtc_state && crtc_state->stream) {
9824 			dc_stream_set_cursor_position(crtc_state->stream,
9825 						      &position);
9826 			update->cursor_position = &crtc_state->stream->cursor_position;
9827 		}
9828 		return;
9829 	}
9830 
9831 	amdgpu_crtc->cursor_width = plane->state->crtc_w;
9832 	amdgpu_crtc->cursor_height = plane->state->crtc_h;
9833 
9834 	memset(&attributes, 0, sizeof(attributes));
9835 	attributes.address.high_part = upper_32_bits(address);
9836 	attributes.address.low_part  = lower_32_bits(address);
9837 	attributes.width             = plane->state->crtc_w;
9838 	attributes.height            = plane->state->crtc_h;
9839 	attributes.color_format      = CURSOR_MODE_COLOR_PRE_MULTIPLIED_ALPHA;
9840 	attributes.rotation_angle    = 0;
9841 	attributes.attribute_flags.value = 0;
9842 
9843 	/* Enable cursor degamma ROM on DCN3+ for implicit sRGB degamma in DRM
9844 	 * legacy gamma setup.
9845 	 */
9846 	if (crtc_state->cm_is_degamma_srgb &&
9847 	    adev->dm.dc->caps.color.dpp.gamma_corr)
9848 		attributes.attribute_flags.bits.ENABLE_CURSOR_DEGAMMA = 1;
9849 
9850 	if (afb)
9851 		attributes.pitch = afb->base.pitches[0] / afb->base.format->cpp[0];
9852 
9853 	if (crtc_state->stream) {
9854 		if (!dc_stream_set_cursor_attributes(crtc_state->stream,
9855 						     &attributes))
9856 			drm_err(adev_to_drm(adev), "DC failed to set cursor attributes\n");
9857 
9858 		update->cursor_attributes = &crtc_state->stream->cursor_attributes;
9859 
9860 		if (!dc_stream_set_cursor_position(crtc_state->stream,
9861 						   &position))
9862 			drm_err(adev_to_drm(adev), "DC failed to set cursor position\n");
9863 
9864 		update->cursor_position = &crtc_state->stream->cursor_position;
9865 	}
9866 }
9867 
amdgpu_dm_enable_self_refresh(struct amdgpu_crtc * acrtc_attach,const struct dm_crtc_state * acrtc_state,const u64 current_ts)9868 static void amdgpu_dm_enable_self_refresh(struct amdgpu_crtc *acrtc_attach,
9869 					  const struct dm_crtc_state *acrtc_state,
9870 					  const u64 current_ts)
9871 {
9872 	struct psr_settings *psr = &acrtc_state->stream->link->psr_settings;
9873 	struct replay_settings *pr = &acrtc_state->stream->link->replay_settings;
9874 	struct amdgpu_dm_connector *aconn =
9875 		(struct amdgpu_dm_connector *)acrtc_state->stream->dm_stream_context;
9876 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
9877 
9878 	if (acrtc_state->update_type > UPDATE_TYPE_FAST) {
9879 		if (pr->config.replay_supported && !pr->replay_feature_enabled)
9880 			amdgpu_dm_link_setup_replay(acrtc_state->stream->link, aconn);
9881 		else if (psr->psr_version != DC_PSR_VERSION_UNSUPPORTED &&
9882 			     !psr->psr_feature_enabled)
9883 			if (!aconn->disallow_edp_enter_psr)
9884 				amdgpu_dm_link_setup_psr(acrtc_state->stream);
9885 	}
9886 
9887 	/* Decrement skip count when SR is enabled and we're doing fast updates. */
9888 	if (acrtc_state->update_type == UPDATE_TYPE_FAST &&
9889 	    (psr->psr_feature_enabled || pr->config.replay_supported)) {
9890 		if (aconn->sr_skip_count > 0)
9891 			aconn->sr_skip_count--;
9892 
9893 		/* Allow SR when skip count is 0. */
9894 		acrtc_attach->dm_irq_params.allow_sr_entry = !aconn->sr_skip_count;
9895 
9896 		/*
9897 		 * If sink supports PSR SU/Panel Replay, there is no need to rely on
9898 		 * a vblank event disable request to enable PSR/RP. PSR SU/RP
9899 		 * can be enabled immediately once OS demonstrates an
9900 		 * adequate number of fast atomic commits to notify KMD
9901 		 * of update events. See `vblank_control_worker()`.
9902 		 */
9903 		if (!vrr_active &&
9904 		    acrtc_attach->dm_irq_params.allow_sr_entry &&
9905 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
9906 		    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
9907 #endif
9908 		    (current_ts - psr->psr_dirty_rects_change_timestamp_ns) > 500000000) {
9909 			if (pr->replay_feature_enabled && !pr->replay_allow_active)
9910 				amdgpu_dm_replay_enable(acrtc_state->stream, true);
9911 			if (psr->psr_version == DC_PSR_VERSION_SU_1 &&
9912 			    !psr->psr_allow_active && !aconn->disallow_edp_enter_psr)
9913 				amdgpu_dm_psr_enable(acrtc_state->stream);
9914 		}
9915 	} else {
9916 		acrtc_attach->dm_irq_params.allow_sr_entry = false;
9917 	}
9918 }
9919 
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)9920 static void amdgpu_dm_commit_planes(struct drm_atomic_state *state,
9921 				    struct drm_device *dev,
9922 				    struct amdgpu_display_manager *dm,
9923 				    struct drm_crtc *pcrtc,
9924 				    bool wait_for_vblank)
9925 {
9926 	u32 i;
9927 	u64 timestamp_ns = ktime_get_ns();
9928 	struct drm_plane *plane;
9929 	struct drm_plane_state *old_plane_state, *new_plane_state;
9930 	struct amdgpu_crtc *acrtc_attach = to_amdgpu_crtc(pcrtc);
9931 	struct drm_crtc_state *new_pcrtc_state =
9932 			drm_atomic_get_new_crtc_state(state, pcrtc);
9933 	struct dm_crtc_state *acrtc_state = to_dm_crtc_state(new_pcrtc_state);
9934 	struct dm_crtc_state *dm_old_crtc_state =
9935 			to_dm_crtc_state(drm_atomic_get_old_crtc_state(state, pcrtc));
9936 	int planes_count = 0, vpos, hpos;
9937 	unsigned long flags;
9938 	u32 target_vblank, last_flip_vblank;
9939 	bool vrr_active = amdgpu_dm_crtc_vrr_active(acrtc_state);
9940 	bool cursor_update = false;
9941 	bool pflip_present = false;
9942 	bool dirty_rects_changed = false;
9943 	bool updated_planes_and_streams = false;
9944 	struct {
9945 		struct dc_surface_update surface_updates[MAX_SURFACES];
9946 		struct dc_plane_info plane_infos[MAX_SURFACES];
9947 		struct dc_scaling_info scaling_infos[MAX_SURFACES];
9948 		struct dc_flip_addrs flip_addrs[MAX_SURFACES];
9949 		struct dc_stream_update stream_update;
9950 	} *bundle;
9951 
9952 	bundle = kzalloc_obj(*bundle, GFP_KERNEL);
9953 
9954 	if (!bundle) {
9955 		drm_err(dev, "Failed to allocate update bundle\n");
9956 		goto cleanup;
9957 	}
9958 
9959 	/*
9960 	 * Disable the cursor first if we're disabling all the planes.
9961 	 * It'll remain on the screen after the planes are re-enabled
9962 	 * if we don't.
9963 	 *
9964 	 * If the cursor is transitioning from native to overlay mode, the
9965 	 * native cursor needs to be disabled first.
9966 	 */
9967 	if (acrtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE &&
9968 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
9969 		struct dc_cursor_position cursor_position = {0};
9970 
9971 		if (!dc_stream_set_cursor_position(acrtc_state->stream,
9972 						   &cursor_position))
9973 			drm_err(dev, "DC failed to disable native cursor\n");
9974 
9975 		bundle->stream_update.cursor_position =
9976 				&acrtc_state->stream->cursor_position;
9977 	}
9978 
9979 	if (acrtc_state->active_planes == 0 &&
9980 	    dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
9981 		amdgpu_dm_commit_cursors(state);
9982 
9983 	/* update planes when needed */
9984 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
9985 		struct drm_crtc *crtc = new_plane_state->crtc;
9986 		struct drm_crtc_state *new_crtc_state;
9987 		struct drm_framebuffer *fb = new_plane_state->fb;
9988 		struct amdgpu_framebuffer *afb = (struct amdgpu_framebuffer *)fb;
9989 		bool plane_needs_flip;
9990 		struct dc_plane_state *dc_plane;
9991 		struct dm_plane_state *dm_new_plane_state = to_dm_plane_state(new_plane_state);
9992 
9993 		/* Cursor plane is handled after stream updates */
9994 		if (plane->type == DRM_PLANE_TYPE_CURSOR &&
9995 		    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE) {
9996 			if ((fb && crtc == pcrtc) ||
9997 			    (old_plane_state->fb && old_plane_state->crtc == pcrtc)) {
9998 				cursor_update = true;
9999 				if (amdgpu_ip_version(dm->adev, DCE_HWIP, 0) != 0)
10000 					amdgpu_dm_update_cursor(plane, old_plane_state, &bundle->stream_update);
10001 			}
10002 
10003 			continue;
10004 		}
10005 
10006 		if (!fb || !crtc || pcrtc != crtc)
10007 			continue;
10008 
10009 		new_crtc_state = drm_atomic_get_new_crtc_state(state, crtc);
10010 		if (!new_crtc_state->active)
10011 			continue;
10012 
10013 		dc_plane = dm_new_plane_state->dc_state;
10014 		if (!dc_plane)
10015 			continue;
10016 
10017 		bundle->surface_updates[planes_count].surface = dc_plane;
10018 		if (new_pcrtc_state->color_mgmt_changed) {
10019 			bundle->surface_updates[planes_count].gamma = &dc_plane->gamma_correction;
10020 			bundle->surface_updates[planes_count].in_transfer_func = &dc_plane->in_transfer_func;
10021 			bundle->surface_updates[planes_count].gamut_remap_matrix = &dc_plane->gamut_remap_matrix;
10022 			bundle->surface_updates[planes_count].hdr_mult = dc_plane->hdr_mult;
10023 			bundle->surface_updates[planes_count].func_shaper = &dc_plane->in_shaper_func;
10024 			bundle->surface_updates[planes_count].lut3d_func = &dc_plane->lut3d_func;
10025 			bundle->surface_updates[planes_count].blend_tf = &dc_plane->blend_tf;
10026 		}
10027 
10028 		amdgpu_dm_plane_fill_dc_scaling_info(dm->adev, new_plane_state,
10029 				     &bundle->scaling_infos[planes_count]);
10030 
10031 		bundle->surface_updates[planes_count].scaling_info =
10032 			&bundle->scaling_infos[planes_count];
10033 
10034 		plane_needs_flip = old_plane_state->fb && new_plane_state->fb;
10035 
10036 		pflip_present = pflip_present || plane_needs_flip;
10037 
10038 		if (!plane_needs_flip) {
10039 			planes_count += 1;
10040 			continue;
10041 		}
10042 
10043 		fill_dc_plane_info_and_addr(
10044 			dm->adev, new_plane_state,
10045 			afb->tiling_flags,
10046 			&bundle->plane_infos[planes_count],
10047 			&bundle->flip_addrs[planes_count].address,
10048 			afb->tmz_surface);
10049 
10050 		drm_dbg_state(state->dev, "plane: id=%d dcc_en=%d\n",
10051 				 new_plane_state->plane->index,
10052 				 bundle->plane_infos[planes_count].dcc.enable);
10053 
10054 		bundle->surface_updates[planes_count].plane_info =
10055 			&bundle->plane_infos[planes_count];
10056 
10057 		if (acrtc_state->stream->link->psr_settings.psr_feature_enabled ||
10058 		    acrtc_state->stream->link->replay_settings.replay_feature_enabled) {
10059 			fill_dc_dirty_rects(plane, old_plane_state,
10060 					    new_plane_state, new_crtc_state,
10061 					    &bundle->flip_addrs[planes_count],
10062 					    acrtc_state->stream->link->psr_settings.psr_version ==
10063 					    DC_PSR_VERSION_SU_1,
10064 					    &dirty_rects_changed);
10065 
10066 			/*
10067 			 * If the dirty regions changed, PSR-SU need to be disabled temporarily
10068 			 * and enabled it again after dirty regions are stable to avoid video glitch.
10069 			 * PSR-SU will be enabled in vblank_control_worker() if user pause the video
10070 			 * during the PSR-SU was disabled.
10071 			 */
10072 			if (acrtc_state->stream->link->psr_settings.psr_version >= DC_PSR_VERSION_SU_1 &&
10073 			    acrtc_attach->dm_irq_params.allow_sr_entry &&
10074 #ifdef CONFIG_DRM_AMD_SECURE_DISPLAY
10075 			    !amdgpu_dm_crc_window_is_activated(acrtc_state->base.crtc) &&
10076 #endif
10077 			    dirty_rects_changed) {
10078 				mutex_lock(&dm->dc_lock);
10079 				acrtc_state->stream->link->psr_settings.psr_dirty_rects_change_timestamp_ns =
10080 				timestamp_ns;
10081 				if (acrtc_state->stream->link->psr_settings.psr_allow_active)
10082 					amdgpu_dm_psr_disable(acrtc_state->stream, true);
10083 				mutex_unlock(&dm->dc_lock);
10084 			}
10085 		}
10086 
10087 		/*
10088 		 * Only allow immediate flips for fast updates that don't
10089 		 * change memory domain, FB pitch, DCC state, rotation or
10090 		 * mirroring.
10091 		 *
10092 		 * dm_crtc_helper_atomic_check() only accepts async flips with
10093 		 * fast updates.
10094 		 */
10095 		if (crtc->state->async_flip &&
10096 		    (acrtc_state->update_type != UPDATE_TYPE_FAST ||
10097 		     get_mem_type(old_plane_state->fb) != get_mem_type(fb)))
10098 			drm_warn_once(state->dev,
10099 				      "[PLANE:%d:%s] async flip with non-fast update\n",
10100 				      plane->base.id, plane->name);
10101 
10102 		bundle->flip_addrs[planes_count].flip_immediate =
10103 			crtc->state->async_flip &&
10104 			acrtc_state->update_type == UPDATE_TYPE_FAST &&
10105 			get_mem_type(old_plane_state->fb) == get_mem_type(fb);
10106 
10107 		timestamp_ns = ktime_get_ns();
10108 		bundle->flip_addrs[planes_count].flip_timestamp_in_us = div_u64(timestamp_ns, 1000);
10109 		bundle->surface_updates[planes_count].flip_addr = &bundle->flip_addrs[planes_count];
10110 		bundle->surface_updates[planes_count].surface = dc_plane;
10111 
10112 		if (!bundle->surface_updates[planes_count].surface) {
10113 			drm_err(dev, "No surface for CRTC: id=%d\n",
10114 					acrtc_attach->crtc_id);
10115 			continue;
10116 		}
10117 
10118 		if (plane == pcrtc->primary)
10119 			update_freesync_state_on_stream(
10120 				dm,
10121 				acrtc_state,
10122 				acrtc_state->stream,
10123 				dc_plane,
10124 				bundle->flip_addrs[planes_count].flip_timestamp_in_us);
10125 
10126 		drm_dbg_state(state->dev, "%s Flipping to hi: 0x%x, low: 0x%x\n",
10127 				 __func__,
10128 				 bundle->flip_addrs[planes_count].address.grph.addr.high_part,
10129 				 bundle->flip_addrs[planes_count].address.grph.addr.low_part);
10130 
10131 		planes_count += 1;
10132 
10133 	}
10134 
10135 	if (pflip_present) {
10136 		if (!vrr_active) {
10137 			/* Use old throttling in non-vrr fixed refresh rate mode
10138 			 * to keep flip scheduling based on target vblank counts
10139 			 * working in a backwards compatible way, e.g., for
10140 			 * clients using the GLX_OML_sync_control extension or
10141 			 * DRI3/Present extension with defined target_msc.
10142 			 */
10143 			last_flip_vblank = amdgpu_get_vblank_counter_kms(pcrtc);
10144 		} else {
10145 			/* For variable refresh rate mode only:
10146 			 * Get vblank of last completed flip to avoid > 1 vrr
10147 			 * flips per video frame by use of throttling, but allow
10148 			 * flip programming anywhere in the possibly large
10149 			 * variable vrr vblank interval for fine-grained flip
10150 			 * timing control and more opportunity to avoid stutter
10151 			 * on late submission of flips.
10152 			 */
10153 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10154 			last_flip_vblank = acrtc_attach->dm_irq_params.last_flip_vblank;
10155 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10156 		}
10157 
10158 		target_vblank = last_flip_vblank + wait_for_vblank;
10159 
10160 		/*
10161 		 * Wait until we're out of the vertical blank period before the one
10162 		 * targeted by the flip
10163 		 */
10164 		while ((acrtc_attach->enabled &&
10165 			(amdgpu_display_get_crtc_scanoutpos(dm->ddev, acrtc_attach->crtc_id,
10166 							    0, &vpos, &hpos, NULL,
10167 							    NULL, &pcrtc->hwmode)
10168 			 & (DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK)) ==
10169 			(DRM_SCANOUTPOS_VALID | DRM_SCANOUTPOS_IN_VBLANK) &&
10170 			(int)(target_vblank -
10171 			  amdgpu_get_vblank_counter_kms(pcrtc)) > 0)) {
10172 			usleep_range(1000, 1100);
10173 		}
10174 
10175 		/**
10176 		 * Prepare the flip event for the pageflip interrupt to handle.
10177 		 *
10178 		 * This only works in the case where we've already turned on the
10179 		 * appropriate hardware blocks (eg. HUBP) so in the transition case
10180 		 * from 0 -> n planes we have to skip a hardware generated event
10181 		 * and rely on sending it from software.
10182 		 */
10183 		if (acrtc_attach->base.state->event &&
10184 		    acrtc_state->active_planes > 0) {
10185 			drm_crtc_vblank_get(pcrtc);
10186 
10187 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10188 
10189 			WARN_ON(acrtc_attach->pflip_status != AMDGPU_FLIP_NONE);
10190 			prepare_flip_isr(acrtc_attach);
10191 
10192 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10193 		}
10194 
10195 		if (acrtc_state->stream) {
10196 			if (acrtc_state->freesync_vrr_info_changed)
10197 				bundle->stream_update.vrr_infopacket =
10198 					&acrtc_state->stream->vrr_infopacket;
10199 		}
10200 	} else if (cursor_update && acrtc_state->active_planes > 0) {
10201 		spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10202 		if (acrtc_attach->base.state->event) {
10203 			drm_crtc_vblank_get(pcrtc);
10204 			acrtc_attach->event = acrtc_attach->base.state->event;
10205 			acrtc_attach->base.state->event = NULL;
10206 		}
10207 		spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10208 	}
10209 
10210 	/* Update the planes if changed or disable if we don't have any. */
10211 	if ((planes_count || acrtc_state->active_planes == 0) &&
10212 		acrtc_state->stream) {
10213 		/*
10214 		 * If PSR or idle optimizations are enabled then flush out
10215 		 * any pending work before hardware programming.
10216 		 */
10217 		if (dm->vblank_control_workqueue)
10218 			flush_workqueue(dm->vblank_control_workqueue);
10219 
10220 		bundle->stream_update.stream = acrtc_state->stream;
10221 		if (new_pcrtc_state->mode_changed) {
10222 			bundle->stream_update.src = acrtc_state->stream->src;
10223 			bundle->stream_update.dst = acrtc_state->stream->dst;
10224 		}
10225 
10226 		if (new_pcrtc_state->color_mgmt_changed) {
10227 			/*
10228 			 * TODO: This isn't fully correct since we've actually
10229 			 * already modified the stream in place.
10230 			 */
10231 			bundle->stream_update.gamut_remap =
10232 				&acrtc_state->stream->gamut_remap_matrix;
10233 			bundle->stream_update.output_csc_transform =
10234 				&acrtc_state->stream->csc_color_matrix;
10235 			bundle->stream_update.out_transfer_func =
10236 				&acrtc_state->stream->out_transfer_func;
10237 			bundle->stream_update.lut3d_func =
10238 				(struct dc_3dlut *) acrtc_state->stream->lut3d_func;
10239 			bundle->stream_update.func_shaper =
10240 				(struct dc_transfer_func *) acrtc_state->stream->func_shaper;
10241 		}
10242 
10243 		acrtc_state->stream->abm_level = acrtc_state->abm_level;
10244 		if (acrtc_state->abm_level != dm_old_crtc_state->abm_level)
10245 			bundle->stream_update.abm_level = &acrtc_state->abm_level;
10246 
10247 		mutex_lock(&dm->dc_lock);
10248 		if ((acrtc_state->update_type > UPDATE_TYPE_FAST) || vrr_active) {
10249 			if (acrtc_state->stream->link->replay_settings.replay_allow_active)
10250 				amdgpu_dm_replay_disable(acrtc_state->stream);
10251 			if (acrtc_state->stream->link->psr_settings.psr_allow_active)
10252 				amdgpu_dm_psr_disable(acrtc_state->stream, true);
10253 		}
10254 		mutex_unlock(&dm->dc_lock);
10255 
10256 		/*
10257 		 * If FreeSync state on the stream has changed then we need to
10258 		 * re-adjust the min/max bounds now that DC doesn't handle this
10259 		 * as part of commit.
10260 		 */
10261 		if (is_dc_timing_adjust_needed(dm_old_crtc_state, acrtc_state)) {
10262 			spin_lock_irqsave(&pcrtc->dev->event_lock, flags);
10263 			dc_stream_adjust_vmin_vmax(
10264 				dm->dc, acrtc_state->stream,
10265 				&acrtc_attach->dm_irq_params.vrr_params.adjust);
10266 			spin_unlock_irqrestore(&pcrtc->dev->event_lock, flags);
10267 		}
10268 		mutex_lock(&dm->dc_lock);
10269 		update_planes_and_stream_adapter(dm->dc,
10270 					 acrtc_state->update_type,
10271 					 planes_count,
10272 					 acrtc_state->stream,
10273 					 &bundle->stream_update,
10274 					 bundle->surface_updates);
10275 		updated_planes_and_streams = true;
10276 
10277 		/**
10278 		 * Enable or disable the interrupts on the backend.
10279 		 *
10280 		 * Most pipes are put into power gating when unused.
10281 		 *
10282 		 * When power gating is enabled on a pipe we lose the
10283 		 * interrupt enablement state when power gating is disabled.
10284 		 *
10285 		 * So we need to update the IRQ control state in hardware
10286 		 * whenever the pipe turns on (since it could be previously
10287 		 * power gated) or off (since some pipes can't be power gated
10288 		 * on some ASICs).
10289 		 */
10290 		if (dm_old_crtc_state->active_planes != acrtc_state->active_planes)
10291 			dm_update_pflip_irq_state(drm_to_adev(dev),
10292 						  acrtc_attach);
10293 
10294 		amdgpu_dm_enable_self_refresh(acrtc_attach, acrtc_state, timestamp_ns);
10295 		mutex_unlock(&dm->dc_lock);
10296 	}
10297 
10298 	/*
10299 	 * Update cursor state *after* programming all the planes.
10300 	 * This avoids redundant programming in the case where we're going
10301 	 * to be disabling a single plane - those pipes are being disabled.
10302 	 */
10303 	if (acrtc_state->active_planes &&
10304 	    (!updated_planes_and_streams || amdgpu_ip_version(dm->adev, DCE_HWIP, 0) == 0) &&
10305 	    acrtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE)
10306 		amdgpu_dm_commit_cursors(state);
10307 
10308 cleanup:
10309 	kfree(bundle);
10310 }
10311 
amdgpu_dm_commit_audio(struct drm_device * dev,struct drm_atomic_state * state)10312 static void amdgpu_dm_commit_audio(struct drm_device *dev,
10313 				   struct drm_atomic_state *state)
10314 {
10315 	struct amdgpu_device *adev = drm_to_adev(dev);
10316 	struct amdgpu_dm_connector *aconnector;
10317 	struct drm_connector *connector;
10318 	struct drm_connector_state *old_con_state, *new_con_state;
10319 	struct drm_crtc_state *new_crtc_state;
10320 	struct dm_crtc_state *new_dm_crtc_state;
10321 	const struct dc_stream_status *status;
10322 	int i, inst;
10323 
10324 	/* Notify device removals. */
10325 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10326 		if (old_con_state->crtc != new_con_state->crtc) {
10327 			/* CRTC changes require notification. */
10328 			goto notify;
10329 		}
10330 
10331 		if (!new_con_state->crtc)
10332 			continue;
10333 
10334 		new_crtc_state = drm_atomic_get_new_crtc_state(
10335 			state, new_con_state->crtc);
10336 
10337 		if (!new_crtc_state)
10338 			continue;
10339 
10340 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10341 			continue;
10342 
10343 notify:
10344 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10345 			continue;
10346 
10347 		aconnector = to_amdgpu_dm_connector(connector);
10348 
10349 		mutex_lock(&adev->dm.audio_lock);
10350 		inst = aconnector->audio_inst;
10351 		aconnector->audio_inst = -1;
10352 		mutex_unlock(&adev->dm.audio_lock);
10353 
10354 		amdgpu_dm_audio_eld_notify(adev, inst);
10355 	}
10356 
10357 	/* Notify audio device additions. */
10358 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
10359 		if (!new_con_state->crtc)
10360 			continue;
10361 
10362 		new_crtc_state = drm_atomic_get_new_crtc_state(
10363 			state, new_con_state->crtc);
10364 
10365 		if (!new_crtc_state)
10366 			continue;
10367 
10368 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
10369 			continue;
10370 
10371 		new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
10372 		if (!new_dm_crtc_state->stream)
10373 			continue;
10374 
10375 		status = dc_stream_get_status(new_dm_crtc_state->stream);
10376 		if (!status)
10377 			continue;
10378 
10379 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10380 			continue;
10381 
10382 		aconnector = to_amdgpu_dm_connector(connector);
10383 
10384 		mutex_lock(&adev->dm.audio_lock);
10385 		inst = status->audio_inst;
10386 		aconnector->audio_inst = inst;
10387 		mutex_unlock(&adev->dm.audio_lock);
10388 
10389 		amdgpu_dm_audio_eld_notify(adev, inst);
10390 	}
10391 }
10392 
10393 /*
10394  * amdgpu_dm_crtc_copy_transient_flags - copy mirrored flags from DRM to DC
10395  * @crtc_state: the DRM CRTC state
10396  * @stream_state: the DC stream state.
10397  *
10398  * Copy the mirrored transient state flags from DRM, to DC. It is used to bring
10399  * a dc_stream_state's flags in sync with a drm_crtc_state's flags.
10400  */
amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state * crtc_state,struct dc_stream_state * stream_state)10401 static void amdgpu_dm_crtc_copy_transient_flags(struct drm_crtc_state *crtc_state,
10402 						struct dc_stream_state *stream_state)
10403 {
10404 	stream_state->mode_changed = drm_atomic_crtc_needs_modeset(crtc_state);
10405 }
10406 
dm_clear_writeback(struct amdgpu_display_manager * dm,struct dm_crtc_state * crtc_state)10407 static void dm_clear_writeback(struct amdgpu_display_manager *dm,
10408 			      struct dm_crtc_state *crtc_state)
10409 {
10410 	dc_stream_remove_writeback(dm->dc, crtc_state->stream, 0);
10411 }
10412 
amdgpu_dm_commit_streams(struct drm_atomic_state * state,struct dc_state * dc_state)10413 static void amdgpu_dm_commit_streams(struct drm_atomic_state *state,
10414 					struct dc_state *dc_state)
10415 {
10416 	struct drm_device *dev = state->dev;
10417 	struct amdgpu_device *adev = drm_to_adev(dev);
10418 	struct amdgpu_display_manager *dm = &adev->dm;
10419 	struct drm_crtc *crtc;
10420 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10421 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10422 	struct drm_connector_state *old_con_state;
10423 	struct drm_connector *connector;
10424 	bool mode_set_reset_required = false;
10425 	u32 i;
10426 	struct dc_commit_streams_params params = {dc_state->streams, dc_state->stream_count};
10427 	bool set_backlight_level = false;
10428 
10429 	/* Disable writeback */
10430 	for_each_old_connector_in_state(state, connector, old_con_state, i) {
10431 		struct dm_connector_state *dm_old_con_state;
10432 		struct amdgpu_crtc *acrtc;
10433 
10434 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
10435 			continue;
10436 
10437 		old_crtc_state = NULL;
10438 
10439 		dm_old_con_state = to_dm_connector_state(old_con_state);
10440 		if (!dm_old_con_state->base.crtc)
10441 			continue;
10442 
10443 		acrtc = to_amdgpu_crtc(dm_old_con_state->base.crtc);
10444 		if (acrtc)
10445 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10446 
10447 		if (!acrtc || !acrtc->wb_enabled)
10448 			continue;
10449 
10450 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10451 
10452 		dm_clear_writeback(dm, dm_old_crtc_state);
10453 		acrtc->wb_enabled = false;
10454 	}
10455 
10456 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state,
10457 				      new_crtc_state, i) {
10458 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10459 
10460 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10461 
10462 		if (old_crtc_state->active &&
10463 		    (!new_crtc_state->active ||
10464 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10465 			manage_dm_interrupts(adev, acrtc, NULL);
10466 			dc_stream_release(dm_old_crtc_state->stream);
10467 		}
10468 	}
10469 
10470 	drm_atomic_helper_calc_timestamping_constants(state);
10471 
10472 	/* update changed items */
10473 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10474 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10475 
10476 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10477 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10478 
10479 		drm_dbg_state(state->dev,
10480 			"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
10481 			acrtc->crtc_id,
10482 			new_crtc_state->enable,
10483 			new_crtc_state->active,
10484 			new_crtc_state->planes_changed,
10485 			new_crtc_state->mode_changed,
10486 			new_crtc_state->active_changed,
10487 			new_crtc_state->connectors_changed);
10488 
10489 		/* Disable cursor if disabling crtc */
10490 		if (old_crtc_state->active && !new_crtc_state->active) {
10491 			struct dc_cursor_position position;
10492 
10493 			memset(&position, 0, sizeof(position));
10494 			mutex_lock(&dm->dc_lock);
10495 			dc_exit_ips_for_hw_access(dm->dc);
10496 			dc_stream_program_cursor_position(dm_old_crtc_state->stream, &position);
10497 			mutex_unlock(&dm->dc_lock);
10498 		}
10499 
10500 		/* Copy all transient state flags into dc state */
10501 		if (dm_new_crtc_state->stream) {
10502 			amdgpu_dm_crtc_copy_transient_flags(&dm_new_crtc_state->base,
10503 							    dm_new_crtc_state->stream);
10504 		}
10505 
10506 		/* handles headless hotplug case, updating new_state and
10507 		 * aconnector as needed
10508 		 */
10509 
10510 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, dm_new_crtc_state->stream, dm_old_crtc_state->stream)) {
10511 
10512 			drm_dbg_atomic(dev,
10513 				       "Atomic commit: SET crtc id %d: [%p]\n",
10514 				       acrtc->crtc_id, acrtc);
10515 
10516 			if (!dm_new_crtc_state->stream) {
10517 				/*
10518 				 * this could happen because of issues with
10519 				 * userspace notifications delivery.
10520 				 * In this case userspace tries to set mode on
10521 				 * display which is disconnected in fact.
10522 				 * dc_sink is NULL in this case on aconnector.
10523 				 * We expect reset mode will come soon.
10524 				 *
10525 				 * This can also happen when unplug is done
10526 				 * during resume sequence ended
10527 				 *
10528 				 * In this case, we want to pretend we still
10529 				 * have a sink to keep the pipe running so that
10530 				 * hw state is consistent with the sw state
10531 				 */
10532 				drm_dbg_atomic(dev,
10533 					       "Failed to create new stream for crtc %d\n",
10534 						acrtc->base.base.id);
10535 				continue;
10536 			}
10537 
10538 			if (dm_old_crtc_state->stream)
10539 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10540 
10541 			pm_runtime_get_noresume(dev->dev);
10542 
10543 			acrtc->enabled = true;
10544 			acrtc->hw_mode = new_crtc_state->mode;
10545 			crtc->hwmode = new_crtc_state->mode;
10546 			mode_set_reset_required = true;
10547 			set_backlight_level = true;
10548 		} else if (modereset_required(new_crtc_state)) {
10549 			drm_dbg_atomic(dev,
10550 				       "Atomic commit: RESET. crtc id %d:[%p]\n",
10551 				       acrtc->crtc_id, acrtc);
10552 			/* i.e. reset mode */
10553 			if (dm_old_crtc_state->stream)
10554 				remove_stream(adev, acrtc, dm_old_crtc_state->stream);
10555 
10556 			mode_set_reset_required = true;
10557 		}
10558 	} /* for_each_crtc_in_state() */
10559 
10560 	/* if there mode set or reset, disable eDP PSR, Replay */
10561 	if (mode_set_reset_required) {
10562 		if (dm->vblank_control_workqueue)
10563 			flush_workqueue(dm->vblank_control_workqueue);
10564 
10565 		amdgpu_dm_replay_disable_all(dm);
10566 		amdgpu_dm_psr_disable_all(dm);
10567 	}
10568 
10569 	dm_enable_per_frame_crtc_master_sync(dc_state);
10570 	mutex_lock(&dm->dc_lock);
10571 	dc_exit_ips_for_hw_access(dm->dc);
10572 	WARN_ON(!dc_commit_streams(dm->dc, &params));
10573 
10574 	/* Allow idle optimization when vblank count is 0 for display off */
10575 	if ((dm->active_vblank_irq_count == 0) && amdgpu_dm_is_headless(dm->adev))
10576 		dc_allow_idle_optimizations(dm->dc, true);
10577 	mutex_unlock(&dm->dc_lock);
10578 
10579 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
10580 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
10581 
10582 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10583 
10584 		if (dm_new_crtc_state->stream != NULL) {
10585 			const struct dc_stream_status *status =
10586 					dc_stream_get_status(dm_new_crtc_state->stream);
10587 
10588 			if (!status)
10589 				status = dc_state_get_stream_status(dc_state,
10590 									 dm_new_crtc_state->stream);
10591 			if (!status)
10592 				drm_err(dev,
10593 					"got no status for stream %p on acrtc%p\n",
10594 					dm_new_crtc_state->stream, acrtc);
10595 			else
10596 				acrtc->otg_inst = status->primary_otg_inst;
10597 		}
10598 	}
10599 
10600 	/* During boot up and resume the DC layer will reset the panel brightness
10601 	 * to fix a flicker issue.
10602 	 * It will cause the dm->actual_brightness is not the current panel brightness
10603 	 * level. (the dm->brightness is the correct panel level)
10604 	 * So we set the backlight level with dm->brightness value after set mode
10605 	 */
10606 	if (set_backlight_level) {
10607 		for (i = 0; i < dm->num_of_edps; i++) {
10608 			if (dm->backlight_dev[i])
10609 				amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
10610 		}
10611 	}
10612 }
10613 
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)10614 static void dm_set_writeback(struct amdgpu_display_manager *dm,
10615 			      struct dm_crtc_state *crtc_state,
10616 			      struct drm_connector *connector,
10617 			      struct drm_connector_state *new_con_state)
10618 {
10619 	struct drm_writeback_connector *wb_conn = drm_connector_to_writeback(connector);
10620 	struct amdgpu_device *adev = dm->adev;
10621 	struct amdgpu_crtc *acrtc;
10622 	struct dc_writeback_info *wb_info;
10623 	struct pipe_ctx *pipe = NULL;
10624 	struct amdgpu_framebuffer *afb;
10625 	int i = 0;
10626 
10627 	wb_info = kzalloc_obj(*wb_info, GFP_KERNEL);
10628 	if (!wb_info) {
10629 		drm_err(adev_to_drm(adev), "Failed to allocate wb_info\n");
10630 		return;
10631 	}
10632 
10633 	acrtc = to_amdgpu_crtc(wb_conn->encoder.crtc);
10634 	if (!acrtc) {
10635 		drm_err(adev_to_drm(adev), "no amdgpu_crtc found\n");
10636 		kfree(wb_info);
10637 		return;
10638 	}
10639 
10640 	afb = to_amdgpu_framebuffer(new_con_state->writeback_job->fb);
10641 	if (!afb) {
10642 		drm_err(adev_to_drm(adev), "No amdgpu_framebuffer found\n");
10643 		kfree(wb_info);
10644 		return;
10645 	}
10646 
10647 	for (i = 0; i < MAX_PIPES; i++) {
10648 		if (dm->dc->current_state->res_ctx.pipe_ctx[i].stream == crtc_state->stream) {
10649 			pipe = &dm->dc->current_state->res_ctx.pipe_ctx[i];
10650 			break;
10651 		}
10652 	}
10653 
10654 	/* fill in wb_info */
10655 	wb_info->wb_enabled = true;
10656 
10657 	wb_info->dwb_pipe_inst = 0;
10658 	wb_info->dwb_params.dwbscl_black_color = 0;
10659 	wb_info->dwb_params.hdr_mult = 0x1F000;
10660 	wb_info->dwb_params.csc_params.gamut_adjust_type = CM_GAMUT_ADJUST_TYPE_BYPASS;
10661 	wb_info->dwb_params.csc_params.gamut_coef_format = CM_GAMUT_REMAP_COEF_FORMAT_S2_13;
10662 	wb_info->dwb_params.output_depth = DWB_OUTPUT_PIXEL_DEPTH_10BPC;
10663 	wb_info->dwb_params.cnv_params.cnv_out_bpc = DWB_CNV_OUT_BPC_10BPC;
10664 
10665 	/* width & height from crtc */
10666 	wb_info->dwb_params.cnv_params.src_width = acrtc->base.mode.crtc_hdisplay;
10667 	wb_info->dwb_params.cnv_params.src_height = acrtc->base.mode.crtc_vdisplay;
10668 	wb_info->dwb_params.dest_width = acrtc->base.mode.crtc_hdisplay;
10669 	wb_info->dwb_params.dest_height = acrtc->base.mode.crtc_vdisplay;
10670 
10671 	wb_info->dwb_params.cnv_params.crop_en = false;
10672 	wb_info->dwb_params.stereo_params.stereo_enabled = false;
10673 
10674 	wb_info->dwb_params.cnv_params.out_max_pix_val = 0x3ff;	// 10 bits
10675 	wb_info->dwb_params.cnv_params.out_min_pix_val = 0;
10676 	wb_info->dwb_params.cnv_params.fc_out_format = DWB_OUT_FORMAT_32BPP_ARGB;
10677 	wb_info->dwb_params.cnv_params.out_denorm_mode = DWB_OUT_DENORM_BYPASS;
10678 
10679 	wb_info->dwb_params.out_format = dwb_scaler_mode_bypass444;
10680 
10681 	wb_info->dwb_params.capture_rate = dwb_capture_rate_0;
10682 
10683 	wb_info->dwb_params.scaler_taps.h_taps = 1;
10684 	wb_info->dwb_params.scaler_taps.v_taps = 1;
10685 	wb_info->dwb_params.scaler_taps.h_taps_c = 1;
10686 	wb_info->dwb_params.scaler_taps.v_taps_c = 1;
10687 	wb_info->dwb_params.subsample_position = DWB_INTERSTITIAL_SUBSAMPLING;
10688 
10689 	wb_info->mcif_buf_params.luma_pitch = afb->base.pitches[0];
10690 	wb_info->mcif_buf_params.chroma_pitch = afb->base.pitches[1];
10691 
10692 	for (i = 0; i < DWB_MCIF_BUF_COUNT; i++) {
10693 		wb_info->mcif_buf_params.luma_address[i] = afb->address;
10694 		wb_info->mcif_buf_params.chroma_address[i] = 0;
10695 	}
10696 
10697 	wb_info->mcif_buf_params.p_vmid = 1;
10698 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) >= IP_VERSION(3, 0, 0)) {
10699 		wb_info->mcif_warmup_params.start_address.quad_part = afb->address;
10700 		wb_info->mcif_warmup_params.region_size =
10701 			wb_info->mcif_buf_params.luma_pitch * wb_info->dwb_params.dest_height;
10702 	}
10703 	wb_info->mcif_warmup_params.p_vmid = 1;
10704 	wb_info->writeback_source_plane = pipe->plane_state;
10705 
10706 	dc_stream_add_writeback(dm->dc, crtc_state->stream, wb_info);
10707 
10708 	acrtc->wb_pending = true;
10709 	acrtc->wb_conn = wb_conn;
10710 	drm_writeback_queue_job(wb_conn, new_con_state);
10711 }
10712 
amdgpu_dm_update_hdcp(struct drm_atomic_state * state)10713 static void amdgpu_dm_update_hdcp(struct drm_atomic_state *state)
10714 {
10715 	struct drm_connector_state *old_con_state, *new_con_state;
10716 	struct drm_device *dev = state->dev;
10717 	struct drm_connector *connector;
10718 	struct amdgpu_device *adev = drm_to_adev(dev);
10719 	int i;
10720 
10721 	if (!adev->dm.hdcp_workqueue)
10722 		return;
10723 
10724 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10725 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10726 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10727 		struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10728 		struct dm_crtc_state *dm_new_crtc_state;
10729 		struct amdgpu_dm_connector *aconnector;
10730 
10731 		if (!connector || connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
10732 			continue;
10733 
10734 		aconnector = to_amdgpu_dm_connector(connector);
10735 
10736 		drm_dbg(dev, "[HDCP_DM] -------------- i : %x ----------\n", i);
10737 
10738 		drm_dbg(dev, "[HDCP_DM] connector->index: %x connect_status: %x dpms: %x\n",
10739 			connector->index, connector->status, connector->dpms);
10740 		drm_dbg(dev, "[HDCP_DM] state protection old: %x new: %x\n",
10741 			old_con_state->content_protection, new_con_state->content_protection);
10742 
10743 		if (aconnector->dc_sink) {
10744 			if (aconnector->dc_sink->sink_signal != SIGNAL_TYPE_VIRTUAL &&
10745 				aconnector->dc_sink->sink_signal != SIGNAL_TYPE_NONE) {
10746 				drm_dbg(dev, "[HDCP_DM] pipe_ctx dispname=%s\n",
10747 				aconnector->dc_sink->edid_caps.display_name);
10748 			}
10749 		}
10750 
10751 		new_crtc_state = NULL;
10752 		old_crtc_state = NULL;
10753 
10754 		if (acrtc) {
10755 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
10756 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10757 		}
10758 
10759 		if (old_crtc_state)
10760 			drm_dbg(dev, "old crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
10761 			old_crtc_state->enable,
10762 			old_crtc_state->active,
10763 			old_crtc_state->mode_changed,
10764 			old_crtc_state->active_changed,
10765 			old_crtc_state->connectors_changed);
10766 
10767 		if (new_crtc_state)
10768 			drm_dbg(dev, "NEW crtc en: %x a: %x m: %x a-chg: %x c-chg: %x\n",
10769 			new_crtc_state->enable,
10770 			new_crtc_state->active,
10771 			new_crtc_state->mode_changed,
10772 			new_crtc_state->active_changed,
10773 			new_crtc_state->connectors_changed);
10774 
10775 
10776 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10777 
10778 		if (dm_new_crtc_state && dm_new_crtc_state->stream == NULL &&
10779 		    connector->state->content_protection == DRM_MODE_CONTENT_PROTECTION_ENABLED) {
10780 			hdcp_reset_display(adev->dm.hdcp_workqueue, aconnector->dc_link->link_index);
10781 			new_con_state->content_protection = DRM_MODE_CONTENT_PROTECTION_DESIRED;
10782 			dm_new_con_state->update_hdcp = true;
10783 			continue;
10784 		}
10785 
10786 		if (is_content_protection_different(new_crtc_state, old_crtc_state, new_con_state,
10787 											old_con_state, connector, adev->dm.hdcp_workqueue)) {
10788 			/* when display is unplugged from mst hub, connctor will
10789 			 * be destroyed within dm_dp_mst_connector_destroy. connector
10790 			 * hdcp perperties, like type, undesired, desired, enabled,
10791 			 * will be lost. So, save hdcp properties into hdcp_work within
10792 			 * amdgpu_dm_atomic_commit_tail. if the same display is
10793 			 * plugged back with same display index, its hdcp properties
10794 			 * will be retrieved from hdcp_work within dm_dp_mst_get_modes
10795 			 */
10796 
10797 			bool enable_encryption = false;
10798 
10799 			if (new_con_state->content_protection == DRM_MODE_CONTENT_PROTECTION_DESIRED)
10800 				enable_encryption = true;
10801 
10802 			if (aconnector->dc_link && aconnector->dc_sink &&
10803 				aconnector->dc_link->type == dc_connection_mst_branch) {
10804 				struct hdcp_workqueue *hdcp_work = adev->dm.hdcp_workqueue;
10805 				struct hdcp_workqueue *hdcp_w =
10806 					&hdcp_work[aconnector->dc_link->link_index];
10807 
10808 				hdcp_w->hdcp_content_type[connector->index] =
10809 					new_con_state->hdcp_content_type;
10810 				hdcp_w->content_protection[connector->index] =
10811 					new_con_state->content_protection;
10812 			}
10813 
10814 			if (new_crtc_state && new_crtc_state->mode_changed &&
10815 				new_con_state->content_protection >= DRM_MODE_CONTENT_PROTECTION_DESIRED)
10816 				enable_encryption = true;
10817 
10818 			drm_info(dev, "[HDCP_DM] hdcp_update_display enable_encryption = %x\n", enable_encryption);
10819 
10820 			if (aconnector->dc_link)
10821 				hdcp_update_display(
10822 					adev->dm.hdcp_workqueue, aconnector->dc_link->link_index, aconnector,
10823 					new_con_state->hdcp_content_type, enable_encryption);
10824 		}
10825 	}
10826 }
10827 
amdgpu_dm_atomic_setup_commit(struct drm_atomic_state * state)10828 static int amdgpu_dm_atomic_setup_commit(struct drm_atomic_state *state)
10829 {
10830 	struct drm_crtc *crtc;
10831 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10832 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10833 	int i, ret;
10834 
10835 	ret = drm_dp_mst_atomic_setup_commit(state);
10836 	if (ret)
10837 		return ret;
10838 
10839 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
10840 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10841 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10842 		/*
10843 		 * Color management settings. We also update color properties
10844 		 * when a modeset is needed, to ensure it gets reprogrammed.
10845 		 */
10846 		if (dm_new_crtc_state->base.active && dm_new_crtc_state->stream &&
10847 		    (dm_new_crtc_state->base.color_mgmt_changed ||
10848 		     dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
10849 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
10850 			ret = amdgpu_dm_update_crtc_color_mgmt(dm_new_crtc_state);
10851 			if (ret) {
10852 				drm_dbg_atomic(state->dev, "Failed to update color state\n");
10853 				return ret;
10854 			}
10855 		}
10856 	}
10857 
10858 	return 0;
10859 }
10860 
10861 /**
10862  * amdgpu_dm_atomic_commit_tail() - AMDgpu DM's commit tail implementation.
10863  * @state: The atomic state to commit
10864  *
10865  * This will tell DC to commit the constructed DC state from atomic_check,
10866  * programming the hardware. Any failures here implies a hardware failure, since
10867  * atomic check should have filtered anything non-kosher.
10868  */
amdgpu_dm_atomic_commit_tail(struct drm_atomic_state * state)10869 static void amdgpu_dm_atomic_commit_tail(struct drm_atomic_state *state)
10870 {
10871 	struct drm_device *dev = state->dev;
10872 	struct amdgpu_device *adev = drm_to_adev(dev);
10873 	struct amdgpu_display_manager *dm = &adev->dm;
10874 	struct dm_atomic_state *dm_state;
10875 	struct dc_state *dc_state = NULL;
10876 	u32 i, j;
10877 	struct drm_crtc *crtc;
10878 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
10879 	unsigned long flags;
10880 	bool wait_for_vblank = true;
10881 	struct drm_connector *connector;
10882 	struct drm_connector_state *old_con_state = NULL, *new_con_state = NULL;
10883 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
10884 	int crtc_disable_count = 0;
10885 
10886 	trace_amdgpu_dm_atomic_commit_tail_begin(state);
10887 
10888 	drm_atomic_helper_update_legacy_modeset_state(dev, state);
10889 	drm_dp_mst_atomic_wait_for_dependencies(state);
10890 
10891 	dm_state = dm_atomic_get_new_state(state);
10892 	if (dm_state && dm_state->context) {
10893 		dc_state = dm_state->context;
10894 		amdgpu_dm_commit_streams(state, dc_state);
10895 	}
10896 
10897 	amdgpu_dm_update_hdcp(state);
10898 
10899 	/* Handle connector state changes */
10900 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
10901 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
10902 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
10903 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
10904 		struct dc_surface_update *dummy_updates;
10905 		struct dc_stream_update stream_update;
10906 		struct dc_info_packet hdr_packet;
10907 		struct dc_stream_status *status = NULL;
10908 		bool abm_changed, hdr_changed, scaling_changed, output_color_space_changed = false;
10909 
10910 		memset(&stream_update, 0, sizeof(stream_update));
10911 
10912 		if (acrtc) {
10913 			new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
10914 			old_crtc_state = drm_atomic_get_old_crtc_state(state, &acrtc->base);
10915 		}
10916 
10917 		/* Skip any modesets/resets */
10918 		if (!acrtc || drm_atomic_crtc_needs_modeset(new_crtc_state))
10919 			continue;
10920 
10921 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
10922 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
10923 
10924 		scaling_changed = is_scaling_state_different(dm_new_con_state,
10925 							     dm_old_con_state);
10926 
10927 		if ((new_con_state->hdmi.broadcast_rgb != old_con_state->hdmi.broadcast_rgb) &&
10928 			(dm_old_crtc_state->stream->output_color_space !=
10929 				get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state)))
10930 			output_color_space_changed = true;
10931 
10932 		abm_changed = dm_new_crtc_state->abm_level !=
10933 			      dm_old_crtc_state->abm_level;
10934 
10935 		hdr_changed =
10936 			!drm_connector_atomic_hdr_metadata_equal(old_con_state, new_con_state);
10937 
10938 		if (!scaling_changed && !abm_changed && !hdr_changed && !output_color_space_changed)
10939 			continue;
10940 
10941 		stream_update.stream = dm_new_crtc_state->stream;
10942 		if (scaling_changed) {
10943 			update_stream_scaling_settings(dev, &dm_new_con_state->base.crtc->mode,
10944 					dm_new_con_state, dm_new_crtc_state->stream);
10945 
10946 			stream_update.src = dm_new_crtc_state->stream->src;
10947 			stream_update.dst = dm_new_crtc_state->stream->dst;
10948 		}
10949 
10950 		if (output_color_space_changed) {
10951 			dm_new_crtc_state->stream->output_color_space
10952 				= get_output_color_space(&dm_new_crtc_state->stream->timing, new_con_state);
10953 
10954 			stream_update.output_color_space = &dm_new_crtc_state->stream->output_color_space;
10955 		}
10956 
10957 		if (abm_changed) {
10958 			dm_new_crtc_state->stream->abm_level = dm_new_crtc_state->abm_level;
10959 
10960 			stream_update.abm_level = &dm_new_crtc_state->abm_level;
10961 		}
10962 
10963 		if (hdr_changed) {
10964 			fill_hdr_info_packet(new_con_state, &hdr_packet);
10965 			stream_update.hdr_static_metadata = &hdr_packet;
10966 		}
10967 
10968 		status = dc_stream_get_status(dm_new_crtc_state->stream);
10969 
10970 		if (WARN_ON(!status))
10971 			continue;
10972 
10973 		WARN_ON(!status->plane_count);
10974 
10975 		/*
10976 		 * TODO: DC refuses to perform stream updates without a dc_surface_update.
10977 		 * Here we create an empty update on each plane.
10978 		 * To fix this, DC should permit updating only stream properties.
10979 		 */
10980 		dummy_updates = kzalloc(sizeof(struct dc_surface_update) * MAX_SURFACES, GFP_KERNEL);
10981 		if (!dummy_updates) {
10982 			drm_err(adev_to_drm(adev), "Failed to allocate memory for dummy_updates.\n");
10983 			continue;
10984 		}
10985 		for (j = 0; j < status->plane_count; j++)
10986 			dummy_updates[j].surface = status->plane_states[j];
10987 
10988 		sort(dummy_updates, status->plane_count,
10989 		     sizeof(*dummy_updates), dm_plane_layer_index_cmp, NULL);
10990 
10991 		mutex_lock(&dm->dc_lock);
10992 		dc_exit_ips_for_hw_access(dm->dc);
10993 		dc_update_planes_and_stream(dm->dc,
10994 					    dummy_updates,
10995 					    status->plane_count,
10996 					    dm_new_crtc_state->stream,
10997 					    &stream_update);
10998 		mutex_unlock(&dm->dc_lock);
10999 		kfree(dummy_updates);
11000 
11001 		drm_connector_update_privacy_screen(new_con_state);
11002 	}
11003 
11004 	/**
11005 	 * Enable interrupts for CRTCs that are newly enabled or went through
11006 	 * a modeset. It was intentionally deferred until after the front end
11007 	 * state was modified to wait until the OTG was on and so the IRQ
11008 	 * handlers didn't access stale or invalid state.
11009 	 */
11010 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
11011 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(crtc);
11012 #ifdef CONFIG_DEBUG_FS
11013 		enum amdgpu_dm_pipe_crc_source cur_crc_src;
11014 #endif
11015 		/* Count number of newly disabled CRTCs for dropping PM refs later. */
11016 		if (old_crtc_state->active && !new_crtc_state->active)
11017 			crtc_disable_count++;
11018 
11019 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11020 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11021 
11022 		/* For freesync config update on crtc state and params for irq */
11023 		update_stream_irq_parameters(dm, dm_new_crtc_state);
11024 
11025 #ifdef CONFIG_DEBUG_FS
11026 		spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11027 		cur_crc_src = acrtc->dm_irq_params.crc_src;
11028 		spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11029 #endif
11030 
11031 		if (new_crtc_state->active &&
11032 		    (!old_crtc_state->active ||
11033 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11034 			dc_stream_retain(dm_new_crtc_state->stream);
11035 			acrtc->dm_irq_params.stream = dm_new_crtc_state->stream;
11036 			manage_dm_interrupts(adev, acrtc, dm_new_crtc_state);
11037 		}
11038 		/* Handle vrr on->off / off->on transitions */
11039 		amdgpu_dm_handle_vrr_transition(dm_old_crtc_state, dm_new_crtc_state);
11040 
11041 #ifdef CONFIG_DEBUG_FS
11042 		if (new_crtc_state->active &&
11043 		    (!old_crtc_state->active ||
11044 		     drm_atomic_crtc_needs_modeset(new_crtc_state))) {
11045 			/**
11046 			 * Frontend may have changed so reapply the CRC capture
11047 			 * settings for the stream.
11048 			 */
11049 			if (amdgpu_dm_is_valid_crc_source(cur_crc_src)) {
11050 #if defined(CONFIG_DRM_AMD_SECURE_DISPLAY)
11051 				if (amdgpu_dm_crc_window_is_activated(crtc)) {
11052 					uint8_t cnt;
11053 
11054 					spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11055 					for (cnt = 0; cnt < MAX_CRC_WINDOW_NUM; cnt++) {
11056 						if (acrtc->dm_irq_params.window_param[cnt].enable) {
11057 							acrtc->dm_irq_params.window_param[cnt].update_win = true;
11058 
11059 							/**
11060 							 * It takes 2 frames for HW to stably generate CRC when
11061 							 * resuming from suspend, so we set skip_frame_cnt 2.
11062 							 */
11063 							acrtc->dm_irq_params.window_param[cnt].skip_frame_cnt = 2;
11064 						}
11065 					}
11066 					spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11067 				}
11068 #endif
11069 				if (amdgpu_dm_crtc_configure_crc_source(
11070 					crtc, dm_new_crtc_state, cur_crc_src))
11071 					drm_dbg_atomic(dev, "Failed to configure crc source");
11072 			}
11073 		}
11074 #endif
11075 	}
11076 
11077 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j)
11078 		if (new_crtc_state->async_flip)
11079 			wait_for_vblank = false;
11080 
11081 	/* update planes when needed per crtc*/
11082 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, j) {
11083 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11084 
11085 		if (dm_new_crtc_state->stream)
11086 			amdgpu_dm_commit_planes(state, dev, dm, crtc, wait_for_vblank);
11087 	}
11088 
11089 	/* Enable writeback */
11090 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11091 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
11092 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
11093 
11094 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11095 			continue;
11096 
11097 		if (!new_con_state->writeback_job)
11098 			continue;
11099 
11100 		new_crtc_state = drm_atomic_get_new_crtc_state(state, &acrtc->base);
11101 
11102 		if (!new_crtc_state)
11103 			continue;
11104 
11105 		if (acrtc->wb_enabled)
11106 			continue;
11107 
11108 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11109 
11110 		dm_set_writeback(dm, dm_new_crtc_state, connector, new_con_state);
11111 		acrtc->wb_enabled = true;
11112 	}
11113 
11114 	/* Update audio instances for each connector. */
11115 	amdgpu_dm_commit_audio(dev, state);
11116 
11117 	/* restore the backlight level */
11118 	for (i = 0; i < dm->num_of_edps; i++) {
11119 		if (dm->backlight_dev[i] &&
11120 		    (dm->actual_brightness[i] != dm->brightness[i]))
11121 			amdgpu_dm_backlight_set_level(dm, i, dm->brightness[i]);
11122 	}
11123 
11124 	/*
11125 	 * send vblank event on all events not handled in flip and
11126 	 * mark consumed event for drm_atomic_helper_commit_hw_done
11127 	 */
11128 	spin_lock_irqsave(&adev_to_drm(adev)->event_lock, flags);
11129 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
11130 
11131 		if (new_crtc_state->event)
11132 			drm_send_event_locked(dev, &new_crtc_state->event->base);
11133 
11134 		new_crtc_state->event = NULL;
11135 	}
11136 	spin_unlock_irqrestore(&adev_to_drm(adev)->event_lock, flags);
11137 
11138 	/* Signal HW programming completion */
11139 	drm_atomic_helper_commit_hw_done(state);
11140 
11141 	if (wait_for_vblank)
11142 		drm_atomic_helper_wait_for_flip_done(dev, state);
11143 
11144 	drm_atomic_helper_cleanup_planes(dev, state);
11145 
11146 	/* Don't free the memory if we are hitting this as part of suspend.
11147 	 * This way we don't free any memory during suspend; see
11148 	 * amdgpu_bo_free_kernel().  The memory will be freed in the first
11149 	 * non-suspend modeset or when the driver is torn down.
11150 	 */
11151 	if (!adev->in_suspend) {
11152 		/* return the stolen vga memory back to VRAM */
11153 		if (!adev->mman.keep_stolen_vga_memory)
11154 			amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
11155 		amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
11156 	}
11157 
11158 	/*
11159 	 * Finally, drop a runtime PM reference for each newly disabled CRTC,
11160 	 * so we can put the GPU into runtime suspend if we're not driving any
11161 	 * displays anymore
11162 	 */
11163 	for (i = 0; i < crtc_disable_count; i++)
11164 		pm_runtime_put_autosuspend(dev->dev);
11165 	pm_runtime_mark_last_busy(dev->dev);
11166 
11167 	trace_amdgpu_dm_atomic_commit_tail_finish(state);
11168 }
11169 
dm_force_atomic_commit(struct drm_connector * connector)11170 static int dm_force_atomic_commit(struct drm_connector *connector)
11171 {
11172 	int ret = 0;
11173 	struct drm_device *ddev = connector->dev;
11174 	struct drm_atomic_state *state = drm_atomic_state_alloc(ddev);
11175 	struct amdgpu_crtc *disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11176 	struct drm_plane *plane = disconnected_acrtc->base.primary;
11177 	struct drm_connector_state *conn_state;
11178 	struct drm_crtc_state *crtc_state;
11179 	struct drm_plane_state *plane_state;
11180 
11181 	if (!state)
11182 		return -ENOMEM;
11183 
11184 	state->acquire_ctx = ddev->mode_config.acquire_ctx;
11185 
11186 	/* Construct an atomic state to restore previous display setting */
11187 
11188 	/*
11189 	 * Attach connectors to drm_atomic_state
11190 	 */
11191 	conn_state = drm_atomic_get_connector_state(state, connector);
11192 
11193 	/* Check for error in getting connector state */
11194 	if (IS_ERR(conn_state)) {
11195 		ret = PTR_ERR(conn_state);
11196 		goto out;
11197 	}
11198 
11199 	/* Attach crtc to drm_atomic_state*/
11200 	crtc_state = drm_atomic_get_crtc_state(state, &disconnected_acrtc->base);
11201 
11202 	/* Check for error in getting crtc state */
11203 	if (IS_ERR(crtc_state)) {
11204 		ret = PTR_ERR(crtc_state);
11205 		goto out;
11206 	}
11207 
11208 	/* force a restore */
11209 	crtc_state->mode_changed = true;
11210 
11211 	/* Attach plane to drm_atomic_state */
11212 	plane_state = drm_atomic_get_plane_state(state, plane);
11213 
11214 	/* Check for error in getting plane state */
11215 	if (IS_ERR(plane_state)) {
11216 		ret = PTR_ERR(plane_state);
11217 		goto out;
11218 	}
11219 
11220 	/* Call commit internally with the state we just constructed */
11221 	ret = drm_atomic_commit(state);
11222 
11223 out:
11224 	drm_atomic_state_put(state);
11225 	if (ret)
11226 		drm_err(ddev, "Restoring old state failed with %i\n", ret);
11227 
11228 	return ret;
11229 }
11230 
11231 /*
11232  * This function handles all cases when set mode does not come upon hotplug.
11233  * This includes when a display is unplugged then plugged back into the
11234  * same port and when running without usermode desktop manager supprot
11235  */
dm_restore_drm_connector_state(struct drm_device * dev,struct drm_connector * connector)11236 void dm_restore_drm_connector_state(struct drm_device *dev,
11237 				    struct drm_connector *connector)
11238 {
11239 	struct amdgpu_dm_connector *aconnector;
11240 	struct amdgpu_crtc *disconnected_acrtc;
11241 	struct dm_crtc_state *acrtc_state;
11242 
11243 	if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11244 		return;
11245 
11246 	aconnector = to_amdgpu_dm_connector(connector);
11247 
11248 	if (!aconnector->dc_sink || !connector->state || !connector->encoder)
11249 		return;
11250 
11251 	disconnected_acrtc = to_amdgpu_crtc(connector->encoder->crtc);
11252 	if (!disconnected_acrtc)
11253 		return;
11254 
11255 	acrtc_state = to_dm_crtc_state(disconnected_acrtc->base.state);
11256 	if (!acrtc_state->stream)
11257 		return;
11258 
11259 	/*
11260 	 * If the previous sink is not released and different from the current,
11261 	 * we deduce we are in a state where we can not rely on usermode call
11262 	 * to turn on the display, so we do it here
11263 	 */
11264 	if (acrtc_state->stream->sink != aconnector->dc_sink)
11265 		dm_force_atomic_commit(&aconnector->base);
11266 }
11267 
11268 /*
11269  * Grabs all modesetting locks to serialize against any blocking commits,
11270  * Waits for completion of all non blocking commits.
11271  */
do_aquire_global_lock(struct drm_device * dev,struct drm_atomic_state * state)11272 static int do_aquire_global_lock(struct drm_device *dev,
11273 				 struct drm_atomic_state *state)
11274 {
11275 	struct drm_crtc *crtc;
11276 	struct drm_crtc_commit *commit;
11277 	long ret;
11278 
11279 	/*
11280 	 * Adding all modeset locks to aquire_ctx will
11281 	 * ensure that when the framework release it the
11282 	 * extra locks we are locking here will get released to
11283 	 */
11284 	ret = drm_modeset_lock_all_ctx(dev, state->acquire_ctx);
11285 	if (ret)
11286 		return ret;
11287 
11288 	list_for_each_entry(crtc, &dev->mode_config.crtc_list, head) {
11289 		spin_lock(&crtc->commit_lock);
11290 		commit = list_first_entry_or_null(&crtc->commit_list,
11291 				struct drm_crtc_commit, commit_entry);
11292 		if (commit)
11293 			drm_crtc_commit_get(commit);
11294 		spin_unlock(&crtc->commit_lock);
11295 
11296 		if (!commit)
11297 			continue;
11298 
11299 		/*
11300 		 * Make sure all pending HW programming completed and
11301 		 * page flips done
11302 		 */
11303 		ret = wait_for_completion_interruptible_timeout(&commit->hw_done, 10*HZ);
11304 
11305 		if (ret > 0)
11306 			ret = wait_for_completion_interruptible_timeout(
11307 					&commit->flip_done, 10*HZ);
11308 
11309 		if (ret == 0)
11310 			drm_err(dev, "[CRTC:%d:%s] hw_done or flip_done timed out\n",
11311 				  crtc->base.id, crtc->name);
11312 
11313 		drm_crtc_commit_put(commit);
11314 	}
11315 
11316 	return ret < 0 ? ret : 0;
11317 }
11318 
get_freesync_config_for_crtc(struct dm_crtc_state * new_crtc_state,struct dm_connector_state * new_con_state)11319 static void get_freesync_config_for_crtc(
11320 	struct dm_crtc_state *new_crtc_state,
11321 	struct dm_connector_state *new_con_state)
11322 {
11323 	struct mod_freesync_config config = {0};
11324 	struct amdgpu_dm_connector *aconnector;
11325 	struct drm_display_mode *mode = &new_crtc_state->base.mode;
11326 	int vrefresh = drm_mode_vrefresh(mode);
11327 	bool fs_vid_mode = false;
11328 
11329 	if (new_con_state->base.connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
11330 		return;
11331 
11332 	aconnector = to_amdgpu_dm_connector(new_con_state->base.connector);
11333 
11334 	new_crtc_state->vrr_supported = new_con_state->freesync_capable &&
11335 					vrefresh >= aconnector->min_vfreq &&
11336 					vrefresh <= aconnector->max_vfreq;
11337 
11338 	if (new_crtc_state->vrr_supported) {
11339 		new_crtc_state->stream->ignore_msa_timing_param = true;
11340 		fs_vid_mode = new_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED;
11341 
11342 		config.min_refresh_in_uhz = aconnector->min_vfreq * 1000000;
11343 		config.max_refresh_in_uhz = aconnector->max_vfreq * 1000000;
11344 		config.vsif_supported = true;
11345 		config.btr = true;
11346 
11347 		if (fs_vid_mode) {
11348 			config.state = VRR_STATE_ACTIVE_FIXED;
11349 			config.fixed_refresh_in_uhz = new_crtc_state->freesync_config.fixed_refresh_in_uhz;
11350 			goto out;
11351 		} else if (new_crtc_state->base.vrr_enabled) {
11352 			config.state = VRR_STATE_ACTIVE_VARIABLE;
11353 		} else {
11354 			config.state = VRR_STATE_INACTIVE;
11355 		}
11356 	} else {
11357 		config.state = VRR_STATE_UNSUPPORTED;
11358 	}
11359 out:
11360 	new_crtc_state->freesync_config = config;
11361 }
11362 
reset_freesync_config_for_crtc(struct dm_crtc_state * new_crtc_state)11363 static void reset_freesync_config_for_crtc(
11364 	struct dm_crtc_state *new_crtc_state)
11365 {
11366 	new_crtc_state->vrr_supported = false;
11367 
11368 	memset(&new_crtc_state->vrr_infopacket, 0,
11369 	       sizeof(new_crtc_state->vrr_infopacket));
11370 }
11371 
11372 static bool
is_timing_unchanged_for_freesync(struct drm_crtc_state * old_crtc_state,struct drm_crtc_state * new_crtc_state)11373 is_timing_unchanged_for_freesync(struct drm_crtc_state *old_crtc_state,
11374 				 struct drm_crtc_state *new_crtc_state)
11375 {
11376 	const struct drm_display_mode *old_mode, *new_mode;
11377 
11378 	if (!old_crtc_state || !new_crtc_state)
11379 		return false;
11380 
11381 	old_mode = &old_crtc_state->mode;
11382 	new_mode = &new_crtc_state->mode;
11383 
11384 	if (old_mode->clock       == new_mode->clock &&
11385 	    old_mode->hdisplay    == new_mode->hdisplay &&
11386 	    old_mode->vdisplay    == new_mode->vdisplay &&
11387 	    old_mode->htotal      == new_mode->htotal &&
11388 	    old_mode->vtotal      != new_mode->vtotal &&
11389 	    old_mode->hsync_start == new_mode->hsync_start &&
11390 	    old_mode->vsync_start != new_mode->vsync_start &&
11391 	    old_mode->hsync_end   == new_mode->hsync_end &&
11392 	    old_mode->vsync_end   != new_mode->vsync_end &&
11393 	    old_mode->hskew       == new_mode->hskew &&
11394 	    old_mode->vscan       == new_mode->vscan &&
11395 	    (old_mode->vsync_end - old_mode->vsync_start) ==
11396 	    (new_mode->vsync_end - new_mode->vsync_start))
11397 		return true;
11398 
11399 	return false;
11400 }
11401 
set_freesync_fixed_config(struct dm_crtc_state * dm_new_crtc_state)11402 static void set_freesync_fixed_config(struct dm_crtc_state *dm_new_crtc_state)
11403 {
11404 	u64 num, den, res;
11405 	struct drm_crtc_state *new_crtc_state = &dm_new_crtc_state->base;
11406 
11407 	dm_new_crtc_state->freesync_config.state = VRR_STATE_ACTIVE_FIXED;
11408 
11409 	num = (unsigned long long)new_crtc_state->mode.clock * 1000 * 1000000;
11410 	den = (unsigned long long)new_crtc_state->mode.htotal *
11411 	      (unsigned long long)new_crtc_state->mode.vtotal;
11412 
11413 	res = div_u64(num, den);
11414 	dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = res;
11415 }
11416 
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)11417 static int dm_update_crtc_state(struct amdgpu_display_manager *dm,
11418 			 struct drm_atomic_state *state,
11419 			 struct drm_crtc *crtc,
11420 			 struct drm_crtc_state *old_crtc_state,
11421 			 struct drm_crtc_state *new_crtc_state,
11422 			 bool enable,
11423 			 bool *lock_and_validation_needed)
11424 {
11425 	struct dm_atomic_state *dm_state = NULL;
11426 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11427 	struct dc_stream_state *new_stream;
11428 	struct amdgpu_device *adev = dm->adev;
11429 	int ret = 0;
11430 
11431 	/*
11432 	 * TODO Move this code into dm_crtc_atomic_check once we get rid of dc_validation_set
11433 	 * update changed items
11434 	 */
11435 	struct amdgpu_crtc *acrtc = NULL;
11436 	struct drm_connector *connector = NULL;
11437 	struct amdgpu_dm_connector *aconnector = NULL;
11438 	struct drm_connector_state *drm_new_conn_state = NULL, *drm_old_conn_state = NULL;
11439 	struct dm_connector_state *dm_new_conn_state = NULL, *dm_old_conn_state = NULL;
11440 
11441 	new_stream = NULL;
11442 
11443 	dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11444 	dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11445 	acrtc = to_amdgpu_crtc(crtc);
11446 	connector = amdgpu_dm_find_first_crtc_matching_connector(state, crtc);
11447 	if (connector)
11448 		aconnector = to_amdgpu_dm_connector(connector);
11449 
11450 	/* TODO This hack should go away */
11451 	if (connector && enable) {
11452 		/* Make sure fake sink is created in plug-in scenario */
11453 		drm_new_conn_state = drm_atomic_get_new_connector_state(state,
11454 									connector);
11455 		drm_old_conn_state = drm_atomic_get_old_connector_state(state,
11456 									connector);
11457 
11458 		if (WARN_ON(!drm_new_conn_state)) {
11459 			ret = -EINVAL;
11460 			goto fail;
11461 		}
11462 
11463 		dm_new_conn_state = to_dm_connector_state(drm_new_conn_state);
11464 		dm_old_conn_state = to_dm_connector_state(drm_old_conn_state);
11465 
11466 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11467 			goto skip_modeset;
11468 
11469 		new_stream = create_validate_stream_for_sink(connector,
11470 							     &new_crtc_state->mode,
11471 							     dm_new_conn_state,
11472 							     dm_old_crtc_state->stream);
11473 
11474 		/*
11475 		 * we can have no stream on ACTION_SET if a display
11476 		 * was disconnected during S3, in this case it is not an
11477 		 * error, the OS will be updated after detection, and
11478 		 * will do the right thing on next atomic commit
11479 		 */
11480 
11481 		if (!new_stream) {
11482 			drm_dbg_driver(adev_to_drm(adev), "%s: Failed to create new stream for crtc %d\n",
11483 					__func__, acrtc->base.base.id);
11484 			ret = -ENOMEM;
11485 			goto fail;
11486 		}
11487 
11488 		/*
11489 		 * TODO: Check VSDB bits to decide whether this should
11490 		 * be enabled or not.
11491 		 */
11492 		new_stream->triggered_crtc_reset.enabled =
11493 			dm->force_timing_sync;
11494 
11495 		dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11496 
11497 		ret = fill_hdr_info_packet(drm_new_conn_state,
11498 					   &new_stream->hdr_static_metadata);
11499 		if (ret)
11500 			goto fail;
11501 
11502 		/*
11503 		 * If we already removed the old stream from the context
11504 		 * (and set the new stream to NULL) then we can't reuse
11505 		 * the old stream even if the stream and scaling are unchanged.
11506 		 * We'll hit the BUG_ON and black screen.
11507 		 *
11508 		 * TODO: Refactor this function to allow this check to work
11509 		 * in all conditions.
11510 		 */
11511 		if (amdgpu_freesync_vid_mode &&
11512 		    dm_new_crtc_state->stream &&
11513 		    is_timing_unchanged_for_freesync(new_crtc_state, old_crtc_state))
11514 			goto skip_modeset;
11515 
11516 		if (dm_new_crtc_state->stream &&
11517 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11518 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream)) {
11519 			new_crtc_state->mode_changed = false;
11520 			drm_dbg_driver(adev_to_drm(adev), "Mode change not required, setting mode_changed to %d",
11521 					 new_crtc_state->mode_changed);
11522 		}
11523 	}
11524 
11525 	/* mode_changed flag may get updated above, need to check again */
11526 	if (!drm_atomic_crtc_needs_modeset(new_crtc_state))
11527 		goto skip_modeset;
11528 
11529 	drm_dbg_state(state->dev,
11530 		"amdgpu_crtc id:%d crtc_state_flags: enable:%d, active:%d, planes_changed:%d, mode_changed:%d,active_changed:%d,connectors_changed:%d\n",
11531 		acrtc->crtc_id,
11532 		new_crtc_state->enable,
11533 		new_crtc_state->active,
11534 		new_crtc_state->planes_changed,
11535 		new_crtc_state->mode_changed,
11536 		new_crtc_state->active_changed,
11537 		new_crtc_state->connectors_changed);
11538 
11539 	/* Remove stream for any changed/disabled CRTC */
11540 	if (!enable) {
11541 
11542 		if (!dm_old_crtc_state->stream)
11543 			goto skip_modeset;
11544 
11545 		/* Unset freesync video if it was active before */
11546 		if (dm_old_crtc_state->freesync_config.state == VRR_STATE_ACTIVE_FIXED) {
11547 			dm_new_crtc_state->freesync_config.state = VRR_STATE_INACTIVE;
11548 			dm_new_crtc_state->freesync_config.fixed_refresh_in_uhz = 0;
11549 		}
11550 
11551 		/* Now check if we should set freesync video mode */
11552 		if (amdgpu_freesync_vid_mode && dm_new_crtc_state->stream &&
11553 		    dc_is_stream_unchanged(new_stream, dm_old_crtc_state->stream) &&
11554 		    dc_is_stream_scaling_unchanged(new_stream, dm_old_crtc_state->stream) &&
11555 		    is_timing_unchanged_for_freesync(new_crtc_state,
11556 						     old_crtc_state)) {
11557 			new_crtc_state->mode_changed = false;
11558 			drm_dbg_driver(adev_to_drm(adev),
11559 				"Mode change not required for front porch change, setting mode_changed to %d",
11560 				new_crtc_state->mode_changed);
11561 
11562 			set_freesync_fixed_config(dm_new_crtc_state);
11563 
11564 			goto skip_modeset;
11565 		} else if (amdgpu_freesync_vid_mode && aconnector &&
11566 			   is_freesync_video_mode(&new_crtc_state->mode,
11567 						  aconnector)) {
11568 			struct drm_display_mode *high_mode;
11569 
11570 			high_mode = get_highest_refresh_rate_mode(aconnector, false);
11571 			if (!drm_mode_equal(&new_crtc_state->mode, high_mode))
11572 				set_freesync_fixed_config(dm_new_crtc_state);
11573 		}
11574 
11575 		ret = dm_atomic_get_state(state, &dm_state);
11576 		if (ret)
11577 			goto fail;
11578 
11579 		drm_dbg_driver(adev_to_drm(adev), "Disabling DRM crtc: %d\n",
11580 				crtc->base.id);
11581 
11582 		/* i.e. reset mode */
11583 		if (dc_state_remove_stream(
11584 				dm->dc,
11585 				dm_state->context,
11586 				dm_old_crtc_state->stream) != DC_OK) {
11587 			ret = -EINVAL;
11588 			goto fail;
11589 		}
11590 
11591 		dc_stream_release(dm_old_crtc_state->stream);
11592 		dm_new_crtc_state->stream = NULL;
11593 
11594 		reset_freesync_config_for_crtc(dm_new_crtc_state);
11595 
11596 		*lock_and_validation_needed = true;
11597 
11598 	} else {/* Add stream for any updated/enabled CRTC */
11599 		/*
11600 		 * Quick fix to prevent NULL pointer on new_stream when
11601 		 * added MST connectors not found in existing crtc_state in the chained mode
11602 		 * TODO: need to dig out the root cause of that
11603 		 */
11604 		if (!connector)
11605 			goto skip_modeset;
11606 
11607 		if (modereset_required(new_crtc_state))
11608 			goto skip_modeset;
11609 
11610 		if (amdgpu_dm_crtc_modeset_required(new_crtc_state, new_stream,
11611 				     dm_old_crtc_state->stream)) {
11612 
11613 			WARN_ON(dm_new_crtc_state->stream);
11614 
11615 			ret = dm_atomic_get_state(state, &dm_state);
11616 			if (ret)
11617 				goto fail;
11618 
11619 			dm_new_crtc_state->stream = new_stream;
11620 
11621 			dc_stream_retain(new_stream);
11622 
11623 			drm_dbg_atomic(adev_to_drm(adev), "Enabling DRM crtc: %d\n",
11624 					 crtc->base.id);
11625 
11626 			if (dc_state_add_stream(
11627 					dm->dc,
11628 					dm_state->context,
11629 					dm_new_crtc_state->stream) != DC_OK) {
11630 				ret = -EINVAL;
11631 				goto fail;
11632 			}
11633 
11634 			*lock_and_validation_needed = true;
11635 		}
11636 	}
11637 
11638 skip_modeset:
11639 	/* Release extra reference */
11640 	if (new_stream)
11641 		dc_stream_release(new_stream);
11642 
11643 	/*
11644 	 * We want to do dc stream updates that do not require a
11645 	 * full modeset below.
11646 	 */
11647 	if (!(enable && connector && new_crtc_state->active))
11648 		return 0;
11649 	/*
11650 	 * Given above conditions, the dc state cannot be NULL because:
11651 	 * 1. We're in the process of enabling CRTCs (just been added
11652 	 *    to the dc context, or already is on the context)
11653 	 * 2. Has a valid connector attached, and
11654 	 * 3. Is currently active and enabled.
11655 	 * => The dc stream state currently exists.
11656 	 */
11657 	BUG_ON(dm_new_crtc_state->stream == NULL);
11658 
11659 	/* Scaling or underscan settings */
11660 	if (is_scaling_state_different(dm_old_conn_state, dm_new_conn_state) ||
11661 				drm_atomic_crtc_needs_modeset(new_crtc_state))
11662 		update_stream_scaling_settings(adev_to_drm(adev),
11663 			&new_crtc_state->mode, dm_new_conn_state, dm_new_crtc_state->stream);
11664 
11665 	/* ABM settings */
11666 	dm_new_crtc_state->abm_level = dm_new_conn_state->abm_level;
11667 
11668 	/*
11669 	 * Color management settings. We also update color properties
11670 	 * when a modeset is needed, to ensure it gets reprogrammed.
11671 	 */
11672 	if (dm_new_crtc_state->base.color_mgmt_changed ||
11673 	    dm_old_crtc_state->regamma_tf != dm_new_crtc_state->regamma_tf ||
11674 	    drm_atomic_crtc_needs_modeset(new_crtc_state)) {
11675 		ret = amdgpu_dm_check_crtc_color_mgmt(dm_new_crtc_state, true);
11676 		if (ret)
11677 			goto fail;
11678 	}
11679 
11680 	/* Update Freesync settings. */
11681 	get_freesync_config_for_crtc(dm_new_crtc_state,
11682 				     dm_new_conn_state);
11683 
11684 	return ret;
11685 
11686 fail:
11687 	if (new_stream)
11688 		dc_stream_release(new_stream);
11689 	return ret;
11690 }
11691 
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)11692 static bool should_reset_plane(struct drm_atomic_state *state,
11693 			       struct drm_plane *plane,
11694 			       struct drm_plane_state *old_plane_state,
11695 			       struct drm_plane_state *new_plane_state)
11696 {
11697 	struct drm_plane *other;
11698 	struct drm_plane_state *old_other_state, *new_other_state;
11699 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11700 	struct dm_crtc_state *old_dm_crtc_state, *new_dm_crtc_state;
11701 	struct amdgpu_device *adev = drm_to_adev(plane->dev);
11702 	struct drm_connector_state *new_con_state;
11703 	struct drm_connector *connector;
11704 	int i;
11705 
11706 	/*
11707 	 * TODO: Remove this hack for all asics once it proves that the
11708 	 * fast updates works fine on DCN3.2+.
11709 	 */
11710 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) < IP_VERSION(3, 2, 0) &&
11711 	    state->allow_modeset)
11712 		return true;
11713 
11714 	/* Check for writeback commit */
11715 	for_each_new_connector_in_state(state, connector, new_con_state, i) {
11716 		if (connector->connector_type != DRM_MODE_CONNECTOR_WRITEBACK)
11717 			continue;
11718 
11719 		if (new_con_state->writeback_job)
11720 			return true;
11721 	}
11722 
11723 	if (amdgpu_in_reset(adev) && state->allow_modeset)
11724 		return true;
11725 
11726 	/* Exit early if we know that we're adding or removing the plane. */
11727 	if (old_plane_state->crtc != new_plane_state->crtc)
11728 		return true;
11729 
11730 	/* old crtc == new_crtc == NULL, plane not in context. */
11731 	if (!new_plane_state->crtc)
11732 		return false;
11733 
11734 	new_crtc_state =
11735 		drm_atomic_get_new_crtc_state(state, new_plane_state->crtc);
11736 	old_crtc_state =
11737 		drm_atomic_get_old_crtc_state(state, old_plane_state->crtc);
11738 
11739 	if (!new_crtc_state)
11740 		return true;
11741 
11742 	/*
11743 	 * A change in cursor mode means a new dc pipe needs to be acquired or
11744 	 * released from the state
11745 	 */
11746 	old_dm_crtc_state = to_dm_crtc_state(old_crtc_state);
11747 	new_dm_crtc_state = to_dm_crtc_state(new_crtc_state);
11748 	if (plane->type == DRM_PLANE_TYPE_CURSOR &&
11749 	    old_dm_crtc_state != NULL &&
11750 	    old_dm_crtc_state->cursor_mode != new_dm_crtc_state->cursor_mode) {
11751 		return true;
11752 	}
11753 
11754 	/* CRTC Degamma changes currently require us to recreate planes. */
11755 	if (new_crtc_state->color_mgmt_changed)
11756 		return true;
11757 
11758 	/*
11759 	 * On zpos change, planes need to be reordered by removing and re-adding
11760 	 * them one by one to the dc state, in order of descending zpos.
11761 	 *
11762 	 * TODO: We can likely skip bandwidth validation if the only thing that
11763 	 * changed about the plane was it'z z-ordering.
11764 	 */
11765 	if (old_plane_state->normalized_zpos != new_plane_state->normalized_zpos)
11766 		return true;
11767 
11768 	if (drm_atomic_crtc_needs_modeset(new_crtc_state))
11769 		return true;
11770 
11771 	/*
11772 	 * If there are any new primary or overlay planes being added or
11773 	 * removed then the z-order can potentially change. To ensure
11774 	 * correct z-order and pipe acquisition the current DC architecture
11775 	 * requires us to remove and recreate all existing planes.
11776 	 *
11777 	 * TODO: Come up with a more elegant solution for this.
11778 	 */
11779 	for_each_oldnew_plane_in_state(state, other, old_other_state, new_other_state, i) {
11780 		struct amdgpu_framebuffer *old_afb, *new_afb;
11781 		struct dm_plane_state *dm_new_other_state, *dm_old_other_state;
11782 
11783 		dm_new_other_state = to_dm_plane_state(new_other_state);
11784 		dm_old_other_state = to_dm_plane_state(old_other_state);
11785 
11786 		if (other->type == DRM_PLANE_TYPE_CURSOR)
11787 			continue;
11788 
11789 		if (old_other_state->crtc != new_plane_state->crtc &&
11790 		    new_other_state->crtc != new_plane_state->crtc)
11791 			continue;
11792 
11793 		if (old_other_state->crtc != new_other_state->crtc)
11794 			return true;
11795 
11796 		/* Src/dst size and scaling updates. */
11797 		if (old_other_state->src_w != new_other_state->src_w ||
11798 		    old_other_state->src_h != new_other_state->src_h ||
11799 		    old_other_state->crtc_w != new_other_state->crtc_w ||
11800 		    old_other_state->crtc_h != new_other_state->crtc_h)
11801 			return true;
11802 
11803 		/* Rotation / mirroring updates. */
11804 		if (old_other_state->rotation != new_other_state->rotation)
11805 			return true;
11806 
11807 		/* Blending updates. */
11808 		if (old_other_state->pixel_blend_mode !=
11809 		    new_other_state->pixel_blend_mode)
11810 			return true;
11811 
11812 		/* Alpha updates. */
11813 		if (old_other_state->alpha != new_other_state->alpha)
11814 			return true;
11815 
11816 		/* Colorspace changes. */
11817 		if (old_other_state->color_range != new_other_state->color_range ||
11818 		    old_other_state->color_encoding != new_other_state->color_encoding)
11819 			return true;
11820 
11821 		/* HDR/Transfer Function changes. */
11822 		if (dm_old_other_state->degamma_tf != dm_new_other_state->degamma_tf ||
11823 		    dm_old_other_state->degamma_lut != dm_new_other_state->degamma_lut ||
11824 		    dm_old_other_state->hdr_mult != dm_new_other_state->hdr_mult ||
11825 		    dm_old_other_state->ctm != dm_new_other_state->ctm ||
11826 		    dm_old_other_state->shaper_lut != dm_new_other_state->shaper_lut ||
11827 		    dm_old_other_state->shaper_tf != dm_new_other_state->shaper_tf ||
11828 		    dm_old_other_state->lut3d != dm_new_other_state->lut3d ||
11829 		    dm_old_other_state->blend_lut != dm_new_other_state->blend_lut ||
11830 		    dm_old_other_state->blend_tf != dm_new_other_state->blend_tf)
11831 			return true;
11832 
11833 		/* Framebuffer checks fall at the end. */
11834 		if (!old_other_state->fb || !new_other_state->fb)
11835 			continue;
11836 
11837 		/* Pixel format changes can require bandwidth updates. */
11838 		if (old_other_state->fb->format != new_other_state->fb->format)
11839 			return true;
11840 
11841 		old_afb = (struct amdgpu_framebuffer *)old_other_state->fb;
11842 		new_afb = (struct amdgpu_framebuffer *)new_other_state->fb;
11843 
11844 		/* Tiling and DCC changes also require bandwidth updates. */
11845 		if (old_afb->tiling_flags != new_afb->tiling_flags ||
11846 		    old_afb->base.modifier != new_afb->base.modifier)
11847 			return true;
11848 	}
11849 
11850 	return false;
11851 }
11852 
dm_check_cursor_fb(struct amdgpu_crtc * new_acrtc,struct drm_plane_state * new_plane_state,struct drm_framebuffer * fb)11853 static int dm_check_cursor_fb(struct amdgpu_crtc *new_acrtc,
11854 			      struct drm_plane_state *new_plane_state,
11855 			      struct drm_framebuffer *fb)
11856 {
11857 	struct amdgpu_device *adev = drm_to_adev(new_acrtc->base.dev);
11858 	struct amdgpu_framebuffer *afb = to_amdgpu_framebuffer(fb);
11859 	unsigned int pitch;
11860 	bool linear;
11861 
11862 	if (fb->width > new_acrtc->max_cursor_width ||
11863 	    fb->height > new_acrtc->max_cursor_height) {
11864 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB size %dx%d\n",
11865 				 new_plane_state->fb->width,
11866 				 new_plane_state->fb->height);
11867 		return -EINVAL;
11868 	}
11869 	if (new_plane_state->src_w != fb->width << 16 ||
11870 	    new_plane_state->src_h != fb->height << 16) {
11871 		drm_dbg_atomic(adev_to_drm(adev), "Cropping not supported for cursor plane\n");
11872 		return -EINVAL;
11873 	}
11874 
11875 	/* Pitch in pixels */
11876 	pitch = fb->pitches[0] / fb->format->cpp[0];
11877 
11878 	if (fb->width != pitch) {
11879 		drm_dbg_atomic(adev_to_drm(adev), "Cursor FB width %d doesn't match pitch %d",
11880 				 fb->width, pitch);
11881 		return -EINVAL;
11882 	}
11883 
11884 	switch (pitch) {
11885 	case 64:
11886 	case 128:
11887 	case 256:
11888 		/* FB pitch is supported by cursor plane */
11889 		break;
11890 	default:
11891 		drm_dbg_atomic(adev_to_drm(adev), "Bad cursor FB pitch %d px\n", pitch);
11892 		return -EINVAL;
11893 	}
11894 
11895 	/* Core DRM takes care of checking FB modifiers, so we only need to
11896 	 * check tiling flags when the FB doesn't have a modifier.
11897 	 */
11898 	if (!(fb->flags & DRM_MODE_FB_MODIFIERS)) {
11899 		if (adev->family == AMDGPU_FAMILY_GC_12_0_0) {
11900 			linear = AMDGPU_TILING_GET(afb->tiling_flags, GFX12_SWIZZLE_MODE) == 0;
11901 		} else if (adev->family >= AMDGPU_FAMILY_AI) {
11902 			linear = AMDGPU_TILING_GET(afb->tiling_flags, SWIZZLE_MODE) == 0;
11903 		} else {
11904 			linear = AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_2D_TILED_THIN1 &&
11905 				 AMDGPU_TILING_GET(afb->tiling_flags, ARRAY_MODE) != DC_ARRAY_1D_TILED_THIN1 &&
11906 				 AMDGPU_TILING_GET(afb->tiling_flags, MICRO_TILE_MODE) == 0;
11907 		}
11908 		if (!linear) {
11909 			drm_dbg_atomic(adev_to_drm(adev), "Cursor FB not linear");
11910 			return -EINVAL;
11911 		}
11912 	}
11913 
11914 	return 0;
11915 }
11916 
11917 /*
11918  * Helper function for checking the cursor in native mode
11919  */
dm_check_native_cursor_state(struct drm_crtc * new_plane_crtc,struct drm_plane * plane,struct drm_plane_state * new_plane_state,bool enable)11920 static int dm_check_native_cursor_state(struct drm_crtc *new_plane_crtc,
11921 					struct drm_plane *plane,
11922 					struct drm_plane_state *new_plane_state,
11923 					bool enable)
11924 {
11925 
11926 	struct amdgpu_crtc *new_acrtc;
11927 	int ret;
11928 
11929 	if (!enable || !new_plane_crtc ||
11930 	    drm_atomic_plane_disabling(plane->state, new_plane_state))
11931 		return 0;
11932 
11933 	new_acrtc = to_amdgpu_crtc(new_plane_crtc);
11934 
11935 	if (new_plane_state->src_x != 0 || new_plane_state->src_y != 0) {
11936 		drm_dbg_atomic(new_plane_crtc->dev, "Cropping not supported for cursor plane\n");
11937 		return -EINVAL;
11938 	}
11939 
11940 	if (new_plane_state->fb) {
11941 		ret = dm_check_cursor_fb(new_acrtc, new_plane_state,
11942 						new_plane_state->fb);
11943 		if (ret)
11944 			return ret;
11945 	}
11946 
11947 	return 0;
11948 }
11949 
dm_should_update_native_cursor(struct drm_atomic_state * state,struct drm_crtc * old_plane_crtc,struct drm_crtc * new_plane_crtc,bool enable)11950 static bool dm_should_update_native_cursor(struct drm_atomic_state *state,
11951 					   struct drm_crtc *old_plane_crtc,
11952 					   struct drm_crtc *new_plane_crtc,
11953 					   bool enable)
11954 {
11955 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11956 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
11957 
11958 	if (!enable) {
11959 		if (old_plane_crtc == NULL)
11960 			return true;
11961 
11962 		old_crtc_state = drm_atomic_get_old_crtc_state(
11963 			state, old_plane_crtc);
11964 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
11965 
11966 		return dm_old_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
11967 	} else {
11968 		if (new_plane_crtc == NULL)
11969 			return true;
11970 
11971 		new_crtc_state = drm_atomic_get_new_crtc_state(
11972 			state, new_plane_crtc);
11973 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
11974 
11975 		return dm_new_crtc_state->cursor_mode == DM_CURSOR_NATIVE_MODE;
11976 	}
11977 }
11978 
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)11979 static int dm_update_plane_state(struct dc *dc,
11980 				 struct drm_atomic_state *state,
11981 				 struct drm_plane *plane,
11982 				 struct drm_plane_state *old_plane_state,
11983 				 struct drm_plane_state *new_plane_state,
11984 				 bool enable,
11985 				 bool *lock_and_validation_needed,
11986 				 bool *is_top_most_overlay)
11987 {
11988 
11989 	struct dm_atomic_state *dm_state = NULL;
11990 	struct drm_crtc *new_plane_crtc, *old_plane_crtc;
11991 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
11992 	struct dm_crtc_state *dm_new_crtc_state, *dm_old_crtc_state;
11993 	struct dm_plane_state *dm_new_plane_state, *dm_old_plane_state;
11994 	bool needs_reset, update_native_cursor;
11995 	int ret = 0;
11996 
11997 
11998 	new_plane_crtc = new_plane_state->crtc;
11999 	old_plane_crtc = old_plane_state->crtc;
12000 	dm_new_plane_state = to_dm_plane_state(new_plane_state);
12001 	dm_old_plane_state = to_dm_plane_state(old_plane_state);
12002 
12003 	update_native_cursor = dm_should_update_native_cursor(state,
12004 							      old_plane_crtc,
12005 							      new_plane_crtc,
12006 							      enable);
12007 
12008 	if (plane->type == DRM_PLANE_TYPE_CURSOR && update_native_cursor) {
12009 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12010 						    new_plane_state, enable);
12011 		if (ret)
12012 			return ret;
12013 
12014 		return 0;
12015 	}
12016 
12017 	needs_reset = should_reset_plane(state, plane, old_plane_state,
12018 					 new_plane_state);
12019 
12020 	/* Remove any changed/removed planes */
12021 	if (!enable) {
12022 		if (!needs_reset)
12023 			return 0;
12024 
12025 		if (!old_plane_crtc)
12026 			return 0;
12027 
12028 		old_crtc_state = drm_atomic_get_old_crtc_state(
12029 				state, old_plane_crtc);
12030 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12031 
12032 		if (!dm_old_crtc_state->stream)
12033 			return 0;
12034 
12035 		drm_dbg_atomic(old_plane_crtc->dev, "Disabling DRM plane: %d on DRM crtc %d\n",
12036 				plane->base.id, old_plane_crtc->base.id);
12037 
12038 		ret = dm_atomic_get_state(state, &dm_state);
12039 		if (ret)
12040 			return ret;
12041 
12042 		if (!dc_state_remove_plane(
12043 				dc,
12044 				dm_old_crtc_state->stream,
12045 				dm_old_plane_state->dc_state,
12046 				dm_state->context)) {
12047 
12048 			return -EINVAL;
12049 		}
12050 
12051 		if (dm_old_plane_state->dc_state)
12052 			dc_plane_state_release(dm_old_plane_state->dc_state);
12053 
12054 		dm_new_plane_state->dc_state = NULL;
12055 
12056 		*lock_and_validation_needed = true;
12057 
12058 	} else { /* Add new planes */
12059 		struct dc_plane_state *dc_new_plane_state;
12060 
12061 		if (drm_atomic_plane_disabling(plane->state, new_plane_state))
12062 			return 0;
12063 
12064 		if (!new_plane_crtc)
12065 			return 0;
12066 
12067 		new_crtc_state = drm_atomic_get_new_crtc_state(state, new_plane_crtc);
12068 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12069 
12070 		if (!dm_new_crtc_state->stream)
12071 			return 0;
12072 
12073 		if (!needs_reset)
12074 			return 0;
12075 
12076 		ret = amdgpu_dm_plane_helper_check_state(new_plane_state, new_crtc_state);
12077 		if (ret)
12078 			goto out;
12079 
12080 		WARN_ON(dm_new_plane_state->dc_state);
12081 
12082 		dc_new_plane_state = dc_create_plane_state(dc);
12083 		if (!dc_new_plane_state) {
12084 			ret = -ENOMEM;
12085 			goto out;
12086 		}
12087 
12088 		drm_dbg_atomic(new_plane_crtc->dev, "Enabling DRM plane: %d on DRM crtc %d\n",
12089 				 plane->base.id, new_plane_crtc->base.id);
12090 
12091 		ret = fill_dc_plane_attributes(
12092 			drm_to_adev(new_plane_crtc->dev),
12093 			dc_new_plane_state,
12094 			new_plane_state,
12095 			new_crtc_state);
12096 		if (ret) {
12097 			dc_plane_state_release(dc_new_plane_state);
12098 			goto out;
12099 		}
12100 
12101 		ret = dm_atomic_get_state(state, &dm_state);
12102 		if (ret) {
12103 			dc_plane_state_release(dc_new_plane_state);
12104 			goto out;
12105 		}
12106 
12107 		/*
12108 		 * Any atomic check errors that occur after this will
12109 		 * not need a release. The plane state will be attached
12110 		 * to the stream, and therefore part of the atomic
12111 		 * state. It'll be released when the atomic state is
12112 		 * cleaned.
12113 		 */
12114 		if (!dc_state_add_plane(
12115 				dc,
12116 				dm_new_crtc_state->stream,
12117 				dc_new_plane_state,
12118 				dm_state->context)) {
12119 
12120 			dc_plane_state_release(dc_new_plane_state);
12121 			ret = -EINVAL;
12122 			goto out;
12123 		}
12124 
12125 		dm_new_plane_state->dc_state = dc_new_plane_state;
12126 
12127 		dm_new_crtc_state->mpo_requested |= (plane->type == DRM_PLANE_TYPE_OVERLAY);
12128 
12129 		/* Tell DC to do a full surface update every time there
12130 		 * is a plane change. Inefficient, but works for now.
12131 		 */
12132 		dm_new_plane_state->dc_state->update_flags.bits.full_update = 1;
12133 
12134 		*lock_and_validation_needed = true;
12135 	}
12136 
12137 out:
12138 	/* If enabling cursor overlay failed, attempt fallback to native mode */
12139 	if (enable && ret == -EINVAL && plane->type == DRM_PLANE_TYPE_CURSOR) {
12140 		ret = dm_check_native_cursor_state(new_plane_crtc, plane,
12141 						    new_plane_state, enable);
12142 		if (ret)
12143 			return ret;
12144 
12145 		dm_new_crtc_state->cursor_mode = DM_CURSOR_NATIVE_MODE;
12146 	}
12147 
12148 	return ret;
12149 }
12150 
dm_get_oriented_plane_size(struct drm_plane_state * plane_state,int * src_w,int * src_h)12151 static void dm_get_oriented_plane_size(struct drm_plane_state *plane_state,
12152 				       int *src_w, int *src_h)
12153 {
12154 	switch (plane_state->rotation & DRM_MODE_ROTATE_MASK) {
12155 	case DRM_MODE_ROTATE_90:
12156 	case DRM_MODE_ROTATE_270:
12157 		*src_w = plane_state->src_h >> 16;
12158 		*src_h = plane_state->src_w >> 16;
12159 		break;
12160 	case DRM_MODE_ROTATE_0:
12161 	case DRM_MODE_ROTATE_180:
12162 	default:
12163 		*src_w = plane_state->src_w >> 16;
12164 		*src_h = plane_state->src_h >> 16;
12165 		break;
12166 	}
12167 }
12168 
12169 static void
dm_get_plane_scale(struct drm_plane_state * plane_state,int * out_plane_scale_w,int * out_plane_scale_h)12170 dm_get_plane_scale(struct drm_plane_state *plane_state,
12171 		   int *out_plane_scale_w, int *out_plane_scale_h)
12172 {
12173 	int plane_src_w, plane_src_h;
12174 
12175 	dm_get_oriented_plane_size(plane_state, &plane_src_w, &plane_src_h);
12176 	*out_plane_scale_w = plane_src_w ? plane_state->crtc_w * 1000 / plane_src_w : 0;
12177 	*out_plane_scale_h = plane_src_h ? plane_state->crtc_h * 1000 / plane_src_h : 0;
12178 }
12179 
12180 /*
12181  * The normalized_zpos value cannot be used by this iterator directly. It's only
12182  * calculated for enabled planes, potentially causing normalized_zpos collisions
12183  * between enabled/disabled planes in the atomic state. We need a unique value
12184  * so that the iterator will not generate the same object twice, or loop
12185  * indefinitely.
12186  */
__get_next_zpos(struct drm_atomic_state * state,struct __drm_planes_state * prev)12187 static inline struct __drm_planes_state *__get_next_zpos(
12188 	struct drm_atomic_state *state,
12189 	struct __drm_planes_state *prev)
12190 {
12191 	unsigned int highest_zpos = 0, prev_zpos = 256;
12192 	uint32_t highest_id = 0, prev_id = UINT_MAX;
12193 	struct drm_plane_state *new_plane_state;
12194 	struct drm_plane *plane;
12195 	int i, highest_i = -1;
12196 
12197 	if (prev != NULL) {
12198 		prev_zpos = prev->new_state->zpos;
12199 		prev_id = prev->ptr->base.id;
12200 	}
12201 
12202 	for_each_new_plane_in_state(state, plane, new_plane_state, i) {
12203 		/* Skip planes with higher zpos than the previously returned */
12204 		if (new_plane_state->zpos > prev_zpos ||
12205 		    (new_plane_state->zpos == prev_zpos &&
12206 		     plane->base.id >= prev_id))
12207 			continue;
12208 
12209 		/* Save the index of the plane with highest zpos */
12210 		if (new_plane_state->zpos > highest_zpos ||
12211 		    (new_plane_state->zpos == highest_zpos &&
12212 		     plane->base.id > highest_id)) {
12213 			highest_zpos = new_plane_state->zpos;
12214 			highest_id = plane->base.id;
12215 			highest_i = i;
12216 		}
12217 	}
12218 
12219 	if (highest_i < 0)
12220 		return NULL;
12221 
12222 	return &state->planes[highest_i];
12223 }
12224 
12225 /*
12226  * Use the uniqueness of the plane's (zpos, drm obj ID) combination to iterate
12227  * by descending zpos, as read from the new plane state. This is the same
12228  * ordering as defined by drm_atomic_normalize_zpos().
12229  */
12230 #define for_each_oldnew_plane_in_descending_zpos(__state, plane, old_plane_state, new_plane_state) \
12231 	for (struct __drm_planes_state *__i = __get_next_zpos((__state), NULL); \
12232 	     __i != NULL; __i = __get_next_zpos((__state), __i))		\
12233 		for_each_if(((plane) = __i->ptr,				\
12234 			     (void)(plane) /* Only to avoid unused-but-set-variable warning */, \
12235 			     (old_plane_state) = __i->old_state,		\
12236 			     (new_plane_state) = __i->new_state, 1))
12237 
add_affected_mst_dsc_crtcs(struct drm_atomic_state * state,struct drm_crtc * crtc)12238 static int add_affected_mst_dsc_crtcs(struct drm_atomic_state *state, struct drm_crtc *crtc)
12239 {
12240 	struct drm_connector *connector;
12241 	struct drm_connector_state *conn_state, *old_conn_state;
12242 	struct amdgpu_dm_connector *aconnector = NULL;
12243 	int i;
12244 
12245 	for_each_oldnew_connector_in_state(state, connector, old_conn_state, conn_state, i) {
12246 		if (!conn_state->crtc)
12247 			conn_state = old_conn_state;
12248 
12249 		if (conn_state->crtc != crtc)
12250 			continue;
12251 
12252 		if (connector->connector_type == DRM_MODE_CONNECTOR_WRITEBACK)
12253 			continue;
12254 
12255 		aconnector = to_amdgpu_dm_connector(connector);
12256 		if (!aconnector->mst_output_port || !aconnector->mst_root)
12257 			aconnector = NULL;
12258 		else
12259 			break;
12260 	}
12261 
12262 	if (!aconnector)
12263 		return 0;
12264 
12265 	return drm_dp_mst_add_affected_dsc_crtcs(state, &aconnector->mst_root->mst_mgr);
12266 }
12267 
12268 /**
12269  * DOC: Cursor Modes - Native vs Overlay
12270  *
12271  * In native mode, the cursor uses a integrated cursor pipe within each DCN hw
12272  * plane. It does not require a dedicated hw plane to enable, but it is
12273  * subjected to the same z-order and scaling as the hw plane. It also has format
12274  * restrictions, a RGB cursor in native mode cannot be enabled within a non-RGB
12275  * hw plane.
12276  *
12277  * In overlay mode, the cursor uses a separate DCN hw plane, and thus has its
12278  * own scaling and z-pos. It also has no blending restrictions. It lends to a
12279  * cursor behavior more akin to a DRM client's expectations. However, it does
12280  * occupy an extra DCN plane, and therefore will only be used if a DCN plane is
12281  * available.
12282  */
12283 
12284 /**
12285  * dm_crtc_get_cursor_mode() - Determine the required cursor mode on crtc
12286  * @adev: amdgpu device
12287  * @state: DRM atomic state
12288  * @dm_crtc_state: amdgpu state for the CRTC containing the cursor
12289  * @cursor_mode: Returns the required cursor mode on dm_crtc_state
12290  *
12291  * Get whether the cursor should be enabled in native mode, or overlay mode, on
12292  * the dm_crtc_state.
12293  *
12294  * The cursor should be enabled in overlay mode if there exists an underlying
12295  * plane - on which the cursor may be blended - that is either YUV formatted, or
12296  * scaled differently from the cursor.
12297  *
12298  * Since zpos info is required, drm_atomic_normalize_zpos must be called before
12299  * calling this function.
12300  *
12301  * Return: 0 on success, or an error code if getting the cursor plane state
12302  * failed.
12303  */
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)12304 static int dm_crtc_get_cursor_mode(struct amdgpu_device *adev,
12305 				   struct drm_atomic_state *state,
12306 				   struct dm_crtc_state *dm_crtc_state,
12307 				   enum amdgpu_dm_cursor_mode *cursor_mode)
12308 {
12309 	struct drm_plane_state *old_plane_state, *plane_state, *cursor_state;
12310 	struct drm_crtc_state *crtc_state = &dm_crtc_state->base;
12311 	struct drm_plane *plane;
12312 	bool consider_mode_change = false;
12313 	bool entire_crtc_covered = false;
12314 	bool cursor_changed = false;
12315 	int underlying_scale_w, underlying_scale_h;
12316 	int cursor_scale_w, cursor_scale_h;
12317 	int i;
12318 
12319 	/* Overlay cursor not supported on HW before DCN
12320 	 * DCN401 does not have the cursor-on-scaled-plane or cursor-on-yuv-plane restrictions
12321 	 * as previous DCN generations, so enable native mode on DCN401
12322 	 */
12323 	if (amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1)) {
12324 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12325 		return 0;
12326 	}
12327 
12328 	/* Init cursor_mode to be the same as current */
12329 	*cursor_mode = dm_crtc_state->cursor_mode;
12330 
12331 	/*
12332 	 * Cursor mode can change if a plane's format changes, scale changes, is
12333 	 * enabled/disabled, or z-order changes.
12334 	 */
12335 	for_each_oldnew_plane_in_state(state, plane, old_plane_state, plane_state, i) {
12336 		int new_scale_w, new_scale_h, old_scale_w, old_scale_h;
12337 
12338 		/* Only care about planes on this CRTC */
12339 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0)
12340 			continue;
12341 
12342 		if (plane->type == DRM_PLANE_TYPE_CURSOR)
12343 			cursor_changed = true;
12344 
12345 		if (drm_atomic_plane_enabling(old_plane_state, plane_state) ||
12346 		    drm_atomic_plane_disabling(old_plane_state, plane_state) ||
12347 		    old_plane_state->fb->format != plane_state->fb->format) {
12348 			consider_mode_change = true;
12349 			break;
12350 		}
12351 
12352 		dm_get_plane_scale(plane_state, &new_scale_w, &new_scale_h);
12353 		dm_get_plane_scale(old_plane_state, &old_scale_w, &old_scale_h);
12354 		if (new_scale_w != old_scale_w || new_scale_h != old_scale_h) {
12355 			consider_mode_change = true;
12356 			break;
12357 		}
12358 	}
12359 
12360 	if (!consider_mode_change && !crtc_state->zpos_changed)
12361 		return 0;
12362 
12363 	/*
12364 	 * If no cursor change on this CRTC, and not enabled on this CRTC, then
12365 	 * no need to set cursor mode. This avoids needlessly locking the cursor
12366 	 * state.
12367 	 */
12368 	if (!cursor_changed &&
12369 	    !(drm_plane_mask(crtc_state->crtc->cursor) & crtc_state->plane_mask)) {
12370 		return 0;
12371 	}
12372 
12373 	cursor_state = drm_atomic_get_plane_state(state,
12374 						  crtc_state->crtc->cursor);
12375 	if (IS_ERR(cursor_state))
12376 		return PTR_ERR(cursor_state);
12377 
12378 	/* Cursor is disabled */
12379 	if (!cursor_state->fb)
12380 		return 0;
12381 
12382 	/* For all planes in descending z-order (all of which are below cursor
12383 	 * as per zpos definitions), check their scaling and format
12384 	 */
12385 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, plane_state) {
12386 
12387 		/* Only care about non-cursor planes on this CRTC */
12388 		if ((drm_plane_mask(plane) & crtc_state->plane_mask) == 0 ||
12389 		    plane->type == DRM_PLANE_TYPE_CURSOR)
12390 			continue;
12391 
12392 		/* Underlying plane is YUV format - use overlay cursor */
12393 		if (amdgpu_dm_plane_is_video_format(plane_state->fb->format->format)) {
12394 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12395 			return 0;
12396 		}
12397 
12398 		dm_get_plane_scale(plane_state,
12399 				   &underlying_scale_w, &underlying_scale_h);
12400 		dm_get_plane_scale(cursor_state,
12401 				   &cursor_scale_w, &cursor_scale_h);
12402 
12403 		/* Underlying plane has different scale - use overlay cursor */
12404 		if (cursor_scale_w != underlying_scale_w &&
12405 		    cursor_scale_h != underlying_scale_h) {
12406 			*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12407 			return 0;
12408 		}
12409 
12410 		/* If this plane covers the whole CRTC, no need to check planes underneath */
12411 		if (plane_state->crtc_x <= 0 && plane_state->crtc_y <= 0 &&
12412 		    plane_state->crtc_x + plane_state->crtc_w >= crtc_state->mode.hdisplay &&
12413 		    plane_state->crtc_y + plane_state->crtc_h >= crtc_state->mode.vdisplay) {
12414 			entire_crtc_covered = true;
12415 			break;
12416 		}
12417 	}
12418 
12419 	/* If planes do not cover the entire CRTC, use overlay mode to enable
12420 	 * cursor over holes
12421 	 */
12422 	if (entire_crtc_covered)
12423 		*cursor_mode = DM_CURSOR_NATIVE_MODE;
12424 	else
12425 		*cursor_mode = DM_CURSOR_OVERLAY_MODE;
12426 
12427 	return 0;
12428 }
12429 
amdgpu_dm_crtc_mem_type_changed(struct drm_device * dev,struct drm_atomic_state * state,struct drm_crtc_state * crtc_state)12430 static bool amdgpu_dm_crtc_mem_type_changed(struct drm_device *dev,
12431 					    struct drm_atomic_state *state,
12432 					    struct drm_crtc_state *crtc_state)
12433 {
12434 	struct drm_plane *plane;
12435 	struct drm_plane_state *new_plane_state, *old_plane_state;
12436 
12437 	drm_for_each_plane_mask(plane, dev, crtc_state->plane_mask) {
12438 		new_plane_state = drm_atomic_get_plane_state(state, plane);
12439 		old_plane_state = drm_atomic_get_plane_state(state, plane);
12440 
12441 		if (IS_ERR(new_plane_state) || IS_ERR(old_plane_state)) {
12442 			drm_err(dev, "Failed to get plane state for plane %s\n", plane->name);
12443 			return false;
12444 		}
12445 
12446 		if (old_plane_state->fb && new_plane_state->fb &&
12447 		    get_mem_type(old_plane_state->fb) != get_mem_type(new_plane_state->fb))
12448 			return true;
12449 	}
12450 
12451 	return false;
12452 }
12453 
12454 /**
12455  * amdgpu_dm_atomic_check() - Atomic check implementation for AMDgpu DM.
12456  *
12457  * @dev: The DRM device
12458  * @state: The atomic state to commit
12459  *
12460  * Validate that the given atomic state is programmable by DC into hardware.
12461  * This involves constructing a &struct dc_state reflecting the new hardware
12462  * state we wish to commit, then querying DC to see if it is programmable. It's
12463  * important not to modify the existing DC state. Otherwise, atomic_check
12464  * may unexpectedly commit hardware changes.
12465  *
12466  * When validating the DC state, it's important that the right locks are
12467  * acquired. For full updates case which removes/adds/updates streams on one
12468  * CRTC while flipping on another CRTC, acquiring global lock will guarantee
12469  * that any such full update commit will wait for completion of any outstanding
12470  * flip using DRMs synchronization events.
12471  *
12472  * Note that DM adds the affected connectors for all CRTCs in state, when that
12473  * might not seem necessary. This is because DC stream creation requires the
12474  * DC sink, which is tied to the DRM connector state. Cleaning this up should
12475  * be possible but non-trivial - a possible TODO item.
12476  *
12477  * Return: -Error code if validation failed.
12478  */
amdgpu_dm_atomic_check(struct drm_device * dev,struct drm_atomic_state * state)12479 static int amdgpu_dm_atomic_check(struct drm_device *dev,
12480 				  struct drm_atomic_state *state)
12481 {
12482 	struct amdgpu_device *adev = drm_to_adev(dev);
12483 	struct dm_atomic_state *dm_state = NULL;
12484 	struct dc *dc = adev->dm.dc;
12485 	struct drm_connector *connector;
12486 	struct drm_connector_state *old_con_state, *new_con_state;
12487 	struct drm_crtc *crtc;
12488 	struct drm_crtc_state *old_crtc_state, *new_crtc_state;
12489 	struct drm_plane *plane;
12490 	struct drm_plane_state *old_plane_state, *new_plane_state, *new_cursor_state;
12491 	enum dc_status status;
12492 	int ret, i;
12493 	bool lock_and_validation_needed = false;
12494 	bool is_top_most_overlay = true;
12495 	struct dm_crtc_state *dm_old_crtc_state, *dm_new_crtc_state;
12496 	struct drm_dp_mst_topology_mgr *mgr;
12497 	struct drm_dp_mst_topology_state *mst_state;
12498 	struct dsc_mst_fairness_vars vars[MAX_PIPES] = {0};
12499 
12500 	trace_amdgpu_dm_atomic_check_begin(state);
12501 
12502 	ret = drm_atomic_helper_check_modeset(dev, state);
12503 	if (ret) {
12504 		drm_dbg_atomic(dev, "drm_atomic_helper_check_modeset() failed\n");
12505 		goto fail;
12506 	}
12507 
12508 	/* Check connector changes */
12509 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
12510 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
12511 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
12512 
12513 		/* Skip connectors that are disabled or part of modeset already. */
12514 		if (!new_con_state->crtc)
12515 			continue;
12516 
12517 		new_crtc_state = drm_atomic_get_crtc_state(state, new_con_state->crtc);
12518 		if (IS_ERR(new_crtc_state)) {
12519 			drm_dbg_atomic(dev, "drm_atomic_get_crtc_state() failed\n");
12520 			ret = PTR_ERR(new_crtc_state);
12521 			goto fail;
12522 		}
12523 
12524 		if (dm_old_con_state->abm_level != dm_new_con_state->abm_level ||
12525 		    dm_old_con_state->scaling != dm_new_con_state->scaling)
12526 			new_crtc_state->connectors_changed = true;
12527 	}
12528 
12529 	if (dc_resource_is_dsc_encoding_supported(dc)) {
12530 		for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12531 			if (drm_atomic_crtc_needs_modeset(new_crtc_state)) {
12532 				ret = add_affected_mst_dsc_crtcs(state, crtc);
12533 				if (ret) {
12534 					drm_dbg_atomic(dev, "add_affected_mst_dsc_crtcs() failed\n");
12535 					goto fail;
12536 				}
12537 			}
12538 		}
12539 	}
12540 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12541 		dm_old_crtc_state = to_dm_crtc_state(old_crtc_state);
12542 
12543 		if (!drm_atomic_crtc_needs_modeset(new_crtc_state) &&
12544 		    !new_crtc_state->color_mgmt_changed &&
12545 		    old_crtc_state->vrr_enabled == new_crtc_state->vrr_enabled &&
12546 			dm_old_crtc_state->dsc_force_changed == false)
12547 			continue;
12548 
12549 		ret = amdgpu_dm_verify_lut_sizes(new_crtc_state);
12550 		if (ret) {
12551 			drm_dbg_atomic(dev, "amdgpu_dm_verify_lut_sizes() failed\n");
12552 			goto fail;
12553 		}
12554 
12555 		if (!new_crtc_state->enable)
12556 			continue;
12557 
12558 		ret = drm_atomic_add_affected_connectors(state, crtc);
12559 		if (ret) {
12560 			drm_dbg_atomic(dev, "drm_atomic_add_affected_connectors() failed\n");
12561 			goto fail;
12562 		}
12563 
12564 		ret = drm_atomic_add_affected_planes(state, crtc);
12565 		if (ret) {
12566 			drm_dbg_atomic(dev, "drm_atomic_add_affected_planes() failed\n");
12567 			goto fail;
12568 		}
12569 
12570 		if (dm_old_crtc_state->dsc_force_changed)
12571 			new_crtc_state->mode_changed = true;
12572 	}
12573 
12574 	/*
12575 	 * Add all primary and overlay planes on the CRTC to the state
12576 	 * whenever a plane is enabled to maintain correct z-ordering
12577 	 * and to enable fast surface updates.
12578 	 */
12579 	drm_for_each_crtc(crtc, dev) {
12580 		bool modified = false;
12581 
12582 		for_each_oldnew_plane_in_state(state, plane, old_plane_state, new_plane_state, i) {
12583 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12584 				continue;
12585 
12586 			if (new_plane_state->crtc == crtc ||
12587 			    old_plane_state->crtc == crtc) {
12588 				modified = true;
12589 				break;
12590 			}
12591 		}
12592 
12593 		if (!modified)
12594 			continue;
12595 
12596 		drm_for_each_plane_mask(plane, state->dev, crtc->state->plane_mask) {
12597 			if (plane->type == DRM_PLANE_TYPE_CURSOR)
12598 				continue;
12599 
12600 			new_plane_state =
12601 				drm_atomic_get_plane_state(state, plane);
12602 
12603 			if (IS_ERR(new_plane_state)) {
12604 				ret = PTR_ERR(new_plane_state);
12605 				drm_dbg_atomic(dev, "new_plane_state is BAD\n");
12606 				goto fail;
12607 			}
12608 		}
12609 	}
12610 
12611 	/*
12612 	 * DC consults the zpos (layer_index in DC terminology) to determine the
12613 	 * hw plane on which to enable the hw cursor (see
12614 	 * `dcn10_can_pipe_disable_cursor`). By now, all modified planes are in
12615 	 * atomic state, so call drm helper to normalize zpos.
12616 	 */
12617 	ret = drm_atomic_normalize_zpos(dev, state);
12618 	if (ret) {
12619 		drm_dbg(dev, "drm_atomic_normalize_zpos() failed\n");
12620 		goto fail;
12621 	}
12622 
12623 	/*
12624 	 * Determine whether cursors on each CRTC should be enabled in native or
12625 	 * overlay mode.
12626 	 */
12627 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12628 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12629 
12630 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
12631 					      &dm_new_crtc_state->cursor_mode);
12632 		if (ret) {
12633 			drm_dbg(dev, "Failed to determine cursor mode\n");
12634 			goto fail;
12635 		}
12636 
12637 		/*
12638 		 * If overlay cursor is needed, DC cannot go through the
12639 		 * native cursor update path. All enabled planes on the CRTC
12640 		 * need to be added for DC to not disable a plane by mistake
12641 		 */
12642 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE) {
12643 			if (amdgpu_ip_version(adev, DCE_HWIP, 0) == 0) {
12644 				drm_dbg(dev, "Overlay cursor not supported on DCE\n");
12645 				ret = -EINVAL;
12646 				goto fail;
12647 			}
12648 
12649 			ret = drm_atomic_add_affected_planes(state, crtc);
12650 			if (ret)
12651 				goto fail;
12652 		}
12653 	}
12654 
12655 	/* Remove exiting planes if they are modified */
12656 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
12657 
12658 		ret = dm_update_plane_state(dc, state, plane,
12659 					    old_plane_state,
12660 					    new_plane_state,
12661 					    false,
12662 					    &lock_and_validation_needed,
12663 					    &is_top_most_overlay);
12664 		if (ret) {
12665 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
12666 			goto fail;
12667 		}
12668 	}
12669 
12670 	/* Disable all crtcs which require disable */
12671 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12672 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
12673 					   old_crtc_state,
12674 					   new_crtc_state,
12675 					   false,
12676 					   &lock_and_validation_needed);
12677 		if (ret) {
12678 			drm_dbg_atomic(dev, "DISABLE: dm_update_crtc_state() failed\n");
12679 			goto fail;
12680 		}
12681 	}
12682 
12683 	/* Enable all crtcs which require enable */
12684 	for_each_oldnew_crtc_in_state(state, crtc, old_crtc_state, new_crtc_state, i) {
12685 		ret = dm_update_crtc_state(&adev->dm, state, crtc,
12686 					   old_crtc_state,
12687 					   new_crtc_state,
12688 					   true,
12689 					   &lock_and_validation_needed);
12690 		if (ret) {
12691 			drm_dbg_atomic(dev, "ENABLE: dm_update_crtc_state() failed\n");
12692 			goto fail;
12693 		}
12694 	}
12695 
12696 	/* Add new/modified planes */
12697 	for_each_oldnew_plane_in_descending_zpos(state, plane, old_plane_state, new_plane_state) {
12698 		ret = dm_update_plane_state(dc, state, plane,
12699 					    old_plane_state,
12700 					    new_plane_state,
12701 					    true,
12702 					    &lock_and_validation_needed,
12703 					    &is_top_most_overlay);
12704 		if (ret) {
12705 			drm_dbg_atomic(dev, "dm_update_plane_state() failed\n");
12706 			goto fail;
12707 		}
12708 	}
12709 
12710 #if defined(CONFIG_DRM_AMD_DC_FP)
12711 	if (dc_resource_is_dsc_encoding_supported(dc)) {
12712 		ret = pre_validate_dsc(state, &dm_state, vars);
12713 		if (ret != 0)
12714 			goto fail;
12715 	}
12716 #endif
12717 
12718 	/* Run this here since we want to validate the streams we created */
12719 	ret = drm_atomic_helper_check_planes(dev, state);
12720 	if (ret) {
12721 		drm_dbg_atomic(dev, "drm_atomic_helper_check_planes() failed\n");
12722 		goto fail;
12723 	}
12724 
12725 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12726 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12727 		if (dm_new_crtc_state->mpo_requested)
12728 			drm_dbg_atomic(dev, "MPO enablement requested on crtc:[%p]\n", crtc);
12729 	}
12730 
12731 	/* Check cursor restrictions */
12732 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12733 		enum amdgpu_dm_cursor_mode required_cursor_mode;
12734 		int is_rotated, is_scaled;
12735 
12736 		/* Overlay cusor not subject to native cursor restrictions */
12737 		dm_new_crtc_state = to_dm_crtc_state(new_crtc_state);
12738 		if (dm_new_crtc_state->cursor_mode == DM_CURSOR_OVERLAY_MODE)
12739 			continue;
12740 
12741 		/* Check if rotation or scaling is enabled on DCN401 */
12742 		if ((drm_plane_mask(crtc->cursor) & new_crtc_state->plane_mask) &&
12743 		    amdgpu_ip_version(adev, DCE_HWIP, 0) == IP_VERSION(4, 0, 1)) {
12744 			new_cursor_state = drm_atomic_get_new_plane_state(state, crtc->cursor);
12745 
12746 			is_rotated = new_cursor_state &&
12747 				((new_cursor_state->rotation & DRM_MODE_ROTATE_MASK) != DRM_MODE_ROTATE_0);
12748 			is_scaled = new_cursor_state && ((new_cursor_state->src_w >> 16 != new_cursor_state->crtc_w) ||
12749 				(new_cursor_state->src_h >> 16 != new_cursor_state->crtc_h));
12750 
12751 			if (is_rotated || is_scaled) {
12752 				drm_dbg_driver(
12753 					crtc->dev,
12754 					"[CRTC:%d:%s] cannot enable hardware cursor due to rotation/scaling\n",
12755 					crtc->base.id, crtc->name);
12756 				ret = -EINVAL;
12757 				goto fail;
12758 			}
12759 		}
12760 
12761 		/* If HW can only do native cursor, check restrictions again */
12762 		ret = dm_crtc_get_cursor_mode(adev, state, dm_new_crtc_state,
12763 					      &required_cursor_mode);
12764 		if (ret) {
12765 			drm_dbg_driver(crtc->dev,
12766 				       "[CRTC:%d:%s] Checking cursor mode failed\n",
12767 				       crtc->base.id, crtc->name);
12768 			goto fail;
12769 		} else if (required_cursor_mode == DM_CURSOR_OVERLAY_MODE) {
12770 			drm_dbg_driver(crtc->dev,
12771 				       "[CRTC:%d:%s] Cannot enable native cursor due to scaling or YUV restrictions\n",
12772 				       crtc->base.id, crtc->name);
12773 			ret = -EINVAL;
12774 			goto fail;
12775 		}
12776 	}
12777 
12778 	if (state->legacy_cursor_update) {
12779 		/*
12780 		 * This is a fast cursor update coming from the plane update
12781 		 * helper, check if it can be done asynchronously for better
12782 		 * performance.
12783 		 */
12784 		state->async_update =
12785 			!drm_atomic_helper_async_check(dev, state);
12786 
12787 		/*
12788 		 * Skip the remaining global validation if this is an async
12789 		 * update. Cursor updates can be done without affecting
12790 		 * state or bandwidth calcs and this avoids the performance
12791 		 * penalty of locking the private state object and
12792 		 * allocating a new dc_state.
12793 		 */
12794 		if (state->async_update)
12795 			return 0;
12796 	}
12797 
12798 	/* Check scaling and underscan changes*/
12799 	/* TODO Removed scaling changes validation due to inability to commit
12800 	 * new stream into context w\o causing full reset. Need to
12801 	 * decide how to handle.
12802 	 */
12803 	for_each_oldnew_connector_in_state(state, connector, old_con_state, new_con_state, i) {
12804 		struct dm_connector_state *dm_old_con_state = to_dm_connector_state(old_con_state);
12805 		struct dm_connector_state *dm_new_con_state = to_dm_connector_state(new_con_state);
12806 		struct amdgpu_crtc *acrtc = to_amdgpu_crtc(dm_new_con_state->base.crtc);
12807 
12808 		/* Skip any modesets/resets */
12809 		if (!acrtc || drm_atomic_crtc_needs_modeset(
12810 				drm_atomic_get_new_crtc_state(state, &acrtc->base)))
12811 			continue;
12812 
12813 		/* Skip any thing not scale or underscan changes */
12814 		if (!is_scaling_state_different(dm_new_con_state, dm_old_con_state))
12815 			continue;
12816 
12817 		lock_and_validation_needed = true;
12818 	}
12819 
12820 	/* set the slot info for each mst_state based on the link encoding format */
12821 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
12822 		struct amdgpu_dm_connector *aconnector;
12823 		struct drm_connector *connector;
12824 		struct drm_connector_list_iter iter;
12825 		u8 link_coding_cap;
12826 
12827 		drm_connector_list_iter_begin(dev, &iter);
12828 		drm_for_each_connector_iter(connector, &iter) {
12829 			if (connector->index == mst_state->mgr->conn_base_id) {
12830 				aconnector = to_amdgpu_dm_connector(connector);
12831 				link_coding_cap = dc_link_dp_mst_decide_link_encoding_format(aconnector->dc_link);
12832 				drm_dp_mst_update_slots(mst_state, link_coding_cap);
12833 
12834 				break;
12835 			}
12836 		}
12837 		drm_connector_list_iter_end(&iter);
12838 	}
12839 
12840 	/**
12841 	 * Streams and planes are reset when there are changes that affect
12842 	 * bandwidth. Anything that affects bandwidth needs to go through
12843 	 * DC global validation to ensure that the configuration can be applied
12844 	 * to hardware.
12845 	 *
12846 	 * We have to currently stall out here in atomic_check for outstanding
12847 	 * commits to finish in this case because our IRQ handlers reference
12848 	 * DRM state directly - we can end up disabling interrupts too early
12849 	 * if we don't.
12850 	 *
12851 	 * TODO: Remove this stall and drop DM state private objects.
12852 	 */
12853 	if (lock_and_validation_needed) {
12854 		ret = dm_atomic_get_state(state, &dm_state);
12855 		if (ret) {
12856 			drm_dbg_atomic(dev, "dm_atomic_get_state() failed\n");
12857 			goto fail;
12858 		}
12859 
12860 		ret = do_aquire_global_lock(dev, state);
12861 		if (ret) {
12862 			drm_dbg_atomic(dev, "do_aquire_global_lock() failed\n");
12863 			goto fail;
12864 		}
12865 
12866 #if defined(CONFIG_DRM_AMD_DC_FP)
12867 		if (dc_resource_is_dsc_encoding_supported(dc)) {
12868 			ret = compute_mst_dsc_configs_for_state(state, dm_state->context, vars);
12869 			if (ret) {
12870 				drm_dbg_atomic(dev, "MST_DSC compute_mst_dsc_configs_for_state() failed\n");
12871 				ret = -EINVAL;
12872 				goto fail;
12873 			}
12874 		}
12875 #endif
12876 
12877 		ret = dm_update_mst_vcpi_slots_for_dsc(state, dm_state->context, vars);
12878 		if (ret) {
12879 			drm_dbg_atomic(dev, "dm_update_mst_vcpi_slots_for_dsc() failed\n");
12880 			goto fail;
12881 		}
12882 
12883 		/*
12884 		 * Perform validation of MST topology in the state:
12885 		 * We need to perform MST atomic check before calling
12886 		 * dc_validate_global_state(), or there is a chance
12887 		 * to get stuck in an infinite loop and hang eventually.
12888 		 */
12889 		ret = drm_dp_mst_atomic_check(state);
12890 		if (ret) {
12891 			drm_dbg_atomic(dev, "MST drm_dp_mst_atomic_check() failed\n");
12892 			goto fail;
12893 		}
12894 		status = dc_validate_global_state(dc, dm_state->context, DC_VALIDATE_MODE_ONLY);
12895 		if (status != DC_OK) {
12896 			drm_dbg_atomic(dev, "DC global validation failure: %s (%d)",
12897 				       dc_status_to_str(status), status);
12898 			ret = -EINVAL;
12899 			goto fail;
12900 		}
12901 	} else {
12902 		/*
12903 		 * The commit is a fast update. Fast updates shouldn't change
12904 		 * the DC context, affect global validation, and can have their
12905 		 * commit work done in parallel with other commits not touching
12906 		 * the same resource. If we have a new DC context as part of
12907 		 * the DM atomic state from validation we need to free it and
12908 		 * retain the existing one instead.
12909 		 *
12910 		 * Furthermore, since the DM atomic state only contains the DC
12911 		 * context and can safely be annulled, we can free the state
12912 		 * and clear the associated private object now to free
12913 		 * some memory and avoid a possible use-after-free later.
12914 		 */
12915 
12916 		for (i = 0; i < state->num_private_objs; i++) {
12917 			struct drm_private_obj *obj = state->private_objs[i].ptr;
12918 
12919 			if (obj->funcs == adev->dm.atomic_obj.funcs) {
12920 				int j = state->num_private_objs-1;
12921 
12922 				dm_atomic_destroy_state(obj,
12923 						state->private_objs[i].state_to_destroy);
12924 
12925 				/* If i is not at the end of the array then the
12926 				 * last element needs to be moved to where i was
12927 				 * before the array can safely be truncated.
12928 				 */
12929 				if (i != j)
12930 					state->private_objs[i] =
12931 						state->private_objs[j];
12932 
12933 				state->private_objs[j].ptr = NULL;
12934 				state->private_objs[j].state_to_destroy = NULL;
12935 				state->private_objs[j].old_state = NULL;
12936 				state->private_objs[j].new_state = NULL;
12937 
12938 				state->num_private_objs = j;
12939 				break;
12940 			}
12941 		}
12942 	}
12943 
12944 	/* Store the overall update type for use later in atomic check. */
12945 	for_each_new_crtc_in_state(state, crtc, new_crtc_state, i) {
12946 		struct dm_crtc_state *dm_new_crtc_state =
12947 			to_dm_crtc_state(new_crtc_state);
12948 
12949 		/*
12950 		 * Only allow async flips for fast updates that don't change
12951 		 * the FB pitch, the DCC state, rotation, mem_type, etc.
12952 		 */
12953 		if (new_crtc_state->async_flip &&
12954 		    (lock_and_validation_needed ||
12955 		     amdgpu_dm_crtc_mem_type_changed(dev, state, new_crtc_state))) {
12956 			drm_dbg_atomic(crtc->dev,
12957 				       "[CRTC:%d:%s] async flips are only supported for fast updates\n",
12958 				       crtc->base.id, crtc->name);
12959 			ret = -EINVAL;
12960 			goto fail;
12961 		}
12962 
12963 		dm_new_crtc_state->update_type = lock_and_validation_needed ?
12964 			UPDATE_TYPE_FULL : UPDATE_TYPE_FAST;
12965 	}
12966 
12967 	/* Must be success */
12968 	WARN_ON(ret);
12969 
12970 	trace_amdgpu_dm_atomic_check_finish(state, ret);
12971 
12972 	return ret;
12973 
12974 fail:
12975 	if (ret == -EDEADLK)
12976 		drm_dbg_atomic(dev, "Atomic check stopped to avoid deadlock.\n");
12977 	else if (ret == -EINTR || ret == -EAGAIN || ret == -ERESTARTSYS)
12978 		drm_dbg_atomic(dev, "Atomic check stopped due to signal.\n");
12979 	else
12980 		drm_dbg_atomic(dev, "Atomic check failed with err: %d\n", ret);
12981 
12982 	trace_amdgpu_dm_atomic_check_finish(state, ret);
12983 
12984 	return ret;
12985 }
12986 
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)12987 static bool dm_edid_parser_send_cea(struct amdgpu_display_manager *dm,
12988 		unsigned int offset,
12989 		unsigned int total_length,
12990 		u8 *data,
12991 		unsigned int length,
12992 		struct amdgpu_hdmi_vsdb_info *vsdb)
12993 {
12994 	bool res;
12995 	union dmub_rb_cmd cmd;
12996 	struct dmub_cmd_send_edid_cea *input;
12997 	struct dmub_cmd_edid_cea_output *output;
12998 
12999 	if (length > DMUB_EDID_CEA_DATA_CHUNK_BYTES)
13000 		return false;
13001 
13002 	memset(&cmd, 0, sizeof(cmd));
13003 
13004 	input = &cmd.edid_cea.data.input;
13005 
13006 	cmd.edid_cea.header.type = DMUB_CMD__EDID_CEA;
13007 	cmd.edid_cea.header.sub_type = 0;
13008 	cmd.edid_cea.header.payload_bytes =
13009 		sizeof(cmd.edid_cea) - sizeof(cmd.edid_cea.header);
13010 	input->offset = offset;
13011 	input->length = length;
13012 	input->cea_total_length = total_length;
13013 	memcpy(input->payload, data, length);
13014 
13015 	res = dc_wake_and_execute_dmub_cmd(dm->dc->ctx, &cmd, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY);
13016 	if (!res) {
13017 		drm_err(adev_to_drm(dm->adev), "EDID CEA parser failed\n");
13018 		return false;
13019 	}
13020 
13021 	output = &cmd.edid_cea.data.output;
13022 
13023 	if (output->type == DMUB_CMD__EDID_CEA_ACK) {
13024 		if (!output->ack.success) {
13025 			drm_err(adev_to_drm(dm->adev), "EDID CEA ack failed at offset %d\n",
13026 					output->ack.offset);
13027 		}
13028 	} else if (output->type == DMUB_CMD__EDID_CEA_AMD_VSDB) {
13029 		if (!output->amd_vsdb.vsdb_found)
13030 			return false;
13031 
13032 		vsdb->freesync_supported = output->amd_vsdb.freesync_supported;
13033 		vsdb->amd_vsdb_version = output->amd_vsdb.amd_vsdb_version;
13034 		vsdb->min_refresh_rate_hz = output->amd_vsdb.min_frame_rate;
13035 		vsdb->max_refresh_rate_hz = output->amd_vsdb.max_frame_rate;
13036 	} else {
13037 		drm_warn(adev_to_drm(dm->adev), "Unknown EDID CEA parser results\n");
13038 		return false;
13039 	}
13040 
13041 	return true;
13042 }
13043 
parse_edid_cea_dmcu(struct amdgpu_display_manager * dm,u8 * edid_ext,int len,struct amdgpu_hdmi_vsdb_info * vsdb_info)13044 static bool parse_edid_cea_dmcu(struct amdgpu_display_manager *dm,
13045 		u8 *edid_ext, int len,
13046 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13047 {
13048 	int i;
13049 
13050 	/* send extension block to DMCU for parsing */
13051 	for (i = 0; i < len; i += 8) {
13052 		bool res;
13053 		int offset;
13054 
13055 		/* send 8 bytes a time */
13056 		if (!dc_edid_parser_send_cea(dm->dc, i, len, &edid_ext[i], 8))
13057 			return false;
13058 
13059 		if (i+8 == len) {
13060 			/* EDID block sent completed, expect result */
13061 			int version, min_rate, max_rate;
13062 
13063 			res = dc_edid_parser_recv_amd_vsdb(dm->dc, &version, &min_rate, &max_rate);
13064 			if (res) {
13065 				/* amd vsdb found */
13066 				vsdb_info->freesync_supported = 1;
13067 				vsdb_info->amd_vsdb_version = version;
13068 				vsdb_info->min_refresh_rate_hz = min_rate;
13069 				vsdb_info->max_refresh_rate_hz = max_rate;
13070 				return true;
13071 			}
13072 			/* not amd vsdb */
13073 			return false;
13074 		}
13075 
13076 		/* check for ack*/
13077 		res = dc_edid_parser_recv_cea_ack(dm->dc, &offset);
13078 		if (!res)
13079 			return false;
13080 	}
13081 
13082 	return false;
13083 }
13084 
parse_edid_cea_dmub(struct amdgpu_display_manager * dm,u8 * edid_ext,int len,struct amdgpu_hdmi_vsdb_info * vsdb_info)13085 static bool parse_edid_cea_dmub(struct amdgpu_display_manager *dm,
13086 		u8 *edid_ext, int len,
13087 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13088 {
13089 	int i;
13090 
13091 	/* send extension block to DMCU for parsing */
13092 	for (i = 0; i < len; i += 8) {
13093 		/* send 8 bytes a time */
13094 		if (!dm_edid_parser_send_cea(dm, i, len, &edid_ext[i], 8, vsdb_info))
13095 			return false;
13096 	}
13097 
13098 	return vsdb_info->freesync_supported;
13099 }
13100 
parse_edid_cea(struct amdgpu_dm_connector * aconnector,u8 * edid_ext,int len,struct amdgpu_hdmi_vsdb_info * vsdb_info)13101 static bool parse_edid_cea(struct amdgpu_dm_connector *aconnector,
13102 		u8 *edid_ext, int len,
13103 		struct amdgpu_hdmi_vsdb_info *vsdb_info)
13104 {
13105 	struct amdgpu_device *adev = drm_to_adev(aconnector->base.dev);
13106 	bool ret;
13107 
13108 	mutex_lock(&adev->dm.dc_lock);
13109 	if (adev->dm.dmub_srv)
13110 		ret = parse_edid_cea_dmub(&adev->dm, edid_ext, len, vsdb_info);
13111 	else
13112 		ret = parse_edid_cea_dmcu(&adev->dm, edid_ext, len, vsdb_info);
13113 	mutex_unlock(&adev->dm.dc_lock);
13114 	return ret;
13115 }
13116 
parse_edid_displayid_vrr(struct drm_connector * connector,const struct edid * edid)13117 static void parse_edid_displayid_vrr(struct drm_connector *connector,
13118 				     const struct edid *edid)
13119 {
13120 	u8 *edid_ext = NULL;
13121 	int i;
13122 	int j = 0;
13123 	u16 min_vfreq;
13124 	u16 max_vfreq;
13125 
13126 	if (edid == NULL || edid->extensions == 0)
13127 		return;
13128 
13129 	/* Find DisplayID extension */
13130 	for (i = 0; i < edid->extensions; i++) {
13131 		edid_ext = (void *)(edid + (i + 1));
13132 		if (edid_ext[0] == DISPLAYID_EXT)
13133 			break;
13134 	}
13135 
13136 	if (edid_ext == NULL)
13137 		return;
13138 
13139 	while (j < EDID_LENGTH) {
13140 		/* Get dynamic video timing range from DisplayID if available */
13141 		if (EDID_LENGTH - j > 13 && edid_ext[j] == 0x25	&&
13142 		    (edid_ext[j+1] & 0xFE) == 0 && (edid_ext[j+2] == 9)) {
13143 			min_vfreq = edid_ext[j+9];
13144 			if (edid_ext[j+1] & 7)
13145 				max_vfreq = edid_ext[j+10] + ((edid_ext[j+11] & 3) << 8);
13146 			else
13147 				max_vfreq = edid_ext[j+10];
13148 
13149 			if (max_vfreq && min_vfreq) {
13150 				connector->display_info.monitor_range.max_vfreq = max_vfreq;
13151 				connector->display_info.monitor_range.min_vfreq = min_vfreq;
13152 
13153 				return;
13154 			}
13155 		}
13156 		j++;
13157 	}
13158 }
13159 
parse_amd_vsdb(struct amdgpu_dm_connector * aconnector,const struct edid * edid,struct amdgpu_hdmi_vsdb_info * vsdb_info)13160 static int parse_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13161 			  const struct edid *edid, struct amdgpu_hdmi_vsdb_info *vsdb_info)
13162 {
13163 	u8 *edid_ext = NULL;
13164 	int i;
13165 	int j = 0;
13166 	int total_ext_block_len;
13167 
13168 	if (edid == NULL || edid->extensions == 0)
13169 		return -ENODEV;
13170 
13171 	/* Find DisplayID extension */
13172 	for (i = 0; i < edid->extensions; i++) {
13173 		edid_ext = (void *)(edid + (i + 1));
13174 		if (edid_ext[0] == DISPLAYID_EXT)
13175 			break;
13176 	}
13177 
13178 	total_ext_block_len = EDID_LENGTH * edid->extensions;
13179 	while (j < total_ext_block_len - sizeof(struct amd_vsdb_block)) {
13180 		struct amd_vsdb_block *amd_vsdb = (struct amd_vsdb_block *)&edid_ext[j];
13181 		unsigned int ieeeId = (amd_vsdb->ieee_id[2] << 16) | (amd_vsdb->ieee_id[1] << 8) | (amd_vsdb->ieee_id[0]);
13182 
13183 		if (ieeeId == HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_IEEE_REGISTRATION_ID &&
13184 				amd_vsdb->version == HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_VERSION_3) {
13185 			u8 panel_type;
13186 			vsdb_info->replay_mode = (amd_vsdb->feature_caps & AMD_VSDB_VERSION_3_FEATURECAP_REPLAYMODE) ? true : false;
13187 			vsdb_info->amd_vsdb_version = HDMI_AMD_VENDOR_SPECIFIC_DATA_BLOCK_VERSION_3;
13188 			drm_dbg_kms(aconnector->base.dev, "Panel supports Replay Mode: %d\n", vsdb_info->replay_mode);
13189 			panel_type = (amd_vsdb->color_space_eotf_support & AMD_VDSB_VERSION_3_PANEL_TYPE_MASK) >> AMD_VDSB_VERSION_3_PANEL_TYPE_SHIFT;
13190 			switch (panel_type) {
13191 			case AMD_VSDB_PANEL_TYPE_OLED:
13192 				aconnector->dc_link->panel_type = PANEL_TYPE_OLED;
13193 				break;
13194 			case AMD_VSDB_PANEL_TYPE_MINILED:
13195 				aconnector->dc_link->panel_type = PANEL_TYPE_MINILED;
13196 				break;
13197 			default:
13198 				aconnector->dc_link->panel_type = PANEL_TYPE_NONE;
13199 				break;
13200 			}
13201 			drm_dbg_kms(aconnector->base.dev, "Panel type: %d\n",
13202 				    aconnector->dc_link->panel_type);
13203 
13204 			return true;
13205 		}
13206 		j++;
13207 	}
13208 
13209 	return false;
13210 }
13211 
parse_hdmi_amd_vsdb(struct amdgpu_dm_connector * aconnector,const struct edid * edid,struct amdgpu_hdmi_vsdb_info * vsdb_info)13212 static int parse_hdmi_amd_vsdb(struct amdgpu_dm_connector *aconnector,
13213 			       const struct edid *edid,
13214 			       struct amdgpu_hdmi_vsdb_info *vsdb_info)
13215 {
13216 	u8 *edid_ext = NULL;
13217 	int i;
13218 	bool valid_vsdb_found = false;
13219 
13220 	/*----- drm_find_cea_extension() -----*/
13221 	/* No EDID or EDID extensions */
13222 	if (edid == NULL || edid->extensions == 0)
13223 		return -ENODEV;
13224 
13225 	/* Find CEA extension */
13226 	for (i = 0; i < edid->extensions; i++) {
13227 		edid_ext = (uint8_t *)edid + EDID_LENGTH * (i + 1);
13228 		if (edid_ext[0] == CEA_EXT)
13229 			break;
13230 	}
13231 
13232 	if (i == edid->extensions)
13233 		return -ENODEV;
13234 
13235 	/*----- cea_db_offsets() -----*/
13236 	if (edid_ext[0] != CEA_EXT)
13237 		return -ENODEV;
13238 
13239 	valid_vsdb_found = parse_edid_cea(aconnector, edid_ext, EDID_LENGTH, vsdb_info);
13240 
13241 	return valid_vsdb_found ? i : -ENODEV;
13242 }
13243 
13244 /**
13245  * amdgpu_dm_update_freesync_caps - Update Freesync capabilities
13246  *
13247  * @connector: Connector to query.
13248  * @drm_edid: DRM EDID from monitor
13249  *
13250  * Amdgpu supports Freesync in DP and HDMI displays, and it is required to keep
13251  * track of some of the display information in the internal data struct used by
13252  * amdgpu_dm. This function checks which type of connector we need to set the
13253  * FreeSync parameters.
13254  */
amdgpu_dm_update_freesync_caps(struct drm_connector * connector,const struct drm_edid * drm_edid)13255 void amdgpu_dm_update_freesync_caps(struct drm_connector *connector,
13256 				    const struct drm_edid *drm_edid)
13257 {
13258 	int i = 0;
13259 	struct amdgpu_dm_connector *amdgpu_dm_connector =
13260 			to_amdgpu_dm_connector(connector);
13261 	struct dm_connector_state *dm_con_state = NULL;
13262 	struct dc_sink *sink;
13263 	struct amdgpu_device *adev = drm_to_adev(connector->dev);
13264 	struct amdgpu_hdmi_vsdb_info vsdb_info = {0};
13265 	const struct edid *edid;
13266 	bool freesync_capable = false;
13267 	enum adaptive_sync_type as_type = ADAPTIVE_SYNC_TYPE_NONE;
13268 
13269 	if (!connector->state) {
13270 		drm_err(adev_to_drm(adev), "%s - Connector has no state", __func__);
13271 		goto update;
13272 	}
13273 
13274 	sink = amdgpu_dm_connector->dc_sink ?
13275 		amdgpu_dm_connector->dc_sink :
13276 		amdgpu_dm_connector->dc_em_sink;
13277 
13278 	drm_edid_connector_update(connector, drm_edid);
13279 
13280 	if (!drm_edid || !sink) {
13281 		dm_con_state = to_dm_connector_state(connector->state);
13282 
13283 		amdgpu_dm_connector->min_vfreq = 0;
13284 		amdgpu_dm_connector->max_vfreq = 0;
13285 		freesync_capable = false;
13286 
13287 		goto update;
13288 	}
13289 
13290 	dm_con_state = to_dm_connector_state(connector->state);
13291 
13292 	if (!adev->dm.freesync_module || !dc_supports_vrr(sink->ctx->dce_version))
13293 		goto update;
13294 
13295 	edid = drm_edid_raw(drm_edid); // FIXME: Get rid of drm_edid_raw()
13296 
13297 	/* Some eDP panels only have the refresh rate range info in DisplayID */
13298 	if ((connector->display_info.monitor_range.min_vfreq == 0 ||
13299 	     connector->display_info.monitor_range.max_vfreq == 0))
13300 		parse_edid_displayid_vrr(connector, edid);
13301 
13302 	if (edid && (sink->sink_signal == SIGNAL_TYPE_DISPLAY_PORT ||
13303 		     sink->sink_signal == SIGNAL_TYPE_EDP)) {
13304 		if (amdgpu_dm_connector->dc_link &&
13305 		    amdgpu_dm_connector->dc_link->dpcd_caps.allow_invalid_MSA_timing_param) {
13306 			amdgpu_dm_connector->min_vfreq = connector->display_info.monitor_range.min_vfreq;
13307 			amdgpu_dm_connector->max_vfreq = connector->display_info.monitor_range.max_vfreq;
13308 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13309 				freesync_capable = true;
13310 		}
13311 
13312 		parse_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13313 
13314 		if (vsdb_info.replay_mode) {
13315 			amdgpu_dm_connector->vsdb_info.replay_mode = vsdb_info.replay_mode;
13316 			amdgpu_dm_connector->vsdb_info.amd_vsdb_version = vsdb_info.amd_vsdb_version;
13317 			amdgpu_dm_connector->as_type = ADAPTIVE_SYNC_TYPE_EDP;
13318 		}
13319 
13320 	} else if (drm_edid && sink->sink_signal == SIGNAL_TYPE_HDMI_TYPE_A) {
13321 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13322 		if (i >= 0 && vsdb_info.freesync_supported) {
13323 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13324 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13325 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13326 				freesync_capable = true;
13327 
13328 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13329 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13330 		}
13331 	}
13332 
13333 	if (amdgpu_dm_connector->dc_link)
13334 		as_type = dm_get_adaptive_sync_support_type(amdgpu_dm_connector->dc_link);
13335 
13336 	if (as_type == FREESYNC_TYPE_PCON_IN_WHITELIST) {
13337 		i = parse_hdmi_amd_vsdb(amdgpu_dm_connector, edid, &vsdb_info);
13338 		if (i >= 0 && vsdb_info.freesync_supported && vsdb_info.amd_vsdb_version > 0) {
13339 
13340 			amdgpu_dm_connector->pack_sdp_v1_3 = true;
13341 			amdgpu_dm_connector->as_type = as_type;
13342 			amdgpu_dm_connector->vsdb_info = vsdb_info;
13343 
13344 			amdgpu_dm_connector->min_vfreq = vsdb_info.min_refresh_rate_hz;
13345 			amdgpu_dm_connector->max_vfreq = vsdb_info.max_refresh_rate_hz;
13346 			if (amdgpu_dm_connector->max_vfreq - amdgpu_dm_connector->min_vfreq > 10)
13347 				freesync_capable = true;
13348 
13349 			connector->display_info.monitor_range.min_vfreq = vsdb_info.min_refresh_rate_hz;
13350 			connector->display_info.monitor_range.max_vfreq = vsdb_info.max_refresh_rate_hz;
13351 		}
13352 	}
13353 
13354 update:
13355 	if (dm_con_state)
13356 		dm_con_state->freesync_capable = freesync_capable;
13357 
13358 	if (connector->state && amdgpu_dm_connector->dc_link && !freesync_capable &&
13359 	    amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported) {
13360 		amdgpu_dm_connector->dc_link->replay_settings.config.replay_supported = false;
13361 		amdgpu_dm_connector->dc_link->replay_settings.replay_feature_enabled = false;
13362 	}
13363 
13364 	if (connector->vrr_capable_property)
13365 		drm_connector_set_vrr_capable_property(connector,
13366 						       freesync_capable);
13367 }
13368 
amdgpu_dm_trigger_timing_sync(struct drm_device * dev)13369 void amdgpu_dm_trigger_timing_sync(struct drm_device *dev)
13370 {
13371 	struct amdgpu_device *adev = drm_to_adev(dev);
13372 	struct dc *dc = adev->dm.dc;
13373 	int i;
13374 
13375 	mutex_lock(&adev->dm.dc_lock);
13376 	if (dc->current_state) {
13377 		for (i = 0; i < dc->current_state->stream_count; ++i)
13378 			dc->current_state->streams[i]
13379 				->triggered_crtc_reset.enabled =
13380 				adev->dm.force_timing_sync;
13381 
13382 		dm_enable_per_frame_crtc_master_sync(dc->current_state);
13383 		dc_trigger_sync(dc, dc->current_state);
13384 	}
13385 	mutex_unlock(&adev->dm.dc_lock);
13386 }
13387 
amdgpu_dm_exit_ips_for_hw_access(struct dc * dc)13388 static inline void amdgpu_dm_exit_ips_for_hw_access(struct dc *dc)
13389 {
13390 	if (dc->ctx->dmub_srv && !dc->ctx->dmub_srv->idle_exit_counter)
13391 		dc_exit_ips_for_hw_access(dc);
13392 }
13393 
dm_write_reg_func(const struct dc_context * ctx,uint32_t address,u32 value,const char * func_name)13394 void dm_write_reg_func(const struct dc_context *ctx, uint32_t address,
13395 		       u32 value, const char *func_name)
13396 {
13397 #ifdef DM_CHECK_ADDR_0
13398 	if (address == 0) {
13399 		drm_err(adev_to_drm(ctx->driver_context),
13400 			"invalid register write. address = 0");
13401 		return;
13402 	}
13403 #endif
13404 
13405 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13406 	cgs_write_register(ctx->cgs_device, address, value);
13407 	trace_amdgpu_dc_wreg(&ctx->perf_trace->write_count, address, value);
13408 }
13409 
dm_read_reg_func(const struct dc_context * ctx,uint32_t address,const char * func_name)13410 uint32_t dm_read_reg_func(const struct dc_context *ctx, uint32_t address,
13411 			  const char *func_name)
13412 {
13413 	u32 value;
13414 #ifdef DM_CHECK_ADDR_0
13415 	if (address == 0) {
13416 		drm_err(adev_to_drm(ctx->driver_context),
13417 			"invalid register read; address = 0\n");
13418 		return 0;
13419 	}
13420 #endif
13421 
13422 	if (ctx->dmub_srv &&
13423 	    ctx->dmub_srv->reg_helper_offload.gather_in_progress &&
13424 	    !ctx->dmub_srv->reg_helper_offload.should_burst_write) {
13425 		ASSERT(false);
13426 		return 0;
13427 	}
13428 
13429 	amdgpu_dm_exit_ips_for_hw_access(ctx->dc);
13430 
13431 	value = cgs_read_register(ctx->cgs_device, address);
13432 
13433 	trace_amdgpu_dc_rreg(&ctx->perf_trace->read_count, address, value);
13434 
13435 	return value;
13436 }
13437 
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)13438 int amdgpu_dm_process_dmub_aux_transfer_sync(
13439 		struct dc_context *ctx,
13440 		unsigned int link_index,
13441 		struct aux_payload *payload,
13442 		enum aux_return_code_type *operation_result)
13443 {
13444 	struct amdgpu_device *adev = ctx->driver_context;
13445 	struct dmub_notification *p_notify = adev->dm.dmub_notify;
13446 	int ret = -1;
13447 
13448 	mutex_lock(&adev->dm.dpia_aux_lock);
13449 	if (!dc_process_dmub_aux_transfer_async(ctx->dc, link_index, payload)) {
13450 		*operation_result = AUX_RET_ERROR_ENGINE_ACQUIRE;
13451 		goto out;
13452 	}
13453 
13454 	if (!wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13455 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13456 		*operation_result = AUX_RET_ERROR_TIMEOUT;
13457 		goto out;
13458 	}
13459 
13460 	if (p_notify->result != AUX_RET_SUCCESS) {
13461 		/*
13462 		 * Transient states before tunneling is enabled could
13463 		 * lead to this error. We can ignore this for now.
13464 		 */
13465 		if (p_notify->result == AUX_RET_ERROR_PROTOCOL_ERROR) {
13466 			drm_warn(adev_to_drm(adev), "DPIA AUX failed on 0x%x(%d), error %d\n",
13467 					payload->address, payload->length,
13468 					p_notify->result);
13469 		}
13470 		*operation_result = p_notify->result;
13471 		goto out;
13472 	}
13473 
13474 	payload->reply[0] = adev->dm.dmub_notify->aux_reply.command & 0xF;
13475 	if (adev->dm.dmub_notify->aux_reply.command & 0xF0)
13476 		/* The reply is stored in the top nibble of the command. */
13477 		payload->reply[0] = (adev->dm.dmub_notify->aux_reply.command >> 4) & 0xF;
13478 
13479 	/*write req may receive a byte indicating partially written number as well*/
13480 	if (p_notify->aux_reply.length)
13481 		memcpy(payload->data, p_notify->aux_reply.data,
13482 				p_notify->aux_reply.length);
13483 
13484 	/* success */
13485 	ret = p_notify->aux_reply.length;
13486 	*operation_result = p_notify->result;
13487 out:
13488 	reinit_completion(&adev->dm.dmub_aux_transfer_done);
13489 	mutex_unlock(&adev->dm.dpia_aux_lock);
13490 	return ret;
13491 }
13492 
abort_fused_io(struct dc_context * ctx,const struct dmub_cmd_fused_request * request)13493 static void abort_fused_io(
13494 		struct dc_context *ctx,
13495 		const struct dmub_cmd_fused_request *request
13496 )
13497 {
13498 	union dmub_rb_cmd command = { 0 };
13499 	struct dmub_rb_cmd_fused_io *io = &command.fused_io;
13500 
13501 	io->header.type = DMUB_CMD__FUSED_IO;
13502 	io->header.sub_type = DMUB_CMD__FUSED_IO_ABORT;
13503 	io->header.payload_bytes = sizeof(*io) - sizeof(io->header);
13504 	io->request = *request;
13505 	dm_execute_dmub_cmd(ctx, &command, DM_DMUB_WAIT_TYPE_NO_WAIT);
13506 }
13507 
execute_fused_io(struct amdgpu_device * dev,struct dc_context * ctx,union dmub_rb_cmd * commands,uint8_t count,uint32_t timeout_us)13508 static bool execute_fused_io(
13509 		struct amdgpu_device *dev,
13510 		struct dc_context *ctx,
13511 		union dmub_rb_cmd *commands,
13512 		uint8_t count,
13513 		uint32_t timeout_us
13514 )
13515 {
13516 	const uint8_t ddc_line = commands[0].fused_io.request.u.aux.ddc_line;
13517 
13518 	if (ddc_line >= ARRAY_SIZE(dev->dm.fused_io))
13519 		return false;
13520 
13521 	struct fused_io_sync *sync = &dev->dm.fused_io[ddc_line];
13522 	struct dmub_rb_cmd_fused_io *first = &commands[0].fused_io;
13523 	const bool result = dm_execute_dmub_cmd_list(ctx, count, commands, DM_DMUB_WAIT_TYPE_WAIT_WITH_REPLY)
13524 			&& first->header.ret_status
13525 			&& first->request.status == FUSED_REQUEST_STATUS_SUCCESS;
13526 
13527 	if (!result)
13528 		return false;
13529 
13530 	while (wait_for_completion_timeout(&sync->replied, usecs_to_jiffies(timeout_us))) {
13531 		reinit_completion(&sync->replied);
13532 
13533 		struct dmub_cmd_fused_request *reply = (struct dmub_cmd_fused_request *) sync->reply_data;
13534 
13535 		static_assert(sizeof(*reply) <= sizeof(sync->reply_data), "Size mismatch");
13536 
13537 		if (reply->identifier == first->request.identifier) {
13538 			first->request = *reply;
13539 			return true;
13540 		}
13541 	}
13542 
13543 	reinit_completion(&sync->replied);
13544 	first->request.status = FUSED_REQUEST_STATUS_TIMEOUT;
13545 	abort_fused_io(ctx, &first->request);
13546 	return false;
13547 }
13548 
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)13549 bool amdgpu_dm_execute_fused_io(
13550 		struct amdgpu_device *dev,
13551 		struct dc_link *link,
13552 		union dmub_rb_cmd *commands,
13553 		uint8_t count,
13554 		uint32_t timeout_us)
13555 {
13556 	struct amdgpu_display_manager *dm = &dev->dm;
13557 
13558 	mutex_lock(&dm->dpia_aux_lock);
13559 
13560 	const bool result = execute_fused_io(dev, link->ctx, commands, count, timeout_us);
13561 
13562 	mutex_unlock(&dm->dpia_aux_lock);
13563 	return result;
13564 }
13565 
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)13566 int amdgpu_dm_process_dmub_set_config_sync(
13567 		struct dc_context *ctx,
13568 		unsigned int link_index,
13569 		struct set_config_cmd_payload *payload,
13570 		enum set_config_status *operation_result)
13571 {
13572 	struct amdgpu_device *adev = ctx->driver_context;
13573 	bool is_cmd_complete;
13574 	int ret;
13575 
13576 	mutex_lock(&adev->dm.dpia_aux_lock);
13577 	is_cmd_complete = dc_process_dmub_set_config_async(ctx->dc,
13578 			link_index, payload, adev->dm.dmub_notify);
13579 
13580 	if (is_cmd_complete || wait_for_completion_timeout(&adev->dm.dmub_aux_transfer_done, 10 * HZ)) {
13581 		ret = 0;
13582 		*operation_result = adev->dm.dmub_notify->sc_status;
13583 	} else {
13584 		drm_err(adev_to_drm(adev), "wait_for_completion_timeout timeout!");
13585 		ret = -1;
13586 		*operation_result = SET_CONFIG_UNKNOWN_ERROR;
13587 	}
13588 
13589 	if (!is_cmd_complete)
13590 		reinit_completion(&adev->dm.dmub_aux_transfer_done);
13591 	mutex_unlock(&adev->dm.dpia_aux_lock);
13592 	return ret;
13593 }
13594 
dm_execute_dmub_cmd(const struct dc_context * ctx,union dmub_rb_cmd * cmd,enum dm_dmub_wait_type wait_type)13595 bool dm_execute_dmub_cmd(const struct dc_context *ctx, union dmub_rb_cmd *cmd, enum dm_dmub_wait_type wait_type)
13596 {
13597 	return dc_dmub_srv_cmd_run(ctx->dmub_srv, cmd, wait_type);
13598 }
13599 
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)13600 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)
13601 {
13602 	return dc_dmub_srv_cmd_run_list(ctx->dmub_srv, count, cmd, wait_type);
13603 }
13604 
dm_acpi_process_phy_transition_interlock(const struct dc_context * ctx,struct dm_process_phy_transition_init_params process_phy_transition_init_params)13605 void dm_acpi_process_phy_transition_interlock(
13606 	const struct dc_context *ctx,
13607 	struct dm_process_phy_transition_init_params process_phy_transition_init_params)
13608 {
13609 	// Not yet implemented
13610 }
13611