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