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