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