spiritlevel 0.2.0

TMDS link bring-up for HDMI sources: clock ratio, scrambling and sink configuration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
//! Bring-up: start the TMDS link [`TmdsLinkParams`] describes, in stages: the work before
//! both paths (the FRL clear and `Source_Version`), then the main path (output, the sink's
//! `TMDS_Config`, the PHY, the wait, output on).

use core::time::Duration;

use hdmi_hal::ddc::{DdcError, DdcErrorKind};
use hdmi_hal::phy::{TmdsPhyConfig, TmdsVideo};
use hdmi_hal::time::Timestamp;

use crate::config::{
    BringUpConfig, ClearFrl, OnTmdsConfigFailure, OutputDuringSinkWrite, SinkPresence,
    SourceVersionWrite, TmdsConfigWrite,
};
use crate::error::UpdateError;
use crate::event::{
    CancelPoint, FrlClearSkip, SourceVersionSkip, TmdsConfigSkip, TmdsEvent, TmdsEventKind,
    TmdsStep,
};
use crate::outcome::{
    BringUpError, BringUpOutcome, BringUpWarning, CheckResult, Cleanup, LinkUp, OutputState,
    ScramblingCheck, Warnings,
};
use crate::params::TmdsLinkParams;

use super::check::scrambling_check;
use super::{TmdsIo, tear_down};

/// A step that stopped the bring-up, and its error.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Stop<S> {
    pub(crate) step: TmdsStep,
    pub(crate) error: S,
}

/// Whether an error may pass: everything but a bus that is gone (`Detached`) or a request
/// that cannot be done (`Unsupported`). A kind added later counts as transient.
pub(crate) fn transient(kind: DdcErrorKind) -> bool {
    !matches!(kind, DdcErrorKind::Detached | DdcErrorKind::Unsupported)
}

/// A failed SCDC step before both paths: a warning, whatever the error's kind.
fn failed<Io: TmdsIo, E: DdcError>(
    io: &Io,
    emit: &mut impl FnMut(&Io, TmdsEventKind),
    step: TmdsStep,
    error: E,
    warning: impl FnOnce(E) -> BringUpWarning<Io::ScdcError>,
    warnings: &mut Warnings<Io::ScdcError>,
) {
    let kind = error.kind();
    emit(
        io,
        TmdsEventKind::ScdcStepFailed {
            step,
            kind,
            ends: false,
        },
    );
    warnings.push(warning(error));
}

/// Why the work before both paths or the sink's write ended early: a step's stop, or the
/// cancel flag.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Halt<S> {
    Stop(Stop<S>),
    Cancelled(CancelPoint),
}

impl<S> From<Stop<S>> for Halt<S> {
    fn from(stop: Stop<S>) -> Self {
        Self::Stop(stop)
    }
}

impl<S> From<CancelPoint> for Halt<S> {
    fn from(at: CancelPoint) -> Self {
        Self::Cancelled(at)
    }
}

impl<S> Halt<S> {
    /// The failure, with the output's state at a stop.
    fn into_failure<P>(self, output: OutputState) -> Failure<S, P> {
        match self {
            Self::Stop(stop) => Failure::Scdc(stop, output),
            Self::Cancelled(at) => Failure::Cancelled(at),
        }
    }
}

/// `Err(at)` when the caller's cancel flag is set.
fn checkpoint<Io: TmdsIo>(io: &Io, at: CancelPoint) -> Result<(), CancelPoint> {
    if io.cancelled() { Err(at) } else { Ok(()) }
}

/// The work before both paths, in order: the FRL clear (`Config_1`, then `FLT_update`) when
/// the settings give it, then `Source_Version`. Nothing on a sink without SCDC. A failed
/// step is a warning whatever the error's kind, as no source treats one as fatal: a bus
/// that is gone (`Detached`) fails the `TMDS_Config` write that follows, which stops the
/// bring-up, and a request the implementation cannot do (`Unsupported`) does not block the
/// link. The cancel flag is read before each step.
pub(crate) async fn before_both_paths<Io: TmdsIo>(
    io: &mut Io,
    link: &TmdsLinkParams,
    config: &BringUpConfig,
    warnings: &mut Warnings<Io::ScdcError>,
    emit: &mut impl FnMut(&Io, TmdsEventKind),
) -> Result<(), Halt<Io::ScdcError>> {
    let sink = link.sink();

    let clear = match config.clear_frl {
        _ if !sink.scdc_present => Err(FrlClearSkip::NoScdc),
        ClearFrl::EveryScdcSink => Ok(()),
        ClearFrl::IfSinkDeclaresFrl if sink.frl_capable => Ok(()),
        _ => Err(FrlClearSkip::SinkDeclaresNoFrl),
    };
    match clear {
        Err(reason) => emit(io, TmdsEventKind::FrlClearSkipped { reason }),
        Ok(()) => {
            checkpoint(io, CancelPoint::Step(TmdsStep::ClearFrlRate))?;
            match io.clear_frl_rate().await {
                Ok(()) => emit(io, TmdsEventKind::FrlRateCleared),
                Err(e) => failed(
                    io,
                    emit,
                    TmdsStep::ClearFrlRate,
                    e,
                    BringUpWarning::FrlRateClearFailed,
                    warnings,
                ),
            }
            checkpoint(io, CancelPoint::Step(TmdsStep::ClearFltUpdate))?;
            match io.clear_flt_update().await {
                Ok(was_set) => emit(io, TmdsEventKind::FltUpdateCleared { was_set }),
                Err(e) => failed(
                    io,
                    emit,
                    TmdsStep::ClearFltUpdate,
                    e,
                    BringUpWarning::FltUpdateClearFailed,
                    warnings,
                ),
            }
        }
    }

    let skip = |reason| TmdsEventKind::SourceVersionSkipped { reason };
    if !sink.scdc_present {
        emit(io, skip(SourceVersionSkip::NoScdc));
        return Ok(());
    }
    let reads_version = match config.source_version {
        SourceVersionWrite::EveryBringUp => false,
        SourceVersionWrite::IfSinkVersion1 => true,
        SourceVersionWrite::WhenScrambling if link.scrambling() => true,
        SourceVersionWrite::WhenScrambling => {
            emit(io, skip(SourceVersionSkip::NotScrambled));
            return Ok(());
        }
        _ => {
            emit(io, skip(SourceVersionSkip::Never));
            return Ok(());
        }
    };
    if reads_version {
        checkpoint(io, CancelPoint::Step(TmdsStep::SinkVersion))?;
        let version = match io.read_sink_version().await {
            Ok(version) => version,
            Err(e) => {
                failed(
                    io,
                    emit,
                    TmdsStep::SinkVersion,
                    e,
                    BringUpWarning::SinkVersionReadFailed,
                    warnings,
                );
                emit(io, skip(SourceVersionSkip::SinkVersionUnread));
                return Ok(());
            }
        };
        emit(io, TmdsEventKind::SinkVersionRead { version });
        let due = match config.source_version {
            SourceVersionWrite::IfSinkVersion1 => version == 1,
            _ => version != 0,
        };
        if !due {
            emit(io, skip(SourceVersionSkip::SinkVersion { version }));
            return Ok(());
        }
    }
    checkpoint(io, CancelPoint::Step(TmdsStep::SourceVersion))?;
    match io.write_source_version(1).await {
        Ok(()) => emit(io, TmdsEventKind::SourceVersionWritten { version: 1 }),
        Err(e) => failed(
            io,
            emit,
            TmdsStep::SourceVersion,
            e,
            BringUpWarning::SourceVersionWriteFailed,
            warnings,
        ),
    }
    Ok(())
}

/// Why a bring-up stopped, before the cleanup: a step, its error, and the output's state;
/// or the cancel flag, and where it was seen.
enum Failure<S, P> {
    Scdc(Stop<S>, OutputState),
    Phy(TmdsStep, P, OutputState),
    Cancelled(CancelPoint),
}

impl<S, P> From<CancelPoint> for Failure<S, P> {
    fn from(at: CancelPoint) -> Self {
        Self::Cancelled(at)
    }
}

/// What the main path produced, for `LinkUp`.
struct Up<S> {
    sink_written_at: Option<Timestamp>,
    output_started_at: Timestamp,
    check: ScramblingCheck<S>,
}

/// Records `kind` at the I/O's time.
fn emit<Io: TmdsIo, F: FnMut(TmdsEvent)>(io: &Io, record: &mut F, kind: TmdsEventKind) {
    record(TmdsEvent::new(io.now(), kind));
}

/// A PHY call's error as a failure, recorded.
fn phy_failed<Io: TmdsIo, F: FnMut(TmdsEvent)>(
    io: &Io,
    record: &mut F,
    step: TmdsStep,
    error: Io::PhyError,
    output: OutputState,
) -> Failure<Io::ScdcError, Io::PhyError> {
    emit(
        io,
        record,
        TmdsEventKind::PhyStepFailed { step, ends: true },
    );
    Failure::Phy(step, error, output)
}

/// Writes the sink's `TMDS_Config` when a write is due: the time of the write (`None` when
/// none was due, or when the read of a read-modify-write failed, so nothing was written),
/// or the stop. A transient failure under `CarryOn` is a warning; on a plain
/// link it reads the register back. The cancel flag is read before the write and the read.
async fn write_sink<Io: TmdsIo, F: FnMut(TmdsEvent)>(
    io: &mut Io,
    link: &TmdsLinkParams,
    config: &BringUpConfig,
    warnings: &mut Warnings<Io::ScdcError>,
    record: &mut F,
) -> Result<Option<Timestamp>, Halt<Io::ScdcError>> {
    let Some(value) = link.sink_config() else {
        let reason = if link.sink().scdc_present {
            TmdsConfigSkip::Gate
        } else {
            TmdsConfigSkip::NoScdc
        };
        emit(io, record, TmdsEventKind::TmdsConfigSkipped { reason });
        return Ok(None);
    };
    checkpoint(io, CancelPoint::Step(TmdsStep::WriteTmdsConfig))?;
    let result = match config.tmds_config_write {
        TmdsConfigWrite::WholeByte => io
            .write_tmds_config(value)
            .await
            .map_err(UpdateError::Write),
        _ => io.update_tmds_config(value).await,
    };
    let written_at = io.now();
    let error = match result {
        Ok(()) => {
            emit(
                io,
                record,
                TmdsEventKind::TmdsConfigWritten { config: value },
            );
            return Ok(Some(written_at));
        }
        Err(failure) => failure,
    };
    // The step names the half: a read-modify-write whose read failed wrote nothing.
    let step = match error {
        UpdateError::Read(_) => TmdsStep::ReadTmdsConfig,
        UpdateError::Write(_) => TmdsStep::WriteTmdsConfig,
    };
    let kind = error.kind();
    let ends = !transient(kind) || config.on_tmds_config_failure == OnTmdsConfigFailure::Stop;
    let wrote = matches!(error, UpdateError::Write(_));
    emit(
        io,
        record,
        TmdsEventKind::ScdcStepFailed { step, kind, ends },
    );
    if ends {
        return Err(Stop {
            step,
            error: error.into_inner(),
        }
        .into());
    }
    // A plain link has no scrambling check: read the register back so a sink that kept
    // 1/40 after a failed clear does not go unnoticed.
    let read_back = if link.scrambling() {
        None
    } else {
        if io.cancelled() {
            warnings.push(BringUpWarning::TmdsConfigWriteFailed {
                error,
                read_back: None,
            });
            return Err(CancelPoint::Step(TmdsStep::ReadTmdsConfig).into());
        }
        let read = io.read_tmds_config().await;
        match &read {
            Ok(reading) => emit(
                io,
                record,
                TmdsEventKind::TmdsConfigRead { reading: *reading },
            ),
            Err(e) => emit(
                io,
                record,
                TmdsEventKind::ScdcStepFailed {
                    step: TmdsStep::ReadTmdsConfig,
                    kind: e.kind(),
                    ends: false,
                },
            ),
        }
        Some(read)
    };
    warnings.push(BringUpWarning::TmdsConfigWriteFailed { error, read_back });
    // A failed write may have reached the sink, so the wait and the deadline run from it;
    // a failed read wrote nothing.
    Ok(wrote.then_some(written_at))
}

/// Spends what is left of the ratio wait after the write at `written_at`; nothing when no
/// write was made. The wait is spent in slices of at most `slice` (the check interval;
/// one slice when it is 0), with the cancel flag read before each, so a cancel is seen
/// within one interval whatever the wait; with an interval of 0, only before the wait.
async fn wait_after<Io: TmdsIo, F: FnMut(TmdsEvent)>(
    io: &mut Io,
    written_at: Option<Timestamp>,
    wait: Duration,
    slice: Duration,
    record: &mut F,
) -> Result<(), CancelPoint> {
    let Some(written_at) = written_at else {
        return Ok(());
    };
    let left = wait.saturating_sub(io.now().saturating_duration_since(written_at));
    let slice = if slice.is_zero() { left } else { slice };
    let mut remaining = left;
    loop {
        checkpoint(io, CancelPoint::RatioWait)?;
        if remaining.is_zero() {
            break;
        }
        let next = remaining.min(slice);
        io.delay(next).await;
        remaining -= next;
    }
    emit(io, record, TmdsEventKind::WaitSpent { duration: left });
    Ok(())
}

/// The main path in the default order: output off, the sink's write, the PHY with its
/// scrambler, the wait, output on.
async fn main_path<Io: TmdsIo, F: FnMut(TmdsEvent)>(
    io: &mut Io,
    link: &TmdsLinkParams,
    phy: TmdsPhyConfig,
    config: &BringUpConfig,
    warnings: &mut Warnings<Io::ScdcError>,
    record: &mut F,
) -> Result<Up<Io::ScdcError>, Failure<Io::ScdcError, Io::PhyError>> {
    let scrambled = link.scrambling();
    let running = config.output_during_sink_write == OutputDuringSinkWrite::Running;

    if let Err(e) = io.stop_output().await {
        return Err(phy_failed(
            io,
            record,
            TmdsStep::StopOutput,
            e,
            OutputState::MayBeRunning,
        ));
    }
    emit(io, record, TmdsEventKind::OutputStopped);

    if !running {
        let written_at = write_sink(io, link, config, warnings, record)
            .await
            .map_err(|halt| halt.into_failure(OutputState::Stopped))?;
        configure(io, phy, record).await?;
        set_scrambling(io, scrambled, OutputState::Stopped, record).await?;
        wait_after(
            io,
            written_at,
            config.ratio_wait,
            config.check_interval,
            record,
        )
        .await?;
        let started = start(io, written_at, record).await?;
        deadline(io, written_at, started, scrambled, config, warnings, record);
        let check = check_from(io, started, scrambled, config, warnings, record).await?;
        return Ok(Up {
            sink_written_at: written_at,
            output_started_at: started,
            check,
        });
    }

    // `Running`: unscrambled output first, then the sink's write, the wait, and only then
    // the source's scrambler, so no scrambled TMDS reaches the sink before it is told.
    configure(io, phy, record).await?;
    set_scrambling(io, false, OutputState::Stopped, record).await?;
    let started = start(io, None, record).await?;
    let written_at = write_sink(io, link, config, warnings, record)
        .await
        .map_err(|halt| halt.into_failure(OutputState::MayBeRunning))?;
    wait_after(
        io,
        written_at,
        config.ratio_wait,
        config.check_interval,
        record,
    )
    .await?;
    let mut check = ScramblingCheck::NOT_APPLICABLE;
    if scrambled {
        set_scrambling(io, true, OutputState::MayBeRunning, record).await?;
        let scrambling_at = io.now();
        deadline(
            io,
            written_at,
            scrambling_at,
            scrambled,
            config,
            warnings,
            record,
        );
        check = check_from(io, scrambling_at, scrambled, config, warnings, record).await?;
    }
    Ok(Up {
        sink_written_at: written_at,
        output_started_at: started,
        check,
    })
}

async fn configure<Io: TmdsIo, F: FnMut(TmdsEvent)>(
    io: &mut Io,
    phy: TmdsPhyConfig,
    record: &mut F,
) -> Result<(), Failure<Io::ScdcError, Io::PhyError>> {
    match io.configure(phy).await {
        Ok(()) => {
            emit(
                io,
                record,
                TmdsEventKind::PhyConfigured {
                    character_rate_khz: phy.character_rate_khz,
                    clock_ratio: phy.clock_ratio,
                },
            );
            Ok(())
        }
        Err(e) => Err(phy_failed(
            io,
            record,
            TmdsStep::Configure,
            e,
            OutputState::Stopped,
        )),
    }
}

async fn set_scrambling<Io: TmdsIo, F: FnMut(TmdsEvent)>(
    io: &mut Io,
    enabled: bool,
    output: OutputState,
    record: &mut F,
) -> Result<(), Failure<Io::ScdcError, Io::PhyError>> {
    match io.set_scrambling(enabled).await {
        Ok(()) => {
            emit(io, record, TmdsEventKind::ScramblerSet { enabled });
            Ok(())
        }
        Err(e) => Err(phy_failed(io, record, TmdsStep::SetScrambling, e, output)),
    }
}

async fn start<Io: TmdsIo, F: FnMut(TmdsEvent)>(
    io: &mut Io,
    written_at: Option<Timestamp>,
    record: &mut F,
) -> Result<Timestamp, Failure<Io::ScdcError, Io::PhyError>> {
    if let Err(e) = io.start_output().await {
        return Err(phy_failed(
            io,
            record,
            TmdsStep::StartOutput,
            e,
            OutputState::MayBeRunning,
        ));
    }
    let started = io.now();
    let after_write = written_at.map(|w| started.saturating_duration_since(w));
    emit(io, record, TmdsEventKind::OutputStarted { after_write });
    Ok(started)
}

/// The scrambling check from `from`, on a scrambled link; a plain link's check does not
/// apply. A check that did not see scrambling is also a warning; a cancelled check is the
/// bring-up's cancellation.
async fn check_from<Io: TmdsIo, F: FnMut(TmdsEvent)>(
    io: &mut Io,
    from: Timestamp,
    scrambled: bool,
    config: &BringUpConfig,
    warnings: &mut Warnings<Io::ScdcError>,
    record: &mut F,
) -> Result<ScramblingCheck<Io::ScdcError>, CancelPoint> {
    if !scrambled {
        return Ok(ScramblingCheck::NOT_APPLICABLE);
    }
    let check =
        scrambling_check(io, from, config.check_window, config.check_interval, record).await;
    match check.result {
        CheckResult::Cancelled => return Err(CancelPoint::Check),
        result @ (CheckResult::NotSet | CheckResult::Unreadable) => {
            warnings.push(BringUpWarning::ScramblingNotConfirmed { result });
        }
        _ => {}
    }
    Ok(check)
}

/// A warning when scrambled output reached the sink later after its write than the
/// deadline allows. A plain link has no deadline.
fn deadline<Io: TmdsIo, F: FnMut(TmdsEvent)>(
    io: &Io,
    written_at: Option<Timestamp>,
    scrambled_from: Timestamp,
    scrambled: bool,
    config: &BringUpConfig,
    warnings: &mut Warnings<Io::ScdcError>,
    record: &mut F,
) {
    let Some(written_at) = written_at.filter(|_| scrambled) else {
        return;
    };
    let took = scrambled_from.saturating_duration_since(written_at);
    if took > config.scrambling_deadline {
        let by = took - config.scrambling_deadline;
        emit(io, record, TmdsEventKind::DeadlineMissed { by });
        warnings.push(BringUpWarning::DeadlineMissed { by });
    }
}

/// Brings up the TMDS link `link` describes, carrying `video`.
///
/// One attempt: the work before both paths (the FRL clear and `Source_Version`, on a sink
/// with SCDC), then the main path. By default (`OutputDuringSinkWrite::Stopped`) the output
/// is stopped, the sink's `TMDS_Config` written (when a write is due), the PHY configured with
/// its scrambler, the ratio wait spent from the write, and the output started. With `Running`,
/// unscrambled output runs through the write and the source's scrambler comes on after the
/// wait. No scrambled TMDS reaches the sink before its write in either order.
///
/// What carries on is a warning in the outcome: a failed FRL clear or `Source_Version`, a
/// failed `TMDS_Config` write under `OnTmdsConfigFailure::CarryOn` (on a plain link with the
/// register read back), a missed deadline. Whether the sink reports scrambling is the
/// check's, part of the outcome rather than a condition of it.
///
/// # Cancellation
///
/// The caller's cancel flag is read at entry, before each SCDC step, before each slice of
/// the ratio wait (slices of at most `check_interval`) and before each read of the check;
/// never mid-call. Once set, the bring-up ends [`BringUpOutcome::Cancelled`]: at entry
/// before any I/O, otherwise after a tear-down with the caller's `tear_down` settings
/// (`tear_down_on_error` governs errors only), with the sink taken to be present: the flag
/// does not say why it was set, and with `clear_sink` on a sink already gone gets one write
/// that fails fast, a warning. The tear-down is not cancelled, and the flag is never
/// cleared: the caller resets it before its next call.
///
/// Records at most [`MAX_BRING_UP_EVENTS`](crate::MAX_BRING_UP_EVENTS) events.
///
/// # Errors
///
/// [`BringUpError::VideoMismatch`], before any I/O, when `video`'s TMDS character rate
/// ([`TmdsVideo::character_rate_khz`]) is not `link`'s: the caller chooses the link for the
/// rate the video gives.
///
/// [`BringUpError`] when a PHY call failed, or the sink's `TMDS_Config` write failed with a
/// non-transient error (`Detached`, `Unsupported`) or under `OnTmdsConfigFailure::Stop`. A
/// failure before both paths, or of a plain link's read-back, is a warning.
/// With `tear_down_on_error` (the default) a tear-down follows, with the sink taken to be
/// gone when the error was `Detached`; its result is the error's [`Cleanup`].
pub async fn bring_up<Io: TmdsIo, F: FnMut(TmdsEvent)>(
    io: &mut Io,
    link: &TmdsLinkParams,
    video: TmdsVideo,
    config: &BringUpConfig,
    record: &mut F,
) -> Result<BringUpOutcome<Io::ScdcError, Io::PhyError>, BringUpError<Io::ScdcError, Io::PhyError>>
{
    emit(
        io,
        record,
        TmdsEventKind::BringUpStarted {
            link: *link,
            video,
            config: *config,
        },
    );
    // The PHY takes the rate and the video together: they must agree, or it would run at one
    // rate while the sink was set up for the other.
    let video_rate_khz = video.character_rate_khz();
    if video_rate_khz != Some(link.rate_khz()) {
        let link_rate_khz = link.rate_khz();
        emit(
            io,
            record,
            TmdsEventKind::VideoMismatch {
                link_rate_khz,
                video_rate_khz,
            },
        );
        return Err(BringUpError::VideoMismatch {
            link_rate_khz,
            video_rate_khz,
        });
    }
    let mut warnings = Warnings::new();
    if io.cancelled() {
        let at = CancelPoint::Entry;
        emit(io, record, TmdsEventKind::BringUpCancelled { at });
        emit(
            io,
            record,
            TmdsEventKind::BringUpEnded {
                failed_at: None,
                cancelled: true,
            },
        );
        return Ok(BringUpOutcome::Cancelled {
            at,
            cleanup: Cleanup::Skipped,
            warnings,
        });
    }
    let phy = TmdsPhyConfig::new(link.rate_khz(), link.clock_ratio(), video);

    let result = match before_both_paths(io, link, config, &mut warnings, &mut |io, kind| {
        emit(io, record, kind);
    })
    .await
    {
        Ok(()) => main_path(io, link, phy, config, &mut warnings, record).await,
        Err(halt) => Err(halt.into_failure(OutputState::MayBeRunning)),
    };

    let failure = match result {
        Ok(up) => {
            emit(
                io,
                record,
                TmdsEventKind::BringUpEnded {
                    failed_at: None,
                    cancelled: false,
                },
            );
            return Ok(BringUpOutcome::Up(LinkUp {
                link: *link,
                sink_written_at: up.sink_written_at,
                output_started_at: up.output_started_at,
                check: up.check,
                warnings,
            }));
        }
        Err(Failure::Cancelled(at)) => {
            emit(io, record, TmdsEventKind::BringUpCancelled { at });
            let torn = tear_down(io, link, &config.tear_down, SinkPresence::Present, record).await;
            emit(
                io,
                record,
                TmdsEventKind::BringUpEnded {
                    failed_at: None,
                    cancelled: true,
                },
            );
            return Ok(BringUpOutcome::Cancelled {
                at,
                cleanup: Cleanup::TornDown(torn),
                warnings,
            });
        }
        Err(Failure::Scdc(Stop { step, error }, output)) => {
            let presence = if error.kind() == DdcErrorKind::Detached {
                SinkPresence::Gone
            } else {
                SinkPresence::Present
            };
            let error = BringUpError::Scdc {
                step,
                error,
                output,
                cleanup: Cleanup::Skipped,
                warnings,
            };
            (step, presence, error)
        }
        Err(Failure::Phy(step, error, output)) => {
            let error = BringUpError::Phy {
                step,
                error,
                output,
                cleanup: Cleanup::Skipped,
                warnings,
            };
            (step, SinkPresence::Present, error)
        }
    };
    let (step, presence, mut error) = failure;

    if config.tear_down_on_error {
        let torn = tear_down(io, link, &config.tear_down, presence, record).await;
        if let BringUpError::Scdc { cleanup, .. } | BringUpError::Phy { cleanup, .. } = &mut error {
            *cleanup = Cleanup::TornDown(torn);
        }
    }
    emit(
        io,
        record,
        TmdsEventKind::BringUpEnded {
            failed_at: Some(step),
            cancelled: false,
        },
    );
    Err(error)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::procedure::test_io::{Op, TestIo, block_on};
    use crate::types::{SinkTmdsFacts, SourceTmdsFacts, TmdsPolicy};

    /// An HDMI 2.1 sink with SCDC that declares FRL.
    const FRL_SINK: SinkTmdsFacts = SinkTmdsFacts::new(true, true, false);
    const NO_FRL: SinkTmdsFacts = FRL_SINK.with_frl_capable(false);

    fn link(rate_khz: u32, sink: SinkTmdsFacts) -> TmdsLinkParams {
        TmdsLinkParams::choose(
            rate_khz,
            sink,
            SourceTmdsFacts::new(false),
            TmdsPolicy::DEFAULT,
        )
        .unwrap()
    }

    struct Run {
        result: Result<(), Halt<DdcErrorKind>>,
        warnings: Warnings<DdcErrorKind>,
        events: [Option<TmdsEventKind>; 8],
        count: usize,
    }

    impl Run {
        fn has(&self, kind: TmdsEventKind) -> bool {
            self.events[..self.count].contains(&Some(kind))
        }
    }

    fn run(io: &mut TestIo, link: &TmdsLinkParams, config: &BringUpConfig) -> Run {
        let mut warnings = Warnings::new();
        let mut events = [None; 8];
        let mut count = 0;
        let result = block_on(before_both_paths(
            io,
            link,
            config,
            &mut warnings,
            &mut |_, kind| {
                events[count] = Some(kind);
                count += 1;
            },
        ));
        Run {
            result,
            warnings,
            events,
            count,
        }
    }

    #[test]
    fn an_frl_sink_is_cleared_and_gets_source_version_by_default() {
        let mut io = TestIo::new();
        io.flt_update = true;
        let r = run(&mut io, &link(594_000, FRL_SINK), &BringUpConfig::DEFAULT);
        assert_eq!(r.result, Ok(()));
        assert_eq!(
            io.ops(),
            [
                Op::ClearFrlRate,
                Op::ClearFltUpdate,
                Op::WriteSourceVersion(1)
            ]
        );
        assert!(r.has(TmdsEventKind::FrlRateCleared));
        assert!(r.has(TmdsEventKind::FltUpdateCleared { was_set: true }));
        assert!(r.has(TmdsEventKind::SourceVersionWritten { version: 1 }));
        assert!(r.warnings.is_empty());
    }

    #[test]
    fn the_frl_clear_follows_the_setting() {
        let mut io = TestIo::new();
        let r = run(&mut io, &link(594_000, NO_FRL), &BringUpConfig::DEFAULT);
        assert!(r.has(TmdsEventKind::FrlClearSkipped {
            reason: FrlClearSkip::SinkDeclaresNoFrl
        }));
        assert_eq!(io.ops(), [Op::WriteSourceVersion(1)]);

        let every = BringUpConfig::DEFAULT.with_clear_frl(ClearFrl::EveryScdcSink);
        let mut io = TestIo::new();
        run(&mut io, &link(594_000, NO_FRL), &every);
        assert_eq!(
            io.ops(),
            [
                Op::ClearFrlRate,
                Op::ClearFltUpdate,
                Op::WriteSourceVersion(1)
            ]
        );
    }

    #[test]
    fn a_sink_without_scdc_gets_nothing() {
        let mut io = TestIo::new();
        let every = BringUpConfig::DEFAULT.with_clear_frl(ClearFrl::EveryScdcSink);
        let r = run(&mut io, &link(148_500, SinkTmdsFacts::NONE), &every);
        assert_eq!(r.result, Ok(()));
        assert_eq!(io.ops().len(), 0);
        assert!(r.has(TmdsEventKind::FrlClearSkipped {
            reason: FrlClearSkip::NoScdc
        }));
        assert!(r.has(TmdsEventKind::SourceVersionSkipped {
            reason: SourceVersionSkip::NoScdc
        }));
    }

    #[test]
    fn source_version_follows_the_setting() {
        let only = |w| {
            BringUpConfig::DEFAULT
                .with_clear_frl(ClearFrl::IfSinkDeclaresFrl)
                .with_source_version(w)
        };
        let scrambled = link(594_000, NO_FRL);
        let plain = link(148_500, NO_FRL);

        // Only when Sink_Version is 1.
        let mut io = TestIo::new();
        io.sink_version = 1;
        run(
            &mut io,
            &scrambled,
            &only(SourceVersionWrite::IfSinkVersion1),
        );
        assert_eq!(io.ops(), [Op::ReadSinkVersion, Op::WriteSourceVersion(1)]);
        let mut io = TestIo::new();
        io.sink_version = 2;
        let r = run(
            &mut io,
            &scrambled,
            &only(SourceVersionWrite::IfSinkVersion1),
        );
        assert_eq!(io.ops(), [Op::ReadSinkVersion]);
        assert!(r.has(TmdsEventKind::SourceVersionSkipped {
            reason: SourceVersionSkip::SinkVersion { version: 2 }
        }));

        // Only on a scrambled link, to a sink reporting a non-zero version.
        let mut io = TestIo::new();
        io.sink_version = 3;
        run(
            &mut io,
            &scrambled,
            &only(SourceVersionWrite::WhenScrambling),
        );
        assert_eq!(io.ops(), [Op::ReadSinkVersion, Op::WriteSourceVersion(1)]);
        let mut io = TestIo::new();
        io.sink_version = 0;
        run(
            &mut io,
            &scrambled,
            &only(SourceVersionWrite::WhenScrambling),
        );
        assert_eq!(io.ops(), [Op::ReadSinkVersion]);
        let mut io = TestIo::new();
        let r = run(&mut io, &plain, &only(SourceVersionWrite::WhenScrambling));
        assert_eq!(io.ops().len(), 0);
        assert!(r.has(TmdsEventKind::SourceVersionSkipped {
            reason: SourceVersionSkip::NotScrambled
        }));

        // Never.
        let mut io = TestIo::new();
        let r = run(&mut io, &scrambled, &only(SourceVersionWrite::Never));
        assert_eq!(io.ops().len(), 0);
        assert!(r.has(TmdsEventKind::SourceVersionSkipped {
            reason: SourceVersionSkip::Never
        }));
    }

    #[test]
    fn transient_failures_are_warnings_and_the_work_goes_on() {
        let mut io = TestIo::new();
        io.fail_scdc = Some(DdcErrorKind::Busy);
        let r = run(&mut io, &link(594_000, FRL_SINK), &BringUpConfig::DEFAULT);
        assert_eq!(r.result, Ok(()));
        assert_eq!(
            io.ops(),
            [
                Op::ClearFrlRate,
                Op::ClearFltUpdate,
                Op::WriteSourceVersion(1)
            ]
        );
        let w: [_; 3] = core::array::from_fn(|i| *r.warnings.iter_warnings().nth(i).unwrap());
        assert_eq!(
            w,
            [
                BringUpWarning::FrlRateClearFailed(DdcErrorKind::Busy),
                BringUpWarning::FltUpdateClearFailed(UpdateError::Read(DdcErrorKind::Busy)),
                BringUpWarning::SourceVersionWriteFailed(DdcErrorKind::Busy),
            ]
        );
        assert!(r.has(TmdsEventKind::ScdcStepFailed {
            step: TmdsStep::ClearFrlRate,
            kind: DdcErrorKind::Busy,
            ends: false
        }));

        // A failed Sink_Version read writes nothing.
        let mut io = TestIo::new();
        io.fail_scdc = Some(DdcErrorKind::Timeout);
        let r = run(
            &mut io,
            &link(594_000, NO_FRL),
            &BringUpConfig::DEFAULT.with_source_version(SourceVersionWrite::IfSinkVersion1),
        );
        assert_eq!(io.ops(), [Op::ReadSinkVersion]);
        assert_eq!(
            r.warnings.iter_warnings().next(),
            Some(&BringUpWarning::SinkVersionReadFailed(
                DdcErrorKind::Timeout
            ))
        );
        assert!(r.has(TmdsEventKind::SourceVersionSkipped {
            reason: SourceVersionSkip::SinkVersionUnread
        }));
    }

    #[test]
    fn a_non_transient_error_is_a_warning_too() {
        for (ok_calls, step, warnings) in [
            (0, TmdsStep::ClearFrlRate, 3),
            (1, TmdsStep::ClearFltUpdate, 2),
            (2, TmdsStep::SourceVersion, 1),
        ] {
            let mut io = TestIo::new();
            io.fail_scdc = Some(DdcErrorKind::Detached);
            io.scdc_ok_calls = ok_calls;
            let r = run(&mut io, &link(594_000, FRL_SINK), &BringUpConfig::DEFAULT);
            assert_eq!(r.result, Ok(()));
            // Every step is still attempted, and each failure is a warning.
            assert_eq!(io.ops().len(), 3);
            assert_eq!(r.warnings.len(), warnings);
            assert!(r.has(TmdsEventKind::ScdcStepFailed {
                step,
                kind: DdcErrorKind::Detached,
                ends: false
            }));
        }
        let mut io = TestIo::new();
        io.fail_scdc = Some(DdcErrorKind::Unsupported);
        let r = run(
            &mut io,
            &link(594_000, NO_FRL),
            &BringUpConfig::DEFAULT.with_source_version(SourceVersionWrite::IfSinkVersion1),
        );
        assert_eq!(r.result, Ok(()));
        assert!(matches!(
            r.warnings.iter_warnings().next(),
            Some(BringUpWarning::SinkVersionReadFailed(
                DdcErrorKind::Unsupported
            ))
        ));
        assert!(r.has(TmdsEventKind::SourceVersionSkipped {
            reason: SourceVersionSkip::SinkVersionUnread
        }));
    }

    #[test]
    fn the_flag_is_read_before_each_step_before_both_paths() {
        for (after, step) in [
            (0, TmdsStep::ClearFrlRate),
            (1, TmdsStep::ClearFltUpdate),
            (2, TmdsStep::SourceVersion),
        ] {
            let mut io = TestIo::new();
            io.cancel_after_ops = Some(after);
            let r = run(&mut io, &link(594_000, FRL_SINK), &BringUpConfig::DEFAULT);
            assert_eq!(r.result, Err(Halt::Cancelled(CancelPoint::Step(step))));
            assert_eq!(io.ops().len(), after);
        }
        let mut io = TestIo::new();
        io.cancelled = true;
        let config = BringUpConfig::DEFAULT.with_source_version(SourceVersionWrite::IfSinkVersion1);
        let r = run(&mut io, &link(594_000, NO_FRL), &config);
        assert_eq!(
            r.result,
            Err(Halt::Cancelled(CancelPoint::Step(TmdsStep::SinkVersion)))
        );
        // Skipped steps read nothing.
        let r = run(&mut io, &link(148_500, SinkTmdsFacts::NONE), &config);
        assert_eq!(r.result, Ok(()));
    }

    #[test]
    fn a_kind_added_later_counts_as_transient() {
        assert!(transient(DdcErrorKind::Busy));
        assert!(transient(DdcErrorKind::Other));
        assert!(!transient(DdcErrorKind::Detached));
        assert!(!transient(DdcErrorKind::Unsupported));
    }

    // ---- The whole bring-up ----

    use crate::config::{OutputDuringSinkWrite, TearDownConfig, TmdsConfigWrite};
    use crate::outcome::{SinkClear, TearDownError, TornDown};
    use crate::types::{SinkTmdsConfig, TmdsConfigGate};
    use crate::{CheckResult, ClockRatio, MAX_BRING_UP_EVENTS};
    use hdmi_hal::phy::TmdsVideo;

    /// 8 bpc RGB at the link's rate: the video the link was chosen for.
    fn video(link: &TmdsLinkParams) -> TmdsVideo {
        TmdsVideo::new(
            link.rate_khz(),
            hdmi_hal::ColorBitDepth::Depth8,
            hdmi_hal::ColorFormat::Rgb444,
        )
    }

    /// No FRL clear and no `Source_Version`: only the main path's SCDC calls.
    const MAIN_ONLY: BringUpConfig = BringUpConfig::DEFAULT
        .with_clear_frl(ClearFrl::IfSinkDeclaresFrl)
        .with_source_version(SourceVersionWrite::Never);

    type Outcome = Result<BringUpOutcome<DdcErrorKind, ()>, BringUpError<DdcErrorKind, ()>>;

    struct Up {
        result: Outcome,
        events: [Option<TmdsEventKind>; 32],
        count: usize,
    }

    impl Up {
        fn has(&self, kind: TmdsEventKind) -> bool {
            self.events[..self.count].contains(&Some(kind))
        }

        fn link_up(&self) -> Option<&LinkUp<DdcErrorKind>> {
            match &self.result {
                Ok(BringUpOutcome::Up(up)) => Some(up),
                _ => None,
            }
        }
    }

    fn up(io: &mut TestIo, link: &TmdsLinkParams, config: &BringUpConfig) -> Up {
        let mut events = [None; 32];
        let mut count = 0;
        let result = block_on(bring_up(io, link, video(link), config, &mut |e| {
            events[count] = Some(e.kind);
            count += 1;
        }));
        assert!(count <= MAX_BRING_UP_EVENTS, "{count} events");
        Up {
            result,
            events,
            count,
        }
    }

    fn phy(link: &TmdsLinkParams) -> Op {
        Op::Configure(TmdsPhyConfig::new(
            link.rate_khz(),
            link.clock_ratio(),
            video(link),
        ))
    }

    #[test]
    fn a_video_that_does_not_give_the_links_rate_is_refused_before_any_io() {
        let link = link(594_000, NO_FRL);
        let run = |video: TmdsVideo| {
            let mut io = TestIo::new();
            let mut events = [None; 4];
            let mut count = 0;
            let result = block_on(bring_up(&mut io, &link, video, &MAIN_ONLY, &mut |e| {
                events[count] = Some(e.kind);
                count += 1;
            }));
            assert!(io.ops().is_empty());
            (result, events, count)
        };
        // 1080p for a 4K link.
        let (result, events, count) = run(TmdsVideo::new(
            148_500,
            hdmi_hal::ColorBitDepth::Depth8,
            hdmi_hal::ColorFormat::Rgb444,
        ));
        assert!(matches!(
            result,
            Err(BringUpError::VideoMismatch {
                link_rate_khz: 594_000,
                video_rate_khz: Some(148_500),
            })
        ));
        assert_eq!(count, 2);
        assert_eq!(
            events[1],
            Some(TmdsEventKind::VideoMismatch {
                link_rate_khz: 594_000,
                video_rate_khz: Some(148_500)
            })
        );
        // The same 4K at 10 bits is 742.5 MHz, not this link's rate either.
        let (result, ..) = run(TmdsVideo::new(
            594_000,
            hdmi_hal::ColorBitDepth::Depth10,
            hdmi_hal::ColorFormat::Rgb444,
        ));
        assert!(matches!(
            result,
            Err(BringUpError::VideoMismatch {
                video_rate_khz: Some(742_500),
                ..
            })
        ));
        // A depth TMDS does not carry has no rate.
        let (result, ..) = run(TmdsVideo::new(
            594_000,
            hdmi_hal::ColorBitDepth::Depth6,
            hdmi_hal::ColorFormat::Rgb444,
        ));
        assert!(matches!(
            result,
            Err(BringUpError::VideoMismatch {
                video_rate_khz: None,
                ..
            })
        ));
    }

    #[test]
    fn a_scrambled_link_comes_up_in_the_default_order() {
        let link = link(594_000, FRL_SINK);
        let mut io = TestIo::new();
        io.scrambling_status = 0x01;
        let r = up(&mut io, &link, &BringUpConfig::DEFAULT);
        let ops = io.ops();
        assert_eq!(
            ops[..7],
            [
                Op::ClearFrlRate,
                Op::ClearFltUpdate,
                Op::WriteSourceVersion(1),
                Op::StopOutput,
                Op::UpdateTmdsConfig(SinkTmdsConfig::new(true, true)),
                phy(&link),
                Op::SetScrambling(true),
            ]
        );
        assert!(
            matches!(ops[7], Op::Delay(d) if d > Duration::ZERO && d <= Duration::from_millis(1))
        );
        assert_eq!(ops[8], Op::StartOutput);
        assert_eq!(ops[9], Op::ReadScramblingStatus);
        assert_eq!(ops.len(), 10);

        let up = r.link_up().unwrap();
        assert_eq!(up.link, link);
        assert!(up.warnings.is_empty());
        assert_eq!(up.check.result, CheckResult::Set);
        assert_eq!(up.check.reads, 1);
        let written = up.sink_written_at.unwrap();
        // The wait is measured from the write.
        assert!(
            up.output_started_at.saturating_duration_since(written) >= Duration::from_millis(1)
        );
        assert!(r.has(TmdsEventKind::PhyConfigured {
            character_rate_khz: 594_000,
            clock_ratio: ClockRatio::Div40
        }));
        assert!(r.has(TmdsEventKind::BringUpEnded {
            failed_at: None,
            cancelled: false
        }));
    }

    #[test]
    fn unscrambled_output_runs_through_the_write_with_running() {
        let link = link(594_000, NO_FRL);
        let mut io = TestIo::new();
        io.scrambling_status = 0x01;
        let config = MAIN_ONLY.with_output_during_sink_write(OutputDuringSinkWrite::Running);
        let r = up(&mut io, &link, &config);
        let ops = io.ops();
        assert_eq!(
            ops[..5],
            [
                Op::StopOutput,
                phy(&link),
                Op::SetScrambling(false),
                Op::StartOutput,
                Op::UpdateTmdsConfig(SinkTmdsConfig::new(true, true)),
            ]
        );
        assert!(matches!(ops[5], Op::Delay(_)));
        assert_eq!(ops[6], Op::SetScrambling(true));
        assert!(r.has(TmdsEventKind::OutputStarted { after_write: None }));
        assert!(r.link_up().unwrap().warnings.is_empty());
    }

    #[test]
    fn the_check_runs_from_the_scrambler_with_running_and_not_on_a_plain_link() {
        let mut io = TestIo::new();
        io.status_set_from_read = Some(3);
        let config = MAIN_ONLY.with_output_during_sink_write(OutputDuringSinkWrite::Running);
        let r = up(&mut io, &link(594_000, NO_FRL), &config);
        let check = r.link_up().unwrap().check;
        assert_eq!((check.result, check.reads), (CheckResult::Set, 3));
        assert!(r.has(TmdsEventKind::ScramblingChecked { check }));

        let mut io = TestIo::new();
        let r = up(&mut io, &link(148_500, NO_FRL), &MAIN_ONLY);
        assert_eq!(
            r.link_up().unwrap().check.result,
            CheckResult::NotApplicable
        );
        assert!(!io.ops().contains(&Op::ReadScramblingStatus));
    }

    #[test]
    fn a_plain_link_clears_the_sink_and_has_no_deadline() {
        let link = link(148_500, NO_FRL);
        let mut io = TestIo::new();
        let config = MAIN_ONLY.with_scrambling_deadline(Duration::ZERO);
        let r = up(&mut io, &link, &config);
        assert_eq!(
            io.ops()[1],
            Op::UpdateTmdsConfig(SinkTmdsConfig::new(false, false))
        );
        assert_eq!(io.ops()[3], Op::SetScrambling(false));
        assert!(r.link_up().unwrap().warnings.is_empty());
    }

    #[test]
    fn whole_byte_writes_without_reading() {
        let mut io = TestIo::new();
        up(
            &mut io,
            &link(594_000, NO_FRL),
            &MAIN_ONLY.with_tmds_config_write(TmdsConfigWrite::WholeByte),
        );
        assert_eq!(
            io.ops()[1],
            Op::WriteTmdsConfig(SinkTmdsConfig::new(true, true))
        );
    }

    #[test]
    fn no_write_is_made_where_none_is_due() {
        let mut io = TestIo::new();
        let r = up(
            &mut io,
            &link(148_500, SinkTmdsFacts::NONE),
            &BringUpConfig::DEFAULT,
        );
        assert!(r.has(TmdsEventKind::TmdsConfigSkipped {
            reason: TmdsConfigSkip::NoScdc
        }));
        assert!(!io.ops().iter().any(|op| matches!(op, Op::Delay(_))));
        assert_eq!(r.link_up().unwrap().sink_written_at, None);

        let gated = TmdsLinkParams::choose(
            148_500,
            SinkTmdsFacts::new(true, false, false),
            SourceTmdsFacts::new(false),
            TmdsPolicy::DEFAULT.with_tmds_config_gate(TmdsConfigGate::ScramblingSink),
        )
        .unwrap();
        let mut io = TestIo::new();
        let r = up(&mut io, &gated, &MAIN_ONLY);
        assert!(r.has(TmdsEventKind::TmdsConfigSkipped {
            reason: TmdsConfigSkip::Gate
        }));
    }

    #[test]
    fn the_wait_runs_from_the_write_and_counts_what_came_after_it() {
        // The PHY's two calls after the write cost 300 µs each: of the 1 ms wait, a little
        // under 400 µs is left to spend.
        let mut io = TestIo::new();
        io.scrambling_status = 0x01;
        io.op_micros = 300;
        let r = up(&mut io, &link(594_000, NO_FRL), &MAIN_ONLY);
        let delays: [Duration; 1] = {
            let mut found = [Duration::ZERO; 1];
            let mut n = 0;
            for op in io.ops() {
                if let Op::Delay(d) = op {
                    found[n] = *d;
                    n += 1;
                }
            }
            assert_eq!(n, 1);
            found
        };
        let left = delays[0];
        assert!(
            left > Duration::from_micros(390) && left < Duration::from_micros(400),
            "{left:?}"
        );
        assert!(r.has(TmdsEventKind::WaitSpent { duration: left }));

        // Calls that alone take longer than the wait leave nothing to spend.
        let mut io = TestIo::new();
        io.scrambling_status = 0x01;
        io.op_micros = 600;
        let r = up(&mut io, &link(594_000, NO_FRL), &MAIN_ONLY);
        assert!(!io.ops().iter().any(|op| matches!(op, Op::Delay(_))));
        assert!(r.has(TmdsEventKind::WaitSpent {
            duration: Duration::ZERO
        }));
    }

    #[test]
    fn a_read_modify_write_that_fails_at_the_write_says_so() {
        let mut io = TestIo::new();
        io.fail_scdc = Some(DdcErrorKind::Busy);
        io.update_fails_at_write = true;
        let r = up(&mut io, &link(594_000, NO_FRL), &MAIN_ONLY);
        assert!(matches!(
            r.link_up().unwrap().warnings.iter_warnings().next(),
            Some(BringUpWarning::TmdsConfigWriteFailed {
                error: UpdateError::Write(DdcErrorKind::Busy),
                ..
            })
        ));
        assert!(r.has(TmdsEventKind::ScdcStepFailed {
            step: TmdsStep::WriteTmdsConfig,
            kind: DdcErrorKind::Busy,
            ends: false
        }));
    }

    #[test]
    fn a_check_that_sees_no_scrambling_is_a_warning() {
        let link = link(594_000, NO_FRL);
        // Set: no warning.
        let mut io = TestIo::new();
        io.scrambling_status = 0x01;
        assert!(
            up(&mut io, &link, &MAIN_ONLY)
                .link_up()
                .unwrap()
                .warnings
                .is_empty()
        );
        // Not set within the window, and unreadable.
        for (fail, result) in [
            (None, CheckResult::NotSet),
            (Some(DdcErrorKind::Busy), CheckResult::Unreadable),
        ] {
            let mut io = TestIo::new();
            io.fail_scdc = fail;
            io.scdc_ok_calls = 1; // the sink's write succeeds
            let r = up(&mut io, &link, &MAIN_ONLY);
            let up = r.link_up().unwrap();
            assert_eq!(up.check.result, result);
            assert!(
                up.warnings
                    .iter_warnings()
                    .any(|w| *w == BringUpWarning::ScramblingNotConfirmed { result }),
                "{result:?}"
            );
        }
        // A plain link has no check and no warning.
        let mut io = TestIo::new();
        let r = up(&mut io, &super::tests::link(148_500, NO_FRL), &MAIN_ONLY);
        assert!(r.link_up().unwrap().warnings.is_empty());
    }

    #[test]
    fn a_late_start_is_a_warning() {
        let mut io = TestIo::new();
        io.scrambling_status = 0x01;
        let config = MAIN_ONLY.with_scrambling_deadline(Duration::from_micros(500));
        let r = up(&mut io, &link(594_000, NO_FRL), &config);
        let w = r
            .link_up()
            .unwrap()
            .warnings
            .iter_warnings()
            .next()
            .copied();
        // By exactly how much the output started late after the write.
        let took = r.events[..r.count]
            .iter()
            .find_map(|k| match k {
                Some(TmdsEventKind::OutputStarted {
                    after_write: Some(d),
                }) => Some(*d),
                _ => None,
            })
            .unwrap();
        let by = took - Duration::from_micros(500);
        assert_eq!(w, Some(BringUpWarning::DeadlineMissed { by }));
        assert!(r.has(TmdsEventKind::DeadlineMissed { by }));
        // A deadline of exactly that time is met: the run is the same, step for step.
        let mut io = TestIo::new();
        io.scrambling_status = 0x01;
        let met = config.with_scrambling_deadline(took);
        let r = up(&mut io, &link(594_000, NO_FRL), &met);
        assert!(r.link_up().unwrap().warnings.is_empty());

        // With Running, the deadline runs from the write to the scrambler, the wait included.
        let mut io = TestIo::new();
        io.scrambling_status = 0x01;
        let r = up(
            &mut io,
            &link(594_000, NO_FRL),
            &config.with_output_during_sink_write(OutputDuringSinkWrite::Running),
        );
        let warnings = r.link_up().unwrap().warnings;
        assert_eq!(warnings.len(), 1);
        assert!(matches!(
            warnings.iter_warnings().next(),
            Some(BringUpWarning::DeadlineMissed { by })
                if *by > Duration::from_micros(500) && *by < Duration::from_micros(600)
        ));
    }

    #[test]
    fn a_failed_write_carries_on_and_a_plain_link_reads_back() {
        // A scrambled link: the check covers it, nothing read back.
        let mut io = TestIo::new();
        io.fail_scdc = Some(DdcErrorKind::Busy);
        io.scdc_failures = 1;
        io.scrambling_status = 0x01;
        let r = up(&mut io, &link(594_000, NO_FRL), &MAIN_ONLY);
        assert_eq!(
            r.link_up().unwrap().warnings.iter_warnings().next(),
            Some(&BringUpWarning::TmdsConfigWriteFailed {
                error: UpdateError::Read(DdcErrorKind::Busy),
                read_back: None
            })
        );
        // The read half failed, and the event says so by its step.
        assert!(r.has(TmdsEventKind::ScdcStepFailed {
            step: TmdsStep::ReadTmdsConfig,
            kind: DdcErrorKind::Busy,
            ends: false
        }));
        // It carried on to the output and the check. Nothing was written, so there is no
        // write time, no wait and no deadline to run from one.
        assert_eq!(
            io.ops()[io.ops().len() - 2..],
            [Op::StartOutput, Op::ReadScramblingStatus]
        );
        assert_eq!(r.link_up().unwrap().sink_written_at, None);
        assert!(!io.ops().iter().any(|op| matches!(op, Op::Delay(_))));
        assert!(r.has(TmdsEventKind::OutputStarted { after_write: None }));

        // A plain link: the register read back after the failure.
        let mut io = TestIo::new();
        io.fail_scdc = Some(DdcErrorKind::Busy);
        io.scdc_failures = 1;
        io.tmds_config = 0x03;
        let r = up(
            &mut io,
            &link(148_500, NO_FRL),
            &MAIN_ONLY.with_tmds_config_write(TmdsConfigWrite::WholeByte),
        );
        let read_back = r
            .link_up()
            .unwrap()
            .warnings
            .iter_warnings()
            .next()
            .copied();
        assert!(matches!(
            read_back,
            Some(BringUpWarning::TmdsConfigWriteFailed {
                error: UpdateError::Write(DdcErrorKind::Busy),
                read_back: Some(Ok(read)),
            }) if read.config == SinkTmdsConfig::new(true, true) && read.raw == 0x03
        ));

        // A read-back that fails too is a warning's part, not the end.
        let mut io = TestIo::new();
        io.fail_scdc = Some(DdcErrorKind::Busy);
        io.scdc_failures = 2;
        let r = up(
            &mut io,
            &link(148_500, NO_FRL),
            &MAIN_ONLY.with_tmds_config_write(TmdsConfigWrite::WholeByte),
        );
        assert!(matches!(
            r.link_up().unwrap().warnings.iter_warnings().next(),
            Some(BringUpWarning::TmdsConfigWriteFailed {
                read_back: Some(Err(DdcErrorKind::Busy)),
                ..
            })
        ));
        assert!(r.has(TmdsEventKind::ScdcStepFailed {
            step: TmdsStep::ReadTmdsConfig,
            kind: DdcErrorKind::Busy,
            ends: false
        }));
    }

    #[test]
    fn a_failed_write_stops_under_stop_and_tears_down() {
        let mut io = TestIo::new();
        io.fail_scdc = Some(DdcErrorKind::Busy);
        let config = MAIN_ONLY.with_on_tmds_config_failure(OnTmdsConfigFailure::Stop);
        let r = up(&mut io, &link(594_000, NO_FRL), &config);
        assert_eq!(
            r.result,
            // The read half of the read-modify-write failed: nothing was written.
            Err(BringUpError::Scdc {
                step: TmdsStep::ReadTmdsConfig,
                error: DdcErrorKind::Busy,
                output: OutputState::Stopped,
                cleanup: Cleanup::TornDown(Ok(TornDown {
                    sink: SinkClear::NotRequested
                })),
                warnings: Warnings::new(),
            })
        );
        assert_eq!(io.ops().last(), Some(&Op::StopOutput));
        assert!(r.has(TmdsEventKind::BringUpEnded {
            failed_at: Some(TmdsStep::ReadTmdsConfig),
            cancelled: false
        }));
        // With Running, the output is already on at the write.
        let mut io = TestIo::new();
        io.fail_scdc = Some(DdcErrorKind::Busy);
        let r = up(
            &mut io,
            &link(594_000, NO_FRL),
            &config.with_output_during_sink_write(OutputDuringSinkWrite::Running),
        );
        assert!(matches!(
            r.result,
            Err(BringUpError::Scdc {
                output: OutputState::MayBeRunning,
                ..
            })
        ));
        // The write half names the write.
        let mut io = TestIo::new();
        io.fail_scdc = Some(DdcErrorKind::Busy);
        io.update_fails_at_write = true;
        let r = up(&mut io, &link(594_000, NO_FRL), &config);
        assert!(matches!(
            r.result,
            Err(BringUpError::Scdc {
                step: TmdsStep::WriteTmdsConfig,
                ..
            })
        ));
    }

    #[test]
    fn a_gone_sink_gets_no_writes_in_the_cleanup() {
        let mut io = TestIo::new();
        io.fail_scdc = Some(DdcErrorKind::Detached);
        let config = MAIN_ONLY.with_tear_down(TearDownConfig::DEFAULT.with_clear_sink(true));
        let r = up(&mut io, &link(594_000, NO_FRL), &config);
        assert!(matches!(
            r.result,
            Err(BringUpError::Scdc {
                cleanup: Cleanup::TornDown(Ok(TornDown {
                    sink: SinkClear::SkippedSinkGone
                })),
                ..
            })
        ));
    }

    #[test]
    fn a_phy_failure_says_where_and_whether_output_may_run() {
        for (fail, step, output) in [
            (0, TmdsStep::StopOutput, OutputState::MayBeRunning),
            (1, TmdsStep::Configure, OutputState::Stopped),
            (2, TmdsStep::SetScrambling, OutputState::Stopped),
            (3, TmdsStep::StartOutput, OutputState::MayBeRunning),
        ] {
            let mut io = TestIo::new();
            match fail {
                0 => io.fail_stop_output = true,
                1 => io.fail_configure = true,
                2 => io.fail_set_scrambling = true,
                _ => io.fail_start_output = true,
            }
            let r = up(&mut io, &link(594_000, NO_FRL), &MAIN_ONLY);
            assert!(
                matches!(
                    r.result,
                    Err(BringUpError::Phy {
                        step: s,
                        output: o,
                        cleanup: Cleanup::TornDown(_),
                        ..
                    }) if (s, o) == (step, output)
                ),
                "{step:?}"
            );
        }
        // With Running, the output may run from the output's start on.
        let running = MAIN_ONLY.with_output_during_sink_write(OutputDuringSinkWrite::Running);
        for (fail, step, output) in [
            (0, TmdsStep::Configure, OutputState::Stopped),
            (1, TmdsStep::SetScrambling, OutputState::Stopped),
            (2, TmdsStep::StartOutput, OutputState::MayBeRunning),
            (3, TmdsStep::SetScrambling, OutputState::MayBeRunning),
        ] {
            let mut io = TestIo::new();
            match fail {
                0 => io.fail_configure = true,
                1 => io.fail_set_scrambling = true,
                2 => io.fail_start_output = true,
                _ => io.fail_set_scrambling_on = true,
            }
            let r = up(&mut io, &link(594_000, NO_FRL), &running);
            assert!(
                matches!(
                    r.result,
                    Err(BringUpError::Phy { step: s, output: o, .. }) if (s, o) == (step, output)
                ),
                "Running {fail}"
            );
        }
        // The tear-down after a PHY failure uses the caller's settings, with the sink present.
        let mut io = TestIo::new();
        io.fail_start_output = true;
        let clearing = MAIN_ONLY.with_tear_down(TearDownConfig::DEFAULT.with_clear_sink(true));
        let r = up(&mut io, &link(594_000, NO_FRL), &clearing);
        assert!(matches!(
            r.result,
            Err(BringUpError::Phy {
                cleanup: Cleanup::TornDown(Err(TearDownError {
                    sink: SinkClear::Cleared,
                    ..
                })) | Cleanup::TornDown(Ok(TornDown {
                    sink: SinkClear::Cleared
                })),
                ..
            })
        ));
        assert_eq!(io.tmds_config, 0);

        // The cleanup's own failure is in it.
        let mut io = TestIo::new();
        io.fail_stop_output = true;
        let r = up(&mut io, &link(594_000, NO_FRL), &MAIN_ONLY);
        assert!(matches!(
            r.result,
            Err(BringUpError::Phy {
                cleanup: Cleanup::TornDown(Err(TearDownError {
                    output: Some(()),
                    ..
                })),
                ..
            })
        ));
    }

    #[test]
    fn without_tear_down_on_error_both_ends_stay() {
        let mut io = TestIo::new();
        io.fail_start_output = true;
        let r = up(
            &mut io,
            &link(594_000, NO_FRL),
            &MAIN_ONLY.with_tear_down_on_error(false),
        );
        assert!(matches!(
            r.result,
            Err(BringUpError::Phy {
                cleanup: Cleanup::Skipped,
                ..
            })
        ));
        assert_eq!(io.ops().last(), Some(&Op::StartOutput));
    }

    #[test]
    fn warnings_before_both_paths_are_kept_until_the_write_stops() {
        let mut io = TestIo::new();
        io.fail_scdc = Some(DdcErrorKind::Busy);
        io.scdc_failures = 1; // the FRL rate clear: a warning
        io.scdc_ok_calls = 0;
        let mut config = BringUpConfig::DEFAULT;
        config.on_tmds_config_failure = OnTmdsConfigFailure::Stop;
        let r = up(&mut io, &link(594_000, FRL_SINK), &config);
        assert!(
            r.link_up()
                .unwrap()
                .warnings
                .iter_warnings()
                .any(|w| matches!(w, BringUpWarning::FrlRateClearFailed(_)))
        );

        let mut io = TestIo::new();
        io.fail_scdc = Some(DdcErrorKind::Unsupported);
        let r = up(&mut io, &link(594_000, FRL_SINK), &BringUpConfig::DEFAULT);
        // The work before both paths only warns; the sink's write stops the bring-up.
        assert!(matches!(
            r.result,
            Err(BringUpError::Scdc {
                step: TmdsStep::ReadTmdsConfig,
                output: OutputState::Stopped,
                warnings,
                ..
            }) if warnings.len() == 3
        ));
    }

    /// Where the bring-up stopped and what it left: `None` when the link came up.
    fn cancelled(r: &Up) -> Option<(CancelPoint, &Cleanup<DdcErrorKind, ()>)> {
        match &r.result {
            Ok(BringUpOutcome::Cancelled { at, cleanup, .. }) => Some((*at, cleanup)),
            _ => None,
        }
    }

    #[test]
    fn a_flag_set_at_entry_ends_it_before_any_io() {
        let mut io = TestIo::new();
        io.cancelled = true;
        let r = up(&mut io, &link(594_000, FRL_SINK), &BringUpConfig::DEFAULT);
        assert_eq!(
            r.result,
            Ok(BringUpOutcome::Cancelled {
                at: CancelPoint::Entry,
                cleanup: Cleanup::Skipped,
                warnings: Warnings::new(),
            })
        );
        assert!(io.ops().is_empty());
        assert_eq!(r.count, 3);
        assert_eq!(
            r.events[1],
            Some(TmdsEventKind::BringUpCancelled {
                at: CancelPoint::Entry
            })
        );
        assert_eq!(
            r.events[2],
            Some(TmdsEventKind::BringUpEnded {
                failed_at: None,
                cancelled: true
            })
        );
    }

    #[test]
    fn a_cancel_is_seen_at_the_next_point_and_tears_down() {
        // Ops of the full run: 0 ClearFrlRate, 1 ClearFltUpdate, 2 WriteSourceVersion,
        // 3 StopOutput, 4 UpdateTmdsConfig, 5 Configure, 6 SetScrambling, 7-9 the wait's
        // three slices, 10 StartOutput, then the check: 11 a read, 12 a delay, 13 a read,
        // 14 a delay, 15 the read that sees scrambling.
        let config = BringUpConfig::DEFAULT.with_ratio_wait(Duration::from_millis(3));
        let link = link(594_000, FRL_SINK);
        let run = |after: Option<usize>| {
            let mut io = TestIo::new();
            io.status_set_from_read = Some(3);
            io.cancel_after_ops = after;
            let r = up(&mut io, &link, &config);
            (r, io)
        };
        let (full, io) = run(None);
        assert!(full.link_up().is_some());
        assert_eq!(io.ops().len(), 16);
        let mut all = [Op::StopOutput; 16];
        all.copy_from_slice(io.ops());
        assert!(
            all[7..10]
                .iter()
                .all(|op| matches!(op, Op::Delay(d) if *d <= Duration::from_millis(1)))
        );

        let step = CancelPoint::Step;
        for (after, at, ran) in [
            (1, step(TmdsStep::ClearFltUpdate), 1),
            (2, step(TmdsStep::SourceVersion), 2),
            // The PHY's calls are not points: the next one is the sink's write.
            (3, step(TmdsStep::WriteTmdsConfig), 4),
            (4, step(TmdsStep::WriteTmdsConfig), 4),
            (5, CancelPoint::RatioWait, 7),
            (8, CancelPoint::RatioWait, 8),
            (10, CancelPoint::RatioWait, 10),
            (11, CancelPoint::Check, 11),
            (12, CancelPoint::Check, 13),
            (15, CancelPoint::Check, 15),
        ] {
            let (r, io) = run(Some(after));
            let (seen, cleanup) = cancelled(&r).expect("cancelled");
            assert_eq!(seen, at, "after {after}");
            assert_eq!(io.ops()[..ran], all[..ran], "after {after}");
            // Then the tear-down, whatever `tear_down_on_error` says: the output stopped.
            assert_eq!(io.ops()[ran..], [Op::StopOutput], "after {after}");
            assert_eq!(
                cleanup,
                &Cleanup::TornDown(Ok(TornDown {
                    sink: SinkClear::NotRequested
                }))
            );
            assert!(r.has(TmdsEventKind::BringUpCancelled { at }));
            assert!(r.has(TmdsEventKind::BringUpEnded {
                failed_at: None,
                cancelled: true
            }));
        }
        // A cancelled check is recorded, and it ends the bring-up rather than its outcome.
        let (r, _) = run(Some(11));
        assert!(r.events[..r.count].iter().any(|e| matches!(
            e,
            Some(TmdsEventKind::ScramblingChecked { check }) if check.result == CheckResult::Cancelled
        )));
        // Once the check saw scrambling, a later flag changes nothing.
        let (r, _) = run(Some(16));
        assert!(cancelled(&r).is_none());
        let mut io = TestIo::new();
        io.cancel_after_ops = Some(3);
        let r = up(&mut io, &link, &config.with_tear_down_on_error(false));
        assert!(matches!(cancelled(&r), Some((_, Cleanup::TornDown(_)))));
        // The tear-down after a cancel uses the caller's settings, with the sink present: a
        // cancel in the check clears what the bring-up wrote.
        let mut io = TestIo::new();
        io.cancel_after_ops = Some(11);
        let clearing = config.with_tear_down(TearDownConfig::DEFAULT.with_clear_sink(true));
        let r = up(&mut io, &link, &clearing);
        assert!(matches!(
            cancelled(&r),
            Some((
                CancelPoint::Check,
                Cleanup::TornDown(Ok(TornDown {
                    sink: SinkClear::Cleared
                }))
            ))
        ));
        assert_eq!(io.tmds_config, 0);
    }

    #[test]
    fn a_plain_link_reads_the_flag_before_its_read_back() {
        let mut io = TestIo::new();
        io.fail_scdc = Some(DdcErrorKind::Busy);
        io.scdc_failures = 1;
        io.cancel_after_ops = Some(2); // StopOutput, then the failed write
        let r = up(&mut io, &link(148_500, NO_FRL), &MAIN_ONLY);
        assert!(matches!(
            &r.result,
            Ok(BringUpOutcome::Cancelled {
                at: CancelPoint::Step(TmdsStep::ReadTmdsConfig),
                warnings,
                ..
            }) if warnings.iter_warnings().any(|w| matches!(
                w,
                BringUpWarning::TmdsConfigWriteFailed { read_back: None, .. }
            ))
        ));
        assert!(!io.ops().contains(&Op::ReadTmdsConfig));
    }

    #[test]
    fn a_zero_interval_spends_the_wait_in_one_delay() {
        let mut io = TestIo::new();
        io.scrambling_status = 0x01;
        let config = MAIN_ONLY
            .with_ratio_wait(Duration::from_millis(3))
            .with_check_interval(Duration::ZERO);
        up(&mut io, &link(594_000, NO_FRL), &config);
        let delays = io
            .ops()
            .iter()
            .filter(|op| matches!(op, Op::Delay(_)))
            .count();
        assert_eq!(delays, 1);
    }

    #[test]
    fn no_combination_records_more_than_the_bound() {
        // A plain link, a link scrambled at a low rate and one above 340 Mcsc.
        let links = |sink: SinkTmdsFacts| {
            [
                TmdsLinkParams::choose(
                    148_500,
                    sink,
                    SourceTmdsFacts::new(false),
                    TmdsPolicy::DEFAULT,
                ),
                TmdsLinkParams::choose(
                    148_500,
                    sink,
                    SourceTmdsFacts::new(true),
                    TmdsPolicy::DEFAULT,
                ),
                TmdsLinkParams::choose(
                    594_000,
                    sink,
                    SourceTmdsFacts::new(false),
                    TmdsPolicy::DEFAULT,
                ),
            ]
        };
        let lte = SinkTmdsFacts::new(true, true, true);
        let mut most = 0;
        for sink in [FRL_SINK, NO_FRL, lte, SinkTmdsFacts::NONE] {
            for link in links(sink).into_iter().flatten() {
                for running in [false, true] {
                    for whole in [false, true] {
                        for fail in 0..8 {
                            for cancel in (0..=24).map(Some).chain([None]) {
                                let mut io = TestIo::new();
                                io.cancel_after_ops = cancel;
                                match fail {
                                    1 => io.fail_scdc = Some(DdcErrorKind::Busy),
                                    2 => io.fail_scdc = Some(DdcErrorKind::Detached),
                                    3 => io.fail_configure = true,
                                    4 => io.fail_set_scrambling_on = true,
                                    5 => io.fail_start_output = true,
                                    6 => io.fail_stop_output = true,
                                    7 => {
                                        io.fail_scdc = Some(DdcErrorKind::Busy);
                                        io.fail_stop_output = true;
                                    }
                                    _ => {}
                                }
                                let mut config = BringUpConfig::DEFAULT
                                    .with_clear_frl(ClearFrl::EveryScdcSink)
                                    .with_source_version(SourceVersionWrite::IfSinkVersion1)
                                    .with_scrambling_deadline(Duration::ZERO)
                                    .with_check_window(Duration::from_millis(5))
                                    .with_tear_down(TearDownConfig::DEFAULT.with_clear_sink(true));
                                if running {
                                    config.output_during_sink_write =
                                        OutputDuringSinkWrite::Running;
                                }
                                if whole {
                                    config.tmds_config_write = TmdsConfigWrite::WholeByte;
                                }
                                let r = up(&mut io, &link, &config);
                                most = most.max(r.count);
                                let cancelled =
                                    matches!(r.result, Ok(BringUpOutcome::Cancelled { .. }));
                                assert_eq!(r.link_up().is_some(), r.result.is_ok() && !cancelled);
                            }
                        }
                    }
                }
            }
        }
        // The sweep reaches the worst case: a scrambled link under Running with every SCDC
        // call failing, cancelled in its check, then cleared. The bound is one above it,
        // since a plain link's read-back and a scrambled link's deadline and check never
        // come together.
        assert_eq!(most, MAX_BRING_UP_EVENTS - 1);
    }
}