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