xref: /linux/drivers/gpu/drm/i915/display/intel_dp_link_training.c (revision 1d9d3bc0dad332361e1363df50b058634dcd232d)
1 /*
2  * Copyright © 2008-2015 Intel Corporation
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 (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23 
24 #include <kunit/visibility.h>
25 
26 #include <linux/debugfs.h>
27 #include <linux/iopoll.h>
28 
29 #include <drm/display/drm_dp_helper.h>
30 #include <drm/drm_print.h>
31 
32 #include "intel_display.h"
33 #include "intel_display_core.h"
34 #include "intel_display_jiffies.h"
35 #include "intel_display_types.h"
36 #include "intel_display_utils.h"
37 #include "intel_dp.h"
38 #include "intel_dp_link_caps.h"
39 #include "intel_dp_link_training.h"
40 #include "intel_dp_mst.h"
41 #include "intel_encoder.h"
42 #include "intel_hdmi.h"
43 #include "intel_hotplug.h"
44 #include "intel_modeset_lock.h"
45 #include "intel_panel.h"
46 #include "intel_psr.h"
47 
48 /**
49  * DOC: DisplayPort link training
50  *
51  * This documents the Intel DisplayPort link training implementation and
52  * its internal interfaces, with a current focus on link recovery.
53  *
54  * Documentation of the full link training procedure is not yet included.
55  *
56  * The Intel DP link recovery logic governs how the driver reacts to
57  * link training failures and to links that degrade asynchronously
58  * after a previously successful training. Recovery is first attempted
59  * via automatic retraining (``autoretrain``) and, when that is no
60  * longer possible, by selecting fallback link configurations and
61  * notifying userspace to recover the link via a modeset.
62  *
63  * Recovery sequence and userspace notification
64  * --------------------------------------------
65  *
66  * After the first link training failure following initialization or a
67  * previously successful training, recovery is first attempted by the
68  * driver via automatic retraining, without userspace involvement.
69  * During this phase, a given link configuration is attempted twice
70  * before being abandoned: after the initial link training failure, an
71  * automatic retraining modeset is performed with the same link
72  * parameters, constituting the second attempt.
73  *
74  * Once automatic retraining is no longer possible, recovery is delegated
75  * to userspace, which must select a new modeset configuration, as the
76  * kernel must not do so. From this point onwards, each link configuration
77  * may be attempted only once as userspace iterates through alternative
78  * configurations. A successful link training restores the automatic
79  * retraining model for subsequent failures.
80  *
81  * The failure of the last automatic retraining attempt is reported to
82  * userspace, and from that point onward the driver notifies userspace of
83  * each subsequent failure. This allows userspace to both initiate
84  * recovery via modesets and observe the outcome of those recovery
85  * attempts, even when no further fallback configurations remain.
86  *
87  * Link training failures are always reported to userspace, even when they
88  * result from a kernel-internal modeset. Such modesets only re-apply the
89  * existing userspace-provided state and must not modify it. A failure
90  * triggered by such a modeset is therefore treated the same as a link
91  * degradation after a previously successful training, and recovery is
92  * handled by userspace in place of the kernel caller.
93  *
94  * Contexts
95  * --------
96  *
97  * The following execution contexts (A/B/C) describe how the different
98  * recovery states are reached but are not themselves implementation
99  * states. The actual state machine is defined by &enum
100  * intel_dp_link_training_recovery_state.
101  *
102  * A. Modeset context:
103  *
104  *   Triggered by:
105  *     - link training during a modeset, or
106  *     - via the "i915_dp_force_link_training_failure" debugfs entry,
107  *       forcing this path by emulating a link training failure.
108  *
109  *   Transitions:
110  *     - A1 Link training succeeds.
111  *
112  *       A link check work to recover any degraded link is scheduled
113  *       (and handled if needed in context B).
114  *
115  *       State -> %INTEL_DP_LINK_RECOVERY_IDLE.
116  *
117  *     - A2 First link training fails after initialization or a previously
118  *       successful link training.
119  *
120  *       An automatic retraining work is scheduled (and handled in
121  *       context B) with the same link parameters with which the link
122  *       training failed.
123  *
124  *       State -> %INTEL_DP_LINK_RECOVERY_AUTORETRAIN_PENDING.
125  *
126  *     - A3 Link training fails again after A2 or A3.
127  *
128  *       Through fallback selection, the driver attempts to restrict the
129  *       allowed link configurations for subsequent modesets. This may
130  *       be done either by lowering global limits (rate/lane caps), or by
131  *       disabling only the currently failing configuration while leaving
132  *       all other configurations allowed, even if they use higher rate or
133  *       lane count.
134  *
135  *       (The current implementation may still apply parameter capping as
136  *       a coarse fallback selection mechanism. This is transitional and is
137  *       expected to be replaced by a scheme that disables only the failing
138  *       configuration, rather than removing configurations that have not
139  *       been observed to fail and may still train successfully.)
140  *
141  *       This case may repeat in a loop:
142  *           %INTEL_DP_LINK_RECOVERY_AUTORETRAIN_DISABLED ->
143  *           %INTEL_DP_LINK_RECOVERY_AUTORETRAIN_DISABLED
144  *
145  *       via repeated A3a -> A3a transitions until the configuration fallback
146  *       space is exhausted, reaching the A3b terminal case.
147  *
148  *       - A3a Fallback selection succeeds.
149  *
150  *         Userspace is notified to retry the modeset.
151  *
152  *         State -> %INTEL_DP_LINK_RECOVERY_AUTORETRAIN_DISABLED.
153  *
154  *       - A3b Fallback selection fails.
155  *
156  *         Userspace is notified of the failure and may continue recovery
157  *         by retrying the modeset with the remaining allowed link
158  *         configuration.
159  *
160  *         State -> %INTEL_DP_LINK_RECOVERY_NO_FALLBACK.
161  *
162  * B. Automatic retraining context:
163  *
164  *   Triggered by:
165  *     - after a successful link training in context A1 followed by
166  *       asynchronous link degradation, or
167  *     - after the first failed link training attempt in context A2, or
168  *     - via the "i915_dp_force_link_retrain" debugfs entry, which may
169  *       bypass normal gating and force this path.
170  *
171  *   Transitions:
172  *     - B1 ``Autoretrain`` modeset check and link training succeeds.
173  *
174  *       The case is handled as in A1, scheduling a link check work to
175  *       recover any degraded link.
176  *
177  *       State -> %INTEL_DP_LINK_RECOVERY_IDLE.
178  *
179  *     - B2 ``Autoretrain`` modeset check succeeds but link training fails.
180  *
181  *       - B2a Previously the link degraded asynchronously (current state
182  *         is %INTEL_DP_LINK_RECOVERY_IDLE).
183  *
184  *         This corresponds to a first failure in a new failure
185  *         sequence and is handled as in A2: an automatic retraining
186  *         attempt is scheduled with the same link parameters.
187  *
188  *         State -> %INTEL_DP_LINK_RECOVERY_AUTORETRAIN_PENDING.
189  *
190  *       - B2b Previously a link training failed (current state is
191  *         %INTEL_DP_LINK_RECOVERY_AUTORETRAIN_PENDING).
192  *
193  *         In non-regular (debug-forced) scenarios this may also be
194  *         reached from
195  *         %INTEL_DP_LINK_RECOVERY_AUTORETRAIN_DISABLED or
196  *         %INTEL_DP_LINK_RECOVERY_NO_FALLBACK, effectively behaving
197  *         like a userspace-driven recovery attempt.
198  *
199  *         The failure is handled as in A3, performing a fallback selection:
200  *
201  *         State -> %INTEL_DP_LINK_RECOVERY_AUTORETRAIN_DISABLED (via A3a).
202  *
203  *         or
204  *
205  *         State -> %INTEL_DP_LINK_RECOVERY_NO_FALLBACK (via A3b).
206  *
207  *     - B3 ``Autoretrain`` modeset check fails (and hence the link training
208  *       cannot be started).
209  *
210  *       The modeset check may fail, for example, due to external conditions
211  *       such as changed shared link bandwidth, which can make previously
212  *       valid modeset parameters no longer acceptable.
213  *
214  *       In this case, automatic retraining is disabled without selecting
215  *       a fallback configuration. The driver hands recovery over to
216  *       userspace without modifying the allowed configuration set, so a
217  *       subsequent userspace modeset will retry with the current link
218  *       configuration. Userspace is in a better position to select new
219  *       modeset parameters (e.g. video mode or enabled outputs) that
220  *       satisfy the updated constraints, as the driver is only allowed
221  *       to retry the modeset with the existing userspace-provided modeset
222  *       configuration.
223  *
224  *       This policy preserves the normal retry model, where a given link
225  *       configuration is attempted twice in the automatic retraining
226  *       flow before being abandoned: after a first link training failure,
227  *       an automatic retraining modeset is performed with the same link
228  *       parameters, and if its atomic check passes, the link training
229  *       itself may either succeed or fail, constituting the second
230  *       attempt. In this case, however, the retry modeset's atomic check
231  *       failed, so no second link training attempt with those parameters
232  *       was performed, and selecting a fallback would cause that
233  *       configuration to be tried only once rather than twice.
234  *
235  *       The userspace-driven link recovery continues with subsequent
236  *       userspace modesets handled in A3.
237  *
238  *       State -> %INTEL_DP_LINK_RECOVERY_AUTORETRAIN_DISABLED.
239  *
240  * C. State reset context:
241  *
242  *   Triggered by:
243  *     - sink capability changes, or
244  *     - sink disconnect/reconnect, or
245  *     - system suspend/resume or power transitions where HPD
246  *       handling may have been suppressed, or
247  *     - successful link training.
248  *
249  *   Transitions:
250  *     - The recovery state is reset from any of the recovery states
251  *
252  *       State -> %INTEL_DP_LINK_RECOVERY_IDLE.
253  *
254  *       After reset, the driver may re-check link status and schedule
255  *       retraining if the link is found to remain degraded.
256  *
257  * State transition summary
258  * ------------------------
259  *
260  * - From %INTEL_DP_LINK_RECOVERY_IDLE
261  *
262  *   - To %INTEL_DP_LINK_RECOVERY_IDLE
263  *
264  *     - | In context: B1
265  *       | Action: no action
266  *
267  *   - To %INTEL_DP_LINK_RECOVERY_AUTORETRAIN_PENDING
268  *
269  *     - | In contexts: A2, B2a
270  *       | Action: queue ``autoretrain`` work
271  *
272  *   - To %INTEL_DP_LINK_RECOVERY_AUTORETRAIN_DISABLED
273  *
274  *     - | In context: B3
275  *       | Action: notify userspace
276  *
277  * - From %INTEL_DP_LINK_RECOVERY_AUTORETRAIN_PENDING
278  *
279  *   - To %INTEL_DP_LINK_RECOVERY_AUTORETRAIN_DISABLED
280  *
281  *     - | In contexts: A3a, B2b
282  *       | Action: select fallback configurations, notify userspace
283  *
284  *     - | In context: B3
285  *       | Action: notify userspace
286  *
287  *   - To %INTEL_DP_LINK_RECOVERY_NO_FALLBACK
288  *
289  *     - | In contexts: A3b, B2b
290  *       | Action: notify userspace
291  *
292  * - From %INTEL_DP_LINK_RECOVERY_AUTORETRAIN_DISABLED
293  *
294  *   - To %INTEL_DP_LINK_RECOVERY_AUTORETRAIN_DISABLED
295  *
296  *     - | In contexts: A3a, B2b
297  *       | Action: select fallback configurations, notify userspace
298  *
299  *   - To %INTEL_DP_LINK_RECOVERY_NO_FALLBACK
300  *
301  *     - | In contexts: A3b, B2b
302  *       | Action: notify userspace
303  *
304  * - From %INTEL_DP_LINK_RECOVERY_NO_FALLBACK
305  *
306  *   - To %INTEL_DP_LINK_RECOVERY_NO_FALLBACK
307  *
308  *     - | In contexts: A3b
309  *       | Action: notify userspace
310  *
311  * - From any state
312  *
313  *   - To %INTEL_DP_LINK_RECOVERY_IDLE
314  *
315  *     - | In contexts: C
316  *       | Action: no action
317  *
318  * Recovery flows
319  * --------------
320  *
321  * Userspace modeset link recovery::
322  *
323  *                       [IDLE]
324  *                          |
325  *                          | userspace modeset link training fails
326  *                          | (autoretrain link recovery work scheduled)
327  *                          v
328  *               [AUTORETRAIN_PENDING]-- autoretrain link recovery succeeds -> [IDLE]
329  *                          |
330  *                          | autoretrain link recovery modeset check or link training fails
331  *                          |
332  *                       +--o--+
333  *  modeset check fails  |     | link training fails
334  *  (userspace notified) |     |
335  *                       |     o-------- no fallback (userspace notified) ---> [NO_FALLBACK]
336  *                       |     |
337  *   +-------------+     |     | fallback selected (userspace notified)
338  *   |             |     |     |
339  *   |             v     v     v
340  *   |        [AUTORETRAIN_DISABLED]--- userspace link recovery succeeds ----> [IDLE]
341  *   |                   |
342  *   |                   | userspace link recovery fails
343  *   |                   |
344  *   +-------------------o------------- no fallback (userspace notified) ----> [NO_FALLBACK]
345  *   fallback selected
346  *   (userspace notified)
347  *
348  * Asynchronous link degradation recovery::
349  *
350  *                       [IDLE]
351  *                          |
352  *                          | link degrades
353  *                          | (autoretrain link recovery performed)
354  *                          |
355  *                          o--- autoretrain link recovery succeeds ---> [IDLE]
356  *                          |
357  *                          | autoretrain link recovery modeset check or link training fails
358  *                          |
359  *                       +--o--+
360  *  modeset check fails  |     | link training fails
361  *  (userspace notified) |     | (autoretrain work scheduled)
362  *                       v     v
363  *  [AUTORETRAIN_DISABLED*]   [AUTORETRAIN_PENDING*]
364  *
365  * ``*`` marks states where the sequence continues from the corresponding state
366  * in the Userspace modeset link recovery flow above.
367  *
368  */
369 
370 #define LT_MSG_PREFIX			"[CONNECTOR:%d:%s][ENCODER:%d:%s][%s] "
371 #define LT_MSG_ARGS(_intel_dp, _dp_phy)	(_intel_dp)->attached_connector->base.base.id, \
372 					(_intel_dp)->attached_connector->base.name, \
373 					dp_to_dig_port(_intel_dp)->base.base.base.id, \
374 					dp_to_dig_port(_intel_dp)->base.base.name, \
375 					drm_dp_phy_name(_dp_phy)
376 
377 #define lt_dbg(_intel_dp, _dp_phy, _format, ...) \
378 	drm_dbg_kms(to_intel_display(_intel_dp)->drm, \
379 		    LT_MSG_PREFIX _format, \
380 		    LT_MSG_ARGS(_intel_dp, _dp_phy), ## __VA_ARGS__)
381 
382 #define lt_err(_intel_dp, _dp_phy, _format, ...) do { \
383 	if (intel_digital_port_connected(&dp_to_dig_port(_intel_dp)->base)) \
384 		drm_err(to_intel_display(_intel_dp)->drm, \
385 			LT_MSG_PREFIX _format, \
386 			LT_MSG_ARGS(_intel_dp, _dp_phy), ## __VA_ARGS__); \
387 	else \
388 		lt_dbg(_intel_dp, _dp_phy, "Sink disconnected: " _format, ## __VA_ARGS__); \
389 } while (0)
390 
391 /*
392  * enum intel_dp_link_recovery_state - LT recovery state
393  * @INTEL_DP_LINK_RECOVERY_IDLE:
394  *   No link training failure is currently tracked and no recovery is
395  *   in progress. This is the initial state after driver initialization,
396  *   power state transitions, sink (re-)connection, or after a successful
397  *   link training.
398  *
399  * @INTEL_DP_LINK_RECOVERY_AUTORETRAIN_PENDING:
400  *   A first link training failure has been observed and an automatic
401  *   retraining attempt with the same link parameters is pending. Exactly
402  *   one such attempt is allowed before switching to userspace-driven
403  *   recovery.
404  *
405  * @INTEL_DP_LINK_RECOVERY_AUTORETRAIN_DISABLED:
406  *   Automatic retraining is no longer possible. At this point, a
407  *   fallback selection is made and userspace is notified to take over
408  *   recovery, performing modesets with parameters it determines are
409  *   required. The driver then selects a link configuration from the
410  *   remaining fallback configuration set. Subsequent link training
411  *   failures trigger further fallback selections and userspace
412  *   notifications.
413  *
414  * @INTEL_DP_LINK_RECOVERY_NO_FALLBACK:
415  *   Fallback selection is no longer possible, as no usable fallback link
416  *   configurations remain. Recovery must proceed via userspace modesets
417  *   using the remaining allowed link configuration. Userspace continues
418  *   to be notified of subsequent link training failures.
419  *
420  * Describes the link recovery state used by the Intel DP link recovery
421  * logic.
422  *
423  * See also:
424  *   - DOC: DisplayPort link training
425  *   - link_recovery_autoretrain_pending()
426  *   - link_recovery_autoretrain_allowed()
427  *   - link_recovery_has_no_fallback()
428  *   - link_recovery_mark_train_failure()
429  *   - link_recovery_mark_autoretrain_modeset_failure()
430  *   - link_recovery_mark_no_fallback()
431  *   - link_recovery_reset()
432  */
433 enum intel_dp_link_recovery_state {
434 	/*
435 	 * Keep the enum values ordered from least to most severe
436 	 * recovery state; helper logic relies on that ordering.
437 	 */
438 	INTEL_DP_LINK_RECOVERY_IDLE,
439 	INTEL_DP_LINK_RECOVERY_AUTORETRAIN_PENDING,
440 	INTEL_DP_LINK_RECOVERY_AUTORETRAIN_DISABLED,
441 	INTEL_DP_LINK_RECOVERY_NO_FALLBACK,
442 };
443 
444 struct intel_dp_link_training {
445 	struct intel_dp *dp;
446 
447 	enum intel_dp_link_recovery_state recovery_state;
448 
449 	int force_train_failure;
450 	bool force_retrain;
451 };
452 
453 static struct intel_dp_link_training *connector_to_link_training(struct intel_connector *connector)
454 {
455 	return intel_attached_dp(connector)->link.training;
456 }
457 
458 static void intel_dp_reset_lttpr_common_caps(struct intel_dp *intel_dp)
459 {
460 	memset(intel_dp->lttpr_common_caps, 0, sizeof(intel_dp->lttpr_common_caps));
461 }
462 
463 static void intel_dp_reset_lttpr_count(struct intel_dp *intel_dp)
464 {
465 	intel_dp->lttpr_common_caps[DP_PHY_REPEATER_CNT -
466 				    DP_LT_TUNABLE_PHY_REPEATER_FIELD_DATA_STRUCTURE_REV] = 0;
467 }
468 
469 static u8 *intel_dp_lttpr_phy_caps(struct intel_dp *intel_dp,
470 				   enum drm_dp_phy dp_phy)
471 {
472 	return intel_dp->lttpr_phy_caps[dp_phy - DP_PHY_LTTPR1];
473 }
474 
475 static void intel_dp_read_lttpr_phy_caps(struct intel_dp *intel_dp,
476 					 const u8 dpcd[DP_RECEIVER_CAP_SIZE],
477 					 enum drm_dp_phy dp_phy)
478 {
479 	u8 *phy_caps = intel_dp_lttpr_phy_caps(intel_dp, dp_phy);
480 
481 	if (drm_dp_read_lttpr_phy_caps(&intel_dp->aux, dpcd, dp_phy, phy_caps) < 0) {
482 		lt_dbg(intel_dp, dp_phy, "failed to read the PHY caps\n");
483 		return;
484 	}
485 
486 	lt_dbg(intel_dp, dp_phy, "PHY capabilities: %*ph\n",
487 	       (int)sizeof(intel_dp->lttpr_phy_caps[0]),
488 	       phy_caps);
489 }
490 
491 static bool intel_dp_read_lttpr_common_caps(struct intel_dp *intel_dp,
492 					    const u8 dpcd[DP_RECEIVER_CAP_SIZE])
493 {
494 	int ret;
495 
496 	ret = drm_dp_read_lttpr_common_caps(&intel_dp->aux, dpcd,
497 					    intel_dp->lttpr_common_caps);
498 	if (ret < 0)
499 		goto reset_caps;
500 
501 	lt_dbg(intel_dp, DP_PHY_DPRX, "LTTPR common capabilities: %*ph\n",
502 	       (int)sizeof(intel_dp->lttpr_common_caps),
503 	       intel_dp->lttpr_common_caps);
504 
505 	/* The minimum value of LT_TUNABLE_PHY_REPEATER_FIELD_DATA_STRUCTURE_REV is 1.4 */
506 	if (intel_dp->lttpr_common_caps[0] < 0x14)
507 		goto reset_caps;
508 
509 	return true;
510 
511 reset_caps:
512 	intel_dp_reset_lttpr_common_caps(intel_dp);
513 	return false;
514 }
515 
516 static bool
517 intel_dp_set_lttpr_transparent_mode(struct intel_dp *intel_dp, bool enable)
518 {
519 	u8 val = enable ? DP_PHY_REPEATER_MODE_TRANSPARENT :
520 			  DP_PHY_REPEATER_MODE_NON_TRANSPARENT;
521 
522 	intel_dp->lttpr_common_caps[DP_PHY_REPEATER_MODE -
523 				    DP_LT_TUNABLE_PHY_REPEATER_FIELD_DATA_STRUCTURE_REV] = val;
524 
525 	return true;
526 }
527 
528 bool intel_dp_lttpr_transparent_mode_enabled(struct intel_dp *intel_dp)
529 {
530 	return intel_dp->lttpr_common_caps[DP_PHY_REPEATER_MODE -
531 					   DP_LT_TUNABLE_PHY_REPEATER_FIELD_DATA_STRUCTURE_REV] ==
532 		DP_PHY_REPEATER_MODE_TRANSPARENT;
533 }
534 
535 /*
536  * Read the LTTPR common capabilities and switch the LTTPR PHYs to
537  * non-transparent mode if this is supported. Preserve the
538  * transparent/non-transparent mode on an active link.
539  *
540  * Return the number of detected LTTPRs in non-transparent mode or 0 if the
541  * LTTPRs are in transparent mode or the detection failed.
542  */
543 static int intel_dp_init_lttpr_phys(struct intel_dp *intel_dp, const u8 dpcd[DP_RECEIVER_CAP_SIZE])
544 {
545 	int lttpr_count;
546 	int ret;
547 
548 	if (!intel_dp_read_lttpr_common_caps(intel_dp, dpcd))
549 		return 0;
550 
551 	lttpr_count = drm_dp_lttpr_count(intel_dp->lttpr_common_caps);
552 	/*
553 	 * Prevent setting LTTPR transparent mode explicitly if no LTTPRs are
554 	 * detected as this breaks link training at least on the Dell WD19TB
555 	 * dock.
556 	 */
557 	if (lttpr_count == 0)
558 		return 0;
559 
560 	/*
561 	 * Don't change the mode on an active link, to prevent a loss of link
562 	 * synchronization. See DP Standard v2.0 3.6.7. about the LTTPR
563 	 * resetting its internal state when the mode is changed from
564 	 * non-transparent to transparent.
565 	 */
566 	if (intel_dp->link.active) {
567 		if (lttpr_count < 0 || intel_dp_lttpr_transparent_mode_enabled(intel_dp))
568 			goto out_reset_lttpr_count;
569 
570 		return lttpr_count;
571 	}
572 
573 	ret = drm_dp_lttpr_init(&intel_dp->aux, lttpr_count);
574 	if (ret) {
575 		lt_dbg(intel_dp, DP_PHY_DPRX,
576 		       "Switching to LTTPR non-transparent LT mode failed, fall-back to transparent mode\n");
577 
578 		intel_dp_set_lttpr_transparent_mode(intel_dp, true);
579 
580 		goto out_reset_lttpr_count;
581 	}
582 
583 	intel_dp_set_lttpr_transparent_mode(intel_dp, false);
584 
585 	return lttpr_count;
586 
587 out_reset_lttpr_count:
588 	intel_dp_reset_lttpr_count(intel_dp);
589 
590 	return 0;
591 }
592 
593 static int intel_dp_init_lttpr(struct intel_dp *intel_dp, const u8 dpcd[DP_RECEIVER_CAP_SIZE])
594 {
595 	int lttpr_count;
596 	int i;
597 
598 	lttpr_count = intel_dp_init_lttpr_phys(intel_dp, dpcd);
599 
600 	for (i = 0; i < lttpr_count; i++) {
601 		intel_dp_read_lttpr_phy_caps(intel_dp, dpcd, DP_PHY_LTTPR(i));
602 		drm_dp_dump_lttpr_desc(&intel_dp->aux, DP_PHY_LTTPR(i));
603 	}
604 
605 	return lttpr_count;
606 }
607 
608 int intel_dp_read_dprx_caps(struct intel_dp *intel_dp, u8 dpcd[DP_RECEIVER_CAP_SIZE])
609 {
610 	struct intel_display *display = to_intel_display(intel_dp);
611 
612 	if (intel_dp_is_edp(intel_dp))
613 		return 0;
614 
615 	/*
616 	 * Detecting LTTPRs must be avoided on platforms with an AUX timeout
617 	 * period < 3.2ms. (see DP Standard v2.0, 2.11.2, 3.6.6.1).
618 	 */
619 	if (DISPLAY_VER(display) >= 10 && !display->platform.geminilake)
620 		if (drm_dp_dpcd_probe(&intel_dp->aux,
621 				      DP_LT_TUNABLE_PHY_REPEATER_FIELD_DATA_STRUCTURE_REV))
622 			return -EIO;
623 
624 	if (drm_dp_read_dpcd_caps(&intel_dp->aux, dpcd))
625 		return -EIO;
626 
627 	return 0;
628 }
629 
630 /**
631  * intel_dp_init_lttpr_and_dprx_caps - detect LTTPR and DPRX caps, init the LTTPR link training mode
632  * @intel_dp: Intel DP struct
633  *
634  * Read the LTTPR common and DPRX capabilities and switch to non-transparent
635  * link training mode if any is detected and read the PHY capabilities for all
636  * detected LTTPRs. In case of an LTTPR detection error or if the number of
637  * LTTPRs is more than is supported (8), fall back to the no-LTTPR,
638  * transparent mode link training mode.
639  *
640  * Returns:
641  * - >0  if LTTPRs were detected and the non-transparent LT mode was
642  *       set. The DPRX capabilities are read out.
643  * -  0  if no LTTPRs or more than 8 LTTPRs were detected or in case of
644  *       a detection failure and the transparent LT mode was set. The
645  *       DPRX capabilities are read out.
646  * - <0  Reading out the DPRX capabilities failed.
647  */
648 int intel_dp_init_lttpr_and_dprx_caps(struct intel_dp *intel_dp)
649 {
650 	struct intel_display *display = to_intel_display(intel_dp);
651 	int lttpr_count = 0;
652 
653 	/*
654 	 * Detecting LTTPRs must be avoided on platforms with an AUX timeout
655 	 * period < 3.2ms. (see DP Standard v2.0, 2.11.2, 3.6.6.1).
656 	 */
657 	if (!intel_dp_is_edp(intel_dp) &&
658 	    (DISPLAY_VER(display) >= 10 && !display->platform.geminilake)) {
659 		u8 dpcd[DP_RECEIVER_CAP_SIZE];
660 		int err = intel_dp_read_dprx_caps(intel_dp, dpcd);
661 
662 		if (err != 0)
663 			return err;
664 
665 		lttpr_count = intel_dp_init_lttpr(intel_dp, dpcd);
666 	}
667 
668 	/*
669 	 * The DPTX shall read the DPRX caps after LTTPR detection, so re-read
670 	 * it here.
671 	 */
672 	if (drm_dp_read_dpcd_caps(&intel_dp->aux, intel_dp->dpcd)) {
673 		intel_dp_reset_lttpr_common_caps(intel_dp);
674 		return -EIO;
675 	}
676 
677 	return lttpr_count;
678 }
679 
680 static u8 dp_voltage_max(u8 preemph)
681 {
682 	switch (preemph & DP_TRAIN_PRE_EMPHASIS_MASK) {
683 	case DP_TRAIN_PRE_EMPH_LEVEL_0:
684 		return DP_TRAIN_VOLTAGE_SWING_LEVEL_3;
685 	case DP_TRAIN_PRE_EMPH_LEVEL_1:
686 		return DP_TRAIN_VOLTAGE_SWING_LEVEL_2;
687 	case DP_TRAIN_PRE_EMPH_LEVEL_2:
688 		return DP_TRAIN_VOLTAGE_SWING_LEVEL_1;
689 	case DP_TRAIN_PRE_EMPH_LEVEL_3:
690 	default:
691 		return DP_TRAIN_VOLTAGE_SWING_LEVEL_0;
692 	}
693 }
694 
695 static u8 intel_dp_lttpr_voltage_max(struct intel_dp *intel_dp,
696 				     enum drm_dp_phy dp_phy)
697 {
698 	const u8 *phy_caps = intel_dp_lttpr_phy_caps(intel_dp, dp_phy);
699 
700 	if (drm_dp_lttpr_voltage_swing_level_3_supported(phy_caps))
701 		return DP_TRAIN_VOLTAGE_SWING_LEVEL_3;
702 	else
703 		return DP_TRAIN_VOLTAGE_SWING_LEVEL_2;
704 }
705 
706 static u8 intel_dp_lttpr_preemph_max(struct intel_dp *intel_dp,
707 				     enum drm_dp_phy dp_phy)
708 {
709 	const u8 *phy_caps = intel_dp_lttpr_phy_caps(intel_dp, dp_phy);
710 
711 	if (drm_dp_lttpr_pre_emphasis_level_3_supported(phy_caps))
712 		return DP_TRAIN_PRE_EMPH_LEVEL_3;
713 	else
714 		return DP_TRAIN_PRE_EMPH_LEVEL_2;
715 }
716 
717 static bool
718 intel_dp_phy_is_downstream_of_source(struct intel_dp *intel_dp,
719 				     enum drm_dp_phy dp_phy)
720 {
721 	struct intel_display *display = to_intel_display(intel_dp);
722 	int lttpr_count = drm_dp_lttpr_count(intel_dp->lttpr_common_caps);
723 
724 	drm_WARN_ON_ONCE(display->drm,
725 			 lttpr_count <= 0 && dp_phy != DP_PHY_DPRX);
726 
727 	return lttpr_count <= 0 || dp_phy == DP_PHY_LTTPR(lttpr_count - 1);
728 }
729 
730 static u8 intel_dp_phy_voltage_max(struct intel_dp *intel_dp,
731 				   const struct intel_crtc_state *crtc_state,
732 				   enum drm_dp_phy dp_phy)
733 {
734 	struct intel_display *display = to_intel_display(intel_dp);
735 	u8 voltage_max;
736 
737 	/*
738 	 * Get voltage_max from the DPTX_PHY (source or LTTPR) upstream from
739 	 * the DPRX_PHY we train.
740 	 */
741 	if (intel_dp_phy_is_downstream_of_source(intel_dp, dp_phy))
742 		voltage_max = intel_dp->voltage_max(intel_dp, crtc_state);
743 	else
744 		voltage_max = intel_dp_lttpr_voltage_max(intel_dp, dp_phy + 1);
745 
746 	drm_WARN_ON_ONCE(display->drm,
747 			 voltage_max != DP_TRAIN_VOLTAGE_SWING_LEVEL_2 &&
748 			 voltage_max != DP_TRAIN_VOLTAGE_SWING_LEVEL_3);
749 
750 	return voltage_max;
751 }
752 
753 static u8 intel_dp_phy_preemph_max(struct intel_dp *intel_dp,
754 				   enum drm_dp_phy dp_phy)
755 {
756 	struct intel_display *display = to_intel_display(intel_dp);
757 	u8 preemph_max;
758 
759 	/*
760 	 * Get preemph_max from the DPTX_PHY (source or LTTPR) upstream from
761 	 * the DPRX_PHY we train.
762 	 */
763 	if (intel_dp_phy_is_downstream_of_source(intel_dp, dp_phy))
764 		preemph_max = intel_dp->preemph_max(intel_dp);
765 	else
766 		preemph_max = intel_dp_lttpr_preemph_max(intel_dp, dp_phy + 1);
767 
768 	drm_WARN_ON_ONCE(display->drm,
769 			 preemph_max != DP_TRAIN_PRE_EMPH_LEVEL_2 &&
770 			 preemph_max != DP_TRAIN_PRE_EMPH_LEVEL_3);
771 
772 	return preemph_max;
773 }
774 
775 static bool has_per_lane_signal_levels(struct intel_dp *intel_dp,
776 				       enum drm_dp_phy dp_phy)
777 {
778 	struct intel_display *display = to_intel_display(intel_dp);
779 
780 	return !intel_dp_phy_is_downstream_of_source(intel_dp, dp_phy) ||
781 		DISPLAY_VER(display) >= 10 || display->platform.broxton;
782 }
783 
784 /* 128b/132b */
785 static u8 intel_dp_get_lane_adjust_tx_ffe_preset(struct intel_dp *intel_dp,
786 						 const struct intel_crtc_state *crtc_state,
787 						 enum drm_dp_phy dp_phy,
788 						 const u8 link_status[DP_LINK_STATUS_SIZE],
789 						 int lane)
790 {
791 	u8 tx_ffe = 0;
792 
793 	if (has_per_lane_signal_levels(intel_dp, dp_phy)) {
794 		lane = min(lane, crtc_state->lane_count - 1);
795 		tx_ffe = drm_dp_get_adjust_tx_ffe_preset(link_status, lane);
796 	} else {
797 		for (lane = 0; lane < crtc_state->lane_count; lane++)
798 			tx_ffe = max(tx_ffe, drm_dp_get_adjust_tx_ffe_preset(link_status, lane));
799 	}
800 
801 	return tx_ffe;
802 }
803 
804 /* 8b/10b */
805 static u8 intel_dp_get_lane_adjust_vswing_preemph(struct intel_dp *intel_dp,
806 						  const struct intel_crtc_state *crtc_state,
807 						  enum drm_dp_phy dp_phy,
808 						  const u8 link_status[DP_LINK_STATUS_SIZE],
809 						  int lane)
810 {
811 	u8 v = 0;
812 	u8 p = 0;
813 	u8 voltage_max;
814 	u8 preemph_max;
815 
816 	if (has_per_lane_signal_levels(intel_dp, dp_phy)) {
817 		lane = min(lane, crtc_state->lane_count - 1);
818 
819 		v = drm_dp_get_adjust_request_voltage(link_status, lane);
820 		p = drm_dp_get_adjust_request_pre_emphasis(link_status, lane);
821 	} else {
822 		for (lane = 0; lane < crtc_state->lane_count; lane++) {
823 			v = max(v, drm_dp_get_adjust_request_voltage(link_status, lane));
824 			p = max(p, drm_dp_get_adjust_request_pre_emphasis(link_status, lane));
825 		}
826 	}
827 
828 	preemph_max = intel_dp_phy_preemph_max(intel_dp, dp_phy);
829 	if (p >= preemph_max)
830 		p = preemph_max | DP_TRAIN_MAX_PRE_EMPHASIS_REACHED;
831 
832 	v = min(v, dp_voltage_max(p));
833 
834 	voltage_max = intel_dp_phy_voltage_max(intel_dp, crtc_state, dp_phy);
835 	if (v >= voltage_max)
836 		v = voltage_max | DP_TRAIN_MAX_SWING_REACHED;
837 
838 	return v | p;
839 }
840 
841 static u8 intel_dp_get_lane_adjust_train(struct intel_dp *intel_dp,
842 					 const struct intel_crtc_state *crtc_state,
843 					 enum drm_dp_phy dp_phy,
844 					 const u8 link_status[DP_LINK_STATUS_SIZE],
845 					 int lane)
846 {
847 	if (intel_dp_is_uhbr(crtc_state))
848 		return intel_dp_get_lane_adjust_tx_ffe_preset(intel_dp, crtc_state,
849 							      dp_phy, link_status, lane);
850 	else
851 		return intel_dp_get_lane_adjust_vswing_preemph(intel_dp, crtc_state,
852 							       dp_phy, link_status, lane);
853 }
854 
855 #define TRAIN_REQ_FMT "%d/%d/%d/%d"
856 #define _TRAIN_REQ_VSWING_ARGS(link_status, lane) \
857 	(drm_dp_get_adjust_request_voltage((link_status), (lane)) >> DP_TRAIN_VOLTAGE_SWING_SHIFT)
858 #define TRAIN_REQ_VSWING_ARGS(link_status) \
859 	_TRAIN_REQ_VSWING_ARGS(link_status, 0), \
860 	_TRAIN_REQ_VSWING_ARGS(link_status, 1), \
861 	_TRAIN_REQ_VSWING_ARGS(link_status, 2), \
862 	_TRAIN_REQ_VSWING_ARGS(link_status, 3)
863 #define _TRAIN_REQ_PREEMPH_ARGS(link_status, lane) \
864 	(drm_dp_get_adjust_request_pre_emphasis((link_status), (lane)) >> DP_TRAIN_PRE_EMPHASIS_SHIFT)
865 #define TRAIN_REQ_PREEMPH_ARGS(link_status) \
866 	_TRAIN_REQ_PREEMPH_ARGS(link_status, 0), \
867 	_TRAIN_REQ_PREEMPH_ARGS(link_status, 1), \
868 	_TRAIN_REQ_PREEMPH_ARGS(link_status, 2), \
869 	_TRAIN_REQ_PREEMPH_ARGS(link_status, 3)
870 #define _TRAIN_REQ_TX_FFE_ARGS(link_status, lane) \
871 	drm_dp_get_adjust_tx_ffe_preset((link_status), (lane))
872 #define TRAIN_REQ_TX_FFE_ARGS(link_status) \
873 	_TRAIN_REQ_TX_FFE_ARGS(link_status, 0), \
874 	_TRAIN_REQ_TX_FFE_ARGS(link_status, 1), \
875 	_TRAIN_REQ_TX_FFE_ARGS(link_status, 2), \
876 	_TRAIN_REQ_TX_FFE_ARGS(link_status, 3)
877 
878 bool
879 intel_dp_get_adjust_train(struct intel_dp *intel_dp,
880 			  const struct intel_crtc_state *crtc_state,
881 			  enum drm_dp_phy dp_phy,
882 			  const u8 link_status[DP_LINK_STATUS_SIZE])
883 {
884 	bool changed = false;
885 	int lane;
886 
887 	if (intel_dp_is_uhbr(crtc_state)) {
888 		lt_dbg(intel_dp, dp_phy,
889 		       "128b/132b, lanes: %d, "
890 		       "TX FFE request: " TRAIN_REQ_FMT "\n",
891 		       crtc_state->lane_count,
892 		       TRAIN_REQ_TX_FFE_ARGS(link_status));
893 	} else {
894 		lt_dbg(intel_dp, dp_phy,
895 		       "8b/10b, lanes: %d, "
896 		       "vswing request: " TRAIN_REQ_FMT ", "
897 		       "pre-emphasis request: " TRAIN_REQ_FMT "\n",
898 		       crtc_state->lane_count,
899 		       TRAIN_REQ_VSWING_ARGS(link_status),
900 		       TRAIN_REQ_PREEMPH_ARGS(link_status));
901 	}
902 
903 	for (lane = 0; lane < 4; lane++) {
904 		u8 new = intel_dp_get_lane_adjust_train(intel_dp, crtc_state,
905 							dp_phy, link_status, lane);
906 		if (intel_dp->train_set[lane] == new)
907 			continue;
908 
909 		intel_dp->train_set[lane] = new;
910 		changed = true;
911 	}
912 
913 	return changed;
914 }
915 
916 static int intel_dp_training_pattern_set_reg(struct intel_dp *intel_dp,
917 					     enum drm_dp_phy dp_phy)
918 {
919 	return dp_phy == DP_PHY_DPRX ?
920 		DP_TRAINING_PATTERN_SET :
921 		DP_TRAINING_PATTERN_SET_PHY_REPEATER(dp_phy);
922 }
923 
924 static bool
925 intel_dp_set_link_train(struct intel_dp *intel_dp,
926 			const struct intel_crtc_state *crtc_state,
927 			enum drm_dp_phy dp_phy,
928 			u8 dp_train_pat)
929 {
930 	int reg = intel_dp_training_pattern_set_reg(intel_dp, dp_phy);
931 	u8 buf[sizeof(intel_dp->train_set) + 1];
932 	int ret, len;
933 
934 	intel_dp_program_link_training_pattern(intel_dp, crtc_state,
935 					       dp_phy, dp_train_pat);
936 
937 	buf[0] = dp_train_pat;
938 	/* DP_TRAINING_LANEx_SET follow DP_TRAINING_PATTERN_SET */
939 	memcpy(buf + 1, intel_dp->train_set, crtc_state->lane_count);
940 	len = crtc_state->lane_count + 1;
941 
942 	ret = drm_dp_dpcd_write_data(&intel_dp->aux, reg, buf, len);
943 
944 	return !ret;
945 }
946 
947 static char dp_training_pattern_name(u8 train_pat)
948 {
949 	switch (train_pat) {
950 	case DP_TRAINING_PATTERN_1:
951 	case DP_TRAINING_PATTERN_2:
952 	case DP_TRAINING_PATTERN_3:
953 		return '0' + train_pat;
954 	case DP_TRAINING_PATTERN_4:
955 		return '4';
956 	default:
957 		MISSING_CASE(train_pat);
958 		return '?';
959 	}
960 }
961 
962 void
963 intel_dp_program_link_training_pattern(struct intel_dp *intel_dp,
964 				       const struct intel_crtc_state *crtc_state,
965 				       enum drm_dp_phy dp_phy,
966 				       u8 dp_train_pat)
967 {
968 	u8 train_pat = intel_dp_training_pattern_symbol(dp_train_pat);
969 
970 	if (train_pat != DP_TRAINING_PATTERN_DISABLE)
971 		lt_dbg(intel_dp, dp_phy, "Using DP training pattern TPS%c\n",
972 		       dp_training_pattern_name(train_pat));
973 
974 	intel_dp->set_link_train(intel_dp, crtc_state, dp_train_pat);
975 }
976 
977 #define TRAIN_SET_FMT "%d%s/%d%s/%d%s/%d%s"
978 #define _TRAIN_SET_VSWING_ARGS(train_set) \
979 	((train_set) & DP_TRAIN_VOLTAGE_SWING_MASK) >> DP_TRAIN_VOLTAGE_SWING_SHIFT, \
980 	(train_set) & DP_TRAIN_MAX_SWING_REACHED ? "(max)" : ""
981 #define TRAIN_SET_VSWING_ARGS(train_set) \
982 	_TRAIN_SET_VSWING_ARGS((train_set)[0]), \
983 	_TRAIN_SET_VSWING_ARGS((train_set)[1]), \
984 	_TRAIN_SET_VSWING_ARGS((train_set)[2]), \
985 	_TRAIN_SET_VSWING_ARGS((train_set)[3])
986 #define _TRAIN_SET_PREEMPH_ARGS(train_set) \
987 	((train_set) & DP_TRAIN_PRE_EMPHASIS_MASK) >> DP_TRAIN_PRE_EMPHASIS_SHIFT, \
988 	(train_set) & DP_TRAIN_MAX_PRE_EMPHASIS_REACHED ? "(max)" : ""
989 #define TRAIN_SET_PREEMPH_ARGS(train_set) \
990 	_TRAIN_SET_PREEMPH_ARGS((train_set)[0]), \
991 	_TRAIN_SET_PREEMPH_ARGS((train_set)[1]), \
992 	_TRAIN_SET_PREEMPH_ARGS((train_set)[2]), \
993 	_TRAIN_SET_PREEMPH_ARGS((train_set)[3])
994 #define _TRAIN_SET_TX_FFE_ARGS(train_set) \
995 	((train_set) & DP_TX_FFE_PRESET_VALUE_MASK), ""
996 #define TRAIN_SET_TX_FFE_ARGS(train_set) \
997 	_TRAIN_SET_TX_FFE_ARGS((train_set)[0]), \
998 	_TRAIN_SET_TX_FFE_ARGS((train_set)[1]), \
999 	_TRAIN_SET_TX_FFE_ARGS((train_set)[2]), \
1000 	_TRAIN_SET_TX_FFE_ARGS((train_set)[3])
1001 
1002 void intel_dp_set_signal_levels(struct intel_dp *intel_dp,
1003 				const struct intel_crtc_state *crtc_state,
1004 				enum drm_dp_phy dp_phy)
1005 {
1006 	struct intel_encoder *encoder = &dp_to_dig_port(intel_dp)->base;
1007 
1008 	if (intel_dp_is_uhbr(crtc_state)) {
1009 		lt_dbg(intel_dp, dp_phy,
1010 		       "128b/132b, lanes: %d, "
1011 		       "TX FFE presets: " TRAIN_SET_FMT "\n",
1012 		       crtc_state->lane_count,
1013 		       TRAIN_SET_TX_FFE_ARGS(intel_dp->train_set));
1014 	} else {
1015 		lt_dbg(intel_dp, dp_phy,
1016 		       "8b/10b, lanes: %d, "
1017 		       "vswing levels: " TRAIN_SET_FMT ", "
1018 		       "pre-emphasis levels: " TRAIN_SET_FMT "\n",
1019 		       crtc_state->lane_count,
1020 		       TRAIN_SET_VSWING_ARGS(intel_dp->train_set),
1021 		       TRAIN_SET_PREEMPH_ARGS(intel_dp->train_set));
1022 	}
1023 
1024 	if (intel_dp_phy_is_downstream_of_source(intel_dp, dp_phy))
1025 		encoder->set_signal_levels(encoder, crtc_state);
1026 }
1027 
1028 static bool
1029 intel_dp_reset_link_train(struct intel_dp *intel_dp,
1030 			  const struct intel_crtc_state *crtc_state,
1031 			  enum drm_dp_phy dp_phy,
1032 			  u8 dp_train_pat)
1033 {
1034 	memset(intel_dp->train_set, 0, sizeof(intel_dp->train_set));
1035 	intel_dp_set_signal_levels(intel_dp, crtc_state, dp_phy);
1036 	return intel_dp_set_link_train(intel_dp, crtc_state, dp_phy, dp_train_pat);
1037 }
1038 
1039 static bool
1040 intel_dp_update_link_train(struct intel_dp *intel_dp,
1041 			   const struct intel_crtc_state *crtc_state,
1042 			   enum drm_dp_phy dp_phy)
1043 {
1044 	int reg = dp_phy == DP_PHY_DPRX ?
1045 			    DP_TRAINING_LANE0_SET :
1046 			    DP_TRAINING_LANE0_SET_PHY_REPEATER(dp_phy);
1047 	int ret;
1048 
1049 	intel_dp_set_signal_levels(intel_dp, crtc_state, dp_phy);
1050 
1051 	ret = drm_dp_dpcd_write_data(&intel_dp->aux, reg,
1052 				     intel_dp->train_set, crtc_state->lane_count);
1053 
1054 	return !ret;
1055 }
1056 
1057 /* 128b/132b */
1058 static bool intel_dp_lane_max_tx_ffe_reached(u8 train_set_lane)
1059 {
1060 	return (train_set_lane & DP_TX_FFE_PRESET_VALUE_MASK) ==
1061 		DP_TX_FFE_PRESET_VALUE_MASK;
1062 }
1063 
1064 /*
1065  * 8b/10b
1066  *
1067  * FIXME: The DP spec is very confusing here, also the Link CTS spec seems to
1068  * have self contradicting tests around this area.
1069  *
1070  * In lieu of better ideas let's just stop when we've reached the max supported
1071  * vswing with its max pre-emphasis, which is either 2+1 or 3+0 depending on
1072  * whether vswing level 3 is supported or not.
1073  */
1074 static bool intel_dp_lane_max_vswing_reached(u8 train_set_lane)
1075 {
1076 	u8 v = (train_set_lane & DP_TRAIN_VOLTAGE_SWING_MASK) >>
1077 		DP_TRAIN_VOLTAGE_SWING_SHIFT;
1078 	u8 p = (train_set_lane & DP_TRAIN_PRE_EMPHASIS_MASK) >>
1079 		DP_TRAIN_PRE_EMPHASIS_SHIFT;
1080 
1081 	if ((train_set_lane & DP_TRAIN_MAX_SWING_REACHED) == 0)
1082 		return false;
1083 
1084 	if (v + p != 3)
1085 		return false;
1086 
1087 	return true;
1088 }
1089 
1090 static bool intel_dp_link_max_vswing_reached(struct intel_dp *intel_dp,
1091 					     const struct intel_crtc_state *crtc_state)
1092 {
1093 	int lane;
1094 
1095 	for (lane = 0; lane < crtc_state->lane_count; lane++) {
1096 		u8 train_set_lane = intel_dp->train_set[lane];
1097 
1098 		if (intel_dp_is_uhbr(crtc_state)) {
1099 			if (!intel_dp_lane_max_tx_ffe_reached(train_set_lane))
1100 				return false;
1101 		} else {
1102 			if (!intel_dp_lane_max_vswing_reached(train_set_lane))
1103 				return false;
1104 		}
1105 	}
1106 
1107 	return true;
1108 }
1109 
1110 void intel_dp_link_training_set_mode(struct intel_dp *intel_dp, int link_rate,
1111 				     bool is_vrr,
1112 				     bool pr_with_as_sdp_enable)
1113 {
1114 	u8 link_config[2];
1115 
1116 	link_config[0] = is_vrr ? DP_MSA_TIMING_PAR_IGNORE_EN : 0;
1117 	link_config[0] |= pr_with_as_sdp_enable ? DP_FIXED_VTOTAL_AS_SDP_EN_IN_PR_ACTIVE : 0;
1118 	link_config[1] = drm_dp_is_uhbr_rate(link_rate) ?
1119 			 DP_SET_ANSI_128B132B : DP_SET_ANSI_8B10B;
1120 	drm_dp_dpcd_write_data(&intel_dp->aux, DP_DOWNSPREAD_CTRL, link_config, 2);
1121 }
1122 
1123 static bool
1124 intel_dp_pr_with_as_sdp_enabled(struct intel_dp *intel_dp,
1125 				const struct intel_crtc_state *crtc_state)
1126 {
1127 	return intel_psr_needs_alpm_aux_less(intel_dp, crtc_state) &&
1128 		(crtc_state->infoframes.enable &
1129 		 intel_hdmi_infoframe_enable(DP_SDP_ADAPTIVE_SYNC));
1130 }
1131 
1132 static void intel_dp_update_downspread_ctrl(struct intel_dp *intel_dp,
1133 					    const struct intel_crtc_state *crtc_state)
1134 {
1135 	 /*
1136 	  * Currently, we set the MSA ignore bit based on vrr.in_range.
1137 	  * We can't really read that out during driver load since we don't have
1138 	  * the connector information read in yet. So if we do end up doing a
1139 	  * modeset during initial_commit() we'll clear the MSA ignore bit.
1140 	  * GOP likely wouldn't have set this bit so after the initial commit,
1141 	  * if there are no modesets and we enable VRR mode seamlessly
1142 	  * (without a full modeset), the MSA ignore bit might never get set.
1143 	  *
1144 	  * #TODO: Implement readout of vrr.in_range.
1145 	  * We need fastset support for setting the MSA ignore bit in DPCD,
1146 	  * especially on the first real commit when clearing the inherited flag.
1147 	  */
1148 	intel_dp_link_training_set_mode(intel_dp,
1149 					crtc_state->port_clock,
1150 					crtc_state->vrr.in_range,
1151 					intel_dp_pr_with_as_sdp_enabled(intel_dp, crtc_state));
1152 }
1153 
1154 void intel_dp_link_training_set_bw(struct intel_dp *intel_dp,
1155 				   int link_bw, int rate_select, int lane_count,
1156 				   bool enhanced_framing, bool post_lt_adj_req)
1157 {
1158 	if (enhanced_framing)
1159 		lane_count |= DP_LANE_COUNT_ENHANCED_FRAME_EN;
1160 
1161 	if (post_lt_adj_req)
1162 		lane_count |= DP_POST_LT_ADJ_REQ_GRANTED;
1163 
1164 	if (link_bw) {
1165 		/* DP and eDP v1.3 and earlier link bw set method. */
1166 		u8 link_config[] = { link_bw, lane_count };
1167 
1168 		drm_dp_dpcd_write_data(&intel_dp->aux, DP_LINK_BW_SET, link_config,
1169 				       sizeof(link_config));
1170 	} else {
1171 		/*
1172 		 * eDP v1.4 and later link rate set method.
1173 		 *
1174 		 * eDP v1.4x sinks shall ignore DP_LINK_RATE_SET if
1175 		 * DP_LINK_BW_SET is set. Avoid writing DP_LINK_BW_SET.
1176 		 *
1177 		 * eDP v1.5 sinks allow choosing either, and the last choice
1178 		 * shall be active.
1179 		 */
1180 		drm_dp_dpcd_write_byte(&intel_dp->aux, DP_LANE_COUNT_SET, lane_count);
1181 		drm_dp_dpcd_write_byte(&intel_dp->aux, DP_LINK_RATE_SET, rate_select);
1182 	}
1183 }
1184 
1185 /*
1186  * Pick Training Pattern Sequence (TPS) for channel equalization. 128b/132b TPS2
1187  * for UHBR+, TPS4 for HBR3 or for 1.4 devices that support it, TPS3 for HBR2 or
1188  * 1.2 devices that support it, TPS2 otherwise.
1189  */
1190 static u32 intel_dp_training_pattern(struct intel_dp *intel_dp,
1191 				     const struct intel_crtc_state *crtc_state,
1192 				     enum drm_dp_phy dp_phy)
1193 {
1194 	struct intel_display *display = to_intel_display(intel_dp);
1195 	bool source_tps3, sink_tps3, source_tps4, sink_tps4;
1196 
1197 	/* UHBR+ use separate 128b/132b TPS2 */
1198 	if (intel_dp_is_uhbr(crtc_state))
1199 		return DP_TRAINING_PATTERN_2;
1200 
1201 	/*
1202 	 * TPS4 support is mandatory for all downstream devices that
1203 	 * support HBR3. There are no known eDP panels that support
1204 	 * TPS4 as of Feb 2018 as per VESA eDP_v1.4b_E1 specification.
1205 	 * LTTPRs must support TPS4.
1206 	 */
1207 	source_tps4 = intel_dp_source_supports_tps4(display);
1208 	sink_tps4 = dp_phy != DP_PHY_DPRX ||
1209 		    drm_dp_tps4_supported(intel_dp->dpcd);
1210 	if (source_tps4 && sink_tps4) {
1211 		return DP_TRAINING_PATTERN_4;
1212 	} else if (crtc_state->port_clock == 810000) {
1213 		if (!source_tps4)
1214 			lt_dbg(intel_dp, dp_phy,
1215 			       "8.1 Gbps link rate without source TPS4 support\n");
1216 		if (!sink_tps4)
1217 			lt_dbg(intel_dp, dp_phy,
1218 			       "8.1 Gbps link rate without sink TPS4 support\n");
1219 	}
1220 
1221 	/*
1222 	 * TPS3 support is mandatory for downstream devices that
1223 	 * support HBR2. However, not all sinks follow the spec.
1224 	 */
1225 	source_tps3 = intel_dp_source_supports_tps3(display);
1226 	sink_tps3 = dp_phy != DP_PHY_DPRX ||
1227 		    drm_dp_tps3_supported(intel_dp->dpcd);
1228 	if (source_tps3 && sink_tps3) {
1229 		return  DP_TRAINING_PATTERN_3;
1230 	} else if (crtc_state->port_clock >= 540000) {
1231 		if (!source_tps3)
1232 			lt_dbg(intel_dp, dp_phy,
1233 			       ">=5.4/6.48 Gbps link rate without source TPS3 support\n");
1234 		if (!sink_tps3)
1235 			lt_dbg(intel_dp, dp_phy,
1236 			       ">=5.4/6.48 Gbps link rate without sink TPS3 support\n");
1237 	}
1238 
1239 	return DP_TRAINING_PATTERN_2;
1240 }
1241 
1242 static bool intel_dp_use_post_lt_adj_req(struct intel_dp *intel_dp,
1243 					 const struct intel_crtc_state *crtc_state)
1244 {
1245 	return intel_dp->set_idle_link_train &&
1246 		drm_dp_post_lt_adj_req_supported(intel_dp->dpcd) &&
1247 		intel_dp_training_pattern(intel_dp, crtc_state, DP_PHY_DPRX) != DP_TRAINING_PATTERN_4;
1248 }
1249 
1250 static void intel_dp_update_link_bw_set(struct intel_dp *intel_dp,
1251 					const struct intel_crtc_state *crtc_state,
1252 					u8 link_bw, u8 rate_select)
1253 {
1254 	intel_dp_link_training_set_bw(intel_dp, link_bw, rate_select, crtc_state->lane_count,
1255 				      crtc_state->enhanced_framing,
1256 				      intel_dp_use_post_lt_adj_req(intel_dp, crtc_state));
1257 }
1258 
1259 /*
1260  * Prepare link training by configuring the link parameters. On DDI platforms
1261  * also enable the port here.
1262  */
1263 static bool
1264 intel_dp_prepare_link_train(struct intel_dp *intel_dp,
1265 			    const struct intel_crtc_state *crtc_state)
1266 {
1267 	u8 link_bw, rate_select;
1268 
1269 	if (intel_dp->prepare_link_retrain)
1270 		intel_dp->prepare_link_retrain(intel_dp, crtc_state);
1271 
1272 	intel_dp_compute_rate(intel_dp, crtc_state->port_clock,
1273 			      &link_bw, &rate_select);
1274 
1275 	/*
1276 	 * WaEdpLinkRateDataReload
1277 	 *
1278 	 * Parade PS8461E MUX (used on various TGL+ laptops) needs
1279 	 * to snoop the link rates reported by the sink when we
1280 	 * use LINK_RATE_SET in order to operate in jitter cleaning
1281 	 * mode (as opposed to redriver mode). Unfortunately it
1282 	 * loses track of the snooped link rates when powered down,
1283 	 * so we need to make it re-snoop often. Without this high
1284 	 * link rates are not stable.
1285 	 */
1286 	if (!link_bw) {
1287 		__le16 sink_rates[DP_MAX_SUPPORTED_RATES];
1288 
1289 		lt_dbg(intel_dp, DP_PHY_DPRX, "Reloading eDP link rates\n");
1290 
1291 		drm_dp_dpcd_read_data(&intel_dp->aux, DP_SUPPORTED_LINK_RATES,
1292 				      sink_rates, sizeof(sink_rates));
1293 	}
1294 
1295 	if (link_bw)
1296 		lt_dbg(intel_dp, DP_PHY_DPRX, "Using LINK_BW_SET value %02x\n",
1297 		       link_bw);
1298 	else
1299 		lt_dbg(intel_dp, DP_PHY_DPRX,
1300 		       "Using LINK_RATE_SET value %02x\n",
1301 		       rate_select);
1302 	/*
1303 	 * Spec DP2.1 Section 3.5.2.16
1304 	 * Prior to LT DPTX should set 128b/132b DP Channel coding and then set link rate
1305 	 */
1306 	intel_dp_update_downspread_ctrl(intel_dp, crtc_state);
1307 	intel_dp_update_link_bw_set(intel_dp, crtc_state, link_bw,
1308 				    rate_select);
1309 
1310 	return true;
1311 }
1312 
1313 static bool intel_dp_adjust_request_changed(const struct intel_crtc_state *crtc_state,
1314 					    const u8 old_link_status[DP_LINK_STATUS_SIZE],
1315 					    const u8 new_link_status[DP_LINK_STATUS_SIZE])
1316 {
1317 	int lane;
1318 
1319 	for (lane = 0; lane < crtc_state->lane_count; lane++) {
1320 		u8 old, new;
1321 
1322 		if (intel_dp_is_uhbr(crtc_state)) {
1323 			old = drm_dp_get_adjust_tx_ffe_preset(old_link_status, lane);
1324 			new = drm_dp_get_adjust_tx_ffe_preset(new_link_status, lane);
1325 		} else {
1326 			old = drm_dp_get_adjust_request_voltage(old_link_status, lane) |
1327 				drm_dp_get_adjust_request_pre_emphasis(old_link_status, lane);
1328 			new = drm_dp_get_adjust_request_voltage(new_link_status, lane) |
1329 				drm_dp_get_adjust_request_pre_emphasis(new_link_status, lane);
1330 		}
1331 
1332 		if (old != new)
1333 			return true;
1334 	}
1335 
1336 	return false;
1337 }
1338 
1339 void
1340 intel_dp_dump_link_status(struct intel_dp *intel_dp, enum drm_dp_phy dp_phy,
1341 			  const u8 link_status[DP_LINK_STATUS_SIZE])
1342 {
1343 	lt_dbg(intel_dp, dp_phy,
1344 	       "ln0_1:0x%x ln2_3:0x%x align:0x%x sink:0x%x adj_req0_1:0x%x adj_req2_3:0x%x\n",
1345 	       link_status[0], link_status[1], link_status[2],
1346 	       link_status[3], link_status[4], link_status[5]);
1347 }
1348 
1349 /*
1350  * Perform the link training clock recovery phase on the given DP PHY using
1351  * training pattern 1.
1352  */
1353 static bool
1354 intel_dp_link_training_clock_recovery(struct intel_dp *intel_dp,
1355 				      const struct intel_crtc_state *crtc_state,
1356 				      enum drm_dp_phy dp_phy)
1357 {
1358 	u8 old_link_status[DP_LINK_STATUS_SIZE] = {};
1359 	int voltage_tries, cr_tries, max_cr_tries;
1360 	u8 link_status[DP_LINK_STATUS_SIZE];
1361 	bool max_vswing_reached = false;
1362 	int delay_us;
1363 
1364 	delay_us = drm_dp_read_clock_recovery_delay(&intel_dp->aux,
1365 						    intel_dp->dpcd, dp_phy,
1366 						    intel_dp_is_uhbr(crtc_state));
1367 
1368 	/* clock recovery */
1369 	if (!intel_dp_reset_link_train(intel_dp, crtc_state, dp_phy,
1370 				       DP_TRAINING_PATTERN_1 |
1371 				       DP_LINK_SCRAMBLING_DISABLE)) {
1372 		lt_err(intel_dp, dp_phy, "Failed to enable link training\n");
1373 		return false;
1374 	}
1375 
1376 	/*
1377 	 * The DP 1.4 spec defines the max clock recovery retries value
1378 	 * as 10 but for pre-DP 1.4 devices we set a very tolerant
1379 	 * retry limit of 80 (4 voltage levels x 4 preemphasis levels x
1380 	 * x 5 identical voltage retries). Since the previous specs didn't
1381 	 * define a limit and created the possibility of an infinite loop
1382 	 * we want to prevent any sync from triggering that corner case.
1383 	 */
1384 	if (intel_dp->dpcd[DP_DPCD_REV] >= DP_DPCD_REV_14)
1385 		max_cr_tries = 10;
1386 	else
1387 		max_cr_tries = 80;
1388 
1389 	voltage_tries = 1;
1390 	for (cr_tries = 0; cr_tries < max_cr_tries; ++cr_tries) {
1391 		fsleep(delay_us);
1392 
1393 		if (drm_dp_dpcd_read_phy_link_status(&intel_dp->aux, dp_phy,
1394 						     link_status) < 0) {
1395 			lt_err(intel_dp, dp_phy, "Failed to get link status\n");
1396 			return false;
1397 		}
1398 
1399 		if (drm_dp_clock_recovery_ok(link_status, crtc_state->lane_count)) {
1400 			lt_dbg(intel_dp, dp_phy, "Clock recovery OK\n");
1401 			return true;
1402 		}
1403 
1404 		if (voltage_tries == 5) {
1405 			intel_dp_dump_link_status(intel_dp, dp_phy, link_status);
1406 			lt_dbg(intel_dp, dp_phy, "Same voltage tried 5 times\n");
1407 			return false;
1408 		}
1409 
1410 		if (max_vswing_reached) {
1411 			intel_dp_dump_link_status(intel_dp, dp_phy, link_status);
1412 			lt_dbg(intel_dp, dp_phy, "Max Voltage Swing reached\n");
1413 			return false;
1414 		}
1415 
1416 		/* Update training set as requested by target */
1417 		intel_dp_get_adjust_train(intel_dp, crtc_state, dp_phy,
1418 					  link_status);
1419 		if (!intel_dp_update_link_train(intel_dp, crtc_state, dp_phy)) {
1420 			lt_err(intel_dp, dp_phy, "Failed to update link training\n");
1421 			return false;
1422 		}
1423 
1424 		if (!intel_dp_adjust_request_changed(crtc_state, old_link_status, link_status))
1425 			++voltage_tries;
1426 		else
1427 			voltage_tries = 1;
1428 
1429 		memcpy(old_link_status, link_status, sizeof(link_status));
1430 
1431 		if (intel_dp_link_max_vswing_reached(intel_dp, crtc_state))
1432 			max_vswing_reached = true;
1433 	}
1434 
1435 	intel_dp_dump_link_status(intel_dp, dp_phy, link_status);
1436 	lt_err(intel_dp, dp_phy, "Failed clock recovery %d times, giving up!\n",
1437 	       max_cr_tries);
1438 
1439 	return false;
1440 }
1441 
1442 /*
1443  * Perform the link training channel equalization phase on the given DP PHY
1444  * using one of training pattern 2, 3 or 4 depending on the source and
1445  * sink capabilities.
1446  */
1447 static bool
1448 intel_dp_link_training_channel_equalization(struct intel_dp *intel_dp,
1449 					    const struct intel_crtc_state *crtc_state,
1450 					    enum drm_dp_phy dp_phy)
1451 {
1452 	int tries;
1453 	u32 training_pattern;
1454 	u8 link_status[DP_LINK_STATUS_SIZE];
1455 	bool channel_eq = false;
1456 	int delay_us;
1457 
1458 	delay_us = drm_dp_read_channel_eq_delay(&intel_dp->aux,
1459 						intel_dp->dpcd, dp_phy,
1460 						intel_dp_is_uhbr(crtc_state));
1461 
1462 	training_pattern = intel_dp_training_pattern(intel_dp, crtc_state, dp_phy);
1463 	/* Scrambling is disabled for TPS2/3 and enabled for TPS4 */
1464 	if (training_pattern != DP_TRAINING_PATTERN_4)
1465 		training_pattern |= DP_LINK_SCRAMBLING_DISABLE;
1466 
1467 	/* channel equalization */
1468 	if (!intel_dp_set_link_train(intel_dp, crtc_state, dp_phy,
1469 				     training_pattern)) {
1470 		lt_err(intel_dp, dp_phy, "Failed to start channel equalization\n");
1471 		return false;
1472 	}
1473 
1474 	for (tries = 0; tries < 5; tries++) {
1475 		fsleep(delay_us);
1476 
1477 		if (drm_dp_dpcd_read_phy_link_status(&intel_dp->aux, dp_phy,
1478 						     link_status) < 0) {
1479 			lt_err(intel_dp, dp_phy, "Failed to get link status\n");
1480 			break;
1481 		}
1482 
1483 		/* Make sure clock is still ok */
1484 		if (!drm_dp_clock_recovery_ok(link_status,
1485 					      crtc_state->lane_count)) {
1486 			intel_dp_dump_link_status(intel_dp, dp_phy, link_status);
1487 			lt_dbg(intel_dp, dp_phy,
1488 			       "Clock recovery check failed, cannot continue channel equalization\n");
1489 			break;
1490 		}
1491 
1492 		if (drm_dp_channel_eq_ok(link_status,
1493 					 crtc_state->lane_count)) {
1494 			channel_eq = true;
1495 			lt_dbg(intel_dp, dp_phy, "Channel EQ done. DP Training successful\n");
1496 			break;
1497 		}
1498 
1499 		/* Update training set as requested by target */
1500 		intel_dp_get_adjust_train(intel_dp, crtc_state, dp_phy,
1501 					  link_status);
1502 		if (!intel_dp_update_link_train(intel_dp, crtc_state, dp_phy)) {
1503 			lt_err(intel_dp, dp_phy, "Failed to update link training\n");
1504 			break;
1505 		}
1506 	}
1507 
1508 	/* Try 5 times, else fail and try at lower BW */
1509 	if (tries == 5) {
1510 		intel_dp_dump_link_status(intel_dp, dp_phy, link_status);
1511 		lt_dbg(intel_dp, dp_phy, "Channel equalization failed 5 times\n");
1512 	}
1513 
1514 	return channel_eq;
1515 }
1516 
1517 static bool
1518 intel_dp_post_lt_adj_req(struct intel_dp *intel_dp,
1519 			 const struct intel_crtc_state *crtc_state)
1520 {
1521 	u8 link_status[DP_LINK_STATUS_SIZE];
1522 	unsigned long deadline;
1523 	bool timeout = false;
1524 	bool success = false;
1525 	int changes = 0;
1526 
1527 	if (!intel_dp_use_post_lt_adj_req(intel_dp, crtc_state))
1528 		return true;
1529 
1530 	if (drm_dp_dpcd_read_phy_link_status(&intel_dp->aux, DP_PHY_DPRX,
1531 					     link_status) < 0) {
1532 		lt_err(intel_dp, DP_PHY_DPRX, "Failed to get link status\n");
1533 		return false;
1534 	}
1535 
1536 	deadline = jiffies + msecs_to_jiffies_timeout(200);
1537 
1538 	for (;;) {
1539 		/* Make sure clock is still ok */
1540 		if (!drm_dp_clock_recovery_ok(link_status,
1541 					      crtc_state->lane_count)) {
1542 			intel_dp_dump_link_status(intel_dp, DP_PHY_DPRX, link_status);
1543 			lt_dbg(intel_dp, DP_PHY_DPRX,
1544 			       "Clock recovery check failed, cannot continue POST_LT_ADJ_REQ\n");
1545 			break;
1546 		}
1547 
1548 		if (!drm_dp_channel_eq_ok(link_status,
1549 					  crtc_state->lane_count)) {
1550 			intel_dp_dump_link_status(intel_dp, DP_PHY_DPRX, link_status);
1551 			lt_dbg(intel_dp, DP_PHY_DPRX, "Channel EQ check failed. cannot continue POST_LT_ADJ_REQ\n");
1552 			break;
1553 		}
1554 
1555 		if (!drm_dp_post_lt_adj_req_in_progress(link_status)) {
1556 			success = true;
1557 			intel_dp_dump_link_status(intel_dp, DP_PHY_DPRX, link_status);
1558 			lt_dbg(intel_dp, DP_PHY_DPRX,
1559 			       "POST_LT_ADJ_REQ done (%d changes). DP Training successful\n", changes);
1560 			break;
1561 		}
1562 
1563 		if (changes == 6) {
1564 			success = true;
1565 			intel_dp_dump_link_status(intel_dp, DP_PHY_DPRX, link_status);
1566 			lt_dbg(intel_dp, DP_PHY_DPRX,
1567 			       "POST_LT_ADJ_REQ limit reached (%d changes). DP Training successful\n", changes);
1568 			break;
1569 		}
1570 
1571 		if (timeout) {
1572 			success = true;
1573 			intel_dp_dump_link_status(intel_dp, DP_PHY_DPRX, link_status);
1574 			lt_dbg(intel_dp, DP_PHY_DPRX,
1575 			       "POST_LT_ADJ_REQ timeout reached (%d changes). DP Training successful\n", changes);
1576 			break;
1577 		}
1578 
1579 		fsleep(5000);
1580 
1581 		if (drm_dp_dpcd_read_phy_link_status(&intel_dp->aux, DP_PHY_DPRX,
1582 						     link_status) < 0) {
1583 			lt_err(intel_dp, DP_PHY_DPRX, "Failed to get link status\n");
1584 			break;
1585 		}
1586 
1587 		/* Update training set as requested by target */
1588 		if (intel_dp_get_adjust_train(intel_dp, crtc_state, DP_PHY_DPRX, link_status)) {
1589 			deadline = jiffies + msecs_to_jiffies_timeout(200);
1590 			changes++;
1591 
1592 			if (!intel_dp_update_link_train(intel_dp, crtc_state, DP_PHY_DPRX)) {
1593 				lt_err(intel_dp, DP_PHY_DPRX, "Failed to update link training\n");
1594 				break;
1595 			}
1596 		} else if (time_after(jiffies, deadline)) {
1597 			timeout = true;
1598 		}
1599 	}
1600 
1601 	return success;
1602 }
1603 
1604 static void intel_dp_stop_post_lt_adj_req(struct intel_dp *intel_dp,
1605 					  const struct intel_crtc_state *crtc_state)
1606 {
1607 	u8 lane_count;
1608 
1609 	if (!intel_dp_use_post_lt_adj_req(intel_dp, crtc_state))
1610 		return;
1611 
1612 	/* clear DP_POST_LT_ADJ_REQ_GRANTED */
1613 	lane_count = crtc_state->lane_count;
1614 	if (crtc_state->enhanced_framing)
1615 		lane_count |= DP_LANE_COUNT_ENHANCED_FRAME_EN;
1616 
1617 	drm_dp_dpcd_write_byte(&intel_dp->aux, DP_LANE_COUNT_SET, lane_count);
1618 }
1619 
1620 static bool intel_dp_disable_dpcd_training_pattern(struct intel_dp *intel_dp,
1621 						   enum drm_dp_phy dp_phy)
1622 {
1623 	int reg = intel_dp_training_pattern_set_reg(intel_dp, dp_phy);
1624 	u8 val = DP_TRAINING_PATTERN_DISABLE;
1625 
1626 	return drm_dp_dpcd_write_byte(&intel_dp->aux, reg, val) == 0;
1627 }
1628 
1629 static int
1630 intel_dp_128b132b_intra_hop(struct intel_dp *intel_dp,
1631 			    const struct intel_crtc_state *crtc_state)
1632 {
1633 	u8 sink_status;
1634 	int ret;
1635 
1636 	ret = drm_dp_dpcd_read_byte(&intel_dp->aux, DP_SINK_STATUS, &sink_status);
1637 	if (ret < 0) {
1638 		lt_dbg(intel_dp, DP_PHY_DPRX, "Failed to read sink status (%pe)\n",
1639 		       ERR_PTR(ret));
1640 		return ret;
1641 	}
1642 
1643 	return sink_status & DP_INTRA_HOP_AUX_REPLY_INDICATION ? 1 : 0;
1644 }
1645 
1646 static bool
1647 link_recovery_autoretrain_pending(struct intel_dp_link_training *link_training)
1648 {
1649 	return link_training->recovery_state == INTEL_DP_LINK_RECOVERY_AUTORETRAIN_PENDING;
1650 }
1651 
1652 /*
1653  * Automatic retraining is a driver-driven link recovery mechanism that
1654  * retrains the link with the current userspace provided modeset
1655  * configuration and link parameters.
1656  *
1657  * Autoretrain is allowed while the link configurations available for
1658  * retraining, i.e. those not disabled yet via fallback selection, still
1659  * make it possible to retrain the link for the current userspace provided
1660  * modeset configuration.
1661  *
1662  * Once automatic retraining is no longer allowed, userspace driven link
1663  * recovery via userspace notifications and userspace modesets takes over.
1664  *
1665  * See also:
1666  *   - DOC: DisplayPort link training
1667  */
1668 static bool
1669 link_recovery_autoretrain_allowed(struct intel_dp_link_training *link_training)
1670 {
1671 	switch (link_training->recovery_state) {
1672 	case INTEL_DP_LINK_RECOVERY_IDLE:
1673 	case INTEL_DP_LINK_RECOVERY_AUTORETRAIN_PENDING:
1674 		return true;
1675 	default:
1676 		return false;
1677 	}
1678 }
1679 
1680 static bool
1681 link_recovery_has_no_fallback(struct intel_dp_link_training *link_training)
1682 {
1683 	return link_training->recovery_state == INTEL_DP_LINK_RECOVERY_NO_FALLBACK;
1684 }
1685 
1686 /*
1687  * Record a link training failure and advance the recovery state to
1688  * indicate the next required recovery step.
1689  *
1690  * The caller must proceed with recovery as instructed by the return
1691  * value, either via automatic retraining or, once automatic retraining
1692  * is no longer possible, via userspace modesets after fallback
1693  * selection.
1694  *
1695  * Note that the error reported via this function is the error seen by
1696  * the link training failure handler proper after an actual link
1697  * training failure indicated by the sink device, and so the error and
1698  * corresponding actions required are distinct from an autoretrain
1699  * modeset failure. See link_recovery_mark_autoretrain_modeset_failure() to
1700  * report a modeset failure.
1701  *
1702  * See also:
1703  *   - DOC: DisplayPort link training
1704  */
1705 static bool
1706 link_recovery_mark_train_failure(struct intel_dp_link_training *link_training)
1707 {
1708 	switch (link_training->recovery_state) {
1709 	case INTEL_DP_LINK_RECOVERY_IDLE:
1710 		link_training->recovery_state = INTEL_DP_LINK_RECOVERY_AUTORETRAIN_PENDING;
1711 		break;
1712 	case INTEL_DP_LINK_RECOVERY_AUTORETRAIN_PENDING:
1713 		link_training->recovery_state = INTEL_DP_LINK_RECOVERY_AUTORETRAIN_DISABLED;
1714 		break;
1715 	default:
1716 		break;
1717 	}
1718 
1719 	return link_recovery_autoretrain_allowed(link_training);
1720 }
1721 
1722 /*
1723  * Record a failure of the autoretrain modeset before link training
1724  * itself could run.
1725  *
1726  * Note that the error reported via this function and the corresponding
1727  * expected actions are distinct from an actual link training failure:
1728  * the modeset failed before a link training attempt could be performed.
1729  * See link_recovery_mark_train_failure() to report an actual link
1730  * training failure.
1731  *
1732  * Update the state to indicate that further recovery is to be delegated to
1733  * userspace via a regular modeset.
1734  *
1735  * See also:
1736  *   - DOC: DisplayPort link training
1737  */
1738 static void
1739 link_recovery_mark_autoretrain_modeset_failure(struct intel_dp_link_training *link_training)
1740 {
1741 	if (link_recovery_autoretrain_allowed(link_training))
1742 		link_training->recovery_state = INTEL_DP_LINK_RECOVERY_AUTORETRAIN_DISABLED;
1743 }
1744 
1745 /* Record that no more link fallback configuration is available. */
1746 static void
1747 link_recovery_mark_no_fallback(struct intel_dp_link_training *link_training)
1748 {
1749 	link_training->recovery_state = INTEL_DP_LINK_RECOVERY_NO_FALLBACK;
1750 }
1751 
1752 /**
1753  * link_recovery_reset - reset the link recovery state
1754  * @link_training: link training state
1755  *
1756  * Reset the link recovery state to indicate that no link recovery is
1757  * required.
1758  */
1759 static void link_recovery_reset(struct intel_dp_link_training *link_training)
1760 {
1761 	link_training->recovery_state = INTEL_DP_LINK_RECOVERY_IDLE;
1762 }
1763 
1764 /**
1765  * intel_dp_stop_link_train - stop link training
1766  * @intel_dp: DP struct
1767  * @crtc_state: state for CRTC attached to the encoder
1768  *
1769  * Stop the link training of the @intel_dp port, disabling the training
1770  * pattern in the sink's DPCD, and disabling the test pattern symbol
1771  * generation on the port.
1772  *
1773  * What symbols are output on the port after this point is
1774  * platform specific: On DDI/VLV/CHV platforms it will be the idle pattern
1775  * with the pipe being disabled, on older platforms it's HW specific if/how an
1776  * idle pattern is generated, as the pipe is already enabled here for those.
1777  *
1778  * This function must be called after intel_dp_start_link_train().
1779  */
1780 void intel_dp_stop_link_train(struct intel_dp *intel_dp,
1781 			      const struct intel_crtc_state *crtc_state)
1782 {
1783 	struct intel_dp_link_training *link_training = intel_dp->link.training;
1784 	struct intel_display *display = to_intel_display(intel_dp);
1785 	struct intel_encoder *encoder = &dp_to_dig_port(intel_dp)->base;
1786 	int ret;
1787 
1788 	intel_dp->link.active = true;
1789 
1790 	intel_dp_program_link_training_pattern(intel_dp, crtc_state, DP_PHY_DPRX,
1791 					       DP_TRAINING_PATTERN_DISABLE);
1792 
1793 	if (intel_dp_is_uhbr(crtc_state)) {
1794 		ret = poll_timeout_us(ret = intel_dp_128b132b_intra_hop(intel_dp, crtc_state),
1795 				      ret == 0,
1796 				      500, 500 * 1000, false);
1797 		if (ret)
1798 			lt_dbg(intel_dp, DP_PHY_DPRX, "128b/132b intra-hop not clearing\n");
1799 	}
1800 
1801 	intel_hpd_unblock(encoder);
1802 
1803 	if (!display->hotplug.ignore_long_hpd &&
1804 	    link_recovery_autoretrain_allowed(link_training)) {
1805 		int delay_ms = link_recovery_autoretrain_pending(link_training) ? 0 : 2000;
1806 
1807 		intel_encoder_link_check_queue_work(encoder, delay_ms);
1808 	}
1809 }
1810 
1811 static bool
1812 intel_dp_link_train_phy(struct intel_dp *intel_dp,
1813 			const struct intel_crtc_state *crtc_state,
1814 			enum drm_dp_phy dp_phy)
1815 {
1816 	bool ret = false;
1817 
1818 	if (!intel_dp_link_training_clock_recovery(intel_dp, crtc_state, dp_phy))
1819 		goto out;
1820 
1821 	if (!intel_dp_link_training_channel_equalization(intel_dp, crtc_state, dp_phy))
1822 		goto out;
1823 
1824 	ret = true;
1825 
1826 out:
1827 	lt_dbg(intel_dp, dp_phy,
1828 	       "Link Training %s at link rate = %d, lane count = %d\n",
1829 	       ret ? "passed" : "failed",
1830 	       crtc_state->port_clock, crtc_state->lane_count);
1831 
1832 	return ret;
1833 }
1834 
1835 static bool intel_dp_can_link_train_fallback_for_edp(struct intel_dp *intel_dp,
1836 						     int link_rate,
1837 						     u8 lane_count)
1838 {
1839 	/* FIXME figure out what we actually want here */
1840 	const struct drm_display_mode *fixed_mode =
1841 		intel_panel_preferred_fixed_mode(intel_dp->attached_connector);
1842 	int mode_rate, max_rate;
1843 
1844 	mode_rate = intel_dp_link_required(link_rate, lane_count,
1845 					   fixed_mode->clock, fixed_mode->hdisplay,
1846 					   fxp_q4_from_int(18), 0);
1847 	max_rate = intel_dp_max_link_data_rate(intel_dp, link_rate, lane_count);
1848 	if (mode_rate > max_rate)
1849 		return false;
1850 
1851 	return true;
1852 }
1853 
1854 static bool reduce_link_params(struct intel_dp *intel_dp, const struct intel_crtc_state *crtc_state,
1855 			       int *new_link_rate, int *new_lane_count)
1856 {
1857 	struct intel_dp_link_caps *link_caps = intel_dp->link.caps;
1858 	bool is_mst = intel_crtc_has_type(crtc_state, INTEL_OUTPUT_DP_MST);
1859 	struct intel_dp_link_caps_order order =
1860 		intel_dp_link_caps_connector_fallback_order(is_mst);
1861 	struct intel_dp_link_config old_config = {
1862 		.rate = crtc_state->port_clock,
1863 		.lane_count = crtc_state->lane_count,
1864 	};
1865 	struct intel_dp_link_caps_iter iter;
1866 	struct intel_dp_link_config config;
1867 	bool old_found = false;
1868 	bool new_found = false;
1869 
1870 	intel_dp_link_caps_iter_start(&iter, link_caps, order, INTEL_DP_LINK_CAPS_FILTER_ALL);
1871 	for_each_dp_link_config(&iter, &config) {
1872 		if (!old_found) {
1873 			if (config.rate == old_config.rate &&
1874 			    config.lane_count == old_config.lane_count)
1875 				old_found = true;
1876 
1877 			continue;
1878 		}
1879 
1880 		*new_link_rate = config.rate;
1881 		*new_lane_count = config.lane_count;
1882 		new_found = true;
1883 
1884 		break;
1885 	}
1886 	intel_dp_link_caps_iter_end(&iter);
1887 
1888 	return new_found;
1889 }
1890 
1891 VISIBLE_IF_KUNIT
1892 int intel_dp_get_link_train_fallback_values(struct intel_dp *intel_dp,
1893 					    const struct intel_crtc_state *crtc_state)
1894 {
1895 	struct intel_display *display = to_intel_display(intel_dp);
1896 	struct intel_dp_link_caps *link_caps = intel_dp->link.caps;
1897 	struct intel_dp_link_config max_link_limits;
1898 	struct intel_dp_link_config current_config = {
1899 		.rate = crtc_state->port_clock,
1900 		.lane_count = crtc_state->lane_count,
1901 	};
1902 	int new_link_rate;
1903 	int new_lane_count;
1904 	int err = -1;
1905 
1906 	if (intel_dp_is_edp(intel_dp) && !intel_dp->use_max_params) {
1907 		lt_dbg(intel_dp, DP_PHY_DPRX,
1908 		       "Retrying Link training for eDP with max parameters\n");
1909 		intel_dp->use_max_params = true;
1910 		return 0;
1911 	}
1912 
1913 	/*
1914 	 * Temporarily reset the max link limit before selecting the fallback
1915 	 * config.
1916 	 *
1917 	 * After fallback, the current logic narrows the allowed configurations
1918 	 * to the selected config's rate and lane count. That can make a later
1919 	 * fallback candidate fall outside the current max_limit, so reset it
1920 	 * before searching.
1921 	 *
1922 	 * TODO: Constrain the allowed configurations by only disabling individual
1923 	 * configurations and remove setting maximum link parameters.
1924 	 */
1925 	intel_dp_link_caps_get_max_limits(link_caps, &max_link_limits);
1926 	intel_dp_link_caps_reset_max_limits(link_caps);
1927 
1928 	/*
1929 	 * TODO: Make fallback depend only on disabling the current config,
1930 	 * once max_limit no longer constrains the allowed config set. Then
1931 	 * disabling the current config will define the allowed configs for
1932 	 * the subsequent modeset, so there will be no need to select a
1933 	 * reduced config separately here.
1934 	 */
1935 	if (!reduce_link_params(intel_dp, crtc_state, &new_link_rate, &new_lane_count))
1936 		goto out_restore_max_limits;
1937 
1938 	if (intel_dp_is_edp(intel_dp) &&
1939 	    !intel_dp_can_link_train_fallback_for_edp(intel_dp, new_link_rate, new_lane_count)) {
1940 		lt_dbg(intel_dp, DP_PHY_DPRX,
1941 		       "Retrying Link training for eDP with same parameters\n");
1942 
1943 		err = 0;
1944 
1945 		goto out_restore_max_limits;
1946 	}
1947 
1948 	/*
1949 	 * Shouldn't fail: the current config was enabled, and reducing the
1950 	 * link parameters should still leave the fallback config allowed.
1951 	 */
1952 	if (drm_WARN_ON(display->drm,
1953 			!intel_dp_link_caps_disable_config(link_caps, &current_config)))
1954 		return -1;
1955 
1956 	lt_dbg(intel_dp, DP_PHY_DPRX,
1957 	       "Reducing link parameters from %dx%d to %dx%d\n",
1958 	       crtc_state->lane_count, crtc_state->port_clock,
1959 	       new_lane_count, new_link_rate);
1960 
1961 	max_link_limits.rate = new_link_rate;
1962 	max_link_limits.lane_count = new_lane_count;
1963 
1964 	err = 0;
1965 
1966 out_restore_max_limits:
1967 	/*
1968 	 * Shouldn't fail: setting max_limits can only fail if they drop below
1969 	 * the optionally forced rate/lane-count parameters, but the reduced
1970 	 * config was chosen to satisfy those constraints.
1971 	 */
1972 	if (drm_WARN_ON(display->drm,
1973 			!intel_dp_link_caps_set_max_limits(link_caps, &max_link_limits)))
1974 		err = -1;
1975 
1976 	return err;
1977 }
1978 
1979 static bool intel_dp_schedule_fallback_link_training(struct intel_atomic_state *state,
1980 						     struct intel_dp *intel_dp,
1981 						     const struct intel_crtc_state *crtc_state)
1982 {
1983 	struct intel_encoder *encoder = &dp_to_dig_port(intel_dp)->base;
1984 
1985 	if (!intel_digital_port_connected(&dp_to_dig_port(intel_dp)->base)) {
1986 		lt_dbg(intel_dp, DP_PHY_DPRX, "Link Training failed on disconnected sink.\n");
1987 		return true;
1988 	}
1989 
1990 	if (intel_dp->hobl_active) {
1991 		lt_dbg(intel_dp, DP_PHY_DPRX,
1992 		       "Link Training failed with HOBL active, not enabling it from now on\n");
1993 		intel_dp->hobl_failed = true;
1994 	} else if (intel_dp_get_link_train_fallback_values(intel_dp, crtc_state)) {
1995 		return false;
1996 	}
1997 
1998 	/* Schedule a Hotplug Uevent to userspace to start modeset */
1999 	intel_dp_queue_modeset_retry_for_link(state, encoder, crtc_state);
2000 
2001 	return true;
2002 }
2003 
2004 /* Perform the link training on all LTTPRs and the DPRX on a link. */
2005 static bool
2006 intel_dp_link_train_all_phys(struct intel_dp *intel_dp,
2007 			     const struct intel_crtc_state *crtc_state,
2008 			     int lttpr_count)
2009 {
2010 	bool ret = true;
2011 	int i;
2012 
2013 	for (i = lttpr_count - 1; i >= 0; i--) {
2014 		enum drm_dp_phy dp_phy = DP_PHY_LTTPR(i);
2015 
2016 		ret = intel_dp_link_train_phy(intel_dp, crtc_state, dp_phy);
2017 		intel_dp_disable_dpcd_training_pattern(intel_dp, dp_phy);
2018 
2019 		if (!ret)
2020 			break;
2021 	}
2022 
2023 	if (ret)
2024 		ret = intel_dp_link_train_phy(intel_dp, crtc_state, DP_PHY_DPRX);
2025 
2026 	intel_dp_disable_dpcd_training_pattern(intel_dp, DP_PHY_DPRX);
2027 	intel_dp->set_idle_link_train(intel_dp, crtc_state);
2028 
2029 	if (ret)
2030 		ret = intel_dp_post_lt_adj_req(intel_dp, crtc_state);
2031 
2032 	intel_dp_stop_post_lt_adj_req(intel_dp, crtc_state);
2033 
2034 	return ret;
2035 }
2036 
2037 /*
2038  * 128b/132b DP LANEx_EQ_DONE Sequence (DP 2.0 E11 3.5.2.16.1)
2039  */
2040 static bool
2041 intel_dp_128b132b_lane_eq(struct intel_dp *intel_dp,
2042 			  const struct intel_crtc_state *crtc_state)
2043 {
2044 	u8 link_status[DP_LINK_STATUS_SIZE];
2045 	int delay_us;
2046 	int try, max_tries = 20;
2047 	unsigned long deadline;
2048 	bool timeout = false;
2049 
2050 	/*
2051 	 * Reset signal levels. Start transmitting 128b/132b TPS1.
2052 	 *
2053 	 * Put DPRX and LTTPRs (if any) into intra-hop AUX mode by writing TPS1
2054 	 * in DP_TRAINING_PATTERN_SET.
2055 	 */
2056 	if (!intel_dp_reset_link_train(intel_dp, crtc_state, DP_PHY_DPRX,
2057 				       DP_TRAINING_PATTERN_1)) {
2058 		lt_err(intel_dp, DP_PHY_DPRX, "Failed to start 128b/132b TPS1\n");
2059 		return false;
2060 	}
2061 
2062 	delay_us = drm_dp_128b132b_read_aux_rd_interval(&intel_dp->aux);
2063 
2064 	/* Read the initial TX FFE settings. */
2065 	if (drm_dp_dpcd_read_link_status(&intel_dp->aux, link_status) < 0) {
2066 		lt_err(intel_dp, DP_PHY_DPRX, "Failed to read TX FFE presets\n");
2067 		return false;
2068 	}
2069 
2070 	/* Update signal levels and training set as requested. */
2071 	intel_dp_get_adjust_train(intel_dp, crtc_state, DP_PHY_DPRX, link_status);
2072 	if (!intel_dp_update_link_train(intel_dp, crtc_state, DP_PHY_DPRX)) {
2073 		lt_err(intel_dp, DP_PHY_DPRX, "Failed to set initial TX FFE settings\n");
2074 		return false;
2075 	}
2076 
2077 	/* Start transmitting 128b/132b TPS2. */
2078 	if (!intel_dp_set_link_train(intel_dp, crtc_state, DP_PHY_DPRX,
2079 				     DP_TRAINING_PATTERN_2)) {
2080 		lt_err(intel_dp, DP_PHY_DPRX, "Failed to start 128b/132b TPS2\n");
2081 		return false;
2082 	}
2083 
2084 	/* Time budget for the LANEx_EQ_DONE Sequence */
2085 	deadline = jiffies + msecs_to_jiffies_timeout(450);
2086 
2087 	for (try = 0; try < max_tries; try++) {
2088 		fsleep(delay_us);
2089 
2090 		if (drm_dp_dpcd_read_link_status(&intel_dp->aux, link_status) < 0) {
2091 			lt_err(intel_dp, DP_PHY_DPRX, "Failed to read link status\n");
2092 			return false;
2093 		}
2094 
2095 		if (drm_dp_128b132b_link_training_failed(link_status)) {
2096 			intel_dp_dump_link_status(intel_dp, DP_PHY_DPRX, link_status);
2097 			lt_err(intel_dp, DP_PHY_DPRX,
2098 			       "Downstream link training failure\n");
2099 			return false;
2100 		}
2101 
2102 		if (drm_dp_128b132b_lane_channel_eq_done(link_status, crtc_state->lane_count)) {
2103 			lt_dbg(intel_dp, DP_PHY_DPRX, "Lane channel eq done\n");
2104 			break;
2105 		}
2106 
2107 		if (timeout) {
2108 			intel_dp_dump_link_status(intel_dp, DP_PHY_DPRX, link_status);
2109 			lt_err(intel_dp, DP_PHY_DPRX, "Lane channel eq timeout\n");
2110 			return false;
2111 		}
2112 
2113 		if (time_after(jiffies, deadline))
2114 			timeout = true; /* try one last time after deadline */
2115 
2116 		/*
2117 		 * During LT, Tx shall read AUX_RD_INTERVAL just before writing the new FFE
2118 		 * presets.
2119 		 */
2120 		delay_us = drm_dp_128b132b_read_aux_rd_interval(&intel_dp->aux);
2121 
2122 		intel_dp_get_adjust_train(intel_dp, crtc_state, DP_PHY_DPRX, link_status);
2123 
2124 		/* Update signal levels and training set as requested. */
2125 		if (!intel_dp_update_link_train(intel_dp, crtc_state, DP_PHY_DPRX)) {
2126 			lt_err(intel_dp, DP_PHY_DPRX, "Failed to update TX FFE settings\n");
2127 			return false;
2128 		}
2129 	}
2130 
2131 	if (try == max_tries) {
2132 		intel_dp_dump_link_status(intel_dp, DP_PHY_DPRX, link_status);
2133 		lt_err(intel_dp, DP_PHY_DPRX, "Max loop count reached\n");
2134 		return false;
2135 	}
2136 
2137 	for (;;) {
2138 		if (time_after(jiffies, deadline))
2139 			timeout = true; /* try one last time after deadline */
2140 
2141 		if (drm_dp_dpcd_read_link_status(&intel_dp->aux, link_status) < 0) {
2142 			lt_err(intel_dp, DP_PHY_DPRX, "Failed to read link status\n");
2143 			return false;
2144 		}
2145 
2146 		if (drm_dp_128b132b_link_training_failed(link_status)) {
2147 			intel_dp_dump_link_status(intel_dp, DP_PHY_DPRX, link_status);
2148 			lt_err(intel_dp, DP_PHY_DPRX, "Downstream link training failure\n");
2149 			return false;
2150 		}
2151 
2152 		if (drm_dp_128b132b_eq_interlane_align_done(link_status)) {
2153 			lt_dbg(intel_dp, DP_PHY_DPRX, "Interlane align done\n");
2154 			break;
2155 		}
2156 
2157 		if (timeout) {
2158 			intel_dp_dump_link_status(intel_dp, DP_PHY_DPRX, link_status);
2159 			lt_err(intel_dp, DP_PHY_DPRX, "Interlane align timeout\n");
2160 			return false;
2161 		}
2162 
2163 		usleep_range(2000, 3000);
2164 	}
2165 
2166 	return true;
2167 }
2168 
2169 /*
2170  * 128b/132b DP LANEx_CDS_DONE Sequence (DP 2.0 E11 3.5.2.16.2)
2171  */
2172 static bool
2173 intel_dp_128b132b_lane_cds(struct intel_dp *intel_dp,
2174 			   const struct intel_crtc_state *crtc_state,
2175 			   int lttpr_count)
2176 {
2177 	u8 link_status[DP_LINK_STATUS_SIZE];
2178 	unsigned long deadline;
2179 	int ret;
2180 
2181 	ret = drm_dp_dpcd_write_byte(&intel_dp->aux, DP_TRAINING_PATTERN_SET,
2182 				     DP_TRAINING_PATTERN_2_CDS);
2183 	if (ret < 0) {
2184 		lt_err(intel_dp, DP_PHY_DPRX, "Failed to start 128b/132b TPS2 CDS (%pe)\n",
2185 		       ERR_PTR(ret));
2186 		return false;
2187 	}
2188 
2189 	/* Time budget for the LANEx_CDS_DONE Sequence */
2190 	deadline = jiffies + msecs_to_jiffies_timeout((lttpr_count + 1) * 20);
2191 
2192 	for (;;) {
2193 		bool timeout = false;
2194 
2195 		if (time_after(jiffies, deadline))
2196 			timeout = true; /* try one last time after deadline */
2197 
2198 		usleep_range(2000, 3000);
2199 
2200 		if (drm_dp_dpcd_read_link_status(&intel_dp->aux, link_status) < 0) {
2201 			lt_err(intel_dp, DP_PHY_DPRX, "Failed to read link status\n");
2202 			return false;
2203 		}
2204 
2205 		if (drm_dp_128b132b_eq_interlane_align_done(link_status) &&
2206 		    drm_dp_128b132b_cds_interlane_align_done(link_status) &&
2207 		    drm_dp_128b132b_lane_symbol_locked(link_status, crtc_state->lane_count)) {
2208 			lt_dbg(intel_dp, DP_PHY_DPRX, "CDS interlane align done\n");
2209 			break;
2210 		}
2211 
2212 		if (drm_dp_128b132b_link_training_failed(link_status)) {
2213 			intel_dp_dump_link_status(intel_dp, DP_PHY_DPRX, link_status);
2214 			lt_err(intel_dp, DP_PHY_DPRX, "Downstream link training failure\n");
2215 			return false;
2216 		}
2217 
2218 		if (timeout) {
2219 			intel_dp_dump_link_status(intel_dp, DP_PHY_DPRX, link_status);
2220 			lt_err(intel_dp, DP_PHY_DPRX, "CDS timeout\n");
2221 			return false;
2222 		}
2223 	}
2224 
2225 	return true;
2226 }
2227 
2228 /*
2229  * 128b/132b link training sequence. (DP 2.0 E11 SCR on link training.)
2230  */
2231 static bool
2232 intel_dp_128b132b_link_train(struct intel_dp *intel_dp,
2233 			     const struct intel_crtc_state *crtc_state,
2234 			     int lttpr_count)
2235 {
2236 	bool passed = false;
2237 	int ret;
2238 
2239 	ret = poll_timeout_us(ret = intel_dp_128b132b_intra_hop(intel_dp, crtc_state),
2240 			      ret == 0,
2241 			      500, 500 * 1000, false);
2242 	if (ret) {
2243 		lt_err(intel_dp, DP_PHY_DPRX, "128b/132b intra-hop not clear\n");
2244 		goto out;
2245 	}
2246 
2247 	if (intel_dp_128b132b_lane_eq(intel_dp, crtc_state) &&
2248 	    intel_dp_128b132b_lane_cds(intel_dp, crtc_state, lttpr_count))
2249 		passed = true;
2250 
2251 	lt_dbg(intel_dp, DP_PHY_DPRX,
2252 	       "128b/132b Link Training %s at link rate = %d, lane count = %d\n",
2253 	       passed ? "passed" : "failed",
2254 	       crtc_state->port_clock, crtc_state->lane_count);
2255 
2256 out:
2257 	/*
2258 	 * Ensure that the training pattern does get set to TPS2 even in case
2259 	 * of a failure, as is the case at the end of a passing link training
2260 	 * and what is expected by the transcoder. Leaving TPS1 set (and
2261 	 * disabling the link train mode in DP_TP_CTL later from TPS1 directly)
2262 	 * would result in a stuck transcoder HW state and flip-done timeouts
2263 	 * later in the modeset sequence.
2264 	 */
2265 	if (!passed)
2266 		intel_dp_program_link_training_pattern(intel_dp, crtc_state,
2267 						       DP_PHY_DPRX, DP_TRAINING_PATTERN_2);
2268 
2269 	intel_dp_disable_dpcd_training_pattern(intel_dp, DP_PHY_DPRX);
2270 
2271 	return passed;
2272 }
2273 
2274 /**
2275  * intel_dp_start_link_train - start link training
2276  * @state: Atomic state
2277  * @intel_dp: DP struct
2278  * @crtc_state: state for CRTC attached to the encoder
2279  *
2280  * Start the link training of the @intel_dp port, scheduling a fallback
2281  * retraining with reduced link rate/lane parameters if the link training
2282  * fails.
2283  * After calling this function intel_dp_stop_link_train() must be called.
2284  */
2285 void intel_dp_start_link_train(struct intel_atomic_state *state,
2286 			       struct intel_dp *intel_dp,
2287 			       const struct intel_crtc_state *crtc_state)
2288 {
2289 	struct intel_display *display = to_intel_display(state);
2290 	struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
2291 	struct intel_encoder *encoder = &dig_port->base;
2292 	struct intel_dp_link_training *link_training =
2293 		intel_dp->link.training;
2294 	bool autoretrain_allowed;
2295 	bool passed;
2296 	/*
2297 	 * Reinit the LTTPRs here to ensure that they are switched to
2298 	 * non-transparent mode. During an earlier LTTPR detection this
2299 	 * could've been prevented by an active link.
2300 	 */
2301 	int lttpr_count;
2302 
2303 	intel_hpd_block(encoder);
2304 
2305 	lttpr_count = intel_dp_init_lttpr_and_dprx_caps(intel_dp);
2306 
2307 	if (lttpr_count < 0)
2308 		/* Still continue with enabling the port and link training. */
2309 		lttpr_count = 0;
2310 
2311 	intel_dp_prepare_link_train(intel_dp, crtc_state);
2312 
2313 	if (intel_dp_is_uhbr(crtc_state))
2314 		passed = intel_dp_128b132b_link_train(intel_dp, crtc_state, lttpr_count);
2315 	else
2316 		passed = intel_dp_link_train_all_phys(intel_dp, crtc_state, lttpr_count);
2317 
2318 	if (link_training->force_train_failure) {
2319 		link_training->force_train_failure--;
2320 		lt_dbg(intel_dp, DP_PHY_DPRX, "Forcing link training failure\n");
2321 	} else if (passed) {
2322 		link_recovery_reset(link_training);
2323 		return;
2324 	}
2325 
2326 	autoretrain_allowed = link_recovery_mark_train_failure(link_training);
2327 
2328 	/*
2329 	 * Ignore the link failure in CI
2330 	 *
2331 	 * In fixed environments like CI, sometimes unexpected long HPDs are
2332 	 * generated by the displays. If ignore_long_hpd flag is set, such long
2333 	 * HPDs are ignored. And probably as a consequence of these ignored
2334 	 * long HPDs, subsequent link trainings are failed resulting into CI
2335 	 * execution failures.
2336 	 *
2337 	 * For test cases which rely on the link training or processing of HPDs
2338 	 * ignore_long_hpd flag can unset from the testcase.
2339 	 */
2340 	if (display->hotplug.ignore_long_hpd) {
2341 		lt_dbg(intel_dp, DP_PHY_DPRX, "Ignore the link failure\n");
2342 		return;
2343 	}
2344 
2345 	if (autoretrain_allowed)
2346 		return;
2347 
2348 	if (intel_dp_schedule_fallback_link_training(state, intel_dp, crtc_state))
2349 		return;
2350 
2351 	link_recovery_mark_no_fallback(link_training);
2352 
2353 	if (!passed)
2354 		lt_err(intel_dp, DP_PHY_DPRX, "Can't reduce link training parameters after failure\n");
2355 	else
2356 		lt_dbg(intel_dp, DP_PHY_DPRX, "Can't reduce link training parameters after forced failure\n");
2357 }
2358 
2359 void intel_dp_128b132b_sdp_crc16(struct intel_dp *intel_dp,
2360 				 const struct intel_crtc_state *crtc_state)
2361 {
2362 	/*
2363 	 * VIDEO_DIP_CTL register bit 31 should be set to '0' to not
2364 	 * disable SDP CRC. This is applicable for Display version 13.
2365 	 * Default value of bit 31 is '0' hence discarding the write
2366 	 * TODO: Corrective actions on SDP corruption yet to be defined
2367 	 */
2368 	if (!intel_dp_is_uhbr(crtc_state))
2369 		return;
2370 
2371 	/* DP v2.0 SCR on SDP CRC16 for 128b/132b Link Layer */
2372 	drm_dp_dpcd_write_byte(&intel_dp->aux,
2373 			       DP_SDP_ERROR_DETECTION_CONFIGURATION,
2374 			       DP_SDP_CRC16_128B132B_EN);
2375 
2376 	lt_dbg(intel_dp, DP_PHY_DPRX, "DP2.0 SDP CRC16 for 128b/132b enabled\n");
2377 }
2378 
2379 bool intel_dp_link_params_valid(struct intel_dp *intel_dp, int link_rate,
2380 				u8 lane_count)
2381 {
2382 	struct intel_dp_link_config max_link_limits;
2383 
2384 	/*
2385 	 * FIXME: we need to synchronize the current link parameters with
2386 	 * hardware readout. Currently fast link training doesn't work on
2387 	 * boot-up.
2388 	 *
2389 	 * NOTE:
2390 	 * This may be called from both serialized (locked and synced against
2391 	 * async commit tails) and unserialized (e.g. HPD IRQ) contexts. It
2392 	 * uses the current max link limits as upper bounds to reject
2393 	 * obviously bogus values, even if those bounds may be observed in a
2394 	 * transient or slightly stale state.
2395 	 *
2396 	 * This is not a full validation of the link configuration. Even in
2397 	 * serialized contexts, additional constraints (e.g. source limitations,
2398 	 * bandwidth checks, and other atomic state dependencies) are only
2399 	 * verified during the atomic check of the subsequent commit.
2400 	 *
2401 	 * max_link_limits only provides independent upper bounds for rate and
2402 	 * lane count. Callers must not assume it is itself an allowed link
2403 	 * configuration. Although that happens to be true for now, it will
2404 	 * stop being guaranteed once fallback depends only on disabled configs.
2405 	 */
2406 	intel_dp_link_caps_get_max_limits(intel_dp->link.caps, &max_link_limits);
2407 
2408 	if (link_rate == 0 ||
2409 	    link_rate > max_link_limits.rate)
2410 		return false;
2411 
2412 	if (lane_count == 0 ||
2413 	    lane_count > max_link_limits.lane_count)
2414 		return false;
2415 
2416 	return true;
2417 }
2418 
2419 static bool intel_dp_link_ok(struct intel_dp *intel_dp,
2420 			     u8 link_status[DP_LINK_STATUS_SIZE])
2421 {
2422 	struct intel_display *display = to_intel_display(intel_dp);
2423 	struct intel_encoder *encoder = &dp_to_dig_port(intel_dp)->base;
2424 	bool uhbr = intel_dp->link_rate >= 1000000;
2425 	bool ok;
2426 
2427 	if (uhbr)
2428 		ok = drm_dp_128b132b_lane_channel_eq_done(link_status,
2429 							  intel_dp->lane_count);
2430 	else
2431 		ok = drm_dp_channel_eq_ok(link_status, intel_dp->lane_count);
2432 
2433 	if (ok)
2434 		return true;
2435 
2436 	intel_dp_dump_link_status(intel_dp, DP_PHY_DPRX, link_status);
2437 	drm_dbg_kms(display->drm,
2438 		    "[ENCODER:%d:%s] %s link not ok, retraining\n",
2439 		    encoder->base.base.id, encoder->base.name,
2440 		    uhbr ? "128b/132b" : "8b/10b");
2441 
2442 	return false;
2443 }
2444 
2445 static int
2446 intel_dp_read_link_status(struct intel_dp *intel_dp, u8 link_status[DP_LINK_STATUS_SIZE])
2447 {
2448 	int err;
2449 
2450 	memset(link_status, 0, DP_LINK_STATUS_SIZE);
2451 
2452 	if (intel_dp_mst_active_streams(intel_dp) > 0)
2453 		err = drm_dp_dpcd_read_data(&intel_dp->aux, DP_LANE0_1_STATUS_ESI,
2454 					    link_status, DP_LINK_STATUS_SIZE - 2);
2455 	else
2456 		err = drm_dp_dpcd_read_phy_link_status(&intel_dp->aux, DP_PHY_DPRX,
2457 						       link_status);
2458 
2459 	if (err)
2460 		return err;
2461 
2462 	if (link_status[DP_LANE_ALIGN_STATUS_UPDATED - DP_LANE0_1_STATUS] &
2463 	    DP_DOWNSTREAM_PORT_STATUS_CHANGED)
2464 		WRITE_ONCE(intel_dp->downstream_port_changed, true);
2465 
2466 	return 0;
2467 }
2468 
2469 bool intel_dp_link_training_get_force_retrain(struct intel_dp_link_training *link_training)
2470 {
2471 	return link_training->force_retrain;
2472 }
2473 
2474 static void intel_dp_link_training_set_force_retrain(struct intel_dp_link_training *link_training,
2475 						     bool forced)
2476 {
2477 	link_training->force_retrain = forced;
2478 }
2479 
2480 static bool
2481 intel_dp_needs_link_retrain(struct intel_dp *intel_dp)
2482 {
2483 	struct intel_dp_link_training *link_training = intel_dp->link.training;
2484 	u8 link_status[DP_LINK_STATUS_SIZE];
2485 
2486 	if (!intel_dp->link.active)
2487 		return false;
2488 
2489 	/*
2490 	 * While PSR source HW is enabled, it will control main-link sending
2491 	 * frames, enabling and disabling it so trying to do a retrain will fail
2492 	 * as the link would or not be on or it could mix training patterns
2493 	 * and frame data at the same time causing retrain to fail.
2494 	 * Also when exiting PSR, HW will retrain the link anyways fixing
2495 	 * any link status error.
2496 	 */
2497 	if (intel_psr_enabled(intel_dp))
2498 		return false;
2499 
2500 	if (intel_dp_link_training_get_force_retrain(link_training))
2501 		return true;
2502 
2503 	if (intel_dp_read_link_status(intel_dp, link_status) < 0)
2504 		return false;
2505 
2506 	/*
2507 	 * Validate the cached values of intel_dp->link_rate and
2508 	 * intel_dp->lane_count before attempting to retrain.
2509 	 *
2510 	 * FIXME would be nice to user the crtc state here, but since
2511 	 * we need to call this from the short HPD handler that seems
2512 	 * a bit hard.
2513 	 */
2514 	if (!intel_dp_link_params_valid(intel_dp, intel_dp->link_rate,
2515 					intel_dp->lane_count))
2516 		return false;
2517 
2518 	if (!link_recovery_autoretrain_allowed(link_training))
2519 		return false;
2520 
2521 	if (link_recovery_autoretrain_pending(link_training))
2522 		return true;
2523 
2524 	/* Retrain if link not ok */
2525 	return !intel_dp_link_ok(intel_dp, link_status) &&
2526 		!intel_psr_link_ok(intel_dp);
2527 }
2528 
2529 static bool intel_dp_is_connected(struct intel_dp *intel_dp)
2530 {
2531 	struct intel_connector *connector = intel_dp->attached_connector;
2532 
2533 	return connector->base.status == connector_status_connected ||
2534 		intel_dp->is_mst;
2535 }
2536 
2537 static void queue_modeset_retry_for_links_in_state(struct intel_atomic_state *state,
2538 						   struct intel_encoder *encoder,
2539 						   u8 pipe_mask)
2540 {
2541 	const struct intel_crtc_state *crtc_state;
2542 	struct intel_crtc *crtc;
2543 
2544 	for_each_new_intel_crtc_in_state(state, crtc, crtc_state) {
2545 		if (!(BIT(crtc->pipe) & pipe_mask))
2546 			continue;
2547 
2548 		intel_dp_queue_modeset_retry_for_link(state, encoder, crtc_state);
2549 	}
2550 }
2551 
2552 static int intel_dp_retrain_link(struct intel_encoder *encoder,
2553 				 struct drm_modeset_acquire_ctx *ctx)
2554 {
2555 	struct intel_display *display = to_intel_display(encoder);
2556 	struct intel_dp *intel_dp = enc_to_intel_dp(encoder);
2557 	struct intel_dp_link_training *link_training =
2558 		intel_dp->link.training;
2559 	struct intel_atomic_state *state;
2560 	struct drm_atomic_commit *_state;
2561 	u8 pipe_mask;
2562 	int ret;
2563 
2564 	if (!intel_dp_is_connected(intel_dp))
2565 		return 0;
2566 
2567 	ret = drm_modeset_lock(&display->drm->mode_config.connection_mutex,
2568 			       ctx);
2569 	if (ret)
2570 		return ret;
2571 
2572 	if (!intel_dp_needs_link_retrain(intel_dp))
2573 		return 0;
2574 
2575 	ret = intel_dp_get_active_pipes(intel_dp, ctx, &pipe_mask);
2576 	if (ret)
2577 		return ret;
2578 
2579 	if (pipe_mask == 0)
2580 		return 0;
2581 
2582 	if (!intel_dp_needs_link_retrain(intel_dp))
2583 		return 0;
2584 
2585 	drm_dbg_kms(display->drm,
2586 		    "[ENCODER:%d:%s] retraining link (forced %s)\n",
2587 		    encoder->base.base.id, encoder->base.name,
2588 		    str_yes_no(intel_dp_link_training_get_force_retrain(link_training)));
2589 
2590 	_state = drm_atomic_commit_alloc(display->drm);
2591 	if (!_state)
2592 		return -ENOMEM;
2593 
2594 	state = to_intel_atomic_state(_state);
2595 
2596 	ret = intel_modeset_commit_pipes_for_atomic_state(state, pipe_mask, ctx);
2597 	if (ret == -EDEADLK)
2598 		goto out;
2599 
2600 	intel_dp_link_training_set_force_retrain(link_training, false);
2601 
2602 	if (ret) {
2603 		drm_dbg_kms(display->drm,
2604 			    "[ENCODER:%d:%s] link retraining failed: %pe\n",
2605 			    encoder->base.base.id, encoder->base.name,
2606 			    ERR_PTR(ret));
2607 		/*
2608 		 * intel_dp_needs_link_retrain() only performs a coarse check of
2609 		 * retrainability, so the modeset commit may still fail. Disable
2610 		 * further auto-retrain attempts in that case.
2611 		 *
2612 		 * A sink capability change may restore the retrainable state (see
2613 		 * intel_dp_update_sink_caps(), intel_dp_reset_link_params()),
2614 		 * allowing retraining to be attempted again.
2615 		 */
2616 		link_recovery_mark_autoretrain_modeset_failure(link_training);
2617 		queue_modeset_retry_for_links_in_state(state, encoder, pipe_mask);
2618 	}
2619 out:
2620 	drm_atomic_commit_put(&state->base);
2621 
2622 	return ret;
2623 }
2624 
2625 void intel_dp_link_check(struct intel_encoder *encoder)
2626 {
2627 	struct drm_modeset_acquire_ctx ctx;
2628 	int ret;
2629 
2630 	intel_modeset_lock_ctx_retry(&ctx, NULL, 0, ret)
2631 		ret = intel_dp_retrain_link(encoder, &ctx);
2632 }
2633 
2634 void intel_dp_check_link_state(struct intel_dp *intel_dp)
2635 {
2636 	struct intel_digital_port *dig_port = dp_to_dig_port(intel_dp);
2637 	struct intel_encoder *encoder = &dig_port->base;
2638 
2639 	if (!intel_dp_is_connected(intel_dp))
2640 		return;
2641 
2642 	/*
2643 	 * NOTE:
2644 	 * This may race with an ongoing modeset updating the max link limits
2645 	 * and, with that, the link's retrainability, so
2646 	 * intel_dp_needs_link_retrain() may observe stale state.
2647 	 *
2648 	 * This is harmless: stale params captured as valid may spuriously
2649 	 * allow retraining here, but the decision is rechecked later in a
2650 	 * properly serialized context.
2651 	 *
2652 	 * Conversely, stale params captured as invalid may skip retraining,
2653 	 * but that can only happen before the modeset has completed its own
2654 	 * link training for the new, valid configuration, after which the
2655 	 * link state is rechecked.
2656 	 *
2657 	 * See intel_dp_link_params_valid() for capturing and validating the
2658 	 * params.
2659 	 */
2660 	if (!intel_dp_needs_link_retrain(intel_dp))
2661 		return;
2662 
2663 	intel_encoder_link_check_queue_work(encoder, 0);
2664 }
2665 
2666 static int i915_dp_force_link_training_failure_show(void *data, u64 *val)
2667 {
2668 	struct intel_connector *connector = to_intel_connector(data);
2669 	struct intel_display *display = to_intel_display(connector);
2670 	struct intel_dp_link_training *link_training = connector_to_link_training(connector);
2671 	int err;
2672 
2673 	err = drm_modeset_lock_single_interruptible(&display->drm->mode_config.connection_mutex);
2674 	if (err)
2675 		return err;
2676 
2677 	intel_dp_flush_connector_commits(connector);
2678 
2679 	*val = link_training->force_train_failure;
2680 
2681 	drm_modeset_unlock(&display->drm->mode_config.connection_mutex);
2682 
2683 	return 0;
2684 }
2685 
2686 static int i915_dp_force_link_training_failure_write(void *data, u64 val)
2687 {
2688 	struct intel_connector *connector = to_intel_connector(data);
2689 	struct intel_display *display = to_intel_display(connector);
2690 	struct intel_dp_link_training *link_training = connector_to_link_training(connector);
2691 	int err;
2692 
2693 	if (val > 2)
2694 		return -EINVAL;
2695 
2696 	err = drm_modeset_lock_single_interruptible(&display->drm->mode_config.connection_mutex);
2697 	if (err)
2698 		return err;
2699 
2700 	intel_dp_flush_connector_commits(connector);
2701 
2702 	link_training->force_train_failure = val;
2703 
2704 	drm_modeset_unlock(&display->drm->mode_config.connection_mutex);
2705 
2706 	return 0;
2707 }
2708 DEFINE_DEBUGFS_ATTRIBUTE(i915_dp_force_link_training_failure_fops,
2709 			 i915_dp_force_link_training_failure_show,
2710 			 i915_dp_force_link_training_failure_write, "%llu\n");
2711 
2712 static int i915_dp_force_link_retrain_show(void *data, u64 *val)
2713 {
2714 	struct intel_connector *connector = to_intel_connector(data);
2715 	struct intel_display *display = to_intel_display(connector);
2716 	struct intel_dp_link_training *link_training = connector_to_link_training(connector);
2717 	int err;
2718 
2719 	err = drm_modeset_lock_single_interruptible(&display->drm->mode_config.connection_mutex);
2720 	if (err)
2721 		return err;
2722 
2723 	intel_dp_flush_connector_commits(connector);
2724 
2725 	*val = intel_dp_link_training_get_force_retrain(link_training);
2726 
2727 	drm_modeset_unlock(&display->drm->mode_config.connection_mutex);
2728 
2729 	return 0;
2730 }
2731 
2732 static int i915_dp_force_link_retrain_write(void *data, u64 val)
2733 {
2734 	struct intel_connector *connector = to_intel_connector(data);
2735 	struct intel_display *display = to_intel_display(connector);
2736 	struct intel_dp_link_training *link_training = connector_to_link_training(connector);
2737 	struct intel_dp *intel_dp = link_training->dp;
2738 	int err;
2739 
2740 	err = drm_modeset_lock_single_interruptible(&display->drm->mode_config.connection_mutex);
2741 	if (err)
2742 		return err;
2743 
2744 	intel_dp_flush_connector_commits(connector);
2745 
2746 	intel_dp_link_training_set_force_retrain(link_training, val);
2747 
2748 	drm_modeset_unlock(&display->drm->mode_config.connection_mutex);
2749 
2750 	intel_hpd_trigger_irq(dp_to_dig_port(intel_dp));
2751 
2752 	return 0;
2753 }
2754 DEFINE_DEBUGFS_ATTRIBUTE(i915_dp_force_link_retrain_fops,
2755 			 i915_dp_force_link_retrain_show,
2756 			 i915_dp_force_link_retrain_write, "%llu\n");
2757 
2758 static int i915_dp_link_retrain_disabled_show(struct seq_file *m, void *data)
2759 {
2760 	struct intel_connector *connector = to_intel_connector(m->private);
2761 	struct intel_display *display = to_intel_display(connector);
2762 	struct intel_dp_link_training *link_training = connector_to_link_training(connector);
2763 	int err;
2764 
2765 	err = drm_modeset_lock_single_interruptible(&display->drm->mode_config.connection_mutex);
2766 	if (err)
2767 		return err;
2768 
2769 	intel_dp_flush_connector_commits(connector);
2770 
2771 	/* TODO: Expose this via a debugfs entry reflecting what the state represents. */
2772 	seq_printf(m, "%s\n", str_yes_no(link_recovery_has_no_fallback(link_training)));
2773 
2774 	drm_modeset_unlock(&display->drm->mode_config.connection_mutex);
2775 
2776 	return 0;
2777 }
2778 DEFINE_SHOW_ATTRIBUTE(i915_dp_link_retrain_disabled);
2779 
2780 void intel_dp_link_training_debugfs_add(struct intel_connector *connector)
2781 {
2782 	struct dentry *root = connector->base.debugfs_entry;
2783 
2784 	if (connector->base.connector_type != DRM_MODE_CONNECTOR_DisplayPort &&
2785 	    connector->base.connector_type != DRM_MODE_CONNECTOR_eDP)
2786 		return;
2787 
2788 	debugfs_create_file("i915_dp_force_link_training_failure", 0644, root,
2789 			    connector, &i915_dp_force_link_training_failure_fops);
2790 
2791 	debugfs_create_file("i915_dp_force_link_retrain", 0644, root,
2792 			    connector, &i915_dp_force_link_retrain_fops);
2793 
2794 	debugfs_create_file("i915_dp_link_retrain_disabled", 0444, root,
2795 			    connector, &i915_dp_link_retrain_disabled_fops);
2796 }
2797 
2798 void intel_dp_link_training_reset(struct intel_dp_link_training *link_training)
2799 {
2800 	link_recovery_reset(link_training);
2801 }
2802 
2803 struct intel_dp_link_training *intel_dp_link_training_init(struct intel_dp *intel_dp)
2804 {
2805 	struct intel_dp_link_training *link_training;
2806 
2807 	link_training = kzalloc_obj(*link_training);
2808 	if (!link_training)
2809 		return NULL;
2810 
2811 	link_training->dp = intel_dp;
2812 
2813 	return link_training;
2814 }
2815 
2816 void intel_dp_link_training_cleanup(struct intel_dp_link_training *link_training)
2817 {
2818 	kfree(link_training);
2819 }
2820 
2821 #if IS_ENABLED(CONFIG_KUNIT)
2822 
2823 #define __INIT_MEMBER(__name, __fn) \
2824 	.__name = __fn,
2825 
2826 #define INTEL_DP_LINK_TRAINING_TEST_OPS_INIT \
2827 	INTEL_DP_LINK_TRAINING_TEST_OPS_MEMBERS(__INIT_MEMBER)
2828 
2829 #ifdef I915
2830 
2831 const struct intel_dp_link_training_test_ops i915_display_dp_link_training_test_ops = {
2832 	INTEL_DP_LINK_TRAINING_TEST_OPS_INIT
2833 };
2834 EXPORT_SYMBOL_IF_KUNIT(i915_display_dp_link_training_test_ops);
2835 
2836 #else
2837 
2838 const struct intel_dp_link_training_test_ops intel_display_dp_link_training_test_ops = {
2839 	INTEL_DP_LINK_TRAINING_TEST_OPS_INIT
2840 };
2841 EXPORT_SYMBOL_IF_KUNIT(intel_display_dp_link_training_test_ops);
2842 
2843 #endif	/* I915 */
2844 
2845 #undef INTEL_DP_LINK_TRAINING_TEST_OPS_INIT
2846 #undef __INIT_MEMBER
2847 
2848 #endif	/* CONFIG_KUNIT */
2849