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